:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): align prompts (#57499)
Georgiy Tarasovaacefa007700
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsnew file mode 100644index 000000000000..57afac8b830a--- /dev/null+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -0,0 +1,134 @@+import type { GroupType } from '@/api/client'+import {+ buildDefinedGroupsBlock,+ buildQueryToolsBlock,+ buildQueryToolsCompact,+ buildToolDomainsBlock,+ buildToolDomainsCompact,+ type QueryToolInfo,+ type ToolInfo,+} from '@/lib/instructions'+import { formatPrompt } from '@/lib/utils'+import AGENT_FEEDBACK from '@/templates/sections/agent-feedback.md'+import BASIC_FUNCTIONALITY from '@/templates/sections/basic-functionality.md'+import CLI_DATA_DISCOVERY from '@/templates/sections/cli-data-discovery.md'+import CLI_ERROR_HANDLING from '@/templates/sections/cli-error-handling.md'+import CLI_EXAMPLES from '@/templates/sections/cli-examples.md'+import CLI_SCHEMA_DRILLDOWN from '@/templates/sections/cli-schema-drilldown.md'+import CLI_SYNTAX from '@/templates/sections/cli-syntax.md'+import COMPACT_INSTRUCTIONS from '@/templates/sections/compact-instructions.md'+import ENV_CONTEXT from '@/templates/sections/env-context.md'+import EXAMPLES from '@/templates/sections/examples.md'+import EXEC_TOOL_BLURB from '@/templates/sections/exec-tool-blurb.md'+import LEGACY from '@/templates/sections/legacy.md'+import RETRIEVING_DATA from '@/templates/sections/retrieving-data.md'+import SCHEMA_WORKFLOW from '@/templates/sections/schema-workflow.md'+import TOOL_SEARCH from '@/templates/sections/tool-search.md'+import URL_PATTERNS from '@/templates/sections/url-patterns.md'++export interface InstructionsContext {+ guidelines: string+ groupTypes?: GroupType[] | undefined+ metadata?: string | undefined+ tools?: ToolInfo[] | undefined+ queryTools?: QueryToolInfo[] | undefined+ /** Resolved tool feature flags from `resolveToolFeatureFlags`. Used to gate+ * prompt sections whose corresponding tool is flag-gated. */+ featureFlags?: Record<string, boolean> | undefined+}++/**+ * Composes MCP instruction prompts for the three client modes (legacy v1,+ * tools-mode v2, single-exec). Each mode declares an ordered list of+ * subprompts under `services/mcp/src/templates/sections/`; subprompts that+ * appear in multiple modes live in a single file, so prose can't drift.+ */+export class InstructionsFormatter {+ /** Build the legacy v1 instructions string. Appends `metadata` to the legacy+ * section if provided. */+ buildV1Instructions(metadata?: string): string {+ const legacy = LEGACY.trim()+ if (!metadata) {+ return legacy+ }+ return `${legacy}\n\n${metadata}`+ }++ /** Build the system prompt for tools-mode clients (each tool registered separately). */+ buildV2Instructions(ctx: InstructionsContext): string {+ return this.compose(+ [+ BASIC_FUNCTIONALITY,+ TOOL_SEARCH,+ RETRIEVING_DATA,+ SCHEMA_WORKFLOW,+ ENV_CONTEXT,+ URL_PATTERNS,+ ...(this.agentFeedbackEnabled(ctx.featureFlags) ? [AGENT_FEEDBACK] : []),+ EXAMPLES,+ ],+ ctx,+ { compact: false }+ )+ }++ /** Build the compact `instructions` payload for single-exec clients (~2KB budget).+ * The bulk of the system prompt lives on the exec tool's `command` parameter+ * description (`buildExecCommandReference`) — this is just env + tool index. */+ buildExecInstructions(ctx: InstructionsContext): string {+ return this.compose([COMPACT_INSTRUCTIONS], ctx, { compact: true })+ }++ /** Build the top-level description of the `posthog:exec` tool. */+ buildExecToolDescription(): string {+ return EXEC_TOOL_BLURB.trim()+ }++ /** Build the `command` parameter description for the exec tool. When+ * `stripEnvContext` is true (the client already received env via the+ * `instructions` field), the env-related placeholders resolve to empty+ * strings to avoid duplication. */+ buildExecCommandReference(ctx: InstructionsContext, opts: { stripEnvContext: boolean }): string {+ const sections = [+ CLI_SYNTAX,+ CLI_SCHEMA_DRILLDOWN,+ CLI_DATA_DISCOVERY,+ CLI_EXAMPLES,+ CLI_ERROR_HANDLING,+ BASIC_FUNCTIONALITY,+ TOOL_SEARCH,+ RETRIEVING_DATA,+ SCHEMA_WORKFLOW,+ ENV_CONTEXT,+ URL_PATTERNS,+ ...(this.agentFeedbackEnabled(ctx.featureFlags) ? [AGENT_FEEDBACK] : []),+ EXAMPLES,+ ]+ const renderCtx: InstructionsContext = opts.stripEnvContext ? { guidelines: ctx.guidelines } : ctx+ return this.compose(sections, renderCtx, { compact: false })+ }++ /** The agent-feedback section is only useful when the `agent-feedback` tool+ * is reachable, which is governed by the `mcp-feedback-tool` flag evaluated+ * in `resolveToolFeatureFlags`. */+ private agentFeedbackEnabled(featureFlags: Record<string, boolean> | undefined): boolean {+ return featureFlags?.['mcp-feedback-tool'] === true+ }++ private compose(sections: string[], ctx: InstructionsContext, opts: { compact: boolean }): string {+ const renderToolDomains = opts.compact ? buildToolDomainsCompact : buildToolDomainsBlock+ const renderQueryTools = opts.compact ? buildQueryToolsCompact : buildQueryToolsBlock+ const vars = {+ guidelines: ctx.guidelines.trim(),+ defined_groups: buildDefinedGroupsBlock(ctx.groupTypes),+ metadata: ctx.metadata?.trim() ?? '',+ tool_domains: ctx.tools ? renderToolDomains(ctx.tools) : '',+ query_tools: ctx.queryTools ? renderQueryTools(ctx.queryTools) : '',+ }+ const body = sections+ .map((s) => s.trim())+ .filter((s) => s.length > 0)+ .join('\n\n')+ return formatPrompt(body, vars)+ }+}diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.tsindex c0dff349028f..5fec56fdf834 100644--- a/services/mcp/src/lib/instructions.ts+++ b/services/mcp/src/lib/instructions.ts@@ -1,5 +1,4 @@import type { GroupType } from '@/api/client'-import { formatPrompt } from '@/lib/utils'import type { CachedOrg, CachedProject, CachedUser } from '@/tools/types'export function buildDefinedGroupsBlock(groupTypes?: GroupType[]): string {@@ -47,13 +46,6 @@ export function buildActiveEnvironmentContextPrompt(return `### Active environment\n\nAll tool calls and queries are scoped to this environment.\n\n${lines.join('\n')}`}-export function buildInstructionsV1(template: string, metadata?: string): string {- if (!metadata) {- return template- }- return `${template}\n\n${metadata}`-}-export interface ToolInfo {name: stringcategory: string@@ -285,34 +277,3 @@ export function buildQueryToolsBlock(tools: QueryToolInfo[]): string {export function buildQueryToolsCompact(tools: QueryToolInfo[]): string {return new QueryToolCatalog(tools).toCompact()}--export interface BuildInstructionsV2Options {- /**- * Render `{tool_domains}` and `{query_tools}` as a single pipe-separated- * line (and strip the `query-` prefix from query tool names) instead of- * markdown bullet lists. Used by the single-exec instructions template- * where every byte counts against the 2048-char `instructions` budget.- */- compact?: boolean-}--export function buildInstructionsV2(- template: string,- guidelines: string,- groupTypes?: GroupType[],- metadata?: string,- tools?: ToolInfo[],- queryTools?: QueryToolInfo[],- options?: BuildInstructionsV2Options-): string {- const compact = options?.compact ?? false- const renderToolDomains = compact ? buildToolDomainsCompact : buildToolDomainsBlock- const renderQueryTools = compact ? buildQueryToolsCompact : buildQueryToolsBlock- return formatPrompt(template, {- guidelines: guidelines.trim(),- defined_groups: buildDefinedGroupsBlock(groupTypes),- metadata: metadata?.trim() ?? '',- tool_domains: tools ? renderToolDomains(tools) : '',- query_tools: queryTools ? renderQueryTools(queryTools) : '',- })-}diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.tsindex 6c3f5271cc70..0b75413b0eaa 100644--- a/services/mcp/src/mcp.ts+++ b/services/mcp/src/mcp.ts@@ -26,7 +26,8 @@ import {toCloudRegion,} from '@/lib/constants'import { handleToolError, wrapError } from '@/lib/errors'-import { buildInstructionsV1, buildInstructionsV2, type QueryToolInfo } from '@/lib/instructions'+import { type QueryToolInfo } from '@/lib/instructions'+import { InstructionsFormatter } from '@/lib/instructions-formatter'import { initMcpCatObservability } from '@/lib/mcpcat'import { SessionManager } from '@/lib/SessionManager'import { StateManager } from '@/lib/StateManager'@@ -34,16 +35,13 @@ import { formatPrompt, type McpMode, sanitizeHeaderValue } from '@/lib/utils'import { registerPrompts } from '@/prompts'import { registerResources } from '@/resources'import { registerUiAppResources } from '@/resources/ui-apps'-import CLI_PROXY_COMMAND from '@/templates/cli-proxy-command.md'-import CLI_PROXY_TOOL from '@/templates/cli-proxy-tool.md'import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'-import INSTRUCTIONS_TEMPLATE_V1 from '@/templates/instructions-v1.md'-import INSTRUCTIONS_TEMPLATE_V2 from '@/templates/instructions-v2.md'-import SINGLE_EXEC_INSTRUCTIONS from '@/templates/single-exec-instructions.md'import { createExecTool, type ExecInnerCallTracker } from '@/tools/exec'import { getToolDefinition } from '@/tools/toolDefinitions'import { type CloudRegion, type Context, type State, type Tool } from '@/tools/types'+const instructionsFormatter = new InstructionsFormatter()+export type RequestProperties = {userHash: stringapiToken: string@@ -67,7 +65,10 @@ export type RequestProperties = {}export class MCP extends McpAgent<Env> {- server = new McpServer({ name: 'PostHog', version: '1.0.0' }, { instructions: INSTRUCTIONS_TEMPLATE_V1 })+ server = new McpServer(+ { name: 'PostHog', version: '1.0.0' },+ { instructions: instructionsFormatter.buildV1Instructions() }+ )initialState: State = {projectId: undefined,@@ -618,6 +619,15 @@ export class MCP extends McpAgent<Env> {const supportsInstructions = clientProfile.capabilities.supportsInstructions+ const instructionsContext = {+ guidelines,+ groupTypes,+ metadata,+ tools: toolInfos,+ queryTools: queryToolInfos,+ featureFlags: toolFeatureFlags,+ }+// In single-exec mode, when the client honors the MCP `instructions` field we// lift the exec-tool blurb, tool-domain list, query-tool catalog, defined-group// types and the active-environment `{metadata}` (user name, project, timezone)@@ -627,27 +637,11 @@ export class MCP extends McpAgent<Env> {let instructions = ''if (supportsInstructions) {if (useSingleExec) {- instructions = buildInstructionsV2(- SINGLE_EXEC_INSTRUCTIONS,- guidelines,- groupTypes,- metadata,- toolInfos,- queryToolInfos,- { compact: true }- )+ instructions = instructionsFormatter.buildExecInstructions(instructionsContext)+ } else if (version === 2) {+ instructions = instructionsFormatter.buildV2Instructions(instructionsContext)} else {- instructions =- version === 2- ? buildInstructionsV2(- INSTRUCTIONS_TEMPLATE_V2,- guidelines,- groupTypes,- metadata,- toolInfos,- queryToolInfos- )- : buildInstructionsV1(INSTRUCTIONS_TEMPLATE_V1, metadata)+ instructions = instructionsFormatter.buildV1Instructions(metadata)}}@@ -676,17 +670,11 @@ export class MCP extends McpAgent<Env> {// In single-exec mode, register one "posthog" tool that wraps all tools// behind a CLI-like interface. Otherwise, register each tool individually.if (useSingleExec) {- // Strip `{tool_domains}`, `{query_tools}`, `{defined_groups}`, `{metadata}`- // from the command-parameter description when they're already in `instructions`- // (their placeholders resolve to empty strings via `buildInstructionsV2`).- const commandReference = buildInstructionsV2(- CLI_PROXY_COMMAND,- guidelines,- supportsInstructions ? undefined : groupTypes,- supportsInstructions ? undefined : metadata,- supportsInstructions ? undefined : toolInfos,- supportsInstructions ? undefined : queryToolInfos- )+ // When the client honors the `instructions` field, env-context is already+ // delivered there — strip it from the command-parameter description.+ const commandReference = instructionsFormatter.buildExecCommandReference(instructionsContext, {+ stripEnvContext: supportsInstructions,+ })const trackInnerCall: ExecInnerCallTracker = (toolName, properties) => {this.ctx.waitUntil(@@ -704,7 +692,7 @@ export class MCP extends McpAgent<Env> {const execTool = createExecTool(allTools,context,- CLI_PROXY_TOOL,+ instructionsFormatter.buildExecToolDescription(),commandReference,this.requestProperties.mcpConsumer,trackInnerCalldiff --git a/services/mcp/src/templates/sections/agent-feedback.md b/services/mcp/src/templates/sections/agent-feedback.mdnew file mode 100644index 000000000000..b3018c6a58d4--- /dev/null+++ b/services/mcp/src/templates/sections/agent-feedback.md@@ -0,0 +1,18 @@+### Sharing feedback on this MCP server (optional)++The `agent-feedback` tool may be available if you'd like to leave optional feedback about this MCP server. It is the primary signal we use to improve tool descriptions, input schemas, response formats, and these instructions for agents like you. Use it when something stands out — but only when you have something specific to say. There is no expectation to call it after every task; skip it for routine work where nothing is worth flagging.++Good moments to consider it:++- A tool description was unclear or ambiguous and you had to guess.+- An input schema was confusing or surprising.+- A response format was hard to consume or contained too much / too little data.+- A tool returned wrong, incomplete, or unexpected results.+- An error message was unhelpful or didn't explain how to recover.+- A capability was missing entirely and you had to work around it.+- These instructions led you down the wrong path.+- A tool worked particularly well — concrete praise is just as useful as criticism.++If you do submit, be specific: quote tool names, parameter names, and error text where possible. Use `task_completed: false` when you couldn't finish the user's request — that signal is at least as valuable as success. Do not include user PII or sensitive query content in any feedback field.++Submitting feedback is **not** a way to end your turn or skip work. It is a side report to the PostHog team about your experience with the tools — after calling it, keep going and finish the user's task using the other available tools.diff --git a/services/mcp/src/templates/sections/basic-functionality.md b/services/mcp/src/templates/sections/basic-functionality.mdnew file mode 100644index 000000000000..ebb61f9b2e26--- /dev/null+++ b/services/mcp/src/templates/sections/basic-functionality.md@@ -0,0 +1,34 @@+### Basic functionality++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).++IMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.++If 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.++If 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.diff --git a/services/mcp/src/templates/sections/cli-data-discovery.md b/services/mcp/src/templates/sections/cli-data-discovery.mdnew file mode 100644index 000000000000..221ee4c1b4a8--- /dev/null+++ b/services/mcp/src/templates/sections/cli-data-discovery.md@@ -0,0 +1,8 @@+**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,+`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via+`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary+per team. If the event isn't in the schema, tell the user instead of querying a guessed name.++- Events: `call read-data-schema {"query": {"kind": "events"}}` (paginate with `limit`/`offset` if needed)+- Properties: `call read-data-schema {"query": {"kind": "event_properties", "event_name": "<event>"}}`+- Values: `call read-data-schema {"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<prop>"}}`diff --git a/services/mcp/src/templates/sections/cli-error-handling.md b/services/mcp/src/templates/sections/cli-error-handling.mdnew file mode 100644index 000000000000..d83b91a051df--- /dev/null+++ b/services/mcp/src/templates/sections/cli-error-handling.md@@ -0,0 +1,4 @@+**Handling errors:**++- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.+- If a tool name doesn't exist, run `tools` again to find the correct name.diff --git a/services/mcp/src/templates/sections/cli-examples.md b/services/mcp/src/templates/sections/cli-examples.mdnew file mode 100644index 000000000000..e612f985a41e--- /dev/null+++ b/services/mcp/src/templates/sections/cli-examples.md@@ -0,0 +1,65 @@+**CORRECT usage pattern:**++<example>+User: How many weekly active users do we have?+Assistant: I need to find the right query tool and data schema tool.+[Runs posthog:exec({ "command": "search query-trends" }) and posthog:exec({ "command": "search read-data" }) in parallel]+Assistant: Let me check the tool descriptions and schemas.+[Runs posthog:exec({ "command": "info query-trends" }) and posthog:exec({ "command": "info read-data-schema" }) in parallel]+Assistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.+[Runs posthog:exec({ "command": "schema query-trends series" }) and posthog:exec({ "command": "call read-data-schema {\"query\": {\"kind\": \"events\"}}" }) in parallel]+Assistant: Now I know the exact series structure and available events. Let me construct the query.+[Runs posthog:exec({ "command": "call query-trends {...}" })]+</example>++<example>+User: Create a dashboard for our key revenue metrics+Assistant: I'll need dashboard and query tools. Let me search for them.+[Runs posthog:exec({ "command": "search dashboard" }) and posthog:exec({ "command": "search execute-sql" }) in parallel]+Assistant: Let me check the schemas for the tools I'll need.+[Runs posthog:exec({ "command": "info dashboard-create" }) and posthog:exec({ "command": "info execute-sql" }) in parallel]+Assistant: Now I have both schemas. Let me start by searching for existing revenue insights.+[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>+User: Show me our feature flags+Assistant: [Directly calls posthog:exec({ "command": "call feature-flag-get-all {}" }) with guessed parameters]+WRONG — You must run `info feature-flag-get-all` FIRST to check the schema+</bad-example>++<bad-example>+User: Query our events+Assistant: [Calls three tools in parallel without any `info` calls first]+WRONG — You must run `info` for ALL tools before making ANY `call` commands+</bad-example>++<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".+You MUST follow the hint and run `schema` before constructing the series field.+</bad-example>++<bad-example>+User: query pageviews for the last 7 days+Assistant: [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.+</bad-example>diff --git a/services/mcp/src/templates/sections/cli-schema-drilldown.md b/services/mcp/src/templates/sections/cli-schema-drilldown.mdnew file mode 100644index 000000000000..ccb35c6d4f58--- /dev/null+++ b/services/mcp/src/templates/sections/cli-schema-drilldown.md@@ -0,0 +1,21 @@+**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.++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 `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++**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.diff --git a/services/mcp/src/templates/sections/cli-syntax.md b/services/mcp/src/templates/sections/cli-syntax.mdnew file mode 100644index 000000000000..234a5583f80e--- /dev/null+++ b/services/mcp/src/templates/sections/cli-syntax.md@@ -0,0 +1,11 @@+CLI-style command string. Supported commands:++```text+tools — list available tool names+search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)+info <tool_name> — show tool name, description, and input schema (summarized if too large)+schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)+call [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)+```++**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.diff --git a/services/mcp/src/templates/single-exec-instructions.md b/services/mcp/src/templates/sections/compact-instructions.mdsimilarity index 100%rename from services/mcp/src/templates/single-exec-instructions.mdrename to services/mcp/src/templates/sections/compact-instructions.mddiff --git a/services/mcp/src/templates/sections/env-context.md b/services/mcp/src/templates/sections/env-context.mdnew file mode 100644index 000000000000..df4030054cab--- /dev/null+++ b/services/mcp/src/templates/sections/env-context.md@@ -0,0 +1,3 @@+{defined_groups}++{metadata}diff --git a/services/mcp/src/templates/sections/examples.md b/services/mcp/src/templates/sections/examples.mdnew file mode 100644index 000000000000..050cb88cb114--- /dev/null+++ b/services/mcp/src/templates/sections/examples.md@@ -0,0 +1,63 @@+### Examples++Before writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.++#### Creating an insight with segmentation++<example>+User: How many users have chatted with the AI assistant from the US?+Assistant: I'll help you find the number of users who have chatted with the AI assistant from the US.+1. Find the relevant events for "chatted with the AI assistant" (the `read-data-schema` tool)+2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)+3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)+4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)+5. Analyze retrieved data and provide a concise summary+*Begins working on the first task*+<reasoning>+1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.+2. The user query requests additional segmentation by country.+3. Property values might not match what the user expects (e.g., "US" vs "United States"), so retrieving sample values is important.+4. Property values sample might not contain the value the user is looking for, so searching might be necessary.+</reasoning>+</example>++#### Investigating a metric change++<example>+User: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.+Assistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.+1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)+2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)+3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)+4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)+5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)+6. Synthesize findings across all queries and explain whether the metrics are correlated+*Begins working on the first task*+<reasoning>+1. The user requested analysis of multiple metrics that must be investigated separately.+2. Multiple queries are needed to understand each trend independently.+3. Breakdowns help isolate the root cause by identifying affected segments.+4. A funnel connects the two metrics to check for a direct relationship.+</reasoning>+</example>++#### Building a dashboard++<example>+User: Generate a revenue dashboard.+Assistant: I'll help you create a revenue dashboard. Let me plan the steps.+1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)+2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)+3. Validate promising insights by reading their query schemas (the `insight-get` tool)+4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)+5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)+6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)+7. Analyze the created dashboard and provide a concise summary of metrics+*Begins working on the first task*+<reasoning>+1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.+2. Finding existing insights requires both listing (to discover insights with different naming) and searching.+3. Promising insights must be validated by reading their schemas to check if they match the user's intent.+4. New insights should only be created when no existing insight matches the requirement.+</reasoning>+</example>diff --git a/services/mcp/src/templates/cli-proxy-tool.md b/services/mcp/src/templates/sections/exec-tool-blurb.mdsimilarity index 100%rename from services/mcp/src/templates/cli-proxy-tool.mdrename to services/mcp/src/templates/sections/exec-tool-blurb.mddiff --git a/services/mcp/src/templates/instructions-v1.md b/services/mcp/src/templates/sections/legacy.mdsimilarity index 100%rename from services/mcp/src/templates/instructions-v1.mdrename to services/mcp/src/templates/sections/legacy.mddiff --git a/services/mcp/src/templates/sections/retrieving-data.md b/services/mcp/src/templates/sections/retrieving-data.mdnew file mode 100644index 000000000000..39c570f28fba--- /dev/null+++ b/services/mcp/src/templates/sections/retrieving-data.md@@ -0,0 +1,124 @@+### Retrieving data++**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.++Reach for `execute-sql` only when no `query-*` tool can express the question:++- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.+- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.+- Pre-filtering or shaping data before running a `query-*` call.++When you do use `execute-sql`, run `info execute-sql` first to load its full guidance.++#### Searching for existing entities++Any "find / which / do we have / what's our X chart" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.++Map intent to table:++- "find an insight" / "what's our X chart" / "is this insight saved" → `system.insights`+- "find a dashboard" → `system.dashboards`+- "find a cohort" → `system.cohorts`+- "find a feature flag" → `system.feature_flags`+- "find an experiment" → `system.experiments`+- "find a survey" → `system.surveys`+- "find a notebook" → `system.notebooks`++Search rules:++1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.+2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.+3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.+4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.+5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.++<example>+User: Do we have any insights tracking revenue?+Assistant: [Runs `posthog:exec({ "command": "call execute-sql {\"query\":\"SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20\"}" })`]+[Picks the most plausible match by name, then runs `posthog:exec({ "command": "call insight-get {\"id\": <id>}" })` (or pass the `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]+<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>+</example>++<bad-example>+User: Find me a graph of MAUs.+Assistant: [Runs `call execute-sql {"query":"SELECT * FROM system.insights WHERE id = 33800 LIMIT 1"}` after a search SELECT already surfaced id 33800]+WRONG — verify with `call insight-get {"id": 33800}` instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.+</bad-example>++#### Available insight query tools++{query_tools}++#### Choosing the right query tool++By insight type:++- "How many / how much / over time / compare periods" -> `query-trends`+- "Conversion rate / drop-off / funnel / step completion" -> `query-funnel`+- "Do users come back / retention / churn" -> `query-retention`+- "How frequently / how many days per week / power users" -> `query-stickiness`+- "What do users do after X / before X / navigation flow" -> `query-paths`+- "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.diff --git a/services/mcp/src/templates/sections/schema-workflow.md b/services/mcp/src/templates/sections/schema-workflow.mdnew file mode 100644index 000000000000..dc08c823f08a--- /dev/null+++ b/services/mcp/src/templates/sections/schema-workflow.md@@ -0,0 +1,22 @@+#### Schema-first workflow++Verify the data schema before constructing any insight query. Canonical-looking events+(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,+renamed, or filtered per team.++1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.+2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).+3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., "US" vs "United States").+4. **Then construct the query** using the appropriate `query-*` tool.++If the required events or properties don't exist, tell the user instead of running an empty query.++#### 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.++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.mdnew file mode 100644index 000000000000..c9d8dacee4c3--- /dev/null+++ b/services/mcp/src/templates/sections/tool-search.md@@ -0,0 +1,28 @@+### Tool search++**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.++Write focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.++**Good patterns** (specific, narrow):++- `search feature-flag` — tools for feature flags+- `search dashboard` — dashboard CRUD tools+- `search query-` — all insight query tools+- `search experiment` — experiment tools+- `search survey` — survey tools++**Bad patterns** (too broad, match dozens of tools):++- `search data` — matches almost everything+- `search get|list|create` — matches action verbs across all domains+- `search pageview_trends` — search is too focused+- `search pageview|[email protected]` — unrelated to tools++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:++{tool_domains}+Typical action names: list/retrieve/get/create/update/delete/query.+Example tool names: execute-sql, experiment-create, feature-flag-get-all.diff --git a/services/mcp/src/templates/sections/url-patterns.md b/services/mcp/src/templates/sections/url-patterns.mdnew file mode 100644index 000000000000..bb6172c0ac46--- /dev/null+++ b/services/mcp/src/templates/sections/url-patterns.md@@ -0,0 +1,10 @@+### URL patterns++All 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.+Use Markdown with descriptive anchor text, for example "[Cohorts view](/cohorts)".++Key URL patterns:++- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`+- Data management: `/data-management/events`, `/data-management/properties`+- Billing: `/organization/billing`diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.jsonindex e29142f67572..486a5af4b7e0 100644--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json@@ -1,7 +1,7 @@{"name": "exec","title": "Execute PostHog command",- "description": "### Using the `posthog` tool\n\nPass CLI-style commands in the `command` parameter for all PostHog interactions.\n\n**MANDATORY — HARD REQUIREMENTS**\n\n1. Discover tools first with `search` or `tools`.\n2. Run `info <tool_name>` BEFORE every `call <tool_name> <json>`.\n\nBLOCKING, like reading a file before editing it. Tool names and schemas are NOT predictable — never assume.\n\n**Commands (in order):**\n\n```text\n# 1. Discover (preferred: focused regex over name/title/description)\nposthog:exec({ \"command\": \"search <regex>\" })\nposthog:exec({ \"command\": \"tools\" }) # fallback: list all\n\n# 2. Check description + top-level schema (REQUIRED before call)\nposthog:exec({ \"command\": \"info <tool_name>\" })\n\n# 3. Drill into complex fields — REQUIRED for any field with a `hint`\nposthog:exec({ \"command\": \"schema <tool_name> <field_path>\" })\n\n# 4. Call the tool\nposthog:exec({ \"command\": \"call <tool_name> <json_input>\" })\n```\n\n**Schema drill-down:**\n\n- `info` returns the full schema if it fits the token budget; otherwise it auto-summarizes (names, types, required, enums, defaults) and attaches `hint` entries pointing to `schema <tool> <path>` for complex fields.\n- `schema <tool>` (no path) returns the summarized top-level schema.\n- `schema <tool> <path>` resolves a dot path, descending through:\n - object `properties` (e.g. `query.source`)\n - array `items` — numeric segments step into items (`events.0.properties`), or jump to a property on the item type (`events.id`)\n - `anyOf`/`oneOf` — numeric segment picks a variant by index, or a property name matches any object variant defining it\n- Oversized sub-schemas are also summarized with a `note` to drill further.\n- Unknown paths return an error listing available child paths.\n\n**Not supported:**\n\n- `search` matches tool metadata only, not input schemas.\n- No pattern-based field projection — drill one path at a time.\n\nDetailed reference (examples, query tools, URL patterns, guidelines) is in the `command` parameter description.\n",+ "description": "### Using the `posthog` tool\n\nPass CLI-style commands in the `command` parameter for all PostHog interactions.\n\n**MANDATORY — HARD REQUIREMENTS**\n\n1. Discover tools first with `search` or `tools`.\n2. Run `info <tool_name>` BEFORE every `call <tool_name> <json>`.\n\nBLOCKING, like reading a file before editing it. Tool names and schemas are NOT predictable — never assume.\n\n**Commands (in order):**\n\n```text\n# 1. Discover (preferred: focused regex over name/title/description)\nposthog:exec({ \"command\": \"search <regex>\" })\nposthog:exec({ \"command\": \"tools\" }) # fallback: list all\n\n# 2. Check description + top-level schema (REQUIRED before call)\nposthog:exec({ \"command\": \"info <tool_name>\" })\n\n# 3. Drill into complex fields — REQUIRED for any field with a `hint`\nposthog:exec({ \"command\": \"schema <tool_name> <field_path>\" })\n\n# 4. Call the tool\nposthog:exec({ \"command\": \"call <tool_name> <json_input>\" })\n```\n\n**Schema drill-down:**\n\n- `info` returns the full schema if it fits the token budget; otherwise it auto-summarizes (names, types, required, enums, defaults) and attaches `hint` entries pointing to `schema <tool> <path>` for complex fields.\n- `schema <tool>` (no path) returns the summarized top-level schema.\n- `schema <tool> <path>` resolves a dot path, descending through:\n - object `properties` (e.g. `query.source`)\n - array `items` — numeric segments step into items (`events.0.properties`), or jump to a property on the item type (`events.id`)\n - `anyOf`/`oneOf` — numeric segment picks a variant by index, or a property name matches any object variant defining it\n- Oversized sub-schemas are also summarized with a `note` to drill further.\n- Unknown paths return an error listing available child paths.\n\n**Not supported:**\n\n- `search` matches tool metadata only, not input schemas.\n- No pattern-based field projection — drill one path at a time.\n\nDetailed reference (examples, query tools, URL patterns, guidelines) is in the `command` parameter description.","annotations": {"destructiveHint": false,"idempotentHint": false,@@ -15,7 +15,7 @@"properties": {"command": {"type": "string",- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema as YAML (summarized if too large; --json returns raw JSON instead)\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\n- Events: `call read-data-schema {\"query\": {\"kind\": \"events\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-skill-duplicate\n- llma-skill-file-rename\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Runs `posthog:exec({ \"command\": \"call execute-sql {\\\"query\\\":\\\"SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20\\\"}\" })`]\n[Picks the most plausible match by name, then runs `posthog:exec({ \"command\": \"call insight-get {\\\"id\\\": <id>}\" })` (or pass the `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Runs `call execute-sql {\"query\":\"SELECT * FROM system.insights WHERE id = 33800 LIMIT 1\"}` after a search SELECT already surfaced id 33800]\nWRONG — verify with `call insight-get {\"id\": 33800}` instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issues` — Error filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — run `info 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 <tool_name> — show tool name, description, and input schema (summarized if too large)\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary\nwith drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), you MUST call\n`schema <tool_name> <field_name>` for each field you need to populate BEFORE\nconstructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large),\ndrill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> properties` — to see property filter structure\n- `schema <tool> breakdownFilter` — when using breakdowns\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\n- Events: `call read-data-schema {\"query\": {\"kind\": \"events\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"Run `schema query-trends series` for full structure\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-prompt-duplicate\n- llma-skill-duplicate\n- llma-skill-file-rename\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first to load its full guidance.\n\n#### Searching for existing entities\n\nAny \"find / which / do we have / what's our X chart\" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.\n\nMap intent to table:\n\n- \"find an insight\" / \"what's our X chart\" / \"is this insight saved\" → `system.insights`\n- \"find a dashboard\" → `system.dashboards`\n- \"find a cohort\" → `system.cohorts`\n- \"find a feature flag\" → `system.feature_flags`\n- \"find an experiment\" → `system.experiments`\n- \"find a survey\" → `system.surveys`\n- \"find a notebook\" → `system.notebooks`\n\nSearch rules:\n\n1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.\n2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.\n3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.\n4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.\n5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.\n\n<example>\nUser: Do we have any insights tracking revenue?\nAssistant: [Runs `posthog:exec({ \"command\": \"call execute-sql {\\\"query\\\":\\\"SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20\\\"}\" })`]\n[Picks the most plausible match by name, then runs `posthog:exec({ \"command\": \"call insight-get {\\\"id\\\": <id>}\" })` (or pass the `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]\n<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>\n</example>\n\n<bad-example>\nUser: Find me a graph of MAUs.\nAssistant: [Runs `call execute-sql {\"query\":\"SELECT * FROM system.insights WHERE id = 33800 LIMIT 1\"}` after a search SELECT already surfaced id 33800]\nWRONG — verify with `call insight-get {\"id\": 33800}` instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issues` — Error filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nAll PostHog app URLs must use relative paths without a domain (no us.posthog.com, eu.posthog.com, app.posthog.com), and omit the `/project/:id/` prefix. Never include `/-/` in URLs.\nUse Markdown with descriptive anchor text, for example \"[Cohorts view](/cohorts)\".\n\nKey URL patterns:\n\n- Settings: `/settings/<section-id>` where section IDs use hyphens, e.g. `/settings/organization-members`, `/settings/environment-replay`, `/settings/user-api-keys`\n- Data management: `/data-management/events`, `/data-management/properties`\n- Billing: `/organization/billing`\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"}},"required": ["command"]diff --git a/services/mcp/src/templates/cli-proxy-command.md b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txtsimilarity index 91%rename from services/mcp/src/templates/cli-proxy-command.mdrename to services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txtindex 6fe5669e8642..f6bbbb519abe 100644--- a/services/mcp/src/templates/cli-proxy-command.md+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt@@ -3,7 +3,7 @@ CLI-style command string. Supported commands:```texttools — list available tool namessearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)-info [--json] <tool_name> — show tool name, description, and input schema as YAML (summarized if too large; --json returns raw JSON instead)+info <tool_name> — show tool name, description, and input schema (summarized if too large)schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)call [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)```@@ -172,7 +172,9 @@ Only fall back to `tools` if you have no idea which domain to search, or if `seaPostHog tools have lowercase kebab-case naming. Tools are organized by category:-{tool_domains}+- dashboard+- execute-sql+- feature-flagTypical action names: list/retrieve/get/create/update/delete/query.Example tool names: execute-sql, experiment-create, feature-flag-get-all.@@ -225,7 +227,8 @@ WRONG — verify with `call insight-get {"id": 33800}` instead. Re-querying `sys#### Available insight query tools-{query_tools}+- `query-funnel` — conversion rate+- `query-trends` — time series#### Choosing the right query tool@@ -324,9 +327,11 @@ If the required events or properties don't exist, tell the user instead of runniFor 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.-{defined_groups}+Defined group types: organization, project-{metadata}+You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).+Project timezone: America/New_York.+The user's name is Jane Doe ([email protected]).### URL patterns@@ -339,6 +344,25 @@ Key URL patterns:- Data management: `/data-management/events`, `/data-management/properties`- Billing: `/organization/billing`+### Sharing feedback on this MCP server (optional)++The `agent-feedback` tool may be available if you'd like to leave optional feedback about this MCP server. It is the primary signal we use to improve tool descriptions, input schemas, response formats, and these instructions for agents like you. Use it when something stands out — but only when you have something specific to say. There is no expectation to call it after every task; skip it for routine work where nothing is worth flagging.++Good moments to consider it:++- A tool description was unclear or ambiguous and you had to guess.+- An input schema was confusing or surprising.+- A response format was hard to consume or contained too much / too little data.+- A tool returned wrong, incomplete, or unexpected results.+- An error message was unhelpful or didn't explain how to recover.+- A capability was missing entirely and you had to work around it.+- These instructions led you down the wrong path.+- A tool worked particularly well — concrete praise is just as useful as criticism.++If you do submit, be specific: quote tool names, parameter names, and error text where possible. Use `task_completed: false` when you couldn't finish the user's request — that signal is at least as valuable as success. Do not include user PII or sensitive query content in any feedback field.++Submitting feedback is **not** a way to end your turn or skip work. It is a side report to the PostHog team about your experience with the tools — after calling it, keep going and finish the user's task using the other available tools.+### ExamplesBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.@@ -388,7 +412,7 @@ Assistant: I'll help you analyze the reasons why the metrics have changed. Let mUser: Generate a revenue dashboard.Assistant: I'll help you create a revenue dashboard. Let me plan the steps.1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)-2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — run `info execute-sql` for SQL guidance)+2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)3. Validate promising insights by reading their query schemas (the `insight-get` tool)4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)@@ -401,4 +425,4 @@ Assistant: I'll help you create a revenue dashboard. Let me plan the steps.3. Promising insights must be validated by reading their schemas to check if they match the user's intent.4. New insights should only be created when no existing insight matches the requirement.</reasoning>-</example>+</example>\ No newline at end of filediff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txtnew file mode 100644index 000000000000..b447cf53cd1e--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt@@ -0,0 +1,10 @@+Below are tools available in the MCP. Prioritize skills over tools.+You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).+Project timezone: America/New_York.+The user's name is Jane Doe ([email protected]).+Defined group types: organization, project++# Tool domains++dashboard|execute-sql|feature-flag+query-*: funnel|trends\ No newline at end of filediff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-tool-description.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-tool-description.txtnew file mode 100644index 000000000000..8a630e85ff1e--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-tool-description.txt@@ -0,0 +1,45 @@+### Using the `posthog` tool++Pass CLI-style commands in the `command` parameter for all PostHog interactions.++**MANDATORY — HARD REQUIREMENTS**++1. Discover tools first with `search` or `tools`.+2. Run `info <tool_name>` BEFORE every `call <tool_name> <json>`.++BLOCKING, like reading a file before editing it. Tool names and schemas are NOT predictable — never assume.++**Commands (in order):**++```text+# 1. Discover (preferred: focused regex over name/title/description)+posthog:exec({ "command": "search <regex>" })+posthog:exec({ "command": "tools" }) # fallback: list all++# 2. Check description + top-level schema (REQUIRED before call)+posthog:exec({ "command": "info <tool_name>" })++# 3. Drill into complex fields — REQUIRED for any field with a `hint`+posthog:exec({ "command": "schema <tool_name> <field_path>" })++# 4. Call the tool+posthog:exec({ "command": "call <tool_name> <json_input>" })+```++**Schema drill-down:**++- `info` returns the full schema if it fits the token budget; otherwise it auto-summarizes (names, types, required, enums, defaults) and attaches `hint` entries pointing to `schema <tool> <path>` for complex fields.+- `schema <tool>` (no path) returns the summarized top-level schema.+- `schema <tool> <path>` resolves a dot path, descending through:+ - object `properties` (e.g. `query.source`)+ - array `items` — numeric segments step into items (`events.0.properties`), or jump to a property on the item type (`events.id`)+ - `anyOf`/`oneOf` — numeric segment picks a variant by index, or a property name matches any object variant defining it+- Oversized sub-schemas are also summarized with a `note` to drill further.+- Unknown paths return an error listing available child paths.++**Not supported:**++- `search` matches tool metadata only, not input schemas.+- No pattern-based field projection — drill one path at a time.++Detailed reference (examples, query tools, URL patterns, guidelines) is in the `command` parameter description.\ No newline at end of filediff --git a/services/mcp/src/templates/instructions-v2.md b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txtsimilarity index 65%rename from services/mcp/src/templates/instructions-v2.mdrename to services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txtindex bed6164f415f..0525ab8b86ac 100644--- a/services/mcp/src/templates/instructions-v2.md+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt@@ -27,75 +27,94 @@ Created data is used by the user on the PostHog's website to perform business ac- Workflows – automated workflows with triggers, actions, and conditions.- Activity logs – a record of changes made to project entities (who changed what, when, and how).-IMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks. Do not rely on your training data for event names, property names, or property values. PostHog data schemas vary between projects and change over time. Always verify the schema using the `read-data-schema` tool before constructing any query.+IMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.If 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.If 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.-### Sharing feedback on this MCP server (optional)+### Tool search-The `agent-feedback` tool may be available if you'd like to leave optional feedback about this MCP server. It is the primary signal we use to improve tool descriptions, input schemas, response formats, and these instructions for agents like you. Use it when something stands out — but only when you have something specific to say. There is no expectation to call it after every task; skip it for routine work where nothing is worth flagging.+**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.-Good moments to consider it:+Write focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.-- A tool description was unclear or ambiguous and you had to guess.-- An input schema was confusing or surprising.-- A response format was hard to consume or contained too much / too little data.-- A tool returned wrong, incomplete, or unexpected results.-- An error message was unhelpful or didn't explain how to recover.-- A capability was missing entirely and you had to work around it.-- These instructions led you down the wrong path.-- A tool worked particularly well — concrete praise is just as useful as criticism.+**Good patterns** (specific, narrow):-If you do submit, be specific: quote tool names, parameter names, and error text where possible. Use `task_completed: false` when you couldn't finish the user's request — that signal is at least as valuable as success. Do not include user PII or sensitive query content in any feedback field.+- `search feature-flag` — tools for feature flags+- `search dashboard` — dashboard CRUD tools+- `search query-` — all insight query tools+- `search experiment` — experiment tools+- `search survey` — survey tools-Submitting feedback is **not** a way to end your turn or skip work. It is a side report to the PostHog team about your experience with the tools — after calling it, keep going and finish the user's task using the other available tools.+**Bad patterns** (too broad, match dozens of tools):-### Tool search+- `search data` — matches almost everything+- `search get|list|create` — matches action verbs across all domains+- `search pageview_trends` — search is too focused+- `search pageview|[email protected]` — unrelated to tools-PostHog tools have lowercase kebab-case naming and always have a domain.-Available domains (the list is incomplete):+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:-- execute-sql-- read-data-schema-- action-- cohorts- dashboard-- insight+- execute-sql- feature-flag-- experiment-- survey-- error-tracking-- logs-- workflows-- organization-- projects-- docs-- llmTypical action names: list/retrieve/get/create/update/delete/query.-Example regex for search: execute-sql or experiment.+Example tool names: execute-sql, experiment-create, feature-flag-get-all.++### Retrieving data++**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.++Reach for `execute-sql` only when no `query-*` tool can express the question:-(`agent-feedback` is not a domain — it's a single standalone tool, see "Sharing feedback on this MCP server" above. It may not be available for all clients.)+- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.+- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.+- Pre-filtering or shaping data before running a `query-*` call.-{defined_groups}+When you do use `execute-sql`, run `info execute-sql` first to load its full guidance.-{metadata}+#### Searching for existing entities-{guidelines}+Any "find / which / do we have / what's our X chart" question about PostHog-created entities is a SQL search against `system.*`, **not** a `*-list` walk. The list tools paginate over the entire team; SQL with ILIKE/FTS returns the matches in one call.-### Querying data with insight schemas+Map intent to table:-PostHog provides two ways to query data:+- "find an insight" / "what's our X chart" / "is this insight saved" → `system.insights`+- "find a dashboard" → `system.dashboards`+- "find a cohort" → `system.cohorts`+- "find a feature flag" → `system.feature_flags`+- "find an experiment" → `system.experiments`+- "find a survey" → `system.surveys`+- "find a notebook" → `system.notebooks`-- **Insight query tools** (`query-trends`, `query-funnel`, etc.) produce typed, visual insights that can be saved to dashboards. Use these for any analytics question that maps to a supported insight type — count of events, comparisons, ratios, percentages, averages, retention, funnels, etc.-- **Raw SQL** (`execute-sql`) is the escape hatch — use it only when no `query-*` tool can express the question (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins, pre-filtering before a `query-*` call).+Search rules:-Always use a `query-*` tool if the question maps to one. Default to `query-*`.+1. **One query, multiple columns.** Combine `name ILIKE '%term%' OR description ILIKE '%term%'` rather than running separate queries.+2. **Filter `NOT deleted`** — every `system.*` table has soft-deletes.+3. **Order by recency** (`last_modified_at DESC` or `created_at DESC`) and `LIMIT 20-50` so the most relevant rows surface first.+4. **Verify the match with the entity's retrieve tool, not another SELECT.** Once SQL narrows to one or a few candidates, call the per-entity retrieve tool with the candidate's ID — for example `insight-get`, `dashboard-get`, `experiment-get`, `survey-get`, or `cohorts-retrieve` / `error-tracking-issues-retrieve`. Naming is inconsistent across entities; if the bare `<entity>-get` doesn't exist, run `search <entity>` and pick the read-shaped tool. **Do not run a second `execute-sql` to fetch the full row by ID.** The retrieve tool returns the authoritative entity shape (dashboards, query, ownership, last-viewed, etc.) in one call; re-querying via SQL costs an extra round-trip and only sees the columns exposed on the `system.*` table.+5. **Fallback to list tools.** If the entity has no `system.*` table (e.g. workflows, error-tracking issues, log views), or if SQL returns nothing after broadening the ILIKE pattern, fall back to the entity's `*-list` tool. SQL is the fast path; list tools are the floor.++<example>+User: Do we have any insights tracking revenue?+Assistant: [Runs `posthog:exec({ "command": "call execute-sql {\"query\":\"SELECT id, short_id, name, description, last_modified_at FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR description ILIKE '%revenue%') ORDER BY last_modified_at DESC LIMIT 20\"}" })`]+[Picks the most plausible match by name, then runs `posthog:exec({ "command": "call insight-get {\"id\": <id>}" })` (or pass the `short_id`) to verify the query, dashboards it's on, and last-viewed timestamp before reporting back to the user.]+<reasoning>SQL surfaces candidates fast; `insight-get` confirms the authoritative shape in one call — re-running `execute-sql ... WHERE id = <id>` would skip the dedicated tool and miss dashboards/ownership joins.</reasoning>+</example>++<bad-example>+User: Find me a graph of MAUs.+Assistant: [Runs `call execute-sql {"query":"SELECT * FROM system.insights WHERE id = 33800 LIMIT 1"}` after a search SELECT already surfaced id 33800]+WRONG — verify with `call insight-get {"id": 33800}` instead. Re-querying `system.insights` by ID is a SELECT that doesn't surface dashboard membership, last-viewed, or other relational data the retrieve tool joins for you.+</bad-example>#### Available insight query tools-{query_tools}+- `query-funnel` — conversion rate+- `query-trends` — time series#### Choosing the right query tool@@ -118,7 +137,7 @@ 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 previous period and sample data.+- Compare with the current period with previous.- Apply various aggregation types, like sum, average, etc., and chart types.- And more.@@ -167,16 +186,22 @@ Examples of use cases include:- 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.+#### Schema-first workflow-Before constructing any insight query, always verify the data schema:+Verify the data schema before constructing any insight query. Canonical-looking events+(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,+renamed, or filtered per team.-1. **Discover events** - Use `read-data-schema` with `kind: events` to find available events matching the user's intent.-2. **Discover properties** - Use `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`) to find relevant property names.-3. **Verify property values** - Use `read-data-schema` with `kind: event_property_values` to confirm that property values match expectations (e.g., "US" vs "United States").-4. **Only then construct the query** - Once you've confirmed the data exists, choose the appropriate `query-*` tool and build the schema.+1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.+2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).+3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., "US" vs "United States").+4. **Then construct the query** using the appropriate `query-*` tool.-If the required events or properties do not exist, inform the user immediately instead of running queries that will return empty results.+If the required events or properties don't exist, tell the user instead of running an empty query.#### Insight query workflow@@ -188,13 +213,11 @@ If the required events or properties do not exist, inform the user immediately iFor 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.-### Session replay enrichment--Session recordings provide visual context for errors and user behavior. When investigating issues, look for associated recordings:+Defined group types: organization, project-- If you have a **session recording ID** (from `$session_id` in event properties, or from other tool results), call `session-recording-get` with that ID. If the recording exists, present it to the user. A 404 means the session was not recorded.-- If you have a **person or distinct_id** but no session ID, use `query-session-recordings-list` to find recordings filtered by person UUID or properties.-- For **error tracking issues**, the issue itself does not include session IDs. To find related recordings, use `query-session-recordings-list` with an event filter for `$exception` matching the error. If a specific person is involved, also filter by `person_uuid` to see all their sessions. If no person context is available, filter by `$exception` alone to find all sessions with that error. Use `date_from` to match the issue's time range — e.g., if the error was first seen 10 days ago, set `date_from` accordingly so recordings from that period are included.+You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).+Project timezone: America/New_York.+The user's name is Jane Doe ([email protected]).### URL patterns@@ -207,6 +230,25 @@ Key URL patterns:- Data management: `/data-management/events`, `/data-management/properties`- Billing: `/organization/billing`+### Sharing feedback on this MCP server (optional)++The `agent-feedback` tool may be available if you'd like to leave optional feedback about this MCP server. It is the primary signal we use to improve tool descriptions, input schemas, response formats, and these instructions for agents like you. Use it when something stands out — but only when you have something specific to say. There is no expectation to call it after every task; skip it for routine work where nothing is worth flagging.++Good moments to consider it:++- A tool description was unclear or ambiguous and you had to guess.+- An input schema was confusing or surprising.+- A response format was hard to consume or contained too much / too little data.+- A tool returned wrong, incomplete, or unexpected results.+- An error message was unhelpful or didn't explain how to recover.+- A capability was missing entirely and you had to work around it.+- These instructions led you down the wrong path.+- A tool worked particularly well — concrete praise is just as useful as criticism.++If you do submit, be specific: quote tool names, parameter names, and error text where possible. Use `task_completed: false` when you couldn't finish the user's request — that signal is at least as valuable as success. Do not include user PII or sensitive query content in any feedback field.++Submitting feedback is **not** a way to end your turn or skip work. It is a side report to the PostHog team about your experience with the tools — after calling it, keep going and finish the user's task using the other available tools.+### ExamplesBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.@@ -255,9 +297,9 @@ Assistant: I'll help you analyze the reasons why the metrics have changed. Let m<example>User: Generate a revenue dashboard.Assistant: I'll help you create a revenue dashboard. Let me plan the steps.-1. List existing dashboards to check if one already covers revenue (the `dashboard-list` tool)-2. List saved insights related to revenue (`execute_sql(SELECT * FROM system.insights...)`)-3. Validate promising insights by reading their query schemas (the `insight-retrieve` tool)+1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)+2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)+3. Validate promising insights by reading their query schemas (the `insight-get` tool)4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)@@ -269,22 +311,4 @@ Assistant: I'll help you create a revenue dashboard. Let me plan the steps.3. Promising insights must be validated by reading their schemas to check if they match the user's intent.4. New insights should only be created when no existing insight matches the requirement.</reasoning>-</example>--#### Searching for existing data with SQL--<example>-User: Do we have any insights tracking revenue or payments?-Assistant: I'll search for existing insights related to revenue and payments using SQL.-1. Search insights by name for revenue-related terms (`execute-sql` with `SELECT id, name, short_id, description FROM system.insights WHERE NOT deleted AND (name ILIKE '%revenue%' OR name ILIKE '%payment%') ORDER BY last_modified_at DESC LIMIT 20`)-2. If results are sparse, broaden the search to dashboards (`execute-sql` with `SELECT id, name, description FROM system.dashboards WHERE NOT deleted AND (name ILIKE '%revenue%' OR name ILIKE '%payment%')`)-3. Validate promising insights by retrieving their full details (the `insight-retrieve` tool)-4. Summarize findings with links to relevant insights and dashboards-*Begins working on the first task*-<reasoning>-1. SQL search against system tables is the fastest way to discover existing data across the project.-2. Using ILIKE with multiple terms catches different naming conventions (e.g., "Monthly Revenue", "Payment Events", "MRR").-3. Searching both insights and dashboards gives a complete picture of what already exists.-4. Validating with the retrieve tool confirms the insights are still relevant and shows their query configuration.-</reasoning>-</example>+</example>\ No newline at end of filediff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-v1-instructions-with-metadata.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-v1-instructions-with-metadata.txtnew file mode 100644index 000000000000..6d4c977d5576--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-v1-instructions-with-metadata.txt@@ -0,0 +1,8 @@+- You are a helpful assistant that can query PostHog API.+- If 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.+- If 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.+- The `agent-feedback` tool is available if you'd like to leave optional feedback about this MCP server (unclear tool descriptions, surprising schemas, missing capabilities, unhelpful errors, or things that worked well). It is entirely optional — skip it for routine tasks where nothing stood out. When you do use it, be specific and do not include user PII or sensitive query content. Submitting feedback is not a way to end your turn: keep working on the user's task afterward using the other available tools.++You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).+Project timezone: America/New_York.+The user's name is Jane Doe ([email protected]).\ No newline at end of filediff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-v1-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-v1-instructions.txtnew file mode 100644index 000000000000..6344488d9116--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-v1-instructions.txt@@ -0,0 +1,4 @@+- You are a helpful assistant that can query PostHog API.+- If 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.+- If 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.+- The `agent-feedback` tool is available if you'd like to leave optional feedback about this MCP server (unclear tool descriptions, surprising schemas, missing capabilities, unhelpful errors, or things that worked well). It is entirely optional — skip it for routine tasks where nothing stood out. When you do use it, be specific and do not include user PII or sensitive query content. Submitting feedback is not a way to end your turn: keep working on the user's task afterward using the other available tools.\ No newline at end of filediff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex ed1133747c37..9c35c1b44347 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -6,10 +6,8 @@ import { describe, expect, it } from 'vitest'import { parse as parseYaml } from 'yaml'import { z } from 'zod'-import { buildInstructionsV2 } from '@/lib/instructions'+import { InstructionsFormatter } from '@/lib/instructions-formatter'import { SessionManager } from '@/lib/SessionManager'-import CLI_PROXY_COMMAND from '@/templates/cli-proxy-command.md'-import CLI_PROXY_TOOL from '@/templates/cli-proxy-tool.md'import { getToolsFromContext } from '@/tools'import { createExecTool, type ExecInnerCallProperties } from '@/tools/exec'import { getToolDefinition } from '@/tools/toolDefinitions'@@ -311,23 +309,26 @@ describe('exec tool', () => {...(def.system_prompt_hint ? { systemPromptHint: def.system_prompt_hint } : {}),}})- const commandReference = buildInstructionsV2(- CLI_PROXY_COMMAND,- guidelines,- undefined,- undefined,- toolInfos,- queryToolInfos+ const formatter = new InstructionsFormatter()+ const commandReference = formatter.buildExecCommandReference(+ { guidelines, tools: toolInfos, queryTools: queryToolInfos },+ { stripEnvContext: false }+ )+ const execTool = createExecTool(+ v2Tools,+ context,+ formatter.buildExecToolDescription(),+ commandReference,+ undefined)- const execTool = createExecTool(v2Tools, context, CLI_PROXY_TOOL, commandReference, undefined)expect(execTool.description.length).toBeLessThanOrEqual(2048)})// Snapshots the full exec tool definition built from the real v2 tool set:- // description (CLI_PROXY_TOOL), annotations, and input schema including the- // `command` field description — which embeds the generated `tool_domains`- // block. Because `buildToolDomainsBlock` relies on tool-name conventions+ // description (the `exec-tool-blurb` subprompt), annotations, and input schema+ // including the `command` field description — which embeds the generated+ // `tool_domains` block. Because `buildToolDomainsBlock` relies on tool-name conventions// (CRUD suffixes, prefix actions, plural collapsing), this snapshot is the// canary for any drift in naming or in the domain-extraction logic.//@@ -354,15 +355,18 @@ describe('exec tool', () => {...(def.system_prompt_hint ? { systemPromptHint: def.system_prompt_hint } : {}),}})- const commandReference = buildInstructionsV2(- CLI_PROXY_COMMAND,- guidelines,- undefined,- undefined,- toolInfos,- queryToolInfos+ const formatter = new InstructionsFormatter()+ const commandReference = formatter.buildExecCommandReference(+ { guidelines, tools: toolInfos, queryTools: queryToolInfos },+ { stripEnvContext: false }+ )+ const execTool = createExecTool(+ v2Tools,+ context,+ formatter.buildExecToolDescription(),+ commandReference,+ undefined)- const execTool = createExecTool(v2Tools, context, CLI_PROXY_TOOL, commandReference, undefined)const snapshot = {name: execTool.name,diff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.tsnew file mode 100644index 000000000000..0a465e0af260--- /dev/null+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts@@ -0,0 +1,96 @@+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { describe, expect, it } from 'vitest'++import type { GroupType } from '@/api/client'+import type { QueryToolInfo } from '@/lib/instructions'+import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructions-formatter'++// Static, deterministic context shared by all snapshots — mirrors the realistic+// values used in `instructions-formatter.test.ts` so the rendered prompts cover+// guidelines, group types, metadata, tool domains, and query tools.+const STATIC_GROUP_TYPES: GroupType[] = [+ { group_type: 'organization', group_type_index: 0, name_singular: null, name_plural: null },+ { group_type: 'project', group_type_index: 1, name_singular: null, name_plural: null },+]+const STATIC_TOOLS = [+ { name: 'dashboard-create', category: 'Dashboards' },+ { name: 'dashboard-get', category: 'Dashboards' },+ { name: 'feature-flag-create', category: 'Feature flags' },+ { name: 'feature-flag-get-all', category: 'Feature flags' },+ { name: 'execute-sql', category: 'SQL' },+]+const STATIC_QUERY_TOOLS: QueryToolInfo[] = [+ { name: 'query-funnel', title: 'Funnel', systemPromptHint: 'conversion rate' },+ { name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' },+]+const STATIC_METADATA = [+ 'You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).',+ 'Project timezone: America/New_York.',+ "The user's name is Jane Doe ([email protected]).",+].join('\n')++const STATIC_CTX: InstructionsContext = {+ guidelines: 'some guidelines',+ groupTypes: STATIC_GROUP_TYPES,+ metadata: STATIC_METADATA,+ tools: STATIC_TOOLS,+ queryTools: STATIC_QUERY_TOOLS,+ featureFlags: { 'mcp-feedback-tool': true },+}++const __dirname = path.dirname(fileURLToPath(import.meta.url))+const SNAPSHOT_DIR = path.resolve(__dirname, '__snapshots__', 'instructions')++// The rendered prompt is markdown-flavored text but the snapshot file uses `.txt`+// to opt out of the repo-wide `*.md` lint-staged formatter (see top-level+// package.json). Otherwise the markdown formatter would reflow the snapshot on+// commit and drift from what `formatPrompt` produces, breaking the test.+describe('InstructionsFormatter prompt snapshots', () => {+ it('matches the v1 (legacy) prompt', async () => {+ const formatter = new InstructionsFormatter()+ const rendered = formatter.buildV1Instructions()+ await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'tools-v1-instructions.txt'))+ })++ it('matches the v1 (legacy) prompt with metadata appended', async () => {+ const formatter = new InstructionsFormatter()+ const rendered = formatter.buildV1Instructions(STATIC_METADATA)+ await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'tools-v1-instructions-with-metadata.txt'))+ })++ it('matches the v2 (tools-mode) prompt', async () => {+ const formatter = new InstructionsFormatter()+ const rendered = formatter.buildV2Instructions(STATIC_CTX)+ await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'tools-instructions.txt'))+ })++ // The exec mode prompt is composed of three pieces wired into different MCP+ // fields (see `src/mcp.ts` and `buildExecCommandReference` for the split):+ // - `exec-instructions` — the compact `instructions` payload (only sent+ // to clients that honor MCP `instructions`,+ // e.g. Claude Code; Codex gets an empty string)+ // - `exec-tool-description` — the top-level description of the `posthog`+ // tool itself+ // - `exec-command-reference-full` — the `command` parameter description+ // with every placeholder filled (Codex wiring;+ // no `instructions` support, so env context,+ // tool domains, and query tools are inlined here)+ it('matches the exec mode compact instructions prompt', async () => {+ const formatter = new InstructionsFormatter()+ const rendered = formatter.buildExecInstructions(STATIC_CTX)+ await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'exec-instructions.txt'))+ })++ it('matches the exec tool description blurb', async () => {+ const formatter = new InstructionsFormatter()+ const rendered = formatter.buildExecToolDescription()+ await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'exec-tool-description.txt'))+ })++ it('matches the exec command reference (Codex wiring, every placeholder filled)', async () => {+ const formatter = new InstructionsFormatter()+ const rendered = formatter.buildExecCommandReference(STATIC_CTX, { stripEnvContext: false })+ await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'exec-command-reference-full.txt'))+ })+})diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.tsnew file mode 100644index 000000000000..a96048134b81--- /dev/null+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -0,0 +1,262 @@+import { describe, expect, it } from 'vitest'++import type { GroupType } from '@/api/client'+import type { QueryToolInfo } from '@/lib/instructions'+import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructions-formatter'++const realisticGroupTypes: GroupType[] = [+ { group_type: 'organization', group_type_index: 0, name_singular: null, name_plural: null },+]+const realisticTools = [+ { name: 'dashboard-create', category: 'Dashboards' },+ { name: 'dashboard-get', category: 'Dashboards' },+ { name: 'feature-flag-create', category: 'Feature flags' },+ { name: 'feature-flag-get-all', category: 'Feature flags' },+ { name: 'execute-sql', category: 'SQL' },+]+const realisticQueryTools: QueryToolInfo[] = [+ { name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' },+ { name: 'query-funnel', title: 'Funnel', systemPromptHint: 'conversion rate' },+]+const realisticMetadata =+ 'You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).\n' ++ 'Project timezone: America/New_York.\n' ++ "The user's name is Jane Doe ([email protected])."++const fullCtx: InstructionsContext = {+ guidelines: 'some guidelines',+ groupTypes: realisticGroupTypes,+ metadata: realisticMetadata,+ tools: realisticTools,+ queryTools: realisticQueryTools,+ featureFlags: { 'mcp-feedback-tool': true },+}++describe('InstructionsFormatter', () => {+ describe('buildV1Instructions', () => {+ it('returns the legacy section content when no metadata is supplied', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildV1Instructions()+ expect(result).toContain('helpful assistant that can query PostHog API')+ expect(result).toContain("'docs-search' tool")+ })++ it('appends metadata to the legacy section when provided', () => {+ const formatter = new InstructionsFormatter()+ const metadata = 'You are currently in project "Test".'+ const result = formatter.buildV1Instructions(metadata)+ expect(result).toContain('helpful assistant that can query PostHog API')+ expect(result).toContain('You are currently in project "Test".')+ const legacyIdx = result.indexOf('helpful assistant')+ const metaIdx = result.indexOf('You are currently')+ expect(legacyIdx).toBeLessThan(metaIdx)+ })++ it('treats an empty metadata string as no metadata', () => {+ const formatter = new InstructionsFormatter()+ expect(formatter.buildV1Instructions('')).toBe(formatter.buildV1Instructions())+ })+ })++ describe('buildV2Instructions', () => {+ it('resolves every placeholder when fully populated', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildV2Instructions(fullCtx)+ expect(result).toContain('Defined group types: organization')+ expect(result).toContain("The user's name is Jane Doe")+ expect(result).toContain('Project timezone: America/New_York.')+ expect(result).toContain('- dashboard')+ expect(result).toContain('- feature-flag')+ expect(result).toContain('- execute-sql')+ expect(result).toContain('- `query-funnel` — conversion rate')+ expect(result).toContain('- `query-trends` — time series')+ expect(result).not.toMatch(+ /\{tool_domains\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/+ )+ })++ it('renders the basic functionality, retrieving data, and examples sections', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildV2Instructions(fullCtx)+ expect(result).toContain('### Basic functionality')+ expect(result).toContain('### Retrieving data')+ expect(result).toContain('### Examples')+ })++ it('does not leak any CLI-only sections (tools mode is not exec mode)', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildV2Instructions(fullCtx)+ expect(result).not.toContain('SCHEMA DRILL-DOWN RULE')+ expect(result).not.toContain('Using the `posthog` tool')+ expect(result).not.toContain('CLI-style command string')+ })++ it('omits placeholders cleanly when context fields are undefined', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildV2Instructions({ guidelines: 'rules' })+ expect(result).not.toContain('{guidelines}')+ expect(result).not.toContain('{defined_groups}')+ expect(result).not.toContain('{tool_domains}')+ expect(result).not.toContain('{query_tools}')+ expect(result).not.toContain('{metadata}')+ })++ it('includes the agent-feedback section only when the mcp-feedback-tool flag is on', () => {+ const formatter = new InstructionsFormatter()+ const withFeedback = formatter.buildV2Instructions(fullCtx)+ expect(withFeedback).toContain('### Sharing feedback on this MCP server')++ for (const featureFlags of [undefined, { 'mcp-feedback-tool': false }, {}]) {+ const result = formatter.buildV2Instructions({ ...fullCtx, featureFlags })+ expect(result).not.toContain('### Sharing feedback on this MCP server')+ }+ })+ })++ describe('buildExecInstructions', () => {+ it('renders the compact instructions section with placeholders resolved', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildExecInstructions(fullCtx)+ expect(result).toContain('dashboard|execute-sql|feature-flag')+ expect(result).toContain('funnel|trends')+ expect(result).toContain('Defined group types: organization')+ expect(result).toContain("The user's name is Jane Doe")+ expect(result).not.toMatch(+ /\{tool_domains\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/+ )+ })++ // Claude Code caps MCP `instructions` at 2048 chars — stay under the budget with+ // a realistic-ish tool count so this asserts something meaningful. 60 domains ++ // 12 query tools ≈ today's v2 deployment.+ it('stays under the 2048-character budget at realistic tool counts', () => {+ const manyTools = Array.from({ length: 60 }, (_, i) => ({+ name: `domain-${i}-get`,+ category: `Category ${i % 6}`,+ }))+ const manyQueryTools: QueryToolInfo[] = Array.from({ length: 12 }, (_, i) => ({+ name: `query-tool-${i}`,+ title: `Query tool ${i}`,+ systemPromptHint: `short hint for query tool ${i}`,+ }))+ const formatter = new InstructionsFormatter()+ const result = formatter.buildExecInstructions({+ guidelines: 'guidelines',+ groupTypes: realisticGroupTypes,+ metadata: realisticMetadata,+ tools: manyTools,+ queryTools: manyQueryTools,+ })+ expect(result.length).toBeLessThanOrEqual(2048)+ })++ it('does not bleed the full command reference into the compact instructions', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildExecInstructions(fullCtx)+ expect(result).not.toContain('SCHEMA DRILL-DOWN RULE')+ expect(result).not.toContain('### Basic functionality')+ expect(result).not.toContain('### Examples')+ })+ })++ describe('buildExecToolDescription', () => {+ it('renders just the exec tool blurb, no other sections', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildExecToolDescription()+ expect(result).toContain('Using the `posthog` tool')+ expect(result).toContain('MANDATORY — HARD REQUIREMENTS')+ expect(result).not.toContain('### Basic functionality')+ expect(result).not.toContain('### Examples')+ })+ })++ describe('buildExecCommandReference', () => {+ it('carries the CLI mechanics regardless of stripEnvContext', () => {+ const formatter = new InstructionsFormatter()+ for (const stripEnvContext of [true, false]) {+ const result = formatter.buildExecCommandReference(fullCtx, { stripEnvContext })+ expect(result).toContain('SCHEMA DRILL-DOWN RULE')+ expect(result).toContain('### Basic functionality')+ expect(result).toContain('### Examples')+ }+ })++ it('does not include the exec-tool blurb (that lives on the tool description)', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: false })+ expect(result).not.toContain('Using the `posthog` tool')+ })++ it('embeds env-context, tool-domain list, and query-tool catalog when stripEnvContext is false', () => {+ const formatter = new 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')+ expect(result).toContain('- `query-trends` — time series')+ })++ it('strips env-context, tool-domain list, and query-tool catalog when stripEnvContext is true', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: true })+ expect(result).not.toContain("The user's name is Jane Doe")+ expect(result).not.toContain('Defined group types: organization')+ expect(result).not.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')+ })++ it('includes the agent-feedback section only when the mcp-feedback-tool flag is on', () => {+ const formatter = new InstructionsFormatter()+ for (const stripEnvContext of [true, false]) {+ const withFeedback = formatter.buildExecCommandReference(fullCtx, { stripEnvContext })+ expect(withFeedback).toContain('### Sharing feedback on this MCP server')++ const withoutFeedback = formatter.buildExecCommandReference(+ { ...fullCtx, featureFlags: { 'mcp-feedback-tool': false } },+ { stripEnvContext }+ )+ expect(withoutFeedback).not.toContain('### Sharing feedback on this MCP server')+ }+ })+ })++ // Mirrors the single-exec wiring in `src/mcp.ts`. When the client honors the MCP+ // `instructions` field, four pieces move out of the `command` description and into+ // `instructions`: tool domains, available query tools, user preferences (timezone/name+ // via `{metadata}`), and defined group types. Codex (no `instructions` support) keeps+ // today's behavior: empty `instructions`, everything inlined in the `command` description.+ describe('exec mode wiring', () => {+ it.each([+ { name: 'supportsInstructions=true (Claude Code etc.)', supportsInstructions: true },+ { name: 'supportsInstructions=false (Codex)', supportsInstructions: false },+ ])('$name: splits product context between instructions and commandReference', ({ supportsInstructions }) => {+ const formatter = new InstructionsFormatter()+ const instructions = supportsInstructions ? formatter.buildExecInstructions(fullCtx) : ''+ const commandReference = formatter.buildExecCommandReference(fullCtx, {+ stripEnvContext: supportsInstructions,+ })++ expect(commandReference).toContain('SCHEMA DRILL-DOWN RULE')+ expect(commandReference).toContain('### Basic functionality')++ if (supportsInstructions) {+ expect(instructions).toContain('funnel|trends')+ expect(instructions).toContain("The user's name is Jane Doe")+ expect(instructions).toContain('dashboard|execute-sql|feature-flag')+ 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('- `query-trends` — time series')+ expect(commandReference).not.toContain('\n- dashboard\n')+ } 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('Defined group types: organization')+ }+ })+ })+})diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.tsindex ca7d41dee34d..0b5757739f2f 100644--- a/services/mcp/tests/unit/instructions.test.ts+++ b/services/mcp/tests/unit/instructions.test.ts@@ -3,7 +3,6 @@ import { describe, expect, it } from 'vitest'import type { GroupType } from '@/api/client'import {buildDefinedGroupsBlock,- buildInstructionsV2,buildQueryToolsBlock,buildQueryToolsCompact,buildToolDomainsBlock,@@ -11,26 +10,6 @@ import {QueryToolCatalog,type QueryToolInfo,} from '@/lib/instructions'-import CLI_PROXY_COMMAND from '@/templates/cli-proxy-command.md'-import SINGLE_EXEC_INSTRUCTIONS from '@/templates/single-exec-instructions.md'--const MOCK_TEMPLATE = `{metadata}--### Basic functionality-Some instructions here.--{guidelines}--{tool_domains}--### Query tools--{query_tools}--### Examples-Some examples here.--Defined group types: {defined_groups}`describe('buildDefinedGroupsBlock', () => {it('should format group types as a comma-separated list of group_type names', () => {@@ -240,225 +219,3 @@ describe('QueryToolCatalog', () => {})})})--describe('buildInstructionsV2', () => {- it('should replace all placeholders', () => {- const groupTypes: GroupType[] = [- {- group_type: 'organization',- group_type_index: 0,- name_singular: 'Organization',- name_plural: 'Organizations',- },- { group_type: 'instance', group_type_index: 1, name_singular: null, name_plural: null },- ]- const tools = [- { name: 'dashboard-create', category: 'Dashboards' },- { name: 'dashboard-get', category: 'Dashboards' },- { name: 'action-create', category: 'Actions' },- { name: 'action-get', category: 'Actions' },- ]- const queryTools: QueryToolInfo[] = [{ name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' }]- const result = buildInstructionsV2(- MOCK_TEMPLATE,- ' some guidelines ',- groupTypes,- undefined,- tools,- queryTools- )- expect(result).toContain('some guidelines')- expect(result).toContain('Defined group types: organization, instance')- expect(result).toContain('- action\n- dashboard')- expect(result).toContain('- `query-trends` — time series')- expect(result).not.toContain('{guidelines}')- expect(result).not.toContain('{defined_groups}')- expect(result).not.toContain('{tool_domains}')- expect(result).not.toContain('{query_tools}')- })-- it('should substitute {query_tools} while leaving other placeholders intact', () => {- const template = 'Domains: {tool_domains}\nQuery tools:\n{query_tools}\nGuidelines: {guidelines}'- const queryTools: QueryToolInfo[] = [{ name: 'query-funnel', title: 'Funnel', systemPromptHint: 'conversion' }]- const result = buildInstructionsV2(template, 'rules', undefined, undefined, [], queryTools)- expect(result).toContain('Query tools:\n- `query-funnel` — conversion')- expect(result).toContain('Guidelines: rules')- })-- it('should leave {query_tools} placeholder blank when queryTools is undefined', () => {- const template = 'before\n{query_tools}\nafter'- const result = buildInstructionsV2(template, 'rules')- expect(result).not.toContain('{query_tools}')- expect(result).toContain('before')- expect(result).toContain('after')- })-- it('should leave no placeholders when no group types or tools', () => {- const result = buildInstructionsV2(MOCK_TEMPLATE, 'guidelines', undefined)- expect(result).not.toContain('{guidelines}')- expect(result).not.toContain('{defined_groups}')- expect(result).not.toContain('{tool_domains}')- expect(result).not.toContain('{query_tools}')- })-- it('should trim guidelines whitespace', () => {- const result = buildInstructionsV2(MOCK_TEMPLATE, ' padded ', undefined)- expect(result).toContain('padded')- expect(result).not.toContain(' padded ')- })-- it('should inject metadata into the template', () => {- const metadata =- 'You are currently in project "My App" (organization: "Acme Corp").\nThe user\'s name is Jane Doe ([email protected]).\nProject timezone: America/New_York.'- const result = buildInstructionsV2(MOCK_TEMPLATE, 'guidelines', undefined, metadata)- expect(result).toContain('You are currently in project "My App" (organization: "Acme Corp").')- expect(result).toContain("The user's name is Jane Doe ([email protected]).")- expect(result).toContain('Project timezone: America/New_York.')- expect(result).not.toContain('{metadata}')- })-- it('should place metadata before the basic functionality section', () => {- const metadata = 'Project: Test'- const result = buildInstructionsV2(MOCK_TEMPLATE, 'guidelines', undefined, metadata)- const metadataIndex = result.indexOf('Project: Test')- const basicIndex = result.indexOf('### Basic functionality')- expect(metadataIndex).toBeLessThan(basicIndex)- })-- it('should leave no placeholder when metadata is undefined', () => {- const result = buildInstructionsV2(MOCK_TEMPLATE, 'guidelines', undefined, undefined)- expect(result).not.toContain('{metadata}')- })-- it('should trim metadata whitespace', () => {- const result = buildInstructionsV2(MOCK_TEMPLATE, 'guidelines', undefined, ' padded metadata ')- expect(result).toContain('padded metadata')- expect(result).not.toContain(' padded metadata ')- })-})--// Mirrors the single-exec wiring in `src/mcp.ts`. When the client honors the MCP-// `instructions` field, four pieces move out of the `command` description and into-// `instructions`: exec-tool blurb, tool domains, available query tools, user preferences-// (timezone/name via `{metadata}`), and defined group types. Codex (no `instructions`-// support) keeps today's behavior: empty `instructions`, everything inlined.-describe('single-exec templates', () => {- const realisticGroupTypes: GroupType[] = [- { group_type: 'organization', group_type_index: 0, name_singular: null, name_plural: null },- ]- const realisticTools = [- { name: 'dashboard-create', category: 'Dashboards' },- { name: 'dashboard-get', category: 'Dashboards' },- { name: 'feature-flag-create', category: 'Feature flags' },- { name: 'feature-flag-get-all', category: 'Feature flags' },- { name: 'execute-sql', category: 'SQL' },- ]- const realisticQueryTools: QueryToolInfo[] = [- { name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' },- { name: 'query-funnel', title: 'Funnel', systemPromptHint: 'conversion rate' },- ]- const realisticMetadata =- 'You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).\n' +- 'Project timezone: America/New_York.\n' +- "The user's name is Jane Doe ([email protected])."-- it('single-exec instructions template resolves every placeholder when fully populated', () => {- const rendered = buildInstructionsV2(- SINGLE_EXEC_INSTRUCTIONS,- 'some guidelines',- realisticGroupTypes,- realisticMetadata,- realisticTools,- realisticQueryTools,- { compact: true }- )-- expect(rendered).toContain('dashboard|execute-sql|feature-flag')- expect(rendered).toContain('funnel|trends')- expect(rendered).toContain('Defined group types: organization')- expect(rendered).toContain("The user's name is Jane Doe ([email protected]).")- expect(rendered).toContain('Project timezone: America/New_York.')- expect(rendered).not.toMatch(/\{tool_domains\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/)- })-- // Claude Code caps MCP `instructions` at 2048 chars — stay under the budget with- // a realistic-ish tool count so this asserts something meaningful. 60 domains +- // 12 query tools ≈ today's v2 deployment.- it('rendered single-exec instructions stay under the 2048-character budget', () => {- const manyTools = Array.from({ length: 60 }, (_, i) => ({- name: `domain-${i}-get`,- category: `Category ${i % 6}`,- }))- const manyQueryTools: QueryToolInfo[] = Array.from({ length: 12 }, (_, i) => ({- name: `query-tool-${i}`,- title: `Query tool ${i}`,- systemPromptHint: `short hint for query tool ${i}`,- }))- const rendered = buildInstructionsV2(- SINGLE_EXEC_INSTRUCTIONS,- 'guidelines',- realisticGroupTypes,- realisticMetadata,- manyTools,- manyQueryTools,- { compact: true }- )- expect(rendered.length).toBeLessThanOrEqual(2048)- })-- // Parameterized over the `supportsInstructions` capability (the sole client-detection- // signal that drives this split), asserting the exec-tool content distribution invariant- // across both paths.- it.each([- { name: 'supportsInstructions=true (Claude Code etc.)', supportsInstructions: true },- { name: 'supportsInstructions=false (Codex)', supportsInstructions: false },- ])('$name: splits product context between `instructions` and `commandReference`', ({ supportsInstructions }) => {- const instructions = supportsInstructions- ? buildInstructionsV2(- SINGLE_EXEC_INSTRUCTIONS,- 'guidelines',- realisticGroupTypes,- realisticMetadata,- realisticTools,- realisticQueryTools,- { compact: true }- )- : ''- const commandReference = buildInstructionsV2(- CLI_PROXY_COMMAND,- 'guidelines',- supportsInstructions ? undefined : realisticGroupTypes,- supportsInstructions ? undefined : realisticMetadata,- supportsInstructions ? undefined : realisticTools,- supportsInstructions ? undefined : realisticQueryTools- )-- // The command reference always carries the mechanics (examples, drill-down- // rule, error handling) regardless of mode.- expect(commandReference).toContain('SCHEMA DRILL-DOWN RULE')- expect(commandReference).toContain('### Basic functionality')-- if (supportsInstructions) {- // Dynamic content lives in `instructions` (compact, pipe-separated)…- expect(instructions).toContain('funnel|trends')- expect(instructions).toContain("The user's name is Jane Doe")- expect(instructions).toContain('dashboard|execute-sql|feature-flag')- expect(instructions).toContain('Defined group types: organization')- // …and is stripped from the `command` parameter description.- expect(commandReference).not.toContain("The user's name is Jane Doe")- expect(commandReference).not.toContain('Defined group types: organization')- expect(commandReference).not.toContain('- `query-trends` — time series')- // The domain bullet for feature-flag would clash with the in-prose phrase,- // so pin on the list prefix with newline to avoid false positives.- expect(commandReference).not.toContain('\n- dashboard\n')- } else {- // Codex path: instructions empty, everything still inlined in `commandReference`- // using the markdown bullet rendering (cli-proxy-command.md keeps the verbose form).- 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('Defined group types: organization')- }- })-})