:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(phai): evals for the exec tool (#57472)
Georgiy Tarasovfafa617dcc62
diff --git a/ee/hogai/eval/sandboxed/cli_mcp/__init__.py b/ee/hogai/eval/sandboxed/cli_mcp/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py b/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.pynew file mode 100644index 000000000000..59e194462822--- /dev/null+++ b/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py@@ -0,0 +1,250 @@+"""Eval cases for the ``posthog:exec`` cli workflow conventions.++Five eval functions, each grading a single behavior the cli prompts spell out+in ``services/mcp/src/templates/cli-proxy-tool.md`` and+``services/mcp/src/templates/cli-proxy-command.md``:++* ``eval_typo_recovery`` — when prompted to use a deprecated or misspelled+ tool name, the agent recovers via the redirect / unknown-tool error and+ ends up calling a correct replacement.+* ``eval_schema_drilldown`` — for a non-trivial trends question, the agent+ drills into nested fields (``series``, ``breakdownFilter``) before the+ final ``call``.+* ``eval_search_first`` — for an open-ended request the agent prefers+ ``search <regex>`` over the bare ``tools`` listing.+* ``eval_info_before_call`` — every successful ``call <tool>`` is preceded+ by an ``info <tool>`` in the same run.+* ``eval_verify_event_before_query`` — for ``query-*`` calls, the agent+ verifies the event/property exists via ``read-data-schema`` first.++All five skip when ``--mcp-mode=tools`` because the ``exec`` tool is only+registered in ``cli`` mode (see ``conftest.py:_apply_mcp_mode``).++To run a single eval:+ pytest ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py::eval_typo_recovery --mcp-mode=cli+"""++from __future__ import annotations++import pytest++from ee.hogai.eval.sandboxed.base import SandboxedPublicEval+from ee.hogai.eval.sandboxed.cli_mcp.scorers import (+ CalledTargetTool,+ DrilledIntoSchema,+ InfoBeforeCall,+ PreferredSearchOverTools,+ RanPythonPostProcessing,+ RecoveredToCorrectTool,+ UsedJsonOutputFormat,+ VerifiedEventBeforeQuery,+)+from ee.hogai.eval.sandboxed.config import SandboxedEvalCase+from ee.hogai.eval.sandboxed.scorers import ExitCodeZero+++async def eval_typo_recovery(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Prompted with a deprecated or typo'd tool name, the agent must recover."""+ if mcp_mode == "tools":+ pytest.skip("posthog:exec only exists in cli mode")++ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="deprecated_query_run",+ prompt=("Use the `query-run` tool to find how many `$pageview` events we had in the last 7 days."),+ expected={+ "recovered_to_correct_tool": {+ "wrong": "query-run",+ "correct_any_of": ["query-trends", "execute-sql"],+ },+ },+ ),+ SandboxedEvalCase(+ name="typo_insight_create",+ prompt=("Create an insight named 'Daily pageviews' using the `insite-create` tool."),+ expected={+ "recovered_to_correct_tool": {+ "wrong": "insite-create",+ "correct_any_of": ["insight-create"],+ },+ },+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-cli-mcp-typo-recovery-{mcp_mode}",+ cases=cases,+ scorers=[ExitCodeZero(), RecoveredToCorrectTool()],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )+++async def eval_schema_drilldown(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Trends question with breakdown — the agent must drill into nested schema fields."""+ if mcp_mode == "tools":+ pytest.skip("posthog:exec only exists in cli mode")++ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="trends_with_breakdown",+ prompt=(+ "Run a trends query for `$pageview` over the last 14 days, broken down "+ "by `$browser`. Return the result."+ ),+ expected={+ "drilled_into_schema": {+ "tool": "query-trends",+ "fields": ["series", "breakdownFilter"],+ },+ "called_target_tool": {"tool": "query-trends"},+ },+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-cli-mcp-schema-drilldown-{mcp_mode}",+ cases=cases,+ scorers=[ExitCodeZero(), CalledTargetTool(), DrilledIntoSchema()],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )+++async def eval_search_first(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Open-ended discovery — the agent must prefer ``search`` over bare ``tools``."""+ if mcp_mode == "tools":+ pytest.skip("posthog:exec only exists in cli mode")++ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="find_feature_flag_tool",+ prompt="List all feature flags in this project.",+ expected={+ "preferred_search_over_tools": {},+ "called_target_tool": {"tool": "feature-flag-get-all"},+ },+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-cli-mcp-search-first-{mcp_mode}",+ cases=cases,+ scorers=[ExitCodeZero(), CalledTargetTool(), PreferredSearchOverTools()],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )+++async def eval_info_before_call(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Every successful ``call <tool>`` must be preceded by ``info <tool>``."""+ if mcp_mode == "tools":+ pytest.skip("posthog:exec only exists in cli mode")++ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="info_before_dashboard_create",+ prompt="Create a dashboard named 'Onboarding signals'.",+ expected={+ "info_before_call": {"tool": "dashboard-create"},+ "called_target_tool": {"tool": "dashboard-create"},+ },+ ),+ SandboxedEvalCase(+ name="info_before_read_data_schema",+ prompt="What event names contain the word 'feedback' in this project?",+ expected={+ "info_before_call": {"tool": "read-data-schema"},+ "called_target_tool": {"tool": "read-data-schema"},+ },+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-cli-mcp-info-before-call-{mcp_mode}",+ cases=cases,+ scorers=[ExitCodeZero(), CalledTargetTool(), InfoBeforeCall()],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )+++async def eval_json_for_post_processing(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """Post-processing scenario — agent must request raw JSON and run Python on it.++ The default ``output_format: "optimized"`` is token-efficient but lossy+ (truncated, formatted) and not safe to ``json.loads``. When the agent's+ plan involves programmatic post-processing (counting, filtering, math),+ it should opt into ``output_format: "json"`` so the result is a parseable+ JSON document, then drive Python via ``Bash`` to compute the answer.+ """+ if mcp_mode == "tools":+ pytest.skip("posthog:exec only exists in cli mode")++ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="dashboards_python_postprocess",+ prompt=(+ "List every dashboard in this project, then write a small Python "+ "script that counts how many dashboard names have more than 3 words "+ "(words = whitespace-separated tokens). Return that count along with "+ "the names of those dashboards. Use the JSON output of the listing "+ "tool so you can parse it cleanly in Python."+ ),+ expected={+ "called_target_tool": {"tool": "dashboards-get-all"},+ "used_json_output_format": {"tool": "dashboards-get-all"},+ "ran_python_post_processing": {},+ },+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-cli-mcp-json-postprocess-{mcp_mode}",+ cases=cases,+ scorers=[+ ExitCodeZero(),+ CalledTargetTool(),+ UsedJsonOutputFormat(),+ RanPythonPostProcessing(),+ ],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )+++async def eval_verify_event_before_query(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ """``query-*`` calls must be preceded by a successful ``read-data-schema`` call."""+ if mcp_mode == "tools":+ pytest.skip("posthog:exec only exists in cli mode")++ cases: list[SandboxedEvalCase] = [+ SandboxedEvalCase(+ name="trends_pageview_verifies_first",+ prompt="How many `$pageview` events did we have last week?",+ expected={+ "verified_event_before_query": {"query_tool": "query-trends"},+ "called_target_tool": {"tool": "query-trends"},+ },+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-cli-mcp-verify-event-{mcp_mode}",+ cases=cases,+ scorers=[ExitCodeZero(), CalledTargetTool(), VerifiedEventBeforeQuery()],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )diff --git a/ee/hogai/eval/sandboxed/cli_mcp/scorers.py b/ee/hogai/eval/sandboxed/cli_mcp/scorers.pynew file mode 100644index 000000000000..4d8b278a40a6--- /dev/null+++ b/ee/hogai/eval/sandboxed/cli_mcp/scorers.py@@ -0,0 +1,613 @@+"""Deterministic scorers for the cli_mcp evals.++Each case carries its per-scorer params under the scorer's ``_name()``+in ``expected``, mirroring the convention used by+``LookupIdInOutput`` (see ``retrieval/scorers.py``):++ expected = {+ "called_target_tool": {"tool": "notebooks-create"},+ }++Scorers default to ``score=None`` when their key is missing —+unrelated cases don't drag the rollup down.++* ``CalledTargetTool`` — did the agent successfully invoke+ ``expected[<scorer_name>]["tool"]`` at least once? Returns 1.0/0.0.+* ``RecoveredToCorrectTool`` — when prompted to use a wrong tool name+ (deprecated or typo'd), did the agent end up calling a correct+ replacement?+* ``DrilledIntoSchema`` — did the agent drill into every named field+ via ``schema <tool> <field>`` before the final ``call``?+* ``PreferredSearchOverTools`` — did the agent prefer ``search`` over+ the bare ``tools`` listing for discovery?+* ``InfoBeforeCall`` — was every successful call to the target tool+ preceded by ``info <tool>`` in the same run?+* ``VerifiedEventBeforeQuery`` — did the agent run ``read-data-schema``+ before any successful ``query-*`` call?+"""++from __future__ import annotations++from braintrust import Score+from braintrust_core.score import Scorer++from ee.hogai.eval.sandboxed.log_parser import EXEC_TOOL_NAME, INFO_SYNTHETIC_PREFIX, LogParser, ToolCall++__all__ = [+ "CalledTargetTool",+ "DrilledIntoSchema",+ "InfoBeforeCall",+ "PreferredSearchOverTools",+ "RanPythonPostProcessing",+ "RecoveredToCorrectTool",+ "UsedJsonOutputFormat",+ "VerifiedEventBeforeQuery",+]+++def _read_tool(expected: dict | None, scorer_name: str) -> str | None:+ """Look up ``expected[scorer_name]["tool"]`` with permissive validation."""+ if not isinstance(expected, dict):+ return None+ spec = expected.get(scorer_name)+ if not isinstance(spec, dict):+ return None+ target = spec.get("tool")+ return target if isinstance(target, str) and target else None+++def _read_spec(expected: dict | None, scorer_name: str) -> dict | None:+ """Look up the per-scorer params dict ``expected[scorer_name]`` (any shape)."""+ if not isinstance(expected, dict):+ return None+ spec = expected.get(scorer_name)+ return spec if isinstance(spec, dict) else None+++def _exec_command_head(call: ToolCall) -> tuple[str, str]:+ """Return ``(verb, rest)`` for a raw ``exec`` call's command string.++ Empty tuple for non-``exec`` or already-unwrapped calls. Lets scorers+ inspect the ``search`` / ``schema`` / ``tools`` verbs that+ ``_parse_exec_command`` intentionally drops on the floor.+ """+ if call.is_exec_unwrapped or call.name != EXEC_TOOL_NAME:+ return ("", "")+ cmd = call.input.get("command", "")+ if not isinstance(cmd, str):+ return ("", "")+ head, _, rest = cmd.strip().partition(" ")+ return (head.lower(), rest.strip())+++def _build_parser(output: dict | None) -> LogParser | None:+ if not output:+ return None+ raw_log = output.get("raw_log")+ if not raw_log:+ return None+ return LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+++class CalledTargetTool(Scorer):+ """Binary: did the agent successfully invoke ``expected[<scorer_name>]["tool"]``?"""++ def _name(self) -> str:+ return "called_target_tool"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ if not output:+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})+ target = _read_tool(expected, self._name())+ if not target:+ return Score(+ name=self._name(),+ score=None,+ metadata={"reason": f"No {self._name()}.tool on case"},+ )+ raw_log = output.get("raw_log")+ if not raw_log:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ parser = LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")+ for call in parser.get_tool_calls(target):+ if not call.is_error:+ return Score(name=self._name(), score=1.0, metadata={"tool": target, "call_id": call.call_id})+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": f"Tool '{target}' was never successfully called", "tool": target},+ )+++def _attempted_tool(call: ToolCall, wrong: str) -> bool:+ """True if a tool call represents an attempt against the ``wrong`` name.++ Counts (a) successful or failed unwrapped calls whose inner name matches,+ (b) ``info <wrong>`` synthetic entries, and (c) raw ``exec`` calls whose+ ``call <wrong>`` / ``info <wrong>`` command targets ``wrong`` but didn't+ parse cleanly enough to unwrap.+ """+ if call.name == wrong:+ return True+ if call.name == f"{INFO_SYNTHETIC_PREFIX}{wrong}":+ return True+ head, rest = _exec_command_head(call)+ if head not in ("call", "info"):+ return False+ if head == "call" and rest.startswith("--json"):+ rest = rest[len("--json") :].lstrip()+ target, _, _ = rest.partition(" ")+ return target.strip() == wrong+++class RecoveredToCorrectTool(Scorer):+ """Binary: prompted with a wrong tool name, did the agent recover?++ ``expected = {"recovered_to_correct_tool":+ {"wrong": "query-run", "correct_any_of": ["query-trends", "execute-sql"]}}``++ Score 1.0 if the agent both *attempted* the wrong tool AND eventually made+ a successful unwrapped call to one of ``correct_any_of``. 0.0 if attempted+ but never recovered. ``None`` if ``wrong`` was never attempted (the case+ didn't actually exercise the redirect path).+ """++ def _name(self) -> str:+ return "recovered_to_correct_tool"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ spec = _read_spec(expected, self._name())+ if not spec:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})+ wrong = spec.get("wrong")+ correct_any_of = spec.get("correct_any_of")+ if not isinstance(wrong, str) or not wrong:+ return Score(name=self._name(), score=None, metadata={"reason": "Missing 'wrong' on spec"})+ if not isinstance(correct_any_of, list) or not correct_any_of:+ return Score(name=self._name(), score=None, metadata={"reason": "Missing 'correct_any_of' on spec"})+ correct_set = {c for c in correct_any_of if isinstance(c, str) and c}++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ calls = parser.get_tool_calls()+ attempted = any(_attempted_tool(call, wrong) for call in calls)+ if not attempted:+ return Score(+ name=self._name(),+ score=None,+ metadata={"reason": f"Wrong tool '{wrong}' was never attempted", "wrong": wrong},+ )++ for call in calls:+ if call.is_error:+ continue+ if call.name in correct_set:+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"wrong": wrong, "recovered_to": call.name, "call_id": call.call_id},+ )+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "Wrong tool attempted but no successful call to a correct replacement",+ "wrong": wrong,+ "correct_any_of": sorted(correct_set),+ },+ )+++class DrilledIntoSchema(Scorer):+ """Binary: did the agent drill into every named field via ``schema <tool> <field>``?++ ``expected = {"drilled_into_schema":+ {"tool": "query-trends", "fields": ["series", "breakdownFilter"]}}``++ Looks for raw ``exec`` calls whose ``command`` is ``schema <tool> <field>``+ or ``schema <tool> <field>.<sub>`` (dot-notation prefix counts). Score 1.0+ only if every required field was drilled, 0.0 otherwise with the missing+ fields in metadata. ``None`` if the spec is malformed.+ """++ def _name(self) -> str:+ return "drilled_into_schema"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ spec = _read_spec(expected, self._name())+ if not spec:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})+ tool = spec.get("tool")+ fields = spec.get("fields")+ if not isinstance(tool, str) or not tool:+ return Score(name=self._name(), score=None, metadata={"reason": "Missing 'tool' on spec"})+ if not isinstance(fields, list) or not fields:+ return Score(name=self._name(), score=None, metadata={"reason": "Missing 'fields' on spec"})+ required = [f for f in fields if isinstance(f, str) and f]++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ drilled: set[str] = set()+ for call in parser.get_tool_calls():+ head, rest = _exec_command_head(call)+ if head != "schema":+ continue+ schema_tool, _, field_path = rest.partition(" ")+ if schema_tool.strip() != tool:+ continue+ field_path = field_path.strip()+ if not field_path:+ continue+ top_field, _, _ = field_path.partition(".")+ top_field = top_field.strip()+ if top_field in required:+ drilled.add(top_field)++ missing = [f for f in required if f not in drilled]+ if missing:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "Required fields were not drilled via 'schema'",+ "tool": tool,+ "missing_fields": missing,+ "drilled_fields": sorted(drilled),+ },+ )+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"tool": tool, "drilled_fields": sorted(drilled)},+ )+++class PreferredSearchOverTools(Scorer):+ """Binary: did the agent prefer ``search`` over the bare ``tools`` listing?++ Opt-in via presence of ``expected = {"preferred_search_over_tools": {}}``.++ Walks raw ``exec`` calls in chronological order. Score 1.0 if the first+ discovery action (``search`` or ``tools``) was ``search``, or if ``tools``+ was never used. 0.0 if ``tools`` came first or if ``tools`` was used+ without any ``search`` in the run. ``None`` if no discovery actions at all.+ """++ def _name(self) -> str:+ return "preferred_search_over_tools"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ if _read_spec(expected, self._name()) is None:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ calls_by_position = sorted(parser.get_tool_calls(), key=lambda c: c.position)+ first_discovery: str | None = None+ used_search = False+ used_tools = False+ for call in calls_by_position:+ head, _ = _exec_command_head(call)+ if head not in ("search", "tools"):+ continue+ if first_discovery is None:+ first_discovery = head+ if head == "search":+ used_search = True+ else:+ used_tools = True++ if first_discovery is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No discovery actions"})+ if not used_tools:+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"first_discovery": first_discovery, "used_tools": False},+ )+ if first_discovery == "search":+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"first_discovery": "search", "used_tools": True, "used_search": used_search},+ )+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "Bare 'tools' was the first discovery action",+ "first_discovery": "tools",+ "used_search": used_search,+ },+ )+++class InfoBeforeCall(Scorer):+ """Binary: was every successful call to the target tool preceded by ``info <tool>``?++ ``expected = {"info_before_call": {"tool": "dashboard-create"}}``++ Walks tool calls in chronological order; for each successful unwrapped+ call to ``tool``, requires that an ``info <tool>`` synthetic entry+ appeared earlier. Score 1.0 if all qualifying calls were preceded, 0.0+ otherwise. ``None`` if ``tool`` was never called successfully (caught+ upstream by ``CalledTargetTool``).+ """++ def _name(self) -> str:+ return "info_before_call"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ target = _read_tool(expected, self._name())+ if not target:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.tool on case"})++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ calls = sorted(parser.get_tool_calls(), key=lambda c: c.position)+ info_synthetic = f"{INFO_SYNTHETIC_PREFIX}{target}"+ seen_info = False+ offenders: list[str] = []+ successful_calls = 0+ for call in calls:+ if call.name == info_synthetic and not call.is_error:+ seen_info = True+ continue+ if call.is_exec_unwrapped and call.name == target and not call.is_error:+ successful_calls += 1+ if not seen_info:+ offenders.append(call.call_id)++ if successful_calls == 0:+ return Score(+ name=self._name(),+ score=None,+ metadata={"reason": f"Target '{target}' never called successfully", "tool": target},+ )+ if offenders:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "At least one call to target was not preceded by 'info <tool>'",+ "tool": target,+ "offenders": offenders,+ "total_calls": successful_calls,+ },+ )+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"tool": target, "total_calls": successful_calls},+ )+++class VerifiedEventBeforeQuery(Scorer):+ """Binary: did the agent run ``read-data-schema`` before any successful ``query_tool`` call?++ ``expected = {"verified_event_before_query": {"query_tool": "query-trends"}}``++ For each successful unwrapped call to ``query_tool``, requires that a+ successful ``read-data-schema`` call appeared earlier. Score 1.0 if all+ qualifying calls were preceded, 0.0 otherwise. ``None`` if ``query_tool``+ never called successfully.+ """++ SCHEMA_TOOL = "read-data-schema"++ def _name(self) -> str:+ return "verified_event_before_query"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ spec = _read_spec(expected, self._name())+ if not spec:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} spec on case"})+ query_tool = spec.get("query_tool")+ if not isinstance(query_tool, str) or not query_tool:+ return Score(name=self._name(), score=None, metadata={"reason": "Missing 'query_tool' on spec"})++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ calls = sorted(parser.get_tool_calls(), key=lambda c: c.position)+ seen_schema = False+ offenders: list[str] = []+ successful_calls = 0+ for call in calls:+ if call.is_error:+ continue+ if call.is_exec_unwrapped and call.name == self.SCHEMA_TOOL:+ seen_schema = True+ continue+ if call.is_exec_unwrapped and call.name == query_tool:+ successful_calls += 1+ if not seen_schema:+ offenders.append(call.call_id)++ if successful_calls == 0:+ return Score(+ name=self._name(),+ score=None,+ metadata={"reason": f"Query tool '{query_tool}' never called successfully"},+ )+ if offenders:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": f"'{query_tool}' was called without a prior successful '{self.SCHEMA_TOOL}'",+ "query_tool": query_tool,+ "offenders": offenders,+ "total_calls": successful_calls,+ },+ )+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"query_tool": query_tool, "total_calls": successful_calls},+ )+++class UsedJsonOutputFormat(Scorer):+ """Binary: did the agent request raw JSON output for the named tool?++ ``expected = {"used_json_output_format": {"tool": "dashboards-get-all"}}``++ For every successful unwrapped call to ``tool``, requires+ ``requested_output_format == "json"``. The default is ``"optimized"``,+ which is fine for human-facing answers but lossy / token-truncated for+ Python post-processing — opting into ``"json"`` is the right move when+ the agent plans to parse results programmatically.++ Score 1.0 if at least one successful call to ``tool`` requested+ ``output_format == "json"``. 0.0 if every successful call used the+ default. ``None`` if the tool was never called successfully.+ """++ def _name(self) -> str:+ return "used_json_output_format"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ target = _read_tool(expected, self._name())+ if not target:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()}.tool on case"})++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ relevant = [call for call in parser.get_tool_calls(target) if not call.is_error and call.is_exec_unwrapped]+ if not relevant:+ return Score(+ name=self._name(),+ score=None,+ metadata={"reason": f"No successful exec-unwrapped '{target}' calls", "tool": target},+ )++ json_calls = [call for call in relevant if call.requested_output_format == "json"]+ if json_calls:+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"tool": target, "json_calls": len(json_calls), "total_calls": len(relevant)},+ )+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": f"All successful '{target}' calls used the default output format",+ "tool": target,+ "total_calls": len(relevant),+ "formats_seen": sorted({call.requested_output_format or "default" for call in relevant}),+ },+ )+++class RanPythonPostProcessing(Scorer):+ """Binary: did the agent actually run Python to post-process tool results?++ Opt-in via presence of ``expected = {"ran_python_post_processing": {}}``.++ Walks ``Bash`` tool calls and looks for one whose command contains+ ``python`` or ``python3`` (heuristic — matches ``python -c '...'``,+ ``python3 script.py``, ``cat ... | python3 -``, ``uv run python ...``).+ Score 1.0 if any successful Bash call ran Python, 0.0 otherwise.+ ``None`` if no Bash calls at all.+ """++ PYTHON_TOKENS: frozenset[str] = frozenset({"python", "python3"})++ def _name(self) -> str:+ return "ran_python_post_processing"++ async def _run_eval_async(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _run_eval_sync(self, output, expected=None, **kwargs):+ return self._evaluate(output, expected)++ def _evaluate(self, output: dict | None, expected: dict | None) -> Score:+ if _read_spec(expected, self._name()) is None:+ return Score(name=self._name(), score=None, metadata={"reason": f"No {self._name()} key on case"})++ parser = _build_parser(output)+ if parser is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})++ bash_calls = parser.get_tool_calls("Bash")+ if not bash_calls:+ return Score(name=self._name(), score=None, metadata={"reason": "No Bash calls"})++ for call in bash_calls:+ if call.is_error:+ continue+ cmd = call.input.get("command", "")+ if not isinstance(cmd, str):+ continue+ tokens = {part.split("/")[-1] for part in cmd.split() if part}+ if tokens & self.PYTHON_TOKENS:+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"matched_call_id": call.call_id},+ )+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "No Bash call invoked python/python3",+ "bash_call_count": len(bash_calls),+ },+ )diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.pyindex 7d42192b11af..81fe7842c38c 100644--- a/ee/hogai/eval/sandboxed/conftest.py+++ b/ee/hogai/eval/sandboxed/conftest.py@@ -3,12 +3,13 @@ from __future__ import annotationsimport osimport timeimport atexit+import signalimport socketimport asyncioimport loggingimport threadingimport subprocess-from collections.abc import Generator+from collections.abc import Callable, Generatorfrom pathlib import Pathimport pytest@@ -78,6 +79,102 @@ def pytest_collection_modifyitems(config, items): # noqa: ARG001_EVAL_CONTAINER_PREFIX = "task-sandbox-"+def _start_long_lived_subprocess(+ *,+ name: str,+ port: int,+ cmd: list[str],+ cwd: Path,+ env: dict[str, str],+ log_prefix: str,+ readiness_timeout: float = 30.0,+) -> tuple[subprocess.Popen, Callable[[], None]]:+ """Spawn a long-lived support service (LLM gateway, MCP server) for the eval session.++ Three guarantees beyond a bare ``subprocess.Popen``:++ * **Pre-flight port check** — refuses to start if ``port`` is already bound.+ A previous session's stale process would otherwise pass our TCP-level+ readiness check (we'd connect to the *old* process), and tests would+ silently run against a gateway tied to a deleted test database.++ * **Subprocess-aware readiness wait** — polls ``proc.poll()`` on every+ iteration. If the subprocess died during startup (e.g. EADDRINUSE that+ slipped past the pre-flight check, missing dependency, config error),+ fails loudly with the captured returncode rather than waiting for the+ TCP timeout.++ * **Process-group cleanup on session exit** — ``start_new_session=True``+ puts the child in its own process group, and an ``atexit`` hook sends+ ``SIGTERM`` (then ``SIGKILL``) to the whole group. Mirrors the docker+ container cleanup pattern in ``_cleanup_eval_containers``. Doesn't fire+ on ``SIGKILL`` of pytest itself — but the next session's pre-flight+ check will catch any leak with a specific ``lsof`` hint.+ """+ try:+ pre_sock = socket.create_connection(("localhost", port), timeout=0.5)+ pre_sock.close()+ pytest.fail(+ f"Port {port} is already in use — likely a stale {name} from a prior eval session. "+ f"Find and kill it:\n lsof -iTCP:{port} -sTCP:LISTEN"+ )+ except OSError:+ pass # port is free, proceed++ proc = subprocess.Popen(+ cmd,+ cwd=cwd,+ env=env,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ start_new_session=True,+ )++ def _stop() -> None:+ if proc.poll() is not None:+ return+ try:+ os.killpg(proc.pid, signal.SIGTERM)+ except (ProcessLookupError, PermissionError):+ return+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except (ProcessLookupError, PermissionError):+ pass++ atexit.register(_stop)++ def _pipe_to_logger(pipe, level):+ for line in iter(pipe.readline, b""):+ text = line.decode("utf-8", errors="replace").rstrip()+ if text:+ logger.log(level, "[%s] %s", log_prefix, text)+ pipe.close()++ threading.Thread(target=_pipe_to_logger, args=(proc.stdout, logging.INFO), daemon=True).start()+ threading.Thread(target=_pipe_to_logger, args=(proc.stderr, logging.WARNING), daemon=True).start()++ deadline = time.monotonic() + readiness_timeout+ while time.monotonic() < deadline:+ if proc.poll() is not None:+ pytest.fail(+ f"{name} subprocess exited with code {proc.returncode} during startup. "+ f"Check the [{log_prefix}] WARNING lines above."+ )+ try:+ sock = socket.create_connection(("localhost", port), timeout=1)+ sock.close()+ return proc, _stop+ except OSError:+ time.sleep(0.5)++ _stop()+ pytest.fail(f"{name} failed to start on port {port} within {readiness_timeout:.0f}s.")++def _cleanup_eval_containers():"""Remove any leftover eval Docker containers.@@ -380,8 +477,10 @@ def _llm_gateway(_django_live_server, sandboxed_demo_data):}logger.info("Starting LLM gateway on port %d", LLM_GATEWAY_PORT)- proc = subprocess.Popen(- [+ _, stop = _start_long_lived_subprocess(+ name="LLM gateway",+ port=LLM_GATEWAY_PORT,+ cmd=[str(uvicorn_bin),"llm_gateway.main:app","--host",@@ -391,41 +490,13 @@ def _llm_gateway(_django_live_server, sandboxed_demo_data):],cwd=gateway_dir,env=env,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,+ log_prefix="llm-gateway",)- def _pipe_to_logger(pipe, level):- for line in iter(pipe.readline, b""):- text = line.decode("utf-8", errors="replace").rstrip()- if text:- logger.log(level, "[llm-gateway] %s", text)- pipe.close()-- threading.Thread(target=_pipe_to_logger, args=(proc.stdout, logging.INFO), daemon=True).start()- threading.Thread(target=_pipe_to_logger, args=(proc.stderr, logging.WARNING), daemon=True).start()-- deadline = time.monotonic() + 30- while time.monotonic() < deadline:- try:- sock = socket.create_connection(("localhost", LLM_GATEWAY_PORT), timeout=1)- sock.close()- break- except OSError:- time.sleep(0.5)- else:- proc.terminate()- proc.wait(timeout=5)- pytest.fail(f"LLM gateway failed to start on port {LLM_GATEWAY_PORT} within 30s.")-logger.info("LLM gateway ready on port %d", LLM_GATEWAY_PORT)yield- proc.terminate()- try:- proc.wait(timeout=5)- except subprocess.TimeoutExpired:- proc.kill()+ stop()logger.info("LLM gateway stopped")@@ -463,46 +534,19 @@ def _mcp_server(_django_live_server, _sandbox_settings):var_args.extend(["--var", v])logger.info("Starting MCP server on port %d (API: %s)", MCP_PORT, api_url)- proc = subprocess.Popen(- ["pnpm", "wrangler", "dev", "--port", str(MCP_PORT), *var_args],+ _, stop = _start_long_lived_subprocess(+ name="MCP server",+ port=MCP_PORT,+ cmd=["pnpm", "wrangler", "dev", "--port", str(MCP_PORT), *var_args],cwd=mcp_dir,env=env,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,+ log_prefix="mcp",)- # Stream subprocess output to logger in background threads- def _pipe_to_logger(pipe, level):- for line in iter(pipe.readline, b""):- text = line.decode("utf-8", errors="replace").rstrip()- if text:- logger.log(level, "[mcp] %s", text)- pipe.close()-- threading.Thread(target=_pipe_to_logger, args=(proc.stdout, logging.INFO), daemon=True).start()- threading.Thread(target=_pipe_to_logger, args=(proc.stderr, logging.WARNING), daemon=True).start()-- deadline = time.monotonic() + 30- while time.monotonic() < deadline:- try:- sock = socket.create_connection(("localhost", MCP_PORT), timeout=1)- sock.close()- break- except OSError:- time.sleep(0.5)- else:- proc.terminate()- proc.wait(timeout=5)- pytest.fail(f"MCP server failed to start on port {MCP_PORT} within 30s.")-logger.info("MCP server ready on port %d", MCP_PORT)yield- proc.terminate()- try:- proc.wait(timeout=5)- except subprocess.TimeoutExpired:- proc.kill()+ stop()logger.info("MCP server stopped")diff --git a/ee/hogai/eval/sandboxed/log_parser.py b/ee/hogai/eval/sandboxed/log_parser.pyindex abda3f0d29db..9e5c6287b326 100644--- a/ee/hogai/eval/sandboxed/log_parser.py+++ b/ee/hogai/eval/sandboxed/log_parser.py@@ -76,6 +76,13 @@ class ToolCall(BaseModel):is_exec_unwrapped: bool"""True when this entry was synthesised from an ``exec`` call's command."""+ requested_output_format: str | None = None+ """The ``output_format`` value the agent passed on the ``exec`` call sibling+ to ``command``. ``"json"`` opts into raw-JSON output (suitable for+ Python/Bash post-processing); ``"optimized"`` or ``None`` is the default+ token-efficient view. ``None`` for non-``exec`` calls and for unwrapped+ discovery commands. See ``services/mcp/src/tools/exec.ts`` for the schema."""+class SkillCall(BaseModel):model_config = ConfigDict(frozen=True)@@ -215,6 +222,8 @@ class LogParser:unwrapped = _parse_exec_command(command)if unwrapped is not None:inner_name, inner_input = unwrapped+ output_format = tool_input.get("output_format")+ requested_output_format = output_format if isinstance(output_format, str) else Noneoutput, is_error = self._lookup_result(call_id)return ToolCall(name=inner_name,@@ -225,6 +234,7 @@ class LogParser:position=position,raw_name=raw_name,is_exec_unwrapped=True,+ requested_output_format=requested_output_format,)output, is_error = self._lookup_result(call_id)return ToolCall(diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex 36ec5c760bb1..9c356d5ec639 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -28,6 +28,7 @@ MCP_READ_SCOPES: list[str] = ["insight:read","insight_variable:read","llm_prompt:read",+ "llm_skill:read","logs:read","notebook:read","organization:read",@@ -52,6 +53,7 @@ MCP_WRITE_SCOPES: list[str] = ["insight:write","insight_variable:write","llm_prompt:write",+ "llm_skill:write","notebook:write","survey:write",]diff --git a/services/mcp/src/templates/sections/cli-data-discovery.md b/services/mcp/src/templates/sections/cli-data-discovery.mdindex 221ee4c1b4a8..72a4d4e73932 100644--- a/services/mcp/src/templates/sections/cli-data-discovery.md+++ b/services/mcp/src/templates/sections/cli-data-discovery.md@@ -3,6 +3,8 @@`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they varyper team. If the event isn't in the schema, tell the user instead of querying a guessed name.-- Events: `call read-data-schema {"query": {"kind": "events"}}` (paginate with `limit`/`offset` if needed)+Always run `info read-data-schema` first — the recipes below are common cases, not the full schema.++- Events/Actions: `call read-data-schema {"query": {"kind": "events"/"actions"}}` (paginate with `limit`/`offset` if needed)- Properties: `call read-data-schema {"query": {"kind": "event_properties", "event_name": "<event>"}}`- Values: `call read-data-schema {"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<prop>"}}`diff --git a/services/mcp/src/templates/sections/cli-syntax.md b/services/mcp/src/templates/sections/cli-syntax.mdindex 234a5583f80e..ef5b500827f6 100644--- a/services/mcp/src/templates/sections/cli-syntax.md+++ b/services/mcp/src/templates/sections/cli-syntax.md@@ -1,11 +1,11 @@CLI-style command string. Supported commands:```text-tools — list available tool names-search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)-info <tool_name> — show tool name, description, and input schema (summarized if too large)-schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)-call [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)+tools — list available tool names+search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)+info [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.+schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)+call [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)```**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.diff --git a/services/mcp/src/templates/sections/exec-tool-blurb.md b/services/mcp/src/templates/sections/exec-tool-blurb.mdindex e2a5de032d14..059dc9592c38 100644--- a/services/mcp/src/templates/sections/exec-tool-blurb.md+++ b/services/mcp/src/templates/sections/exec-tool-blurb.md@@ -24,6 +24,7 @@ posthog:exec({ "command": "schema <tool_name> <field_path>" })# 4. Call the toolposthog:exec({ "command": "call <tool_name> <json_input>" })+posthog:exec({ "command": "call --json <tool_name> <json_input>" })```**Schema drill-down:**@@ -41,5 +42,3 @@ posthog:exec({ "command": "call <tool_name> <json_input>" })- `search` matches tool metadata only, not input schemas.- No pattern-based field projection — drill one path at a time.--Detailed reference (examples, query tools, URL patterns, guidelines) is in the `command` parameter description.diff --git a/services/mcp/src/templates/sections/retrieving-data.md b/services/mcp/src/templates/sections/retrieving-data.mdindex 39c570f28fba..a3e8f5cf250c 100644--- a/services/mcp/src/templates/sections/retrieving-data.md+++ b/services/mcp/src/templates/sections/retrieving-data.md@@ -34,15 +34,15 @@ Search rules:<example>User: Do we have any insights tracking revenue?-Assistant: [Runs `posthog:exec({ "command": "call execute-sql {\"query\":\"SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20\"}" })`]-[Picks the most plausible match by name, then runs `posthog:exec({ "command": "call insight-get {\"id\": <id>}" })` (or pass the `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]+Assistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]+[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning></example><bad-example>User: Find me a graph of MAUs.-Assistant: [Runs `call execute-sql {"query":"SELECT * FROM system.insights WHERE id = 33800 LIMIT 1"}` after a search SELECT already surfaced id 33800]-WRONG — verify with `call insight-get {"id": 33800}` instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.+Assistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]+WRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.</bad-example>#### Available insight query toolsdiff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex f4154c86d33c..40f6f772d956 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -206,15 +206,15 @@ export function createExecTool(}const { verb: toolName, rest: jsonBody } = parseCommand(callArgs)const tool = findTool(allTools, toolName)-let input: Record<string, unknown>if (!jsonBody) {input = {}} else {try {input = JSON.parse(jsonBody) as Record<string, unknown>- } catch {- throw new Error(`Invalid JSON input: ${jsonBody}`)+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err)+ throw new Error(`Invalid JSON input: ${detail}`)}}@@ -254,7 +254,7 @@ export function createExecTool(handlerResult: result,toolMeta: tool._meta,toolName: tool.name,- params: forceJson ? { ...input, output_format: 'json' } : input,+ params: useJson ? { ...input, output_format: 'json' } : input,// Consumer is the UI-apps host; keep `structuredContent` for the UI.// Passing `undefined` bypasses the coding-agent suppression in// `buildToolResultPayload` because this path explicitly wants it.diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.jsonindex d43ccfbc64c2..dace4150fc32 100644--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json@@ -1,7 +1,7 @@{"name": "exec","title": "Execute PostHog command",- "description": "### Using the `posthog` tool\n\nPass CLI-style commands in the `command` parameter for all PostHog interactions.\n\n**MANDATORY — HARD REQUIREMENTS**\n\n1. Discover tools first with `search` or `tools`.\n2. Run `info <tool_name>` BEFORE every `call <tool_name> <json>`.\n\nBLOCKING, like reading a file before editing it. Tool names and schemas are NOT predictable — never assume.\n\n**Commands (in order):**\n\n```text\n# 1. Discover (preferred: focused regex over name/title/description)\nposthog:exec({ \"command\": \"search <regex>\" })\nposthog:exec({ \"command\": \"tools\" }) # fallback: list all\n\n# 2. Check description + top-level schema (REQUIRED before call)\nposthog:exec({ \"command\": \"info <tool_name>\" })\n\n# 3. Drill into complex fields — REQUIRED for any field with a `hint`\nposthog:exec({ \"command\": \"schema <tool_name> <field_path>\" })\n\n# 4. Call the tool\nposthog:exec({ \"command\": \"call <tool_name> <json_input>\" })\n```\n\n**Schema drill-down:**\n\n- `info` returns the full schema if it fits the token budget; otherwise it auto-summarizes (names, types, required, enums, defaults) and attaches `hint` entries pointing to `schema <tool> <path>` for complex fields.\n- `schema <tool>` (no path) returns the summarized top-level schema.\n- `schema <tool> <path>` resolves a dot path, descending through:\n - object `properties` (e.g. `query.source`)\n - array `items` — numeric segments step into items (`events.0.properties`), or jump to a property on the item type (`events.id`)\n - `anyOf`/`oneOf` — numeric segment picks a variant by index, or a property name matches any object variant defining it\n- Oversized sub-schemas are also summarized with a `note` to drill further.\n- Unknown paths return an error listing available child paths.\n\n**Not supported:**\n\n- `search` matches tool metadata only, not input schemas.\n- No pattern-based field projection — drill one path at a time.\n\nDetailed reference (examples, query tools, URL patterns, guidelines) is in the `command` parameter description.",+ "description": "### Using the `posthog` tool\n\nPass CLI-style commands in the `command` parameter for all PostHog interactions.\n\n**MANDATORY — HARD REQUIREMENTS**\n\n1. Discover tools first with `search` or `tools`.\n2. Run `info <tool_name>` BEFORE every `call <tool_name> <json>`.\n\nBLOCKING, like reading a file before editing it. Tool names and schemas are NOT predictable — never assume.\n\n**Commands (in order):**\n\n```text\n# 1. Discover (preferred: focused regex over name/title/description)\nposthog:exec({ \"command\": \"search <regex>\" })\nposthog:exec({ \"command\": \"tools\" }) # fallback: list all\n\n# 2. Check description + top-level schema (REQUIRED before call)\nposthog:exec({ \"command\": \"info <tool_name>\" })\n\n# 3. Drill into complex fields — REQUIRED for any field with a `hint`\nposthog:exec({ \"command\": \"schema <tool_name> <field_path>\" })\n\n# 4. Call the tool\nposthog:exec({ \"command\": \"call <tool_name> <json_input>\" })\nposthog:exec({ \"command\": \"call --json <tool_name> <json_input>\" })\n```\n\n**Schema drill-down:**\n\n- `info` returns the full schema if it fits the token budget; otherwise it auto-summarizes (names, types, required, enums, defaults) and attaches `hint` entries pointing to `schema <tool> <path>` for complex fields.\n- `schema <tool>` (no path) returns the summarized top-level schema.\n- `schema <tool> <path>` resolves a dot path, descending through:\n - object `properties` (e.g. `query.source`)\n - array `items` — numeric segments step into items (`events.0.properties`), or jump to a property on the item type (`events.id`)\n - `anyOf`/`oneOf` — numeric segment picks a variant by index, or a property name matches any object variant defining it\n- Oversized sub-schemas are also summarized with a `note` to drill further.\n- Unknown paths return an error listing available child paths.\n\n**Not supported:**\n\n- `search` matches tool metadata only, not input schemas.\n- No pattern-based field projection — drill one path at a time.","annotations": {"destructiveHint": false,"idempotentHint": false,@@ -15,7 +15,7 @@"properties": {"command": {"type": "string",- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo <tool_name> — show tool name, description, and input schema (summarized if too large)\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\n- Events: `call read-data-schema {\"query\": {\"kind\": \"events\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-skill-duplicate\n- llma-skill-file-rename\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Runs `posthog:exec({ \"command\": \"call execute-sql {\\\"query\\\":\\\"SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20\\\"}\" })`]\n[Picks the most plausible match by name, then runs `posthog:exec({ \"command\": \"call insight-get {\\\"id\\\": <id>}\" })` (or pass the `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Runs `call execute-sql {\"query\":\"SELECT * FROM system.insights WHERE id = 33800 LIMIT 1\"}` after a search SELECT already surfaced id 33800]\nWRONG — verify with `call insight-get {\"id\": 33800}` instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issues` — Error filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"+ "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-skill-duplicate\n- llma-skill-file-rename\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]\n[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]\nWRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issues` — Error filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"}},"required": ["command"]diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txtindex 9c307c52b7c6..349fce30f06e 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt@@ -1,11 +1,11 @@CLI-style command string. Supported commands:```text-tools — list available tool names-search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)-info <tool_name> — show tool name, description, and input schema (summarized if too large)-schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)-call [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)+tools — list available tool names+search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)+info [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.+schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)+call [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)```**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.@@ -37,7 +37,9 @@ For query tools, you will typically need:`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they varyper team. If the event isn't in the schema, tell the user instead of querying a guessed name.-- Events: `call read-data-schema {"query": {"kind": "events"}}` (paginate with `limit`/`offset` if needed)+Always run `info read-data-schema` first — the recipes below are common cases, not the full schema.++- Events/Actions: `call read-data-schema {"query": {"kind": "events"/"actions"}}` (paginate with `limit`/`offset` if needed)- Properties: `call read-data-schema {"query": {"kind": "event_properties", "event_name": "<event>"}}`- Values: `call read-data-schema {"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<prop>"}}`@@ -214,15 +216,15 @@ Search rules:<example>User: Do we have any insights tracking revenue?-Assistant: [Runs `posthog:exec({ "command": "call execute-sql {\"query\":\"SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20\"}" })`]-[Picks the most plausible match by name, then runs `posthog:exec({ "command": "call insight-get {\"id\": <id>}" })` (or pass the `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]+Assistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]+[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning></example><bad-example>User: Find me a graph of MAUs.-Assistant: [Runs `call execute-sql {"query":"SELECT * FROM system.insights WHERE id = 33800 LIMIT 1"}` after a search SELECT already surfaced id 33800]-WRONG — verify with `call insight-get {"id": 33800}` instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.+Assistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]+WRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.</bad-example>#### Available insight query toolsdiff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-tool-description.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-tool-description.txtindex 8a630e85ff1e..18bfc191954b 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-tool-description.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-tool-description.txt@@ -24,6 +24,7 @@ posthog:exec({ "command": "schema <tool_name> <field_path>" })# 4. Call the toolposthog:exec({ "command": "call <tool_name> <json_input>" })+posthog:exec({ "command": "call --json <tool_name> <json_input>" })```**Schema drill-down:**@@ -40,6 +41,4 @@ posthog:exec({ "command": "call <tool_name> <json_input>" })**Not supported:**- `search` matches tool metadata only, not input schemas.-- No pattern-based field projection — drill one path at a time.--Detailed reference (examples, query tools, URL patterns, guidelines) is in the `command` parameter description.\ No newline at end of file+- No pattern-based field projection — drill one path at a time.\ No newline at end of filediff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txtindex 3a299c969561..7033c9fe14e4 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt@@ -100,15 +100,15 @@ Search rules:<example>User: Do we have any insights tracking revenue?-Assistant: [Runs `posthog:exec({ "command": "call execute-sql {\"query\":\"SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20\"}" })`]-[Picks the most plausible match by name, then runs `posthog:exec({ "command": "call insight-get {\"id\": <id>}" })` (or pass the `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]+Assistant: [Calls `execute-sql` with `SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20`]+[Picks the most plausible match by name, then calls `insight-get` with the candidate's `id` (or `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning></example><bad-example>User: Find me a graph of MAUs.-Assistant: [Runs `call execute-sql {"query":"SELECT * FROM system.insights WHERE id = 33800 LIMIT 1"}` after a search SELECT already surfaced id 33800]-WRONG — verify with `call insight-get {"id": 33800}` instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.+Assistant: [Calls `execute-sql` with `SELECT * FROM system.insights WHERE id = 33800 LIMIT 1` after a search SELECT already surfaced id 33800]+WRONG — verify with `insight-get` (passing `id: 33800`) instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.</bad-example>#### Available insight query toolsdiff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 9c35c1b44347..fa513b35bc8e 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -43,69 +43,56 @@ describe('exec tool', () => {describe('call command', () => {it('returns TOON-formatted output by default', async () => {const exec = createExec()- const result = await exec.handler(mockContext, { command: 'call mock-tool {}' })+ const result = await exec.handler(mockContext, { command: 'call mock-tool' })// TOON format uses "key: value" style, not JSONexpect(result).toContain('id: 1')expect(result).toContain('name: test')expect(result).not.toBe(JSON.stringify({ id: 1, name: 'test', items: [{ a: 1 }, { a: 2 }] }))})- it('returns raw JSON with --json flag', async () => {+ it('returns raw JSON when --json flag is passed in command', async () => {const exec = createExec()- const result = await exec.handler(mockContext, { command: 'call --json mock-tool {}' })+ const result = await exec.handler(mockContext, { command: 'call --json mock-tool' })const parsed = JSON.parse(result as string)expect(parsed).toEqual({ id: 1, name: 'test', items: [{ a: 1 }, { a: 2 }] })})- it('returns JSON for tool with outputFormat json even without flag', async () => {+ it('returns JSON for tool with outputFormat json even without --json flag', async () => {const tool = makeMockTool({ _meta: { [POSTHOG_META_KEY]: { outputFormat: 'json' } } })const exec = createExec([tool])- const result = await exec.handler(mockContext, { command: 'call mock-tool {}' })+ const result = await exec.handler(mockContext, { command: 'call mock-tool' })const parsed = JSON.parse(result as string)expect(parsed).toEqual({ id: 1, name: 'test', items: [{ a: 1 }, { a: 2 }] })})- it('returns JSON when both --json flag and outputFormat json are present', async () => {+ it('returns JSON when both --json flag and tool meta outputFormat=json are present', async () => {const tool = makeMockTool({ _meta: { [POSTHOG_META_KEY]: { outputFormat: 'json' } } })const exec = createExec([tool])- const result = await exec.handler(mockContext, { command: 'call --json mock-tool {}' })+ const result = await exec.handler(mockContext, { command: 'call --json mock-tool' })const parsed = JSON.parse(result as string)expect(parsed).toEqual({ id: 1, name: 'test', items: [{ a: 1 }, { a: 2 }] })})- it('throws usage error for call --json with no tool name', async () => {+ it('throws usage error for bare call', async () => {const exec = createExec()- await expect(exec.handler(mockContext, { command: 'call --json' })).rejects.toThrow(+ await expect(exec.handler(mockContext, { command: 'call' })).rejects.toThrow('Usage: call [--json] <tool_name> <json_input>')})- it('throws usage error for bare call', async () => {+ it('throws usage error for call --json with no tool name', async () => {const exec = createExec()- await expect(exec.handler(mockContext, { command: 'call' })).rejects.toThrow(+ await expect(exec.handler(mockContext, { command: 'call --json' })).rejects.toThrow('Usage: call [--json] <tool_name> <json_input>')})- it('does not treat --json in JSON body as the flag', async () => {- const tool = makeMockTool({- schema: z.object({ tag: z.string() }),- handler: async (_ctx, params) => params,- })- const exec = createExec([tool])- const result = await exec.handler(mockContext, {- command: 'call mock-tool {"tag": "--json"}',- })- // Without the flag, output is TOON-formatted- expect(result).toContain('tag:')- })-it('propagates _meta.ui.resourceUri and structuredContent when the inner tool has a UI app and consumer is posthog-code', async () => {const tool = makeMockTool({_meta: { ui: { resourceUri: 'ui://posthog/mock-app.html' } },})const exec = createExec([tool], 'posthog-code')- const result = (await exec.handler(mockContext, { command: 'call mock-tool {}' })) as {+ const result = (await exec.handler(mockContext, { command: 'call mock-tool' })) as {content: { type: string; text: string }[]structuredContent: { id: number; name: string; _analytics: { distinctId: string; toolName: string } }_meta: { ui: { resourceUri: string }; [key: string]: unknown }@@ -139,14 +126,14 @@ describe('exec tool', () => {_meta: { ui: { resourceUri: 'ui://posthog/mock-app.html' } },})const exec = createExec([tool], consumer)- const result = await exec.handler(mockContext, { command: 'call mock-tool {}' })+ const result = await exec.handler(mockContext, { command: 'call mock-tool' })expect(typeof result).toBe('string')})it('does not attach UI meta or structuredContent for tools without a UI app', async () => {const exec = createExec()- const result = await exec.handler(mockContext, { command: 'call mock-tool {}' })+ const result = await exec.handler(mockContext, { command: 'call mock-tool' })// Plain text fallback — no CallToolResult shape leaks outexpect(typeof result).toBe('string')})@@ -164,7 +151,7 @@ describe('exec tool', () => {undefined,tracker)- await exec.handler(mockContext, { command: 'call --json mock-tool {}' })+ await exec.handler(mockContext, { command: 'call --json mock-tool' })expect(calls).toHaveLength(1)expect(calls[0]!.toolName).toBe('mock-tool')expect(calls[0]!.properties.success).toBe(true)@@ -172,6 +159,41 @@ describe('exec tool', () => {expect(typeof calls[0]!.properties.duration_ms).toBe('number')})+ it('passes inline JSON arguments to the inner tool', async () => {+ const tool = makeMockTool({+ schema: z.object({ name: z.string(), tags: z.array(z.string()) }),+ handler: async (_ctx, params) => params,+ })+ const exec = createExec([tool])+ const result = await exec.handler(mockContext, {+ command: 'call --json mock-tool {"name":"foo","tags":["a","b"]}',+ })+ expect(JSON.parse(result as string)).toEqual({ name: 'foo', tags: ['a', 'b'] })+ })++ it('preserves quote-heavy and multi-line content in inline JSON', async () => {+ const tool = makeMockTool({+ schema: z.object({ name: z.string(), content: z.string() }),+ handler: async (_ctx, params) => params,+ })+ const exec = createExec([tool])+ const content = '# Title\n\nLine with "double quotes", \'single quotes\', and `backticks` — also unicode ☃.'+ const payload = JSON.stringify({ name: 'skill', content })+ const result = await exec.handler(mockContext, {+ command: `call --json mock-tool ${payload}`,+ })+ expect(JSON.parse(result as string)).toEqual({ name: 'skill', content })+ })++ it('throws a descriptive error when the inline JSON body is malformed', async () => {+ const exec = createExec()+ await expect(+ exec.handler(mockContext, {+ command: 'call mock-tool {not-json}',+ })+ ).rejects.toThrow(/Invalid JSON input:/)+ })+it('invokes the inner-call tracker with success=false when the inner tool throws', async () => {const calls: { toolName: string; properties: ExecInnerCallProperties }[] = []const tracker = (toolName: string, properties: ExecInnerCallProperties): void => {@@ -190,7 +212,7 @@ describe('exec tool', () => {undefined,tracker)- await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toThrow('boom')+ await expect(exec.handler(mockContext, { command: 'call mock-tool' })).rejects.toThrow('boom')expect(calls).toHaveLength(1)expect(calls[0]!.properties.success).toBe(false)expect(calls[0]!.properties.error_message).toBe('boom')@@ -218,14 +240,16 @@ describe('exec tool', () => {expect(parsedSchema.properties.name.description).toBe('Person name')})- it('returns JSON with --json flag', async () => {+ it('returns JSON when --json flag is passed in command', async () => {const exec = createExec()- const result = (await exec.handler(mockContext, { command: 'info --json mock-tool' })) as string+ const result = (await exec.handler(mockContext, {+ command: 'info --json mock-tool',+ })) as stringconst parsed = JSON.parse(result)expect(parsed.name).toBe('mock-tool')expect(parsed.title).toBe('Mock tool')expect(parsed.description).toBe('A mock tool for testing')- // In --json mode, inputSchema is a real object, not a JSON string+ // In JSON mode, inputSchema is a real object, not a JSON stringexpect(typeof parsed.inputSchema).toBe('object')})