Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mcp): fit Claude exec schema within client limit (#70361)

Georgiy Tarasovff5c562367db
diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.ts
index c8771738db1e..bc6f5fbfb6c9 100644
--- a/services/mcp/src/hono/instructions.ts
+++ b/services/mcp/src/hono/instructions.ts
@@ -7,6 +7,7 @@ import { formatPrompt } from '@/lib/utils'
import { RENDER_UI_RESOURCE_URI } from '@/resources/ui-apps.generated'
import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'
import SCHEMA_DISCOVERY from '@/templates/sections/schema-discovery.md'
+import { ExecHelpCatalog } from '@/tools/exec-help'
import {
getRenderableToolNames,
makeRenderUiSchema,
@@ -109,12 +110,21 @@ export class InstructionsBuilder {
// un-stripped path.)
const keepEnvContext = state.clientProfile.isClaudeChatHost()
const ctx = this.buildContext(state)
+ if (keepEnvContext) {
+ return this.formatter.buildClaudeExecCommandReference(ctx)
+ }
return this.formatter.buildExecCommandReference(ctx, {
stripEnvContext: supportsInstructions,
- keepEnvContext,
})
}
+ buildExecHelpCatalog(state: ResolvedState): ExecHelpCatalog | undefined {
+ if (!state.clientProfile.isClaudeChatHost()) {
+ return undefined
+ }
+ return new ExecHelpCatalog(this.formatter.buildClaudeExecHelpEntries(this.buildContext(state)))
+ }
+
buildExecToolDescription(): string {
return this.formatter.buildExecToolDescription()
}
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index a457ba8cb45a..8c6711a00a10 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -411,7 +411,10 @@ export class ToolExecutor {
clientContext.mcpConsumer,
trackInnerCall,
state.scopeGatedTools,
- { isInlineExecUiHost: state.clientProfile.isInlineExecUiHost() }
+ {
+ isInlineExecUiHost: state.clientProfile.isInlineExecUiHost(),
+ helpCatalog: this.instructionsBuilder.buildExecHelpCatalog(state),
+ }
)
return {
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.ts
index 27ba23b55714..2d08464ce783 100644
--- a/services/mcp/src/lib/instructions-formatter.ts
+++ b/services/mcp/src/lib/instructions-formatter.ts
@@ -12,6 +12,7 @@ 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_CLAUDE from '@/templates/sections/cli-examples-claude.md'
import CLI_EXAMPLES from '@/templates/sections/cli-examples.md'
import CLI_RENDERING from '@/templates/sections/cli-rendering.md'
import CLI_SCHEMA_DRILLDOWN from '@/templates/sections/cli-schema-drilldown.md'
@@ -20,11 +21,13 @@ import COMPACT_INSTRUCTIONS from '@/templates/sections/compact-instructions.md'
import ENTITY_SCHEMA_DISCOVERY from '@/templates/sections/entity-schema-discovery.md'
import ENV_CONTEXT from '@/templates/sections/env-context.md'
import EXAMPLES from '@/templates/sections/examples.md'
+import EXEC_LEARN from '@/templates/sections/exec-learn.md'
import EXEC_TOOL_BLURB from '@/templates/sections/exec-tool-blurb.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'
+import type { ExecHelpEntry } from '@/tools/exec-help'
export interface InstructionsContext {
guidelines: string
@@ -75,6 +78,83 @@ export class InstructionsFormatter {
return EXEC_TOOL_BLURB.trim()
}
+ /**
+ * Build the optional guidance catalog used by Claude web/desktop. The
+ * existing prompt sections remain the source of truth; only their delivery
+ * moves from the advertised schema to `exec learn`.
+ */
+ buildClaudeExecHelpEntries(ctx: InstructionsContext): ExecHelpEntry[] {
+ const entries: ExecHelpEntry[] = [
+ {
+ id: 'analytics',
+ kind: 'guide',
+ title: 'Analytics',
+ description: 'Query or analyze PostHog data, metrics, and events.',
+ content: this.compose([RETRIEVING_DATA, SCHEMA_WORKFLOW, EXAMPLES], ctx, { compact: false }),
+ },
+ ]
+
+ if (ctx.renderUiEnabled) {
+ entries.push({
+ id: 'visualizations',
+ kind: 'guide',
+ title: 'Visualizations',
+ description: 'Create or render a visualization.',
+ content: this.compose([CLI_RENDERING], ctx, { compact: false }),
+ })
+ }
+
+ entries.push({
+ id: 'feedback',
+ kind: 'guide',
+ title: 'Feedback',
+ description: 'Send feedback about PostHog.',
+ content: this.compose([AGENT_FEEDBACK], ctx, { compact: false }),
+ })
+
+ return entries
+ }
+
+ /**
+ * claude.ai's registry silently drops a tool whose serialized `inputSchema`
+ * crosses ~16,384 chars. This reference lands in
+ * `inputSchema.properties.command.description`, so keep routine tool-use
+ * guidance inline and move only task-specific sections behind `learn <topic...>`.
+ * Enforced by the budget test in `instructions-formatter-snapshot.test.ts`.
+ */
+ buildClaudeExecCommandReference(ctx: InstructionsContext): string {
+ const helpEntries = this.buildClaudeExecHelpEntries(ctx)
+ const helpTopics = helpEntries.map((entry) => `- ${entry.id}: ${entry.description}`).join('\n')
+ const helpSection = formatPrompt(EXEC_LEARN, { help_topics: helpTopics })
+ const renderCtx: InstructionsContext = {
+ guidelines: ctx.guidelines,
+ metadata: ctx.metadata,
+ groupTypes: ctx.groupTypes,
+ tools: ctx.tools,
+ }
+
+ return this.compose(
+ [
+ CLI_SYNTAX,
+ helpSection,
+ CLI_SCHEMA_DRILLDOWN,
+ CLI_DATA_DISCOVERY,
+ CLI_EXAMPLES_CLAUDE,
+ CLI_ERROR_HANDLING,
+ BASIC_FUNCTIONALITY,
+ TOOL_SEARCH,
+ ENV_CONTEXT,
+ URL_PATTERNS,
+ ],
+ renderCtx,
+ {
+ compact: false,
+ compactToolDomains: true,
+ extraCommands: 'learn <topic...> - load one or more learning topics\n',
+ }
+ )
+ }
+
/** 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 (metadata, group
@@ -88,11 +168,8 @@ export class InstructionsFormatter {
* (project metadata, group types) here even though `stripEnvContext` is
* set, so it still reaches the agent.
*
- * SIZE BUDGET: the serialized exec tool entry must stay under 32,600 chars —
- * clients (e.g. Claude web/desktop) silently drop tools past ~32,768, which
- * breaks the entire MCP for them. Enforced by the budget test in
- * `tests/unit/instructions-formatter-snapshot.test.ts`; when adding prose
- * here or to the section templates, shrink elsewhere to stay under. */
+ * Claude web/desktop uses `buildClaudeExecCommandReference` instead because
+ * its complete JSON schema has a smaller client-enforced size budget. */
buildExecCommandReference(
ctx: InstructionsContext,
opts: { stripEnvContext: boolean; keepEnvContext?: boolean }
@@ -127,8 +204,13 @@ export class InstructionsFormatter {
return this.compose(sections, renderCtx, { compact: false })
}
- private compose(sections: string[], ctx: InstructionsContext, opts: { compact: boolean }): string {
- const renderToolDomains = opts.compact ? buildToolDomainsCompact : buildToolDomainsBlock
+ private compose(
+ sections: string[],
+ ctx: InstructionsContext,
+ opts: { compact: boolean; compactToolDomains?: boolean; extraCommands?: string }
+ ): string {
+ const renderToolDomains =
+ opts.compact || opts.compactToolDomains ? buildToolDomainsCompact : buildToolDomainsBlock
// `{query_tools}` only appears in non-compact sections (the exec command
// reference and tools-mode instructions); compact mode surfaces queries
// via the single `query` tool domain instead.
@@ -139,6 +221,7 @@ export class InstructionsFormatter {
tool_domains: ctx.tools ? renderToolDomains(ctx.tools) : '',
query_tools: ctx.queryTools ? buildQueryToolsBlock(ctx.queryTools) : '',
entity_schema_discovery: ENTITY_SCHEMA_DISCOVERY.trim(),
+ extra_commands: opts.extraCommands ?? '',
}
const body = sections
.map((s) => s.trim())
diff --git a/services/mcp/src/templates/render-ui-prompt.md b/services/mcp/src/templates/render-ui-prompt.md
index f9b3fe1f92da..adc4d72a1753 100644
--- a/services/mcp/src/templates/render-ui-prompt.md
+++ b/services/mcp/src/templates/render-ui-prompt.md
@@ -1,8 +1,8 @@
-Render an interactive, explorable visualization of a PostHog entity for the user. Strongly prefer rendering whenever your answer centers on a specific entity or list that has a UI app — an experiment (or its results), survey (or its stats), cohort, action, error-tracking issue, session recording, trace, or workflow, plus the list view for most — so the user can see and verify it, not just read a text summary. Render in addition to your written summary, not instead of it, and not only when the user explicitly asks to "see" something.
+Render an interactive, explorable PostHog visualization for the user. Strongly prefer rendering whenever your answer centers on an analytics query, specific entity, or list that has a UI app — a trends or funnel result, experiment (or its results), survey (or its stats), cohort, action, error-tracking issue, session recording, trace, or workflow, plus the list view for most — so the user can see and verify it, not just read a text summary. Render in addition to your written summary, not instead of it, and not only when the user explicitly asks to "see" something.
ALWAYS run `exec` first — `render-ui` is the final presentation step, never a discovery step. Use `exec` (`search` → `info` → `schema` → `call`) to resolve the entity (look up its real ID), confirm the data exists, and gather what you need for your written summary; only then render. Never render with a guessed `tool_input`.
-`tool_name` must be a tool from the enum; `tool_input` is the same input you would `call` it with — which you already know from your exec work. The widget fetches its own data, so you may skip a *redundant* `call` of that same UI-app tool purely to populate the widget — but that is the only `call` you may skip, never the discovery/verification workflow. Never invent a `tool_name`. Results from `query-*` tools render through their own app automatically — do not route those through `render-ui`.
+`tool_name` must be a tool from the enum; `tool_input` is the same input you would `call` it with — which you already know from your exec work. The widget fetches its own data, so you may skip a *redundant* `call` of that same UI-app tool purely to populate the widget — but that is the only `call` you may skip, never the discovery/verification workflow. Never invent a `tool_name`.
When to render (always after exec, alongside your written answer):
@@ -10,6 +10,7 @@ When to render (always after exec, alongside your written answer):
- Status, "how is X going" → `render-ui({ "tool_name": "experiment-get", "tool_input": { "id": 2 } })`
- Lists / inventory, "what do we have" → the `*-list` tool, e.g. `render-ui({ "tool_name": "experiment-list", "tool_input": {} })`
- Results / stats, "is it significant", "response rate" → the results tool, e.g. `render-ui({ "tool_name": "survey-stats", "tool_input": { "survey_id": "abc123" } })`
+- Analytics queries → run the query with `exec` for your analysis, then render the same tool with the same input, e.g. `render-ui({ "tool_name": "query-trends", "tool_input": { ... } })`
- After a mutation (create/launch/pause/end/resolve) → the entity's detail tool, to confirm the change landed
- Evidence mid-investigation (a recording, error issue, trace) → render it inline, e.g. `render-ui({ "tool_name": "query-error-tracking-issue", "tool_input": { "issueId": "0190-..." } })`
@@ -42,6 +43,6 @@ WRONG — the answer centers on a single experiment that has a UI app (`experime
<bad-example>
User: Show me a trends chart of weekly signups
-Assistant: [Calls render-ui({ "tool_name": "query-trends", ... })]
-WRONG — `query-*` results render through their own app automatically and are not in `render-ui`'s enum. Run the query directly; do not route it through `render-ui`.
+Assistant: [Runs query-trends through exec, then replies with a text-only summary]
+WRONG — after running the query for analysis, render `query-trends` with the same validated input so the user can explore the chart.
</bad-example>
diff --git a/services/mcp/src/templates/sections/cli-examples-claude.md b/services/mcp/src/templates/sections/cli-examples-claude.md
new file mode 100644
index 000000000000..6279e6e2c04f
--- /dev/null
+++ b/services/mcp/src/templates/sections/cli-examples-claude.md
@@ -0,0 +1,61 @@
+**CORRECT usage pattern:**
+
+<example>
+User: create pageviews visualization
+Assistant: This needs analytics and visualization guidance, so I'll load both first.
+[Runs `posthog:exec({"command":"learn analytics visualizations"})`]
+</example>
+
+<example>
+User: How many weekly active users do we have?
+Assistant: This needs analytics and visualization guidance, so I'll load both before any other command.
+[Runs `posthog:exec({"command":"learn analytics visualizations"})`]
+Assistant: I need the query and data schema tools.
+[Runs `posthog:exec({"command":"search query-trends"})` and `posthog:exec({"command":"search read-data"})` in parallel]
+Assistant: I'll inspect both schemas.
+[Runs `posthog:exec({"command":"info query-trends"})` and `posthog:exec({"command":"info read-data-schema"})` in parallel]
+Assistant: The hinted series needs its full schema, and I need the team's events.
+[Runs `posthog:exec({"command":"schema query-trends series"})` and `posthog:exec({"command":"call read-data-schema {\"query\":{\"kind\":\"events\"}}"})` in parallel]
+Assistant: I now have the inputs for the query.
+[Runs `posthog:exec({"command":"call query-trends {...}"})`]
+Assistant: [Briefly summarizes the weekly active user trend.] I'll render it so you can verify the result.
+[Runs `render-ui({ "tool_name": "query-trends", "tool_input": {...} })` with the same query input]
+</example>
+
+<example>
+User: Create a dashboard for our key revenue metrics
+Assistant: Analytics applies. I'll load it before any other command.
+[Runs `posthog:exec({"command":"learn analytics"})`]
+Assistant: I need dashboard and query tools.
+[Runs `posthog:exec({"command":"search dashboard"})` and `posthog:exec({"command":"search execute-sql"})` in parallel]
+Assistant: I'll inspect both schemas.
+[Runs `posthog:exec({"command":"info dashboard-create"})` and `posthog:exec({"command":"info execute-sql"})` in parallel]
+Assistant: I have the inputs to create the dashboard.
+[Makes call commands with correct parameters]
+</example>
+
+**INCORRECT usage patterns: NEVER do this**
+
+<bad-example>
+User: Show me our feature flags
+Assistant: [Calls `feature-flag-get-all` with guessed parameters]
+WRONG: Run `info feature-flag-get-all` first.
+</bad-example>
+
+<bad-example>
+User: Query our events
+Assistant: [Loads analytics, then calls three tools without inspecting them]
+WRONG: Run `info` for all tools before any `call` commands.
+</bad-example>
+
+<bad-example>
+User: Show me a trends chart of signups
+Assistant: [Runs `learn analytics visualizations`, then runs `info query-trends` and guesses the hinted series structure]
+WRONG: Run `schema query-trends series` before populating a field with a drill-down hint.
+</bad-example>
+
+<bad-example>
+User: query pageviews for the last 7 days
+Assistant: [Runs `learn analytics`, then queries the guessed `$pageview` event]
+WRONG: Confirm the event with `call read-data-schema {"query":{"kind":"events"}}` first.
+</bad-example>
diff --git a/services/mcp/src/templates/sections/cli-syntax.md b/services/mcp/src/templates/sections/cli-syntax.md
index 6f93a30eaa0b..e1213a05b559 100644
--- a/services/mcp/src/templates/sections/cli-syntax.md
+++ b/services/mcp/src/templates/sections/cli-syntax.md
@@ -1,7 +1,7 @@
CLI-style command string. Supported commands:
```text
-tools — list available tool names
+{extra_commands}tools — list available tool names
search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)
info [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.
schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)
diff --git a/services/mcp/src/templates/sections/exec-learn.md b/services/mcp/src/templates/sections/exec-learn.md
new file mode 100644
index 000000000000..de805bba83a7
--- /dev/null
+++ b/services/mcp/src/templates/sections/exec-learn.md
@@ -0,0 +1,5 @@
+**LEARN FIRST: HARD REQUIREMENT**
+
+Load all matching topics in one `learn` command first. Topics are cumulative.
+
+{help_topics}
diff --git a/services/mcp/src/tools/exec-help.ts b/services/mcp/src/tools/exec-help.ts
new file mode 100644
index 000000000000..f398dfd89029
--- /dev/null
+++ b/services/mcp/src/tools/exec-help.ts
@@ -0,0 +1,37 @@
+export type ExecHelpEntryKind = 'guide' | 'skill'
+
+export interface ExecHelpEntry {
+ id: string
+ kind: ExecHelpEntryKind
+ title: string
+ description: string
+ content: string
+}
+
+export type ExecHelpEntrySummary = Omit<ExecHelpEntry, 'content'>
+
+/**
+ * Runtime catalog for optional exec guidance. Guide entries are bundled today;
+ * the same flat ID + kind contract can later include skill-backed entries.
+ */
+export class ExecHelpCatalog {
+ private readonly entriesById: Map<string, ExecHelpEntry>
+
+ constructor(entries: ExecHelpEntry[]) {
+ this.entriesById = new Map()
+ for (const entry of entries) {
+ if (this.entriesById.has(entry.id)) {
+ throw new Error(`Duplicate exec help ID: "${entry.id}"`)
+ }
+ this.entriesById.set(entry.id, entry)
+ }
+ }
+
+ list(): ExecHelpEntrySummary[] {
+ return [...this.entriesById.values()].map(({ content: _content, ...summary }) => summary)
+ }
+
+ get(id: string): ExecHelpEntry | undefined {
+ return this.entriesById.get(id)
+ }
+}
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index be5a24f72eff..70dd8ffff541 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -7,6 +7,7 @@ import { ToolInputValidationError } from '@/lib/errors'
import { estimateTokens } from '@/lib/estimate-tokens'
import { formatResponse } from '@/lib/response'
+import type { ExecHelpCatalog } from './exec-help'
import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'
import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'
import type { ScopeGatedTool } from './toolDefinitions'
@@ -48,6 +49,7 @@ export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallP
export interface ExecToolOptions {
requireDestructiveConfirmation?: boolean
+ helpCatalog?: ExecHelpCatalog
/**
* Client is an inline-exec UI-app host that renders MCP UI apps on the exec
* response (Claude Code, Cowork). Gets the same UI-app payload treatment as the
@@ -253,6 +255,35 @@ export function createExecTool(
const { verb, rest } = parseCommand(params.command)
switch (verb) {
+ case 'learn': {
+ const helpCatalog = options.helpCatalog
+ if (!helpCatalog) {
+ throw new Error('The learning catalog is not available for this client.')
+ }
+ if (!rest) {
+ return JSON.stringify(helpCatalog.list())
+ }
+ const topicIds = [...new Set(rest.split(/\s+/))]
+ const entries = topicIds.map((topicId) => helpCatalog.get(topicId))
+ const unknownTopicIds = topicIds.filter((_, index) => entries[index] === undefined)
+ if (unknownTopicIds.length > 0) {
+ const available = helpCatalog
+ .list()
+ .map((item) => item.id)
+ .join(', ')
+ if (unknownTopicIds.length === 1) {
+ throw new Error(`Unknown learning topic: "${unknownTopicIds[0]}". Available: ${available}`)
+ }
+ const unknownTopics = unknownTopicIds.map((topicId) => `"${topicId}"`).join(', ')
+ throw new Error(`Unknown learning topics: ${unknownTopics}. Available: ${available}`)
+ }
+ const resolvedEntries = entries.filter((entry) => entry !== undefined)
+ if (resolvedEntries.length === 1) {
+ return resolvedEntries[0]!.content
+ }
+ return resolvedEntries.map((entry) => `## ${entry.title}\n\n${entry.content}`).join('\n\n')
+ }
+
case 'tools': {
return JSON.stringify(allTools.map((t) => t.name))
}
@@ -568,7 +599,9 @@ export function createExecTool(
}
default:
- throw new Error(`Unknown command: "${verb}". Supported commands: tools, search, info, schema, call`)
+ throw new Error(
+ `Unknown command: "${verb}". Supported commands: ${options.helpCatalog ? 'learn, ' : ''}tools, search, info, schema, call`
+ )
}
},
}
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 002a62260fef..33d625c6506d 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -15,7 +15,9 @@ import { InstructionsBuilder } from '@/hono/instructions'
import type { ResolvedState } from '@/hono/request-state-resolver'
import { ToolCatalog } from '@/hono/tool-catalog'
import { ToolExecutor } from '@/hono/tool-executor'
+import { buildToolDomainsCompact } from '@/lib/instructions'
import { RENDER_UI_RESOURCE_URI, URI_MAP } from '@/resources/ui-apps.generated'
+import { getToolDefinition } from '@/tools/toolDefinitions'
// A tool with a renderable (dispatchable) UI app — used to exercise the render-ui path.
const uiAppTool = {
@@ -231,8 +233,15 @@ describe('ToolExecutor', () => {
const result = await executor.handleToolsList(state)
const commandDesc = (result.tools[0]!.inputSchema.properties as any).command.description as string
+ const compactDomains = buildToolDomainsCompact(
+ tools.map(({ name }) => ({ name, category: getToolDefinition(name).category }))
+ )
expect(commandDesc).toContain('PostHog tools have lowercase kebab-case naming')
+ expect(commandDesc.includes('**LEARN FIRST: HARD REQUIREMENT**')).toBe(isClaudeChatHost)
+ expect(commandDesc.includes('- analytics:')).toBe(isClaudeChatHost)
+ expect(commandDesc.includes('### Retrieving data')).toBe(!isClaudeChatHost)
+ expect(commandDesc.includes(compactDomains)).toBe(isClaudeChatHost)
if (expectEnv) {
expect(commandDesc).toContain(metadataMarker)
} else {
@@ -241,6 +250,37 @@ describe('ToolExecutor', () => {
}
)
+ it('serves multiple optional guidance topics through exec learn for Claude web/desktop', async () => {
+ const state = makeState(
+ catalog
+ .getPreBuiltEntries()
+ .slice(0, 5)
+ .map(({ name }) => ({ name })),
+ {
+ useSingleExec: true,
+ renderUiEnabled: true,
+ clientProfile: {
+ capabilities: { supportsInstructions: true },
+ isCliModeEnabled: vi.fn(() => true),
+ isClaudeUiHost: vi.fn(() => false),
+ isInlineExecUiHost: vi.fn(() => false),
+ isClaudeChatHost: vi.fn(() => true),
+ } as any,
+ }
+ )
+
+ const result = (await executor.handleToolCall(
+ { name: 'exec', arguments: { command: 'learn analytics visualizations' } },
+ state
+ )) as { content: { text: string }[] }
+
+ expect(result.content[0]!.text).toContain('## Analytics')
+ expect(result.content[0]!.text).toContain('### Retrieving data')
+ expect(result.content[0]!.text).toContain('### Examples')
+ expect(result.content[0]!.text).toContain('## Visualizations')
+ expect(result.content[0]!.text).toContain('### Rendering visualizations')
+ })
+
it('lists render-ui alongside exec when render-ui is enabled and a UI-app tool is available', async () => {
const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt
new file mode 100644
index 000000000000..aa53bf1078ab
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt
@@ -0,0 +1,172 @@
+CLI-style command string. Supported commands:
+
+```text
+learn <topic...> - load one or more learning topics
+tools — list available tool names
+search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)
+info [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.
+schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)
+call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of optimized output in supported tools. Use raw JSON for scripts. --confirm is required by the CLI for destructive tools.)
+```
+
+**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.
+
+**LEARN FIRST: HARD REQUIREMENT**
+
+Load all matching topics in one `learn` command first. Topics are cumulative.
+
+- analytics: Query or analyze PostHog data, metrics, and events.
+- visualizations: Create or render a visualization.
+- feedback: Send feedback about PostHog.
+
+**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), 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> series.properties` — to see property filter structure of series
+
+**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.
+
+**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.
+
+Always run `info read-data-schema` first — the recipes below are common cases, not the full schema.
+
+- Events/Actions: `call read-data-schema {"query": {"kind": "events"/"actions"}}` (paginate with `limit`/`offset` if needed)
+- Properties: `call read-data-schema {"query": {"kind": "event_properties", "event_name": "<event>"}}`
+- Values: `call read-data-schema {"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<prop>"}}`
+
+**CORRECT usage pattern:**
+
+<example>
+User: create pageviews visualization
+Assistant: This needs analytics and visualization guidance, so I'll load both first.
+[Runs `posthog:exec({"command":"learn analytics visualizations"})`]
+</example>
+
+<example>
+User: How many weekly active users do we have?
+Assistant: This needs analytics and visualization guidance, so I'll load both before any other command.
+[Runs `posthog:exec({"command":"learn analytics visualizations"})`]
+Assistant: I need the query and data schema tools.
+[Runs `posthog:exec({"command":"search query-trends"})` and `posthog:exec({"command":"search read-data"})` in parallel]
+Assistant: I'll inspect both schemas.
+[Runs `posthog:exec({"command":"info query-trends"})` and `posthog:exec({"command":"info read-data-schema"})` in parallel]
+Assistant: The hinted series needs its full schema, and I need the team's events.
+[Runs `posthog:exec({"command":"schema query-trends series"})` and `posthog:exec({"command":"call read-data-schema {\"query\":{\"kind\":\"events\"}}"})` in parallel]
+Assistant: I now have the inputs for the query.
+[Runs `posthog:exec({"command":"call query-trends {...}"})`]
+Assistant: [Briefly summarizes the weekly active user trend.] I'll render it so you can verify the result.
+[Runs `render-ui({ "tool_name": "query-trends", "tool_input": {...} })` with the same query input]
+</example>
+
+<example>
+User: Create a dashboard for our key revenue metrics
+Assistant: Analytics applies. I'll load it before any other command.
+[Runs `posthog:exec({"command":"learn analytics"})`]
+Assistant: I need dashboard and query tools.
+[Runs `posthog:exec({"command":"search dashboard"})` and `posthog:exec({"command":"search execute-sql"})` in parallel]
+Assistant: I'll inspect both schemas.
+[Runs `posthog:exec({"command":"info dashboard-create"})` and `posthog:exec({"command":"info execute-sql"})` in parallel]
+Assistant: I have the inputs to create the dashboard.
+[Makes call commands with correct parameters]
+</example>
+
+**INCORRECT usage patterns: NEVER do this**
+
+<bad-example>
+User: Show me our feature flags
+Assistant: [Calls `feature-flag-get-all` with guessed parameters]
+WRONG: Run `info feature-flag-get-all` first.
+</bad-example>
+
+<bad-example>
+User: Query our events
+Assistant: [Loads analytics, then calls three tools without inspecting them]
+WRONG: Run `info` for all tools before any `call` commands.
+</bad-example>
+
+<bad-example>
+User: Show me a trends chart of signups
+Assistant: [Runs `learn analytics visualizations`, then runs `info query-trends` and guesses the hinted series structure]
+WRONG: Run `schema query-trends series` before populating a field with a drill-down hint.
+</bad-example>
+
+<bad-example>
+User: query pageviews for the last 7 days
+Assistant: [Runs `learn analytics`, then queries the guessed `$pageview` event]
+WRONG: Confirm the event with `call read-data-schema {"query":{"kind":"events"}}` first.
+</bad-example>
+
+**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.
+
+### 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 (used for analytics): events (recorded from SDKs, always associated with persons and sometimes groups); persons and groups (captured individuals or groups of individuals); sessions; properties and property values (key-value metadata for segmenting events, actions, persons, groups, etc.); session recordings (captured web/mobile interactions).
+
+Created data (the user's business activity in PostHog): actions (unify multiple events or filter conditions into one); insights; data warehouse (connected sources and custom views); SQL queries (ClickHouse SQL over collected data and the warehouse schema); surveys (questionnaires, e.g. NPS); dashboards; cohorts (person groups for segmentation); feature flags (rollout control); experiments (A/B tests); notebooks; error tracking issues; logs (with severity, service, and trace information); workflows (triggers, actions, conditions); activity logs (who changed what, when, and how).
+
+IMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.
+
+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.
+
+### Tool search
+
+**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <query>` to find what you need.
+
+`search` understands two kinds of query:
+
+- **Plain words** (including multiple words / natural language) — ranked by relevance across tool name, title, and description, with name matches weighted highest. `search create dashboard insight` surfaces `dashboard-create` / `insight-create` at the top. Results are capped to the top matches; narrow the query if you see a truncation note.
+- **Regex** — a query containing regex metacharacters (`- | ( ) [ ] \ . * + ^ $ ?`) is treated as a single case-insensitive regular expression, matched against name/title/description. Use this for precise, narrow patterns.
+
+**Good queries:**
+
+- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools first
+- `search feature-flag` — regex (`-`): tools for feature flags
+- `search query-` — regex (`-`): all insight query tools
+
+**Avoid queries that are too broad** (match dozens of tools): `search data`, `search get list create` — they match almost everything.
+
+Only fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.
+
+PostHog tools have lowercase kebab-case naming. Tools are organized by category:
+
+dashboard|execute-sql|feature-flag|query
+Typical action names: list/retrieve/get/create/update/delete/query.
+Example tool names: execute-sql, experiment-create, feature-flag-get-all.
+
+Defined group types: organization, project
+
+You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).
+Project timezone: America/New_York.
+The user's name is Jane Doe ([email protected]).
+
+### URL patterns
+
+PostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.
+
+Choose the link source in this order:
+
+1. If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.
+2. Only when you actually want to link a specific entity (or the user asks for a link) and it has no `_posthogUrl`, call `generate-app-url` and surface the `url` verbatim — don't hand-write slugs or retype IDs into paths, both are easy to get wrong. Don't fetch a link just because a result has an ID.
+3. Only for genuinely static pages not covered by `generate-app-url` (some settings / data-management pages), build the link from the Base URL in the active-environment block (don't double-prefix):
+ - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`.
+ - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.
\ No newline at end of file
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 1f04b65ec05a..a18fe6290e43 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -9,7 +9,13 @@ import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instruction
import { InstructionsFormatter } from '@/lib/instructions-formatter'
import { SessionManager } from '@/lib/SessionManager'
import { getToolsFromContext } from '@/tools'
-import { createExecTool, type ExecInnerCallProperties, parseExecCallInnerToolName } from '@/tools/exec'
+import {
+ createExecTool,
+ type ExecInnerCallProperties,
+ type ExecToolOptions,
+ parseExecCallInnerToolName,
+} from '@/tools/exec'
+import { ExecHelpCatalog } from '@/tools/exec-help'
import { getToolDefinition } from '@/tools/toolDefinitions'
import {
POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,
@@ -45,7 +51,7 @@ const mockContext = {
function createExec(
tools: Tool<ZodObjectAny>[] = [makeMockTool()],
mcpConsumer?: string,
- options?: { isInlineExecUiHost?: boolean }
+ options?: ExecToolOptions
): Tool<any> {
return createExecTool(
tools,
@@ -60,6 +66,80 @@ function createExec(
}
describe('exec tool', () => {
+ describe('learn command', () => {
+ const helpCatalog = new ExecHelpCatalog([
+ {
+ id: 'analytics',
+ kind: 'guide',
+ title: 'Analytics',
+ description: 'Detailed analytics guidance.',
+ content: '### Retrieving data\n\nUse the analytics tools.',
+ },
+ {
+ id: 'retention-analysis',
+ kind: 'skill',
+ title: 'Retention analysis',
+ description: 'A retention workflow.',
+ content: '### Retention analysis\n\nFollow the workflow.',
+ },
+ ])
+
+ it('lists topic metadata without loading topic content', async () => {
+ const exec = createExec(undefined, undefined, { helpCatalog })
+
+ const result = JSON.parse((await exec.handler(mockContext, { command: 'learn' })) as string)
+
+ expect(result).toEqual([
+ {
+ id: 'analytics',
+ kind: 'guide',
+ title: 'Analytics',
+ description: 'Detailed analytics guidance.',
+ },
+ {
+ id: 'retention-analysis',
+ kind: 'skill',
+ title: 'Retention analysis',
+ description: 'A retention workflow.',
+ },
+ ])
+ })
+
+ it('loads a topic by its globally unique ID', async () => {
+ const exec = createExec(undefined, undefined, { helpCatalog })
+
+ await expect(exec.handler(mockContext, { command: 'learn analytics' })).resolves.toBe(
+ '### Retrieving data\n\nUse the analytics tools.'
+ )
+ })
+
+ it('loads multiple unique topics in the requested order', async () => {
+ const exec = createExec(undefined, undefined, { helpCatalog })
+
+ await expect(
+ exec.handler(mockContext, { command: 'learn retention-analysis analytics retention-analysis' })
+ ).resolves.toBe(
+ '## Retention analysis\n\n### Retention analysis\n\nFollow the workflow.\n\n## Analytics\n\n### Retrieving data\n\nUse the analytics tools.'
+ )
+ })
+
+ it('reports the available IDs when a topic is unknown', async () => {
+ const exec = createExec(undefined, undefined, { helpCatalog })
+
+ await expect(exec.handler(mockContext, { command: 'learn unknown' })).rejects.toThrow(
+ 'Unknown learning topic: "unknown". Available: analytics, retention-analysis'
+ )
+ })
+
+ it('reports every unknown ID without returning partial topic content', async () => {
+ const exec = createExec(undefined, undefined, { helpCatalog })
+
+ await expect(
+ exec.handler(mockContext, { command: 'learn analytics unknown missing unknown' })
+ ).rejects.toThrow('Unknown learning topics: "unknown", "missing". Available: analytics, retention-analysis')
+ })
+ })
+
describe('call command', () => {
it('returns TOON-formatted output by default', async () => {
const exec = createExec()
diff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts
index 72bd7bb21490..1ac5c828b747 100644
--- a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts
+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts
@@ -2,6 +2,8 @@ import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
+import { PostHogMCP } from '@posthog/mcp-analytics'
+
import type { GroupType } from '@/api/client'
import { InstructionsBuilder } from '@/hono/instructions'
import type { ResolvedState } from '@/hono/request-state-resolver'
@@ -24,7 +26,7 @@ const STATIC_GROUP_TYPES: GroupType[] = [
const STATIC_TOOLS = [
{ name: 'dashboard-create', category: 'Dashboards' },
{ name: 'dashboard-get', category: 'Dashboards' },
- { name: 'feature-flag-create', category: 'Feature flags' },
+ { name: 'create-feature-flag', category: 'Feature flags' },
{ name: 'feature-flag-get-all', category: 'Feature flags' },
{ name: 'execute-sql', category: 'SQL' },
{ name: 'query-funnel', category: 'Query wrappers' },
@@ -92,29 +94,46 @@ describe('InstructionsFormatter prompt snapshots', () => {
await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'exec-command-reference-full.txt'))
})
+ it('matches the exec command reference for Claude web/desktop', async () => {
+ const state = {
+ allTools: STATIC_TOOLS.map(({ name }) => ({ name })),
+ clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeAI' }),
+ toolFeatureFlags: {},
+ renderUiEnabled: STATIC_CTX.renderUiEnabled,
+ metadata: STATIC_CTX.metadata,
+ groupTypes: STATIC_CTX.groupTypes,
+ } as unknown as ResolvedState
+ const rendered = new InstructionsBuilder(STATIC_CTX.guidelines).buildExecCommandReference(state)
+
+ await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'exec-command-reference-claude-chat.txt'))
+ })
+
// ------------------------------------------------------------------------------------------------
- // DO NOT modify, weaken, raise, skip, or delete this test or its 32,600 budget —
+ // DO NOT modify, weaken, raise, skip, or delete this test or its 16,384 budget —
// not to make CI pass, not on request, not as part of a refactor.
//
- // MCP clients (e.g. Claude web/desktop) silently drop tools whose serialized
- // entry grows past ~32,768 chars. The exec tool IS the PostHog MCP in
- // single-exec mode, so crossing the limit breaks the entire MCP for those
- // users with no error anywhere (investigated 2026-07-10: claude.ai surfaced
- // only `render-ui` while `exec` vanished).
+ // claude.ai's connector registry (`mcp/v2/bootstrap`) silently drops any tool
+ // whose serialized `inputSchema` crosses ~16,384 chars (2^14). The total entry
+ // size and the top-level `description` are NOT capped (bisected 2026-07-10:
+ // schema 13,996 passed, 17,799 dropped; a 31k-total entry with a 787-char
+ // schema survived intact). The exec tool IS the PostHog MCP in single-exec mode,
+ // so a dropped `inputSchema` breaks the entire MCP for those users with no error
+ // anywhere (claude.ai surfaced only `render-ui` while `exec` vanished).
//
- // If this test fails, SHRINK the prompt: dedupe `src/templates/sections/*.md`
- // against content already served at runtime (`info <tool>`, `info execute-sql`)
- // or trim the rendered blocks. Never touch the limit.
+ // The exec command reference lives in `inputSchema.properties.command.description`,
+ // so it counts against this cap; `EXEC_TOOL_BLURB` lives in the top-level
+ // `description` and does NOT. If this test fails, move optional guidance behind
+ // `learn <topic>` or shrink duplicated prompt content in the command reference —
+ // trimming the top-level description does nothing for this budget.
// ------------------------------------------------------------------------------------------------
- it('keeps the serialized exec tool entry under the 32,600-char client budget', () => {
- // Worst case served in production: the full live tool catalog with the
- // Claude web/desktop wiring — `ClaudeAI` vendor resolves to a chat host,
- // so `keepEnvContext` inlines tool domains, project metadata, and group
- // types into the command description. The metadata goes through the real
+ it('keeps the serialized exec inputSchema under the claude.ai registry cap', () => {
+ // Worst case served in production: Claude web/desktop with every optional
+ // learning topic advertised, the full live tool catalog, and long environment
+ // context. The metadata goes through the real
// env-context builder with inputs at the backing columns' max lengths
// (Team.name 200, Organization.name 64, email 254, Django names 150) plus
// the longer person-on-events branch, so a long org/project/user cannot
- // push a real entry past the cap while this test passes.
+ // push the real schema past the cap while this test passes.
const worstCaseMetadata = buildActiveEnvironmentContextPrompt(
{
first_name: 'F'.repeat(150),
@@ -147,10 +166,14 @@ describe('InstructionsFormatter prompt snapshots', () => {
groupTypes: worstCaseGroupTypes,
} as unknown as ResolvedState
const entry = new InstructionsBuilder('').buildExecToolEntry(state)
- const size = JSON.stringify(entry).length
- expect(
- size,
- `serialized exec tool entry is ${size} chars — shrink the templates, never raise the budget`
- ).toBeLessThan(32_600)
+ const posthog = new PostHogMCP('phc_test', { disabled: true })
+ const finalEntry = posthog.prepareToolList([entry])[0]!
+ // `prepareToolList` injects the `context` property into `inputSchema`, so the
+ // measured schema must include it — measure the final, post-injection schema.
+ const properties = finalEntry.inputSchema.properties as Record<string, unknown>
+ const inputSchemaSize = JSON.stringify(finalEntry.inputSchema).length
+
+ expect(properties).toHaveProperty('context')
+ expect(inputSchemaSize).toBeLessThan(16_384)
})
})
diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.ts
index 0e90033a2d68..154b8439aebe 100644
--- a/services/mcp/tests/unit/instructions-formatter.test.ts
+++ b/services/mcp/tests/unit/instructions-formatter.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { GroupType } from '@/api/client'
-import type { QueryToolInfo } from '@/lib/instructions'
+import { buildToolDomainsCompact, type QueryToolInfo } from '@/lib/instructions'
import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructions-formatter'
const realisticGroupTypes: GroupType[] = [
@@ -226,6 +226,85 @@ describe('InstructionsFormatter', () => {
})
})
+ describe('Claude web/desktop exec guidance', () => {
+ it('keeps routine guidance inline and advertises optional topics', () => {
+ const formatter = new InstructionsFormatter()
+ const result = formatter.buildClaudeExecCommandReference(fullCtx)
+
+ expect(result).toContain('**LEARN FIRST: HARD REQUIREMENT**')
+ expect(result).toContain('learn <topic...> - load one or more learning topics')
+ expect(result).toContain('Topics are cumulative.')
+ expect(result).toContain('User: create pageviews visualization')
+ expect(result).toContain(
+ "Assistant: This needs analytics and visualization guidance, so I'll load both first."
+ )
+ expect(result).toContain('posthog:exec({"command":"learn analytics visualizations"})')
+ expect(result).toContain('User: How many weekly active users do we have?')
+ expect(result).toContain('render-ui({ "tool_name": "query-trends", "tool_input": {...} })')
+ expect(result.indexOf('render-ui({ "tool_name": "query-trends"')).toBeGreaterThan(
+ result.indexOf('posthog:exec({"command":"call query-trends {...}"})')
+ )
+ expect(result).toContain('- analytics:')
+ expect(result).toContain('- visualizations:')
+ expect(result).toContain('- feedback:')
+ expect(result).toContain('SCHEMA DRILL-DOWN RULE')
+ expect(result).toContain('**Data discovery:**')
+ expect(result).toContain('**CORRECT usage pattern:**')
+ expect(result.indexOf('User: create pageviews visualization')).toBeGreaterThan(
+ result.indexOf('**CORRECT usage pattern:**')
+ )
+ expect(result).toContain('### Basic functionality')
+ expect(result).toContain('### Tool search')
+ expect(result).toContain(buildToolDomainsCompact(realisticTools))
+ expect(result).toContain("The user's name is Jane Doe")
+ expect(result).toContain('Defined group types: organization')
+ expect(result).not.toContain('### Retrieving data')
+ expect(result).not.toContain('### Examples')
+ expect(result).not.toContain('### Rendering visualizations')
+ expect(result).not.toContain('### Sharing feedback on PostHog')
+ expect(result).not.toContain('- `query-trends` — time series')
+ expect(result).not.toMatch(/\{help_topics\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/)
+ })
+
+ it('combines analytics guidance and examples in one learning topic', () => {
+ const formatter = new InstructionsFormatter()
+ const entries = formatter.buildClaudeExecHelpEntries(fullCtx)
+ const analytics = entries.find((entry) => entry.id === 'analytics')
+
+ expect(entries.map(({ id, kind }) => ({ id, kind }))).toEqual([
+ { id: 'analytics', kind: 'guide' },
+ { id: 'visualizations', kind: 'guide' },
+ { id: 'feedback', kind: 'guide' },
+ ])
+ expect(analytics?.content).toContain('### Retrieving data')
+ expect(analytics?.content).toContain('### Examples')
+ expect(analytics?.content).toContain('- `query-trends` — time series')
+ expect(entries.find((entry) => entry.id === 'visualizations')?.content).toContain(
+ '### Rendering visualizations'
+ )
+ expect(entries.find((entry) => entry.id === 'feedback')?.content).toContain(
+ '### Sharing feedback on PostHog'
+ )
+ })
+
+ it('only advertises visualizations when rendering is available', () => {
+ const formatter = new InstructionsFormatter()
+ const ctx = {
+ ...fullCtx,
+ renderUiEnabled: false,
+ }
+
+ expect(formatter.buildClaudeExecHelpEntries(ctx).map((entry) => entry.id)).toEqual([
+ 'analytics',
+ 'feedback',
+ ])
+ const result = formatter.buildClaudeExecCommandReference(ctx)
+ expect(result).toContain('- analytics:')
+ expect(result).not.toContain('- visualizations:')
+ expect(result).toContain('- feedback:')
+ })
+ })
+
// Mirrors the single-exec wiring in `src/mcp.ts`. When the client honors the MCP
// `instructions` field, env-context moves out of the `command` description and into
// `instructions`: tool domains (including the `query` domain), user preferences