Skip to content

: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.

feat(mcp): force schema drill-down on truncated exec responses (#58165)

Georgiy Tarasov9b7c6676a937
diff --git a/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py b/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py
index 33e8c0f48928..51676a3b2141 100644
--- a/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py
+++ b/ee/hogai/eval/sandboxed/cli_mcp/eval_workflow.py
@@ -1,6 +1,6 @@
"""Eval cases for the ``posthog:exec`` cli workflow conventions.
-Five eval functions, each grading a single behavior the cli prompts spell out
+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``:
@@ -88,10 +88,15 @@ async def eval_schema_drilldown(sandboxed_demo_data, pytestconfig, posthog_clien
cases: list[SandboxedEvalCase] = [
SandboxedEvalCase(
- name="trends_with_breakdown",
+ name="trends_with_action_and_breakdown",
+ # Uses a seeded hedgebox action ("Visited Marius Tech Tips campaign")
+ # rather than a canonical event so the agent can't reach for
+ # `EventsNode` from priors or copy the worked example in the
+ # query-trends description — it must drill into `series` to discover
+ # `ActionsNode` and its `id` field.
prompt=(
- "Run a trends query for `$pageview` over the last 14 days, broken down "
- "by `$browser`. Return the result."
+ "Run a trends query for the `Visited Marius Tech Tips campaign` "
+ "action over the last 14 days, broken down by `$browser`. Return the result."
),
expected={
"drilled_into_schema": {
diff --git a/ee/hogai/eval/sandboxed/cli_mcp/scorers.py b/ee/hogai/eval/sandboxed/cli_mcp/scorers.py
index 4d8b278a40a6..7f7699b6c24d 100644
--- a/ee/hogai/eval/sandboxed/cli_mcp/scorers.py
+++ b/ee/hogai/eval/sandboxed/cli_mcp/scorers.py
@@ -18,6 +18,8 @@ unrelated cases don't drag the rollup down.
replacement?
* ``DrilledIntoSchema`` — did the agent drill into every named field
via ``schema <tool> <field>`` before the final ``call``?
+* ``RetrievedSchemaPath`` — did the agent successfully retrieve an exact
+ nested schema path via ``schema <tool> <path>``?
* ``PreferredSearchOverTools`` — did the agent prefer ``search`` over
the bare ``tools`` listing for discovery?
* ``InfoBeforeCall`` — was every successful call to the target tool
@@ -40,6 +42,7 @@ __all__ = [
"PreferredSearchOverTools",
"RanPythonPostProcessing",
"RecoveredToCorrectTool",
+ "RetrievedSchemaPath",
"UsedJsonOutputFormat",
"VerifiedEventBeforeQuery",
]
@@ -285,6 +288,89 @@ class DrilledIntoSchema(Scorer):
)
+class RetrievedSchemaPath(Scorer):
+ """Binary: did the agent successfully retrieve an exact nested schema path?
+
+ ``expected = {"retrieved_schema_path":
+ {"tool": "query-trends", "path": "series.properties"}}``
+
+ Looks for a raw ``exec`` call whose ``command`` is exactly
+ ``schema <tool> <path>``. Score 1.0 only when that call succeeded, 0.0
+ when the path was attempted but failed or a different schema path was
+ used, and ``None`` for malformed specs.
+ """
+
+ def _name(self) -> str:
+ return "retrieved_schema_path"
+
+ 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")
+ path = spec.get("path")
+ if not isinstance(tool, str) or not tool:
+ return Score(name=self._name(), score=None, metadata={"reason": "Missing 'tool' on spec"})
+ if not isinstance(path, str) or not path:
+ return Score(name=self._name(), score=None, metadata={"reason": "Missing 'path' on spec"})
+
+ parser = _build_parser(output)
+ if parser is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
+
+ schema_attempts: list[dict[str, object]] = []
+ for call in parser.get_tool_calls():
+ head, rest = _exec_command_head(call)
+ if head != "schema":
+ continue
+ schema_tool, _, field_path = rest.partition(" ")
+ schema_tool = schema_tool.strip()
+ field_path = field_path.strip()
+ schema_attempts.append(
+ {
+ "tool": schema_tool,
+ "path": field_path,
+ "is_error": call.is_error,
+ "call_id": call.call_id,
+ }
+ )
+ if schema_tool != tool or field_path != path:
+ continue
+ if call.is_error:
+ return Score(
+ name=self._name(),
+ score=0.0,
+ metadata={
+ "reason": "Exact schema path was attempted but failed",
+ "tool": tool,
+ "path": path,
+ "call_id": call.call_id,
+ },
+ )
+ return Score(
+ name=self._name(),
+ score=1.0,
+ metadata={"tool": tool, "path": path, "call_id": call.call_id},
+ )
+
+ return Score(
+ name=self._name(),
+ score=0.0,
+ metadata={
+ "reason": "Exact schema path was not retrieved",
+ "tool": tool,
+ "path": path,
+ "schema_attempts": schema_attempts,
+ },
+ )
+
+
class PreferredSearchOverTools(Scorer):
"""Binary: did the agent prefer ``search`` over the bare ``tools`` listing?
diff --git a/services/mcp/src/templates/sections/cli-examples.md b/services/mcp/src/templates/sections/cli-examples.md
index e612f985a41e..9cfc99e9e64e 100644
--- a/services/mcp/src/templates/sections/cli-examples.md
+++ b/services/mcp/src/templates/sections/cli-examples.md
@@ -48,7 +48,7 @@ WRONG — You must run `info` for ALL tools before making ANY `call` commands
<bad-example>
User: Show me a trends chart of signups
Assistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]
-WRONG — info returned a summary with hint: "Run `schema query-trends series` for full structure".
+WRONG — info returned a summary with hint: "DO NOT GUESS – run `schema query-trends series` before populating this field".
You MUST follow the hint and run `schema` before constructing the series field.
</bad-example>
diff --git a/services/mcp/src/templates/sections/cli-schema-drilldown.md b/services/mcp/src/templates/sections/cli-schema-drilldown.md
index ccb35c6d4f58..59ff961d1c99 100644
--- a/services/mcp/src/templates/sections/cli-schema-drilldown.md
+++ b/services/mcp/src/templates/sections/cli-schema-drilldown.md
@@ -1,21 +1,16 @@
**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**
-The `info` command may return the full schema (for simple tools) or a top-level summary
-with drill-down hints (for complex tools). Look for `hint` fields in the response.
+The `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.
-If `info` returned a summary (fields have `hint` values), you MUST call
-`schema <tool_name> <field_name>` for each field you need to populate BEFORE
-constructing that field's value in a `call` command.
+If `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.
-If `schema` also returns a summary (because the field is too large),
-drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.
+If `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.
**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.
For query tools, you will typically need:
- `schema <tool> series` — to see EventsNode/ActionsNode structure
-- `schema <tool> properties` — to see property filter structure
-- `schema <tool> breakdownFilter` — when using breakdowns
+- `schema <tool> series.properties` — to see property filter structure of series
**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 71da07e3bd93..66ed4e7a265a 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -202,8 +202,12 @@ export function createExecTool(
return fullOutput
}
- // Schema too large — return summary with drill-down hints
- return serialize(topShape, summarizeSchema(fullSchema as Record<string, unknown>, tool.name))
+ // Schema too large — return summary with drill-down hints.
+ // Each complex field's `hint` carries the imperative to run
+ // `schema` before populating it, so no separate directive is
+ // needed here.
+ const summary = summarizeSchema(fullSchema as Record<string, unknown>, tool.name)
+ return serialize(topShape, summary)
}
case 'schema': {
@@ -215,6 +219,9 @@ export function createExecTool(
const fullJsonSchema = z.toJSONSchema(schemaTool.schema) as Record<string, unknown>
if (!fieldPath) {
+ // The bare `schema <tool>` view is always a summary. Any
+ // field that still needs drilling carries the imperative
+ // in its own `hint`, so the summary stands on its own.
return JSON.stringify(summarizeSchema(fullJsonSchema, schemaToolName))
}
@@ -232,10 +239,12 @@ export function createExecTool(
return serialized
}
- // Field schema too large — return summary with sub-path hints
+ // Field schema too large — return a summary instead. The
+ // summary's complex sub-fields carry the drill-down `hint`,
+ // so the response shape stays the same as the inline case
+ // (`{ field, schema }`) — no separate top-level note.
return JSON.stringify({
field: fieldPath,
- note: `Full schema is ${Math.ceil(serialized.length / 6000)}k+ tokens. Showing summary. Drill into sub-fields for details.`,
schema: summarizeSchema(resolved as Record<string, unknown>, schemaToolName, fieldPath),
})
}
diff --git a/services/mcp/src/tools/schema-utils.ts b/services/mcp/src/tools/schema-utils.ts
index 7784e155fe3e..58586172e763 100644
--- a/services/mcp/src/tools/schema-utils.ts
+++ b/services/mcp/src/tools/schema-utils.ts
@@ -149,9 +149,11 @@ export function summarizeSchema(schema: JSONSchema, toolName: string, fieldPath?
entry.items = describeItems(prop.items as JSONSchema)
}
- // Add drill-down hint for complex fields
+ // Add drill-down hint for complex fields. Phrased as an imperative, not a
+ // description — models observably treat declarative notes as advisory, so
+ // the directive lives on the field the model is about to populate.
if (isComplex(prop)) {
- entry.hint = `Run \`schema ${toolName} ${pathPrefix}${name}\` for full structure`
+ entry.hint = `DO NOT GUESS — you MUST run \`schema ${toolName} ${pathPrefix}${name}\` before populating this field`
}
result[name] = entry
diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.json
index 6ecd985c46ae..b68ef6496c0e 100644
--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json
+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json
@@ -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 [--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-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\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 for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue 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-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\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 with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill 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> series.properties` — to see property filter structure of series\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: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\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-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\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 for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue 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-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\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.txt
index 504f6f549604..30a53c4b328a 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
@@ -12,23 +12,18 @@ call [--json] <tool_name> <json_input> — call a tool with JSON input (--json r
**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**
-The `info` command may return the full schema (for simple tools) or a top-level summary
-with drill-down hints (for complex tools). Look for `hint` fields in the response.
+The `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.
-If `info` returned a summary (fields have `hint` values), you MUST call
-`schema <tool_name> <field_name>` for each field you need to populate BEFORE
-constructing that field's value in a `call` command.
+If `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.
-If `schema` also returns a summary (because the field is too large),
-drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.
+If `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.
**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.
For query tools, you will typically need:
- `schema <tool> series` — to see EventsNode/ActionsNode structure
-- `schema <tool> properties` — to see property filter structure
-- `schema <tool> breakdownFilter` — when using breakdowns
+- `schema <tool> series.properties` — to see property filter structure of series
**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.
@@ -93,7 +88,7 @@ WRONG — You must run `info` for ALL tools before making ANY `call` commands
<bad-example>
User: Show me a trends chart of signups
Assistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]
-WRONG — info returned a summary with hint: "Run `schema query-trends series` for full structure".
+WRONG — info returned a summary with hint: "DO NOT GUESS – run `schema query-trends series` before populating this field".
You MUST follow the hint and run `schema` before constructing the series field.
</bad-example>
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 5ce80667fdf0..7255cf738331 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -303,6 +303,33 @@ describe('exec tool', () => {
expect(typeof parsed.inputSchema).toBe('object')
})
+ it('bakes the drill-down imperative into each complex field hint when info is summarized', async () => {
+ const wideShape: Record<string, z.ZodType> = {}
+ for (let i = 0; i < 1500; i++) {
+ wideShape[`field_${i}`] = z.string().describe(`Description for field ${i} with extra padding text`)
+ }
+ const tool = makeMockTool({
+ schema: z.object({
+ name: z.string(),
+ filter: z.object({ key: z.string() }),
+ wide: z.object(wideShape),
+ }),
+ })
+ const exec = createExec([tool])
+ const result = (await exec.handler(mockContext, { command: 'info mock-tool' })) as string
+ const envelope = parseYaml(result) as { note?: string; inputSchema: string }
+ // The directive lives on the field the model is about to populate,
+ // not as a separate top-level note it can skim past.
+ expect(envelope.note).toBeUndefined()
+ const parsedSchema = JSON.parse(envelope.inputSchema)
+ expect(parsedSchema.properties.filter.hint).toContain('DO NOT GUESS')
+ expect(parsedSchema.properties.filter.hint).toContain('schema mock-tool filter')
+ expect(parsedSchema.properties.filter.hint).toContain('before populating this field')
+ expect(parsedSchema.properties.wide.hint).toContain('schema mock-tool wide')
+ // Scalar fields carry no hint — nothing to drill into.
+ expect(parsedSchema.properties.name.hint).toBeUndefined()
+ })
+
it('throws usage error for bare info', async () => {
const exec = createExec()
await expect(exec.handler(mockContext, { command: 'info' })).rejects.toThrow(
@@ -318,6 +345,174 @@ describe('exec tool', () => {
})
})
+ describe('schema command', () => {
+ it('throws usage error for bare schema', async () => {
+ const exec = createExec()
+ await expect(exec.handler(mockContext, { command: 'schema' })).rejects.toThrow(
+ 'Usage: schema <tool_name> [field_path]'
+ )
+ })
+
+ it('returns the resolved sub-schema inline when small enough', async () => {
+ const tool = makeMockTool({
+ schema: z.object({
+ name: z.string(),
+ filter: z.object({ key: z.string(), value: z.number() }),
+ }),
+ })
+ const exec = createExec([tool])
+ const result = (await exec.handler(mockContext, { command: 'schema mock-tool filter' })) as string
+ const parsed = JSON.parse(result)
+ expect(parsed.field).toBe('filter')
+ // Small sub-schema: the full resolved JSON Schema is inlined as-is
+ expect(parsed.schema.type).toBe('object')
+ expect(parsed.schema.properties).toEqual(
+ expect.objectContaining({
+ key: expect.objectContaining({ type: 'string' }),
+ value: expect.objectContaining({ type: 'number' }),
+ })
+ )
+ // No drill-down note for an already-inlined schema
+ expect(parsed.note).toBeUndefined()
+ })
+
+ // The bare `schema <tool>` view is the recursive step where models
+ // historically guessed the deeper shape of complex fields (like `series`
+ // or `retentionFilter`) rather than running another `schema` for the
+ // sub-path. The imperative now rides on each complex field's `hint` —
+ // the runtime nudge that pairs with the prompt-side guidance in
+ // `cli-schema-drilldown.md`.
+ it('bakes the drill-down imperative into each complex field hint of the bare schema view', async () => {
+ const tool = makeMockTool({
+ schema: z.object({
+ name: z.string(),
+ filter: z.object({ key: z.string() }),
+ }),
+ })
+ const exec = createExec([tool])
+ const result = (await exec.handler(mockContext, { command: 'schema mock-tool' })) as string
+ const parsed = JSON.parse(result)
+ // Flat summary, no separate note wrapper.
+ expect(parsed.note).toBeUndefined()
+ expect(parsed.schema).toBeUndefined()
+ expect(parsed.properties.filter.hint).toContain('DO NOT GUESS')
+ expect(parsed.properties.filter.hint).toContain('schema mock-tool filter')
+ expect(parsed.properties.filter.hint).toContain('before populating this field')
+ // Scalar fields do not earn a hint
+ expect(parsed.properties.name.hint).toBeUndefined()
+ })
+
+ it('does not attach a drill-down directive when no field carries a hint', async () => {
+ const tool = makeMockTool({
+ schema: z.object({ name: z.string(), count: z.number() }),
+ })
+ const exec = createExec([tool])
+ const result = (await exec.handler(mockContext, { command: 'schema mock-tool' })) as string
+ const parsed = JSON.parse(result)
+ // Without hints, the response is just the raw summary — no `note`
+ // wrapper to distract the model when there's nothing to drill into.
+ expect(parsed.note).toBeUndefined()
+ expect(parsed.schema).toBeUndefined()
+ expect(parsed.type).toBe('object')
+ expect(parsed.properties.name.type).toBe('string')
+ })
+
+ it('returns a summary in the same { field, schema } shape when a sub-field overflows the budget', async () => {
+ // Build a sub-field large enough to exceed TOKEN_CHAR_LIMIT (~48k chars)
+ // once serialized. Each property entry is ~70 chars, so 1500 of them
+ // comfortably crosses the threshold.
+ const wideShape: Record<string, z.ZodType> = {}
+ for (let i = 0; i < 1500; i++) {
+ wideShape[`field_${i}`] = z.string().describe(`Description for field ${i} with extra padding text`)
+ }
+ const tool = makeMockTool({
+ schema: z.object({ wide: z.object(wideShape) }),
+ })
+ const exec = createExec([tool])
+ const result = (await exec.handler(mockContext, { command: 'schema mock-tool wide' })) as string
+ const parsed = JSON.parse(result)
+ expect(parsed.field).toBe('wide')
+ // No top-level note — `hint` is the only drill-down signal in the response.
+ expect(parsed.note).toBeUndefined()
+ // Summary still preserves field names so the model can pick where to drill
+ expect(Object.keys(parsed.schema.properties).length).toBeGreaterThan(0)
+ })
+
+ it('errors with available paths when the field path is unknown', async () => {
+ const tool = makeMockTool({
+ schema: z.object({ name: z.string(), filter: z.object({ key: z.string() }) }),
+ })
+ const exec = createExec([tool])
+ await expect(exec.handler(mockContext, { command: 'schema mock-tool nope' })).rejects.toThrow(
+ /Unknown path "nope"\. Available: name, filter/
+ )
+ })
+
+ // Eval case for `query-retention`, the canonical large-schema query tool
+ // (>200k chars when fully serialized). Validates the end-to-end drill-down
+ // flow against the real tool: bare schema → imperative hints → drill
+ // → resolved sub-schema. If the hint imperative ever loosens or the
+ // schema-summary pipeline regresses, this test catches it.
+ it('eval: query-retention bare schema view produces imperative hints, and a drilled sub-field resolves', async () => {
+ const context: Context = {
+ api: {} as any,
+ cache: {} as any,
+ env: {
+ MCP_APPS_BASE_URL: undefined,
+ POSTHOG_ANALYTICS_API_KEY: undefined,
+ POSTHOG_ANALYTICS_HOST: undefined,
+ POSTHOG_API_BASE_URL: undefined,
+ POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: undefined,
+ POSTHOG_UI_APPS_TOKEN: undefined,
+ },
+ stateManager: {
+ getApiKey: async () => ({ scopes: ['*'] }),
+ getAiConsentGiven: async () => true,
+ } as any,
+ sessionManager: new SessionManager({} as any),
+ getDistinctId: async () => 'test-distinct-id',
+ trackEvent: async () => {},
+ }
+ const v2Tools = await getToolsFromContext(context, { version: 2 })
+ const queryRetention = v2Tools.find((t) => t.name === 'query-retention')
+ expect(queryRetention).not.toBeUndefined()
+ const exec = createExecTool(v2Tools, context, 'test', 'test', undefined)
+
+ // 1. Bare `schema query-retention` returns a flat summary whose
+ // complex fields carry the drill-down imperative in their hints.
+ const bare = JSON.parse((await exec.handler(context, { command: 'schema query-retention' })) as string) as {
+ note?: string
+ properties: Record<string, { hint?: string; type?: string }>
+ }
+ expect(bare.note).toBeUndefined()
+ // At least one of retention's complex fields must surface a hint —
+ // the exact set varies with schema generation, so we assert by shape
+ // (presence of any hint) rather than naming a specific field.
+ const hintedFields = Object.entries(bare.properties).filter(([, v]) => v.hint !== undefined)
+ expect(hintedFields.length).toBeGreaterThan(0)
+ for (const [, v] of hintedFields) {
+ expect(v.hint).toMatch(
+ /^DO NOT GUESS — you MUST run `schema query-retention [\w.]+` before populating this field$/
+ )
+ }
+
+ // 2. Drill into the first hinted sub-field. The follow-up always
+ // returns the same `{ field, schema }` shape — either with the full
+ // resolved JSON Schema (small enough to inline) or with a summary
+ // whose complex sub-fields carry their own hints. No top-level note
+ // distinguishes the two; the model reads the hints either way.
+ const [firstHintedField] = hintedFields[0]!
+ const drilled = JSON.parse(
+ (await exec.handler(context, {
+ command: `schema query-retention ${firstHintedField}`,
+ })) as string
+ ) as { field?: string; note?: string; schema?: unknown }
+ expect(drilled.field).toBe(firstHintedField)
+ expect(drilled.note).toBeUndefined()
+ expect(drilled.schema).not.toBeUndefined()
+ })
+ })
+
describe('deprecated tool redirects', () => {
it.each([
['entity-search', 'execute-sql'],
diff --git a/services/mcp/tests/unit/schema-utils.test.ts b/services/mcp/tests/unit/schema-utils.test.ts
index e9525b91c70d..ec8bceba2252 100644
--- a/services/mcp/tests/unit/schema-utils.test.ts
+++ b/services/mcp/tests/unit/schema-utils.test.ts
@@ -55,7 +55,9 @@ describe('schema-utils', () => {
const result = summarizeSchema(schema, 'my-tool')
- expect(result.properties.filter!.hint).toBe('Run `schema my-tool filter` for full structure')
+ expect(result.properties.filter!.hint).toBe(
+ 'DO NOT GUESS — you MUST run `schema my-tool filter` before populating this field'
+ )
expect(result.properties.filter!.fields).toEqual(['key', 'value'])
})
@@ -86,7 +88,9 @@ describe('schema-utils', () => {
const result = summarizeSchema(schema, 'query-trends')
- expect(result.properties.series!.hint).toBe('Run `schema query-trends series` for full structure')
+ expect(result.properties.series!.hint).toBe(
+ 'DO NOT GUESS — you MUST run `schema query-trends series` before populating this field'
+ )
expect(result.properties.series!.items).toBe('union of 2 types (EventsNode, ActionsNode)')
})
@@ -137,7 +141,9 @@ describe('schema-utils', () => {
const result = summarizeSchema(schema, 'my-tool', 'parent')
- expect(result.properties.nested!.hint).toBe('Run `schema my-tool parent.nested` for full structure')
+ expect(result.properties.nested!.hint).toBe(
+ 'DO NOT GUESS — you MUST run `schema my-tool parent.nested` before populating this field'
+ )
})
})