: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
fix(mcp): keep the exec tool entry under client size caps (#69896)
Georgiy Tarasov3c4a30249369
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex 920df50e645b..5ddf8e781bb7 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -90,7 +90,13 @@ export class InstructionsFormatter {* `supportsInstructions` but don't actually surface the `instructions`* payload to the model (Claude web/desktop): it retains the full env-context* (tool-domain index, project metadata, group types) here even though- * `stripEnvContext` is set, so it still reaches the agent. */+ * `stripEnvContext` is set, so it still reaches the agent.+ *+ * SIZE BUDGET: the serialized exec tool entry must stay under 32,600 chars —+ * clients (e.g. Claude web/desktop) silently drop tools past ~32,768, which+ * breaks the entire MCP for them. Enforced by the budget test in+ * `tests/unit/instructions-formatter-snapshot.test.ts`; when adding prose+ * here or to the section templates, shrink elsewhere to stay under. */buildExecCommandReference(ctx: InstructionsContext,opts: { stripEnvContext: boolean; keepEnvContext?: boolean }@@ -121,7 +127,9 @@ export class InstructionsFormatter {: {}),}: ctx- return this.compose(sections, renderCtx, { compact: false })+ // Compact tool domains: the command reference rides inside a tool schema,+ // where the pipe-separated form buys back budget over the bullet list.+ return this.compose(sections, renderCtx, { compact: false, compactToolDomains: true })}/** The agent-feedback section is only useful when the `agent-feedback` tool@@ -131,8 +139,13 @@ export class InstructionsFormatter {return featureFlags?.['mcp-feedback-tool'] === true}- private compose(sections: string[], ctx: InstructionsContext, opts: { compact: boolean }): string {- const renderToolDomains = opts.compact ? buildToolDomainsCompact : buildToolDomainsBlock+ private compose(+ sections: string[],+ ctx: InstructionsContext,+ opts: { compact: boolean; compactToolDomains?: boolean }+ ): string {+ const renderToolDomains =+ opts.compact || opts.compactToolDomains ? buildToolDomainsCompact : buildToolDomainsBlock// `{query_tools}` only appears in non-compact sections (the exec command// reference and tools-mode instructions); compact mode surfaces queries// via the single `query` tool domain instead.diff --git a/services/mcp/src/templates/sections/basic-functionality.md b/services/mcp/src/templates/sections/basic-functionality.mdindex ebb61f9b2e26..60ef049f4a28 100644--- a/services/mcp/src/templates/sections/basic-functionality.md+++ b/services/mcp/src/templates/sections/basic-functionality.md@@ -2,30 +2,9 @@You 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.-Collected data is used for analytics and has the following types:+Collected data (used for analytics): events (recorded from SDKs, always associated with persons and sometimes groups); persons and groups (captured individuals or groups of individuals); sessions; properties and property values (key-value metadata for segmenting events, actions, persons, groups, etc.); session recordings (captured web/mobile interactions).-- Events – recorded events from SDKs that can be aggregated in visual charts and text.-- 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.-- Sessions – recorded person or group session captured by the user's SDK.-- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).-- Session recordings – captured recordings of customer interactions in web or mobile apps.--Created data is used by the user on the PostHog's website to perform business activity and has the following types:--- Actions – unify multiple events or filtering conditions into one.-- Insights – visual and textual representation of the collected data aggregated by different types.-- Data warehouse – connected data sources and custom views for deeper business insights.-- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.-- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.-- Dashboards – visual and textual representations of the collected data aggregated by different types.-- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.-- Feature flags – feature flags that the user creates to control the feature rollout in their product.-- Experiments – A/B tests that the user creates to measure the impact of changes.-- Notebooks – notebooks that the user creates to perform business analysis.-- Error tracking issues – issues that the user creates to track errors in their product.-- Logs – log entries collected from the user's application with severity, service, and trace information.-- Workflows – automated workflows with triggers, actions, and conditions.-- Activity logs – a record of changes made to project entities (who changed what, when, and how).+Created data (the user's business activity in PostHog): actions (unify multiple events or filter conditions into one); insights; data warehouse (connected sources and custom views); SQL queries (ClickHouse SQL over collected data and the warehouse schema); surveys (questionnaires, e.g. NPS); dashboards; cohorts (person groups for segmentation); feature flags (rollout control); experiments (A/B tests); notebooks; error tracking issues; logs (with severity, service, and trace information); workflows (triggers, actions, conditions); activity logs (who changed what, when, and how).IMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.diff --git a/services/mcp/src/templates/sections/cli-examples.md b/services/mcp/src/templates/sections/cli-examples.mdindex 9cfc99e9e64e..45178ddb4b09 100644--- a/services/mcp/src/templates/sections/cli-examples.md+++ b/services/mcp/src/templates/sections/cli-examples.md@@ -22,15 +22,6 @@ Assistant: Now I have both schemas. Let me start by searching for existing reven[Makes call commands with correct parameters]</example>-<example>-User: Find events related to onboarding-Assistant: Let me find the data schema tool.-[Runs posthog:exec({ "command": "search read-data" })]-[Runs posthog:exec({ "command": "info read-data-schema" })]-Assistant: Now I can list events and pick the onboarding-related ones.-[Runs posthog:exec({ "command": "call read-data-schema {\"query\": {\"kind\": \"events\"}}" })]-</example>-**INCORRECT usage patterns — NEVER do this:**<bad-example>@@ -55,11 +46,5 @@ You MUST follow the hint and run `schema` before constructing the series field.<bad-example>User: query pageviews for the last 7 daysAssistant: [Runs `info query-trends`, then `call query-trends` with `event: "$pageview"` from the prompt]-WRONG — skipped `call read-data-schema {"query": {"kind": "events"}}`. Canonical-looking events still need confirmation per team.-</bad-example>--<bad-example>-User: show me the file downloads trend for the last 7 days-Assistant: [Runs `info query-trends`, then `call query-trends` with `event: "downloaded_file"` inferred from the wording]-WRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.+WRONG — skipped `call read-data-schema {"query": {"kind": "events"}}`. Never query an event name taken or inferred from the prompt — canonical-looking (`$pageview`) or guessed (`downloaded_file`) names still need per-team confirmation.</bad-example>diff --git a/services/mcp/src/templates/sections/cli-rendering.md b/services/mcp/src/templates/sections/cli-rendering.mdindex f0c4c3e9e00b..18ac4c42a3cd 100644--- a/services/mcp/src/templates/sections/cli-rendering.md+++ b/services/mcp/src/templates/sections/cli-rendering.md@@ -11,12 +11,6 @@ Assistant: <concise summary of the results>, then renders it so the user can ver[Runs render-ui({ "tool_name": "experiment-get", "tool_input": { "id": 2 } })]</example>-<bad-example>-User: How is the "File engagement boost" experiment going?-Assistant: [Calls render-ui with a guessed id before running any exec command]-WRONG — run exec first to resolve the real id and read the results; render-ui is not a discovery tool.-</bad-example>-<bad-example>User: How is the "File engagement boost" experiment going?Assistant: [Reads the results via exec, then replies with a long text-only breakdown of every metric and never calls render-ui]diff --git a/services/mcp/src/templates/sections/retrieving-data.md b/services/mcp/src/templates/sections/retrieving-data.mdindex 55d0ba6f47db..4e436956a30f 100644--- a/services/mcp/src/templates/sections/retrieving-data.md+++ b/services/mcp/src/templates/sections/retrieving-data.md@@ -28,64 +28,4 @@ By insight type:- "New vs returning vs dormant / user composition" -> `query-lifecycle`- "LLM traces / AI generations / token usage" -> `query-llm-traces-list`-##### Trends--A trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.--The trends insights have the following features:--- The insight can show multiple trends in one request.-- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.-- Filter and break down data using multiple properties.-- Compare with the current period with previous.-- Apply various aggregation types, like sum, average, etc., and chart types.-- And more.--Examples of use cases include:--- How the product's most important metrics change over time.-- Long-term patterns, or cycles in product's usage.-- The usage of different features side-by-side.-- How the properties of events vary using aggregation (sum, average, etc).-- Users can also visualize the same data points in a variety of ways.--##### Funnel--A 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.--The funnel insights have the following features:--- Various visualization types (steps, time-to-convert, historical trends).-- Filter data and apply exclusion steps (events only, not actions).-- Break down data using a single property.-- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.-- Aggregate by users, sessions, or specific group types.-- Sample data.-- Track first-time conversions with special math aggregations.-- And more.--Examples of use cases include:--- Conversion rates between steps.-- Drop off steps (which step loses most users).-- Steps with the highest friction and time to convert.-- If product changes are improving their funnel over time.-- Average/median/histogram of time to convert.-- Conversion trends over time (using trends visualization type).-- First-time user conversions (using `first_time_for_user` math).--##### Retention--A retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.--The retention insights have the following features: filter data, sample data, and more.--Examples of use cases include:--- How many users come back and perform an action after their first visit.-- How many users come back to perform action X after performing action Y.-- How often users return to use a specific feature.--#### SQL fallback--Reach 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.+Each `query-*` tool's own description carries its full feature set, use cases, and schema documentation — read it (e.g. `info query-trends`) before constructing the query.diff --git a/services/mcp/src/templates/sections/schema-workflow.md b/services/mcp/src/templates/sections/schema-workflow.mdindex dc08c823f08a..fb725a535559 100644--- a/services/mcp/src/templates/sections/schema-workflow.md+++ b/services/mcp/src/templates/sections/schema-workflow.md@@ -13,10 +13,6 @@ If the required events or properties don't exist, tell the user instead of runni#### Insight query workflow-1. Discover the data schema with `read-data-schema` (see schema-first workflow above).-2. Choose the appropriate `query-*` tool based on the user's question.-3. 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.-4. Execute the query and analyze the results.-5. Optionally save as an insight with `insight-create` or add to a dashboard.+After the schema-first steps, choose the `query-*` tool matching the question, construct a minimal query (only the filters, breakdowns, and settings essential to the answer — each tool's description documents its schema with examples), execute, and analyze. Optionally save as an insight with `insight-create` or add to a dashboard.For 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.diff --git a/services/mcp/src/templates/sections/tool-search.md b/services/mcp/src/templates/sections/tool-search.mdindex 98a3bf1e4fd8..e5fc23f914bd 100644--- a/services/mcp/src/templates/sections/tool-search.md+++ b/services/mcp/src/templates/sections/tool-search.md@@ -11,16 +11,9 @@- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools first- `search feature-flag` — regex (`-`): tools for feature flags-- `search dashboard` — dashboard CRUD tools- `search query-` — regex (`-`): all insight query tools-- `search experiment` — experiment tools-- `search survey` — survey tools-**Avoid queries that are too broad** (match dozens of tools):--- `search data` — matches almost everything-- `search get list create` — action verbs across all domains-- `search pageview|[email protected]` — unrelated to tools+**Avoid queries that are too broad** (match dozens of tools): `search data`, `search get list create` — they match almost everything.Only fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.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 ac97413c7657..deeeaedbeee5 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@@ -62,15 +62,6 @@ Assistant: Now I have both schemas. Let me start by searching for existing reven[Makes call commands with correct parameters]</example>-<example>-User: Find events related to onboarding-Assistant: Let me find the data schema tool.-[Runs posthog:exec({ "command": "search read-data" })]-[Runs posthog:exec({ "command": "info read-data-schema" })]-Assistant: Now I can list events and pick the onboarding-related ones.-[Runs posthog:exec({ "command": "call read-data-schema {\"query\": {\"kind\": \"events\"}}" })]-</example>-**INCORRECT usage patterns — NEVER do this:**<bad-example>@@ -95,13 +86,7 @@ You MUST follow the hint and run `schema` before constructing the series field.<bad-example>User: query pageviews for the last 7 daysAssistant: [Runs `info query-trends`, then `call query-trends` with `event: "$pageview"` from the prompt]-WRONG — skipped `call read-data-schema {"query": {"kind": "events"}}`. Canonical-looking events still need confirmation per team.-</bad-example>--<bad-example>-User: show me the file downloads trend for the last 7 days-Assistant: [Runs `info query-trends`, then `call query-trends` with `event: "downloaded_file"` inferred from the wording]-WRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.+WRONG — skipped `call read-data-schema {"query": {"kind": "events"}}`. Never query an event name taken or inferred from the prompt — canonical-looking (`$pageview`) or guessed (`downloaded_file`) names still need per-team confirmation.</bad-example>**Handling errors:**@@ -122,12 +107,6 @@ Assistant: <concise summary of the results>, then renders it so the user can ver[Runs render-ui({ "tool_name": "experiment-get", "tool_input": { "id": 2 } })]</example>-<bad-example>-User: How is the "File engagement boost" experiment going?-Assistant: [Calls render-ui with a guessed id before running any exec command]-WRONG — run exec first to resolve the real id and read the results; render-ui is not a discovery tool.-</bad-example>-<bad-example>User: How is the "File engagement boost" experiment going?Assistant: [Reads the results via exec, then replies with a long text-only breakdown of every metric and never calls render-ui]@@ -138,30 +117,9 @@ WRONG — the answer centers on a single experiment, which has a UI app (`experiYou 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.-Collected data is used for analytics and has the following types:--- Events – recorded events from SDKs that can be aggregated in visual charts and text.-- 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.-- Sessions – recorded person or group session captured by the user's SDK.-- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).-- Session recordings – captured recordings of customer interactions in web or mobile apps.--Created data is used by the user on the PostHog's website to perform business activity and has the following types:--- Actions – unify multiple events or filtering conditions into one.-- Insights – visual and textual representation of the collected data aggregated by different types.-- Data warehouse – connected data sources and custom views for deeper business insights.-- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.-- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.-- Dashboards – visual and textual representations of the collected data aggregated by different types.-- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.-- Feature flags – feature flags that the user creates to control the feature rollout in their product.-- Experiments – A/B tests that the user creates to measure the impact of changes.-- Notebooks – notebooks that the user creates to perform business analysis.-- Error tracking issues – issues that the user creates to track errors in their product.-- Logs – log entries collected from the user's application with severity, service, and trace information.-- Workflows – automated workflows with triggers, actions, and conditions.-- Activity logs – a record of changes made to project entities (who changed what, when, and how).+Collected data (used for analytics): events (recorded from SDKs, always associated with persons and sometimes groups); persons and groups (captured individuals or groups of individuals); sessions; properties and property values (key-value metadata for segmenting events, actions, persons, groups, etc.); session recordings (captured web/mobile interactions).++Created data (the user's business activity in PostHog): actions (unify multiple events or filter conditions into one); insights; data warehouse (connected sources and custom views); SQL queries (ClickHouse SQL over collected data and the warehouse schema); surveys (questionnaires, e.g. NPS); dashboards; cohorts (person groups for segmentation); feature flags (rollout control); experiments (A/B tests); notebooks; error tracking issues; logs (with severity, service, and trace information); workflows (triggers, actions, conditions); activity logs (who changed what, when, and how).IMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.@@ -182,25 +140,15 @@ If you cannot answer the user's PostHog related request or question using other- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools first- `search feature-flag` — regex (`-`): tools for feature flags-- `search dashboard` — dashboard CRUD tools- `search query-` — regex (`-`): all insight query tools-- `search experiment` — experiment tools-- `search survey` — survey tools--**Avoid queries that are too broad** (match dozens of tools):-- `search data` — matches almost everything-- `search get list create` — action verbs across all domains-- `search pageview|[email protected]` — unrelated to tools+**Avoid queries that are too broad** (match dozens of tools): `search data`, `search get list create` — they match almost everything.Only fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.PostHog tools have lowercase kebab-case naming. Tools are organized by category:-- dashboard-- execute-sql-- feature-flag-- query+dashboard|execute-sql|feature-flag|queryTypical action names: list/retrieve/get/create/update/delete/query.Example tool names: execute-sql, experiment-create, feature-flag-get-all.@@ -249,67 +197,7 @@ By insight type:- "New vs returning vs dormant / user composition" -> `query-lifecycle`- "LLM traces / AI generations / token usage" -> `query-llm-traces-list`-##### Trends--A trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.--The trends insights have the following features:--- The insight can show multiple trends in one request.-- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.-- Filter and break down data using multiple properties.-- Compare with the current period with previous.-- Apply various aggregation types, like sum, average, etc., and chart types.-- And more.--Examples of use cases include:--- How the product's most important metrics change over time.-- Long-term patterns, or cycles in product's usage.-- The usage of different features side-by-side.-- How the properties of events vary using aggregation (sum, average, etc).-- Users can also visualize the same data points in a variety of ways.--##### Funnel--A 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.--The funnel insights have the following features:--- Various visualization types (steps, time-to-convert, historical trends).-- Filter data and apply exclusion steps (events only, not actions).-- Break down data using a single property.-- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.-- Aggregate by users, sessions, or specific group types.-- Sample data.-- Track first-time conversions with special math aggregations.-- And more.--Examples of use cases include:--- Conversion rates between steps.-- Drop off steps (which step loses most users).-- Steps with the highest friction and time to convert.-- If product changes are improving their funnel over time.-- Average/median/histogram of time to convert.-- Conversion trends over time (using trends visualization type).-- First-time user conversions (using `first_time_for_user` math).--##### Retention--A retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.--The retention insights have the following features: filter data, sample data, and more.--Examples of use cases include:--- How many users come back and perform an action after their first visit.-- How many users come back to perform action X after performing action Y.-- How often users return to use a specific feature.--#### SQL fallback--Reach 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.+Each `query-*` tool's own description carries its full feature set, use cases, and schema documentation — read it (e.g. `info query-trends`) before constructing the query.#### Schema-first workflow@@ -326,11 +214,7 @@ If the required events or properties don't exist, tell the user instead of runni#### Insight query workflow-1. Discover the data schema with `read-data-schema` (see schema-first workflow above).-2. Choose the appropriate `query-*` tool based on the user's question.-3. 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.-4. Execute the query and analyze the results.-5. Optionally save as an insight with `insight-create` or add to a dashboard.+After the schema-first steps, choose the `query-*` tool matching the question, construct a minimal query (only the filters, breakdowns, and settings essential to the answer — each tool's description documents its schema with examples), execute, and analyze. Optionally save as an insight with `insight-create` or add to a dashboard.For 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.diff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txtindex e05ebf17c464..cbda9b3eeeee 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt@@ -2,30 +2,9 @@You 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.-Collected data is used for analytics and has the following types:--- Events – recorded events from SDKs that can be aggregated in visual charts and text.-- 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.-- Sessions – recorded person or group session captured by the user's SDK.-- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).-- Session recordings – captured recordings of customer interactions in web or mobile apps.--Created data is used by the user on the PostHog's website to perform business activity and has the following types:--- Actions – unify multiple events or filtering conditions into one.-- Insights – visual and textual representation of the collected data aggregated by different types.-- Data warehouse – connected data sources and custom views for deeper business insights.-- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.-- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.-- Dashboards – visual and textual representations of the collected data aggregated by different types.-- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.-- Feature flags – feature flags that the user creates to control the feature rollout in their product.-- Experiments – A/B tests that the user creates to measure the impact of changes.-- Notebooks – notebooks that the user creates to perform business analysis.-- Error tracking issues – issues that the user creates to track errors in their product.-- Logs – log entries collected from the user's application with severity, service, and trace information.-- Workflows – automated workflows with triggers, actions, and conditions.-- Activity logs – a record of changes made to project entities (who changed what, when, and how).+Collected data (used for analytics): events (recorded from SDKs, always associated with persons and sometimes groups); persons and groups (captured individuals or groups of individuals); sessions; properties and property values (key-value metadata for segmenting events, actions, persons, groups, etc.); session recordings (captured web/mobile interactions).++Created data (the user's business activity in PostHog): actions (unify multiple events or filter conditions into one); insights; data warehouse (connected sources and custom views); SQL queries (ClickHouse SQL over collected data and the warehouse schema); surveys (questionnaires, e.g. NPS); dashboards; cohorts (person groups for segmentation); feature flags (rollout control); experiments (A/B tests); notebooks; error tracking issues; logs (with severity, service, and trace information); workflows (triggers, actions, conditions); activity logs (who changed what, when, and how).IMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.@@ -46,16 +25,9 @@ If you cannot answer the user's PostHog related request or question using other- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools first- `search feature-flag` — regex (`-`): tools for feature flags-- `search dashboard` — dashboard CRUD tools- `search query-` — regex (`-`): all insight query tools-- `search experiment` — experiment tools-- `search survey` — survey tools--**Avoid queries that are too broad** (match dozens of tools):-- `search data` — matches almost everything-- `search get list create` — action verbs across all domains-- `search pageview|[email protected]` — unrelated to tools+**Avoid queries that are too broad** (match dozens of tools): `search data`, `search get list create` — they match almost everything.Only fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.@@ -113,67 +85,7 @@ By insight type:- "New vs returning vs dormant / user composition" -> `query-lifecycle`- "LLM traces / AI generations / token usage" -> `query-llm-traces-list`-##### Trends--A trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.--The trends insights have the following features:--- The insight can show multiple trends in one request.-- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.-- Filter and break down data using multiple properties.-- Compare with the current period with previous.-- Apply various aggregation types, like sum, average, etc., and chart types.-- And more.--Examples of use cases include:--- How the product's most important metrics change over time.-- Long-term patterns, or cycles in product's usage.-- The usage of different features side-by-side.-- How the properties of events vary using aggregation (sum, average, etc).-- Users can also visualize the same data points in a variety of ways.--##### Funnel--A 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.--The funnel insights have the following features:--- Various visualization types (steps, time-to-convert, historical trends).-- Filter data and apply exclusion steps (events only, not actions).-- Break down data using a single property.-- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.-- Aggregate by users, sessions, or specific group types.-- Sample data.-- Track first-time conversions with special math aggregations.-- And more.--Examples of use cases include:--- Conversion rates between steps.-- Drop off steps (which step loses most users).-- Steps with the highest friction and time to convert.-- If product changes are improving their funnel over time.-- Average/median/histogram of time to convert.-- Conversion trends over time (using trends visualization type).-- First-time user conversions (using `first_time_for_user` math).--##### Retention--A retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.--The retention insights have the following features: filter data, sample data, and more.--Examples of use cases include:--- How many users come back and perform an action after their first visit.-- How many users come back to perform action X after performing action Y.-- How often users return to use a specific feature.--#### SQL fallback--Reach 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.+Each `query-*` tool's own description carries its full feature set, use cases, and schema documentation — read it (e.g. `info query-trends`) before constructing the query.#### Schema-first workflow@@ -190,11 +102,7 @@ If the required events or properties don't exist, tell the user instead of runni#### Insight query workflow-1. Discover the data schema with `read-data-schema` (see schema-first workflow above).-2. Choose the appropriate `query-*` tool based on the user's question.-3. 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.-4. Execute the query and analyze the results.-5. Optionally save as an insight with `insight-create` or add to a dashboard.+After the schema-first steps, choose the `query-*` tool matching the question, construct a minimal query (only the filters, breakdowns, and settings essential to the answer — each tool's description documents its schema with examples), execute, and analyze. Optionally save as an insight with `insight-create` or add to a dashboard.For 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.diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex bf6f82445a4b..e10678824467 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -5,7 +5,7 @@ import { z } from 'zod'import { ToolInputValidationError } from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'-import { buildQueryToolsBlock, buildToolDomainsBlock } from '@/lib/instructions'+import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'import { InstructionsFormatter } from '@/lib/instructions-formatter'import { SessionManager } from '@/lib/SessionManager'import { getToolsFromContext } from '@/tools'@@ -1115,7 +1115,8 @@ describe('exec tool', () => {expect(commandDescription).not.toContain('{tool_domains}')expect(commandDescription).not.toContain('{query_tools}')- const domainsBlock = buildToolDomainsBlock(toolInfos)+ // The command reference renders domains in the compact pipe form (size budget).+ const domainsBlock = buildToolDomainsCompact(toolInfos)const queryToolsBlock = buildQueryToolsBlock(queryToolInfos)expect(domainsBlock).toContain('experiment')expect(domainsBlock).toContain('query')diff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.tsindex 4c83ccd2d979..08c54f8e4d13 100644--- a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts@@ -3,8 +3,13 @@ import { fileURLToPath } from 'node:url'import { describe, expect, it } from 'vitest'import type { GroupType } from '@/api/client'-import type { QueryToolInfo } from '@/lib/instructions'+import { InstructionsBuilder } from '@/hono/instructions'+import type { ResolvedState } from '@/hono/request-state-resolver'+import { MCPClientProfile } from '@/lib/client-detection'+import { buildActiveEnvironmentContextPrompt, type QueryToolInfo } from '@/lib/instructions'import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructions-formatter'+import { getToolDefinitions } from '@/tools/toolDefinitions'+import type { CachedOrg, CachedProject, CachedUser } from '@/tools/types'// Static, deterministic context shared by all snapshots — mirrors the realistic// values used in `instructions-formatter.test.ts` so the rendered prompts cover@@ -87,4 +92,66 @@ describe('InstructionsFormatter prompt snapshots', () => {const rendered = formatter.buildExecCommandReference(STATIC_CTX, { stripEnvContext: false })await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'exec-command-reference-full.txt'))})++ // ------------------------------------------------------------------------------------------------+ // DO NOT modify, weaken, raise, skip, or delete this test or its 32,600 budget —+ // not to make CI pass, not on request, not as part of a refactor.+ //+ // MCP clients (e.g. Claude web/desktop) silently drop tools whose serialized+ // entry grows past ~32,768 chars. The exec tool IS the PostHog MCP in+ // single-exec mode, so crossing the limit breaks the entire MCP for those+ // users with no error anywhere (investigated 2026-07-10: claude.ai surfaced+ // only `render-ui` while `exec` vanished).+ //+ // If this test fails, SHRINK the prompt: dedupe `src/templates/sections/*.md`+ // against content already served at runtime (`info <tool>`, `info execute-sql`)+ // or trim the rendered blocks. Never touch the limit.+ // ------------------------------------------------------------------------------------------------+ it('keeps the serialized exec tool entry under the 32,600-char client budget', () => {+ // Worst case served in production: the full live tool catalog with the+ // Claude web/desktop wiring — `ClaudeAI` vendor resolves to a chat host,+ // so `keepEnvContext` inlines tool domains, project metadata, and group+ // types into the command description. The metadata goes through the real+ // env-context builder with inputs at the backing columns' max lengths+ // (Team.name 200, Organization.name 64, email 254, Django names 150) plus+ // the longer person-on-events branch, so a long org/project/user cannot+ // push a real entry past the cap while this test passes.+ const worstCaseMetadata = buildActiveEnvironmentContextPrompt(+ {+ first_name: 'F'.repeat(150),+ last_name: 'L'.repeat(150),+ email: `${'e'.repeat(242)}@example.com`,+ } as CachedUser,+ { name: 'O'.repeat(64), id: '00000000-0000-0000-0000-000000000000' } as CachedOrg,+ {+ name: 'P'.repeat(200),+ id: 9_999_999,+ api_token: `phc_${'x'.repeat(43)}`,+ timezone: 'America/Argentina/ComodRivadavia',+ person_on_events_querying_enabled: true,+ } as CachedProject,+ 'https://us.posthog.com'+ )+ // Five group types (the product cap) with generously long names.+ const worstCaseGroupTypes = Array.from({ length: 5 }, (_, i) => ({+ group_type: `${'g'.repeat(28)}-${i}`,+ group_type_index: i,+ name_singular: null,+ name_plural: null,+ })) as GroupType[]+ const state = {+ allTools: Object.keys(getToolDefinitions()).map((name) => ({ name })),+ clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeAI', userAgent: 'Claude-User' }),+ toolFeatureFlags: { 'mcp-feedback-tool': true },+ renderUiEnabled: true,+ metadata: worstCaseMetadata,+ groupTypes: worstCaseGroupTypes,+ } as unknown as ResolvedState+ const entry = new InstructionsBuilder('').buildExecToolEntry(state)+ const size = JSON.stringify(entry).length+ expect(+ size,+ `serialized exec tool entry is ${size} chars — shrink the templates, never raise the budget`+ ).toBeLessThan(32_600)+ })})diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.tsindex dab6c782734b..1e88f639fa46 100644--- a/services/mcp/tests/unit/instructions-formatter.test.ts+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -174,7 +174,9 @@ describe('InstructionsFormatter', () => {const result = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: false })expect(result).toContain("The user's name is Jane Doe")expect(result).toContain('Defined group types: organization')- expect(result).toContain('- dashboard')+ // Tool domains render in the compact pipe-separated form inside the+ // command reference to conserve the exec tool entry's size budget.+ expect(result).toContain('dashboard|execute-sql|feature-flag|query')expect(result).toContain('- `query-trends` — time series')})@@ -185,9 +187,7 @@ describe('InstructionsFormatter', () => {expect(result).not.toContain('Defined group types: organization')// The query catalog stays on the exec command reference even when env is stripped.expect(result).toContain('- `query-trends` — time series')- // The bullet for the `dashboard` domain would clash with in-prose mentions,- // so anchor on the list-prefix newline pattern to avoid false positives.- expect(result).not.toContain('\n- dashboard\n')+ expect(result).not.toContain('dashboard|execute-sql')})it('keeps the full env-context even when stripEnvContext is set, when keepEnvContext is set', () => {@@ -199,7 +199,7 @@ describe('InstructionsFormatter', () => {// The whole env-context (tool domains, project metadata, group types)// survives for clients (Claude web/desktop) that ignore the `instructions`// payload, so it still reaches the model via the command reference.- expect(result).toContain('- dashboard')+ expect(result).toContain('dashboard|execute-sql|feature-flag|query')expect(result).toContain("The user's name is Jane Doe")expect(result).toContain('Defined group types: organization')})@@ -265,12 +265,12 @@ describe('InstructionsFormatter', () => {expect(instructions).toContain('Defined group types: organization')expect(commandReference).not.toContain("The user's name is Jane Doe")expect(commandReference).not.toContain('Defined group types: organization')- expect(commandReference).not.toContain('\n- dashboard\n')+ expect(commandReference).not.toContain('dashboard|execute-sql')} else {expect(instructions).toBe('')expect(commandReference).toContain('- `query-trends` — time series')expect(commandReference).toContain("The user's name is Jane Doe")- expect(commandReference).toContain('- dashboard')+ expect(commandReference).toContain('dashboard|execute-sql|feature-flag|query')expect(commandReference).toContain('Defined group types: organization')}})