: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): record call shape, alias use, and server build (#101133)
ruby childs43440642c22d
diff --git a/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md b/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.mdindex 5223f58bcb15..02dc40be6e20 100644--- a/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md+++ b/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md@@ -88,11 +88,22 @@ refusals into tool error rates, which is also why the status has its own field.time, never by person.Per-event additions: `$mcp_error_status` (upstream HTTP status), `$mcp_error_code` (machine-readable leaf failure code: the API's validation error code or the exec rejection reason), and `$mcp_error_field` (the validation error's field path, array indexes normalized to `N`, e.g. `actions__N__inputs__email`) — all stamped by `services/mcp/src/hono/tool-executor.ts` — **server-side, despite sitting next to the SDK's typed error properties in queries**; and `tool_count`, `read_only`, `via_sse_redirect` on `$mcp_initialize`. Failed calls may also carry-`$mcp_validation_fields` and `$mcp_validation_input_keys` (which fields failed validation, and-which keys the caller actually sent), and exec-mode calls carry `$mcp_exec_verb` (which dispatcher-verb ran) and `$mcp_exec_target_tool` (the tool that `info`/`schema`/`call` named). Those four are-stamped in `tool-executor.ts` but are **not registered in `posthog/taxonomy/taxonomy.py`**, so they-have no descriptions in the property picker — they still query fine.+`$mcp_validation_fields` (which fields failed validation), and exec-mode calls carry `$mcp_exec_verb` (which dispatcher+verb ran) and `$mcp_exec_target_tool` (the tool that `info`/`schema`/`call` named). These properties are+stamped in `tool-executor.ts` and registered in `posthog/taxonomy/taxonomy.py`.++A `$mcp_tool_call` that named a tool and its arguments (a direct-mode call, `render-ui`, or an+exec `call`) also carries the call's shape, stamped in `tool-executor.ts` from the raw input before+any alias is folded away, by the `@posthog/mcp` SDK helper `getToolInputProperties`:+`$mcp_input_keys` (the top-level argument names the caller sent, never values: declared names and+aliases first, capped at 20, with undeclared names recorded as one `[redacted]` entry; in exec mode parsed from the `call` command's JSON) and+`$mcp_input_aliases_used` (`alias:canonical` tokens such as `experimentId:id`, present only when+the normaliser filled the canonical from that alias). Exec+discovery verbs (`tools`, `search`, `info`, `schema`) carry neither, so rate alias use against the+rows where `$mcp_input_keys` is set, not against every `$mcp_tool_call`. Group the two by+`$mcp_client_name` to see which spelling each agent reaches for and how much of it the alias layer+absorbs. A tool that wraps `normalizeParamAliases` inside its own preprocess (`read-data-schema`)+reads as alias-free.A `learn` call also carries `exec_learn_kind` (`search`, `load`, `list` for `learn skills` and a bare `learn`, `describe`, `guide`),stamped before the availability check so a rejected skill command still records its form, plusthe raw `exec_search_query` for `search` (and for a `load` that searches inside the skill with `-s`) and `exec_learn_target` (the qualified skill) for `load`.diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex 172e8f1c6c71..0a16776b138a 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -2265,6 +2265,14 @@],"label": "MCP exec inner tool catalog"},+ "$mcp_exec_target_tool": {+ "description": "The tool an exec info, schema, or call verb named, when it resolves to a tool in the server's catalog; `unrecognized` otherwise so the caller's own token is never recorded. Links an `info` read to the `call` that follows it.",+ "examples": [+ "experiment-get",+ "unrecognized"+ ],+ "label": "MCP exec target tool"+ },"$mcp_exec_tool_call_description": {"description": "In single-exec mode, $mcp_tool_name is always 'exec' (the dispatcher), so the SDK's $mcp_tool_description is the dispatcher's static text on every call. This property carries the description of the inner tool the agent was actually invoking via 'call <tool> ...' \u2014 derived server-side by parsing the exec command and looking the inner tool up in our catalog. Only present when an exec call targets a recognized inner tool.","examples": [@@ -2281,6 +2289,32 @@],"label": "MCP exec inner tool name"},+ "$mcp_exec_verb": {+ "description": "Which exec dispatcher verb the request ran: tools, search, info, schema, call, learn, or `unrecognized` for a verb the server does not accept. Only set in exec mode ($mcp_mode).",+ "examples": [+ "call",+ "info",+ "unrecognized"+ ],+ "label": "MCP exec verb"+ },+ "$mcp_input_aliases_used": {+ "description": "Declared parameter aliases the call relied on, as `alias:canonical` (for example `experimentId:id`). Present only when the call did not send the canonical name and used one of its aliases instead. Both names come from the tool's own alias map. Recorded by the @posthog/mcp SDK helper. Measures how much traffic the alias layer rescues, and which spellings agents reach for.",+ "examples": [+ "experimentId:id",+ "flagKey:key"+ ],+ "label": "MCP input aliases used"+ },+ "$mcp_input_keys": {+ "description": "Top-level argument names the caller sent on a tool call, success or failure: every direct-mode call, `render-ui`, and an exec `call` (parsed from the command string). Exec discovery verbs (tools, search, info, schema) carry none, so rate against rows where it is set rather than every $mcp_tool_call. Recorded by the @posthog/mcp SDK helper: names the tool declares, including its aliases, capped at 20. Undeclared names become one `[redacted]` entry. Names only, never values. Group by it with $mcp_input_aliases_used to see how agents spell a parameter.",+ "examples": [+ "id",+ "experimentId",+ "filters, key, name"+ ],+ "label": "MCP input keys"+ },"$mcp_intent": {"description": "Free-text description of why the agent is calling this tool, written by the agent itself. Comes from a context argument the client supplied at call time, or \u2014 if none was supplied \u2014 from an intentFallback the MCP server provides.","examples": [@@ -2416,6 +2450,13 @@],"label": "MCP scope preset"},+ "$mcp_server_build": {+ "description": "The exact immutable build identifier that the MCP host supplies, such as a Git commit SHA or container image digest. Use it to connect an event to deployed code when one server version has multiple builds.",+ "examples": [+ "b3b941584bae0123"+ ],+ "label": "MCP server build"+ },"$mcp_server_name": {"description": "The advertised name of the MCP server that handled the request.","examples": [@@ -2489,6 +2530,14 @@],"label": "MCP transport"},+ "$mcp_validation_fields": {+ "description": "Parameter paths the MCP server's own input schema rejected, as `path:code` (for example `id:invalid_type`). Names from the tool's schema, never caller values. Only set when the server rejected the input before calling PostHog.",+ "examples": [+ "id:invalid_type",+ "filters.groups:required"+ ],+ "label": "MCP validation fields"+ },"$mcp_vendor_client": {"description": "Vendor client header the MCP client sent on the transport (x-anthropic-client), captured raw. The strongest harness signal: clientInfo.name can't tell one vendor surface from another, but this header can.","examples": [@@ -4685,6 +4734,14 @@],"label": "MCP exec inner tool catalog"},+ "$mcp_exec_target_tool": {+ "description": "The tool an exec info, schema, or call verb named, when it resolves to a tool in the server's catalog; `unrecognized` otherwise so the caller's own token is never recorded. Links an `info` read to the `call` that follows it.",+ "examples": [+ "experiment-get",+ "unrecognized"+ ],+ "label": "MCP exec target tool"+ },"$mcp_exec_tool_call_description": {"description": "In single-exec mode, $mcp_tool_name is always 'exec' (the dispatcher), so the SDK's $mcp_tool_description is the dispatcher's static text on every call. This property carries the description of the inner tool the agent was actually invoking via 'call <tool> ...' \u2014 derived server-side by parsing the exec command and looking the inner tool up in our catalog. Only present when an exec call targets a recognized inner tool.","examples": [@@ -4701,6 +4758,32 @@],"label": "MCP exec inner tool name"},+ "$mcp_exec_verb": {+ "description": "Which exec dispatcher verb the request ran: tools, search, info, schema, call, learn, or `unrecognized` for a verb the server does not accept. Only set in exec mode ($mcp_mode).",+ "examples": [+ "call",+ "info",+ "unrecognized"+ ],+ "label": "MCP exec verb"+ },+ "$mcp_input_aliases_used": {+ "description": "Declared parameter aliases the call relied on, as `alias:canonical` (for example `experimentId:id`). Present only when the call did not send the canonical name and used one of its aliases instead. Both names come from the tool's own alias map. Recorded by the @posthog/mcp SDK helper. Measures how much traffic the alias layer rescues, and which spellings agents reach for.",+ "examples": [+ "experimentId:id",+ "flagKey:key"+ ],+ "label": "MCP input aliases used"+ },+ "$mcp_input_keys": {+ "description": "Top-level argument names the caller sent on a tool call, success or failure: every direct-mode call, `render-ui`, and an exec `call` (parsed from the command string). Exec discovery verbs (tools, search, info, schema) carry none, so rate against rows where it is set rather than every $mcp_tool_call. Recorded by the @posthog/mcp SDK helper: names the tool declares, including its aliases, capped at 20. Undeclared names become one `[redacted]` entry. Names only, never values. Group by it with $mcp_input_aliases_used to see how agents spell a parameter.",+ "examples": [+ "id",+ "experimentId",+ "filters, key, name"+ ],+ "label": "MCP input keys"+ },"$mcp_intent": {"description": "Free-text description of why the agent is calling this tool, written by the agent itself. Comes from a context argument the client supplied at call time, or \u2014 if none was supplied \u2014 from an intentFallback the MCP server provides.","examples": [@@ -4836,6 +4919,13 @@],"label": "MCP scope preset"},+ "$mcp_server_build": {+ "description": "The exact immutable build identifier that the MCP host supplies, such as a Git commit SHA or container image digest. Use it to connect an event to deployed code when one server version has multiple builds.",+ "examples": [+ "b3b941584bae0123"+ ],+ "label": "MCP server build"+ },"$mcp_server_name": {"description": "The advertised name of the MCP server that handled the request.","examples": [@@ -4909,6 +4999,14 @@],"label": "MCP transport"},+ "$mcp_validation_fields": {+ "description": "Parameter paths the MCP server's own input schema rejected, as `path:code` (for example `id:invalid_type`). Names from the tool's schema, never caller values. Only set when the server rejected the input before calling PostHog.",+ "examples": [+ "id:invalid_type",+ "filters.groups:required"+ ],+ "label": "MCP validation fields"+ },"$mcp_vendor_client": {"description": "Vendor client header the MCP client sent on the transport (x-anthropic-client), captured raw. The strongest harness signal: clientInfo.name can't tell one vendor surface from another, but this header can.","examples": [@@ -7597,6 +7695,14 @@],"label": "MCP exec inner tool catalog"},+ "$mcp_exec_target_tool": {+ "description": "The tool an exec info, schema, or call verb named, when it resolves to a tool in the server's catalog; `unrecognized` otherwise so the caller's own token is never recorded. Links an `info` read to the `call` that follows it.",+ "examples": [+ "experiment-get",+ "unrecognized"+ ],+ "label": "MCP exec target tool"+ },"$mcp_exec_tool_call_description": {"description": "In single-exec mode, $mcp_tool_name is always 'exec' (the dispatcher), so the SDK's $mcp_tool_description is the dispatcher's static text on every call. This property carries the description of the inner tool the agent was actually invoking via 'call <tool> ...' \u2014 derived server-side by parsing the exec command and looking the inner tool up in our catalog. Only present when an exec call targets a recognized inner tool.","examples": [@@ -7613,6 +7719,32 @@],"label": "MCP exec inner tool name"},+ "$mcp_exec_verb": {+ "description": "Which exec dispatcher verb the request ran: tools, search, info, schema, call, learn, or `unrecognized` for a verb the server does not accept. Only set in exec mode ($mcp_mode).",+ "examples": [+ "call",+ "info",+ "unrecognized"+ ],+ "label": "MCP exec verb"+ },+ "$mcp_input_aliases_used": {+ "description": "Declared parameter aliases the call relied on, as `alias:canonical` (for example `experimentId:id`). Present only when the call did not send the canonical name and used one of its aliases instead. Both names come from the tool's own alias map. Recorded by the @posthog/mcp SDK helper. Measures how much traffic the alias layer rescues, and which spellings agents reach for.",+ "examples": [+ "experimentId:id",+ "flagKey:key"+ ],+ "label": "MCP input aliases used"+ },+ "$mcp_input_keys": {+ "description": "Top-level argument names the caller sent on a tool call, success or failure: every direct-mode call, `render-ui`, and an exec `call` (parsed from the command string). Exec discovery verbs (tools, search, info, schema) carry none, so rate against rows where it is set rather than every $mcp_tool_call. Recorded by the @posthog/mcp SDK helper: names the tool declares, including its aliases, capped at 20. Undeclared names become one `[redacted]` entry. Names only, never values. Group by it with $mcp_input_aliases_used to see how agents spell a parameter.",+ "examples": [+ "id",+ "experimentId",+ "filters, key, name"+ ],+ "label": "MCP input keys"+ },"$mcp_intent": {"description": "Free-text description of why the agent is calling this tool, written by the agent itself. Comes from a context argument the client supplied at call time, or \u2014 if none was supplied \u2014 from an intentFallback the MCP server provides.","examples": [@@ -7748,6 +7880,13 @@],"label": "MCP scope preset"},+ "$mcp_server_build": {+ "description": "The exact immutable build identifier that the MCP host supplies, such as a Git commit SHA or container image digest. Use it to connect an event to deployed code when one server version has multiple builds.",+ "examples": [+ "b3b941584bae0123"+ ],+ "label": "MCP server build"+ },"$mcp_server_name": {"description": "The advertised name of the MCP server that handled the request.","examples": [@@ -7821,6 +7960,14 @@],"label": "MCP transport"},+ "$mcp_validation_fields": {+ "description": "Parameter paths the MCP server's own input schema rejected, as `path:code` (for example `id:invalid_type`). Names from the tool's schema, never caller values. Only set when the server rejected the input before calling PostHog.",+ "examples": [+ "id:invalid_type",+ "filters.groups:required"+ ],+ "label": "MCP validation fields"+ },"$mcp_vendor_client": {"description": "Vendor client header the MCP client sent on the transport (x-anthropic-client), captured raw. The strongest harness signal: clientInfo.name can't tell one vendor surface from another, but this header can.","examples": [diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 82853b598406..3cadc39cabfe 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -5506,8 +5506,8 @@ importers:specifier: workspace:*version: link:../../packages/llm-normalizer'@posthog/mcp-analytics':- specifier: npm:@posthog/[email protected]- version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))'+ specifier: npm:@posthog/[email protected]+ version: '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))''@posthog/quill':specifier: workspace:*version: link:../../packages/quill/packages/quill@@ -10778,8 +10778,8 @@ packages:react: 18.3.1react-dom: 18.3.1- '@posthog/[email protected]':- resolution: {integrity: sha512-w+mu1kWRgZ6sZ0b4geABAS2QiuKX8MJlKiCe2DSwZ6gB48YF3Ijo67V7XPrpT1tph6X90lMvQm3lS8CxdYJfHQ==}+ '@posthog/[email protected]':+ resolution: {integrity: sha512-NbSJlf1XDLJBbNBFtQWIUKS5oooXb9B1gY6V7a+MLZOAyO8Ap7zAIzagsLkpFngvkEfd757uVtEP1YyAEcWIuw==}engines: {node: ^20.20.0 || >=22.22.0}peerDependencies:'@modelcontextprotocol/sdk': ^1.29.0@@ -30391,7 +30391,7 @@ snapshots:react: 18.3.1react-dom: 18.3.1([email protected])- '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))':+ '@posthog/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))':dependencies:'@posthog/core': 1.55.2posthog-node: 5.54.1([email protected])diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex e3c954fe5887..462ec18515ae 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -2947,6 +2947,31 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"description": "Field path the PostHog API's validation error pointed at, with array indexes normalized to N so one failure mode groups to one value. Only set for validation failures.","examples": ["actions__N__inputs__email", "query"],},+ "$mcp_validation_fields": {+ "label": "MCP validation fields",+ "description": "Parameter paths the MCP server's own input schema rejected, as `path:code` (for example `id:invalid_type`). Names from the tool's schema, never caller values. Only set when the server rejected the input before calling PostHog.",+ "examples": ["id:invalid_type", "filters.groups:required"],+ },+ "$mcp_input_keys": {+ "label": "MCP input keys",+ "description": "Top-level argument names the caller sent on a tool call, success or failure: every direct-mode call, `render-ui`, and an exec `call` (parsed from the command string). Exec discovery verbs (tools, search, info, schema) carry none, so rate against rows where it is set rather than every $mcp_tool_call. Recorded by the @posthog/mcp SDK helper: names the tool declares, including its aliases, capped at 20. Undeclared names become one `[redacted]` entry. Names only, never values. Group by it with $mcp_input_aliases_used to see how agents spell a parameter.",+ "examples": ["id", "experimentId", "filters, key, name"],+ },+ "$mcp_input_aliases_used": {+ "label": "MCP input aliases used",+ "description": "Declared parameter aliases the call relied on, as `alias:canonical` (for example `experimentId:id`). Present only when the call did not send the canonical name and used one of its aliases instead. Both names come from the tool's own alias map. Recorded by the @posthog/mcp SDK helper. Measures how much traffic the alias layer rescues, and which spellings agents reach for.",+ "examples": ["experimentId:id", "flagKey:key"],+ },+ "$mcp_exec_verb": {+ "label": "MCP exec verb",+ "description": "Which exec dispatcher verb the request ran: tools, search, info, schema, call, learn, or `unrecognized` for a verb the server does not accept. Only set in exec mode ($mcp_mode).",+ "examples": ["call", "info", "unrecognized"],+ },+ "$mcp_exec_target_tool": {+ "label": "MCP exec target tool",+ "description": "The tool an exec info, schema, or call verb named, when it resolves to a tool in the server's catalog; `unrecognized` otherwise so the caller's own token is never recorded. Links an `info` read to the `call` that follows it.",+ "examples": ["experiment-get", "unrecognized"],+ },"$mcp_auth_method": {"label": "MCP auth method","description": "Which credential the MCP request authenticated with, derived from the bearer token's prefix: oauth, personal_api_key, id_jag, none, or unknown. Stamped on every event by PostHog's own MCP server. Use it to tell an OAuth connector apart from an API-key connection — for example when a user works around a broken OAuth flow by switching to a personal API key.",@@ -2977,6 +3002,11 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"description": "The advertised name of the MCP server that handled the request.","examples": ["PostHog"],},+ "$mcp_server_build": {+ "label": "MCP server build",+ "description": "The exact immutable build identifier that the MCP host supplies, such as a Git commit SHA or container image digest. Use it to connect an event to deployed code when one server version has multiple builds.",+ "examples": ["b3b941584bae0123"],+ },"$mcp_server_version": {"label": "MCP server version","description": "The advertised version of the MCP server that handled the request.",diff --git a/services/mcp/package.json b/services/mcp/package.jsonindex 71d11a064b67..ab0449ed7d56 100644--- a/services/mcp/package.json+++ b/services/mcp/package.json@@ -51,7 +51,7 @@"@modelcontextprotocol/ext-apps": "^1.5.0","@modelcontextprotocol/sdk": "^1.29.0","@posthog/llm-normalizer": "workspace:*",- "@posthog/mcp-analytics": "npm:@posthog/[email protected]",+ "@posthog/mcp-analytics": "npm:@posthog/[email protected]","@posthog/quill": "workspace:*","@posthog/quill-charts": "workspace:*","@toon-format/toon": "^2.1.0",diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex ade2870ae2c6..dc4a666d3fee 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -27,12 +27,14 @@ import {createExecTool,describeApiValidationError,describeExecCommand,+ describeInputShape,describeValidationError,formatInputValidationError,markNoncanonicalMetricRun,parseExecCallInnerArgs,parseExecCallInnerToolName,repairArgumentNesting,+ UNRECOGNIZED_EXEC_TOKEN,type ExecCommandMeta,type ExecInnerCallTracker,} from '@/tools/exec'@@ -340,6 +342,8 @@ export class ToolExecutor {analyticsMeta?: ToolCallAnalyticsMeta): Promise<unknown> {const rawToolArgs = (params?.arguments ?? {}) as Record<string, unknown>+ // Computed on the raw input, before any alias is folded away by preprocess.+ const inputShape = inputShapeAnalyticsProperties(rawToolArgs, tool.schema)const firstPass = tool.schema.safeParse(rawToolArgs, { reportInput: true })const rewrapped = firstPass.success? undefined@@ -357,14 +361,17 @@ export class ToolExecutor {// Duration is 0: no handler ran (see `trackInnerCall`, same rule).const rejection = new ToolInputValidationError(message,- describeValidationError(validation.error, toolArgs, tool.schema)+ describeValidationError(validation.error, tool.schema))void trackToolCall(tool.name,0,true,state,- errorAnalyticsProperties(classifyToolError(rejection, tool.name), rejection),+ {+ ...inputShape,+ ...errorAnalyticsProperties(classifyToolError(rejection, tool.name), rejection),+ },analyticsMeta,this.servedToolDescription(tool.name))@@ -432,6 +439,7 @@ export class ToolExecutor {false,state,{+ ...inputShape,...skillShape,input_tokens: estimateTokens(validation.data),output_tokens: estimateResponseTokens(response),@@ -484,6 +492,7 @@ export class ToolExecutor {true,state,{+ ...inputShape,...errorAnalyticsProperties(classification, error),...(lookupMiss ? skillLookupMissProperties(lookupMiss.kind) : {}),},@@ -516,7 +525,7 @@ export class ToolExecutor {return { content: [{ type: 'text', text: lookupMiss.message }] }}- const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)+ const sessionUuid = await sessionUuidForError(state)return handleToolError(error, tool.name, state.distinctId, sessionUuid)}}@@ -536,11 +545,42 @@ export class ToolExecutor {const resolved = this.resolveExecTool(state, execMetrics, analyticsMeta)const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>++ // Which verb ran and which tool it targeted. Stamped on every exec event —+ // success and failure alike — so the discovery verbs stop collapsing into+ // one opaque `exec` bucket and an `info <tool>` can be linked to the+ // `call <tool>` that follows it. Read from the raw arguments so a rejected+ // wrapper records what it carried; the wrapper schema has no transform, so a+ // valid `command` is the same string either way.+ const execShape = execCommandAnalyticsProperties(toolArgs, state)+ // The inner tool's argument keys and any alias among them, read from the+ // command string the same way the dispatcher does. Only a `call` carries+ // arguments; the schema comes from this connection's catalog when the+ // target resolved to a tool in it.+ const execInputShape = execInputShapeAnalyticsProperties(toolArgs, execShape, state)const validation = resolved.schema.safeParse(toolArgs, { reportInput: true })if (!validation.success) {+ const wrapperInputShape = inputShapeAnalyticsProperties(toolArgs, resolved.schema)toolCallsTotal.inc({ tool: 'exec', status: 'validation_error' })+ const message = formatInputValidationError(resolved.name, validation.error)+ const rejection = new ToolInputValidationError(+ message,+ describeValidationError(validation.error, resolved.schema)+ )+ void trackToolCall(+ 'exec',+ 0,+ true,+ state,+ {+ ...execShape,+ ...wrapperInputShape,+ ...errorAnalyticsProperties(classifyToolError(rejection, 'exec'), rejection),+ },+ analyticsMeta+ )return {- content: [{ type: 'text', text: formatInputValidationError(resolved.name, validation.error) }],+ content: [{ type: 'text', text: message }],isError: true,}}@@ -557,11 +597,6 @@ export class ToolExecutor {// attributed to `exec`.const execToolName = (): string => execMetrics.innerToolName ?? 'exec'- // Which verb ran and which tool it targeted. Stamped on every exec event —- // success and failure alike — so the discovery verbs stop collapsing into- // one opaque `exec` bucket and an `info <tool>` can be linked to the- // `call <tool>` that follows it.- const execShape = execCommandAnalyticsProperties(validation.data, state)// Which stored skill an exec-routed read returned. Success only, unlike the// verb above: that records what the agent attempted, this records what it got.const execSkillShape = execSkillAnalyticsProperties(validation.data)@@ -597,6 +632,7 @@ export class ToolExecutor {state,{...execShape,+ ...execInputShape,...(failureShape ?? execSkillShape),...(execMetrics.skillLookupMissKind? skillLookupMissProperties(execMetrics.skillLookupMissKind)@@ -626,12 +662,17 @@ export class ToolExecutor {Date.now() - startMs,true,state,- { ...execShape, ...errorAnalyticsProperties(classification, error), ...execMetrics.commandMeta },+ {+ ...execShape,+ ...execInputShape,+ ...errorAnalyticsProperties(classification, error),+ ...execMetrics.commandMeta,+ },analyticsMeta,this.servedToolDescription(metricTool))- const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)+ const sessionUuid = await sessionUuidForError(state)// Attribute the failure to the inner tool that actually ran (e.g. `query-logs`),// not the `exec` wrapper — so the agent-facing `[tool]` label and the 5xx// exception fingerprint point at the real source instead of collapsing every@@ -784,9 +825,29 @@ export class ToolExecutor {}const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>+ // Same shape properties as every other tool call, so this event does not read+ // as a call that sent no arguments.+ const inputShape = inputShapeAnalyticsProperties(toolArgs, renderUiTool.schema)+const validation = renderUiTool.schema.safeParse(toolArgs)if (!validation.success) {toolCallsTotal.inc({ tool: 'render-ui', status: 'validation_error' })+ // The agent keeps zod's own message; the event gets the value-free one `callTool` records.+ const rejection = new ToolInputValidationError(+ formatInputValidationError('render-ui', validation.error),+ describeValidationError(validation.error, renderUiTool.schema)+ )+ void trackToolCall(+ 'render-ui',+ 0,+ true,+ state,+ {+ ...inputShape,+ ...errorAnalyticsProperties(classifyToolError(rejection, 'render-ui'), rejection),+ },+ analyticsMeta+ )return { content: [{ type: 'text', text: `Invalid input: ${validation.error.message}` }], isError: true }}@@ -796,7 +857,7 @@ export class ToolExecutor {const handlerResult = await renderUiTool.handler(state.context, validation.data)toolCallsTotal.inc({ tool: 'render-ui', status: 'success' })stop({ status: 'success' })- void trackToolCall('render-ui', Date.now() - startMs, false, state, undefined, analyticsMeta)+ void trackToolCall('render-ui', Date.now() - startMs, false, state, inputShape, analyticsMeta)// The handler always returns an exec-built payload (UI resourceUri + structuredContent).return handlerResult} catch (error: unknown) {@@ -808,10 +869,10 @@ export class ToolExecutor {Date.now() - startMs,true,state,- errorAnalyticsProperties(classification, error),+ { ...inputShape, ...errorAnalyticsProperties(classification, error) },analyticsMeta)- const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)+ const sessionUuid = await sessionUuidForError(state)return handleToolError(error, 'render-ui', state.distinctId, sessionUuid)}}@@ -833,8 +894,6 @@ interface ToolErrorClassification {status?: number/** Value-free descriptors of a schema rejection (offending field+code). */validationFields?: string[]- /** Top-level keys the caller sent — surfaces unaccepted aliases on a union rejection. */- validationInputKeys?: string[]/** Machine-readable leaf failure code: the API's validation error code or the exec rejection reason. */errorCode?: string/** Field path the API's validation error pointed at, array indexes normalized to `N`. */@@ -862,7 +921,6 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassificationreturn {errorType: 'validation',...(error.fields.length ? { validationFields: error.fields } : {}),- ...(error.inputKeys.length ? { validationInputKeys: error.inputKeys } : {}),}}// Agent-recoverable command mistakes, so keep them out of the `internal` rate@@ -886,9 +944,7 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassificationconst errorCode = apiError.code ? sanitizeErrorToken(apiError.code) : undefinedconst errorField = apiError.attr ? normalizeErrorField(apiError.attr) : undefined// Same descriptor property and format as a local schema rejection, so one- // query covers both layers. There is no `validationInputKeys` counterpart:- // the request body reached the API, so the keys it carried aren't ours to- // reconstruct here.+ // query covers both layers.return {errorType: 'validation',validationFields: describeApiValidationError(apiError.attr, apiError.code),@@ -1000,6 +1056,67 @@ function safeUrlPath(url: string): string {}}+/** The session lookup reads and writes Redis; an outage there must not replace the structured tool error. */+async function sessionUuidForError(state: ResolvedState): Promise<string | undefined> {+ try {+ return await state.reqCtx.getEffectiveSessionUuid(state.requestContext)+ } catch {+ return undefined+ }+}++/**+ * `$mcp_input_keys`: the safe top-level argument names the caller sent, on every+ * event, success and failure alike. Names only, never values (see `describeInputShape`).+ *+ * `$mcp_input_aliases_used`: which declared aliases the call relied on, as+ * `alias:canonical`, present only when at least one was. Both halves are names+ * the tool's own schema declares.+ */+function inputShapeAnalyticsProperties(+ input: unknown,+ schema: ResolvedTool['schema'] | undefined+): Record<string, unknown> {+ // `params.arguments` is an unvalidated cast until `safeParse` runs; only a plain+ // object carries argument names, and walking a string or an array here would build+ // one entry per character or element before the schema gets to reject it.+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {+ return {}+ }+ return describeInputShape(input, schema)+}++/** The target `describeExecCommand` recorded, when it resolved to a real tool name. */+function recordedTargetTool(execShape: Record<string, unknown>): string | undefined {+ const target = execShape.$mcp_exec_target_tool+ return typeof target === 'string' && target !== UNRECOGNIZED_EXEC_TOKEN ? target : undefined+}++/**+ * The exec-mode counterpart of `inputShapeAnalyticsProperties`: the inner arguments+ * live as JSON inside `command`, so they are parsed with the dispatcher's own parser.+ * Verbs other than `call` carry no arguments and get no keys. The schema is looked up+ * only among the tools this connection can see. A gated or retired target has no schema,+ * so its keys become one `[redacted]` marker and its aliases stay absent.+ */+function execInputShapeAnalyticsProperties(+ execArgs: unknown,+ execShape: Record<string, unknown>,+ state: ResolvedState+): Record<string, unknown> {+ const command = (execArgs as { command?: unknown } | undefined)?.command+ if (typeof command !== 'string' || execShape.$mcp_exec_verb !== 'call') {+ return {}+ }+ const innerArgs = parseExecCallInnerArgs(command)+ if (!innerArgs) {+ return {}+ }+ const target = recordedTargetTool(execShape)+ const schema = target ? state.allTools.find((tool) => tool.name === target)?.schema : undefined+ return inputShapeAnalyticsProperties(innerArgs, schema)+}+/*** Properties stamped onto an errored `$mcp_tool_call` so the dashboard can slice* failures by reason. `$mcp_error_type` aligns with the SDK's native field; the@@ -1017,9 +1134,6 @@ function errorAnalyticsProperties(classification: ToolErrorClassification, error$mcp_error_type: classification.errorType,...(classification.status !== undefined ? { $mcp_error_status: classification.status } : {}),...(classification.validationFields?.length ? { $mcp_validation_fields: classification.validationFields } : {}),- ...(classification.validationInputKeys?.length- ? { $mcp_validation_input_keys: classification.validationInputKeys }- : {}),...(classification.errorCode ? { $mcp_error_code: classification.errorCode } : {}),...(classification.errorField ? { $mcp_error_field: classification.errorField } : {}),...(message !== undefined ? { $mcp_error_message: message } : {}),diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex a7731d92c529..51dea5d79218 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -129,17 +129,13 @@ export class PostHogValidationError extends Error {* noise problem the 4xx short-circuit exists to prevent.*/export class ToolInputValidationError extends Error {- /** Value-free descriptors of the rejection for telemetry: offending- * field paths + issue codes, and the top-level keys the caller sent. Never- * includes input VALUES — see `describeValidationError`. */+ /** Value-free descriptors of the rejection for telemetry. */public readonly fields: string[]- public readonly inputKeys: string[]- constructor(message: string, detail?: { fields?: string[]; inputKeys?: string[] }) {+ constructor(message: string, detail?: { fields?: string[] }) {super(message)this.name = 'ToolInputValidationError'this.fields = detail?.fields ?? []- this.inputKeys = detail?.inputKeys ?? []}}diff --git a/services/mcp/src/lib/posthog/client.ts b/services/mcp/src/lib/posthog/client.tsindex 05898dc1f23c..f0b5e2452c87 100644--- a/services/mcp/src/lib/posthog/client.ts+++ b/services/mcp/src/lib/posthog/client.ts@@ -1,14 +1,22 @@+import { readFileSync } from 'node:fs'+import { PostHogMCP } from '@posthog/mcp-analytics'import { env } from '@/lib/env'let _client: PostHogMCP | undefined-// `PostHogMCP` is a drop-in subclass of posthog-node's `PostHog` (capture /-// identify / flush / shutdown all inherited) that adds `captureToolCall` /-// `captureInitialize`. Using it for the shared client means every existing-// `.capture()` callsite keeps working while the hono analytics path gets the-// canonical `$mcp_*` event helpers.+export const getMCPServerBuild = (): string | undefined => {+ try {+ const build = readFileSync('/code/commit.txt', 'utf8').trim()+ return build && build !== 'unknown' ? build : undefined+ } catch {+ return undefined+ }+}++// `PostHogMCP` owns canonical MCP events and custom events from `capture()` or+// `captureImmediate()`. Configure `serverBuild` once so the SDK stamps both paths.export const getPostHogClient = (): PostHogMCP => {if (!_client) {_client = new PostHogMCP(env.POSTHOG_ANALYTICS_API_KEY ?? '', {@@ -20,6 +28,7 @@ export const getPostHogClient = (): PostHogMCP => {// from fanning out a separate `$exception` event into Error Tracking.enableExceptionAutocapture: false,captureModel: true,+ serverBuild: getMCPServerBuild(),before_send: (event) => {if (event?.properties?.is_impersonated === true) {return nulldiff --git a/services/mcp/src/tools/cast-helpers.ts b/services/mcp/src/tools/cast-helpers.tsindex ba733795b678..5f47a55b95dc 100644--- a/services/mcp/src/tools/cast-helpers.ts+++ b/services/mcp/src/tools/cast-helpers.ts@@ -1,3 +1,5 @@+import { z } from 'zod'+/*** Input casts for permissive zod schemas at the MCP tool boundary.*@@ -66,9 +68,8 @@ export const castBooleanToString = (v: unknown): unknown => (typeof v === 'boole* Wired up declaratively via `param_overrides: { id: { aliases: [...] } }` in* product `tools.yaml` files — see services/mcp/scripts/generate-tools.ts.*/-export const normalizeParamAliases =- (aliasMap: Record<string, readonly string[]>) =>- (input: unknown): unknown => {+export const normalizeParamAliases = (aliasMap: Record<string, readonly string[]>): ((input: unknown) => unknown) => {+ const normalize = (input: unknown): unknown => {if (input === null || typeof input !== 'object' || Array.isArray(input)) {return input}@@ -90,3 +91,42 @@ export const normalizeParamAliases =}return result}+ ALIAS_MAPS.set(normalize, aliasMap)+ return normalize+}++/**+ * Alias maps keyed by the preprocess function that applies them. Telemetry reads the+ * map back off a tool's schema to record which alias a call carried, so the map has+ * one source of truth: the same `normalizeParamAliases(...)` call the schema uses.+ */+const ALIAS_MAPS = new WeakMap<(input: unknown) => unknown, Record<string, readonly string[]>>()++/** Deeper than any tool stacks `z.preprocess` today; bounds the walk over a malformed pipe chain. */+const MAX_PREPROCESS_DEPTH = 8++/**+ * The alias maps a schema applies, merged across nested `z.preprocess(normalizeParamAliases(...), ...)`+ * layers, or undefined when it applies none. Walks the pipe chain that `z.preprocess` builds+ * (`ZodPipe` with the transform on `.in`), the same way `schemaHasOutputFormat` walks `.out`.+ * Only a `normalizeParamAliases(...)` closure passed straight to `z.preprocess` is found; a tool+ * that calls it from inside its own preprocess function (`read-data-schema`) reads as alias-free.+ */+export function readParamAliases(schema: z.ZodType): Record<string, readonly string[]> | undefined {+ let merged: Record<string, readonly string[]> | undefined+ let current: unknown = schema+ for (let depth = 0; depth < MAX_PREPROCESS_DEPTH && current instanceof z.ZodPipe; depth++) {+ const transform = (current.in as { def?: { transform?: unknown } }).def?.transform+ const aliasMap =+ typeof transform === 'function' ? ALIAS_MAPS.get(transform as (input: unknown) => unknown) : undefined+ if (aliasMap) {+ // Outer layers normalise first, so their aliases come first for a shared canonical.+ merged ??= {}+ for (const [canonical, aliases] of Object.entries(aliasMap)) {+ merged[canonical] = [...new Set([...(merged[canonical] ?? []), ...aliases])]+ }+ }+ current = current.out+ }+ return merged+}diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 5895d2a63145..309fcaa8c8fd 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -1,6 +1,8 @@import { stringify as stringifyYaml } from 'yaml'import { z } from 'zod'+import { getToolInputProperties } from '@posthog/mcp-analytics'+import { classifyAuthMethod } from '@/lib/auth-method'import { markExecPayload, buildToolResultPayload, estimateResponseTokens } from '@/lib/build-tool-result'import { isPostHogCodeConsumer } from '@/lib/client-detection'@@ -18,6 +20,7 @@ import { formatResponse } from '@/lib/response'import { API_KEY_CACHE_TTL_MS } from '@/lib/StateManager'import { APP_DATA_META_KEY } from '@/ui-apps/types'+import { readParamAliases } from './cast-helpers'import { type ExecLearnCatalog, QUALIFIED_IDENTIFIER, tokenizeLearnInput } from './exec-learn'import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'import { type BuiltInSkillHint, formatSkillLookupMiss, type SkillLookupMissKind } from './skills/notFound'@@ -467,7 +470,7 @@ const TOOL_TARGETING_VERBS = new Set(['info', 'schema', 'call'])* reason (it echoes the caller's tool name); the rejection reason on the event says* which of the two failed, so the sentinel loses only the misspelling itself.*/-const UNRECOGNIZED_EXEC_TOKEN = 'unrecognized'+export const UNRECOGNIZED_EXEC_TOKEN = 'unrecognized'export interface ExecCommandShape {/** The dispatcher verb, or `unrecognized` when it isn't one we accept. */@@ -1480,9 +1483,6 @@ export function describeApiValidationError(attr: string | undefined, code: strin* `fields` are the offending field path + issue code, plus the received type where* that distinguishes the bug (e.g. `id:invalid_type:undefined` for an omitted* parameter vs `query:invalid_union:string` for an envelope the agent flattened).- * `inputKeys` — the top-level keys the caller actually sent — is what surfaces an- * unaccepted alias (e.g. `organizationId` where the schema wants `orgId`).- ** Records only structural information: field names, issue codes, and the TYPE of a* rejected value. It never records input VALUES — the ZodError embeds those in* `issue.input` and in `.message` (see `formatInputValidationError`), so this reads@@ -1490,11 +1490,7 @@ export function describeApiValidationError(attr: string | undefined, code: strin* true of the field paths as well: a key the schema never declared belongs to the* caller, so it is masked rather than recorded (see `normalizeDescriptorPath`).*/-export function describeValidationError(- error: z.ZodError,- input: Record<string, unknown>,- schema: z.ZodType-): { fields: string[]; inputKeys: string[] } {+export function describeValidationError(error: z.ZodError, schema: z.ZodType): { fields: string[] } {const declaredNames = declaredPropertyNames(schema)const fields = [...new Set(@@ -1510,11 +1506,22 @@ export function describeValidationError(})),].slice(0, MAX_VALIDATION_DESCRIPTORS)- const inputKeys = Object.keys(input)- .sort()- .slice(0, MAX_VALIDATION_DESCRIPTORS)- .map((key) => key.slice(0, MAX_KEY_LENGTH))- return { fields, inputKeys }+ return { fields }+}++/**+ * `$mcp_input_keys` and `$mcp_input_aliases_used` for one call, from the SDK helper, with no+ * values. The alias map comes from the schema's own `normalizeParamAliases` layers, so+ * alias names count as declared and each alias the normaliser relied on is recorded as+ * `alias:canonical`. The SDK owns the limits (20 names, 64 characters), declared-names-first+ * ordering, and dropping its injected `context`, `llm_model`, and `conversation_id` unless the+ * schema declares them. Undeclared names become one `[redacted]` marker because caller-controlled+ * names can contain credentials or personal data.+ */+export function describeInputShape(input: unknown, schema?: z.ZodType): Record<string, unknown> {+ return getToolInputProperties(input, schema, {+ inputAliases: schema ? readParamAliases(schema) : undefined,+ })}/** Whether the tool's input schema declares an `output_format` field. Unwraps@@ -1983,7 +1990,7 @@ export function createExecTool(// which field/alias was rejected — without the payload.throw new ToolInputValidationError(message,- describeValidationError(validation.error, input, toolSchema)+ describeValidationError(validation.error, toolSchema))}input = validation.data as Record<string, unknown>diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 3f0c5f74b8bb..5966408bcbaf 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -50,6 +50,8 @@ import {ToolInputValidationError,wrapError,} from '@/lib/errors'+import { URI_MAP } from '@/resources/ui-apps.generated'+import { normalizeParamAliases } from '@/tools/cast-helpers'import { makeToolExecutorState, mockApi, toolFromPreBuilt } from '../shared/test-utils'@@ -61,6 +63,10 @@ function trackToolCallExtras(tool: string): Record<string, unknown> | undefinedreturn call?.[4]}+function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {+ return makeToolExecutorState(tools as any, overrides)+}+type FakeToolBase = { schema: z.ZodObject<Record<string, never>>; handler: ReturnType<typeof vi.fn>; _meta: undefined }function makeFakeTool(@@ -139,11 +145,16 @@ describe('ToolExecutor metrics', () => {)await executor.handleToolCall(- { name: 'fail-tool', arguments: {} },- makeToolExecutorState([{ name: 'fail-tool' }])+ { name: 'fail-tool', arguments: { experimentId: 29 } },+ makeState([{ name: 'fail-tool' }]))- expect(trackToolCallExtras('fail-tool')).toMatchObject({ $mcp_error_type: 'internal' })+ // The errored event carries the call's shape too; this is the path the+ // property exists for.+ expect(trackToolCallExtras('fail-tool')).toMatchObject({+ $mcp_error_type: 'internal',+ $mcp_input_keys: ['[redacted]'],+ })})// $mcp_error_message is readable by every analytics viewer in the project, not just@@ -438,10 +449,10 @@ describe('ToolExecutor metrics', () => {expect(call[1]).toBe(0)expect(trackToolCallExtras('strict-tool')).toMatchObject({$mcp_error_type: 'validation',+ $mcp_input_keys: ['[redacted]'],// `:undefined` is the received type — the param was absent, not// mistyped, which is what separates an alias slip from a coercion bug.$mcp_validation_fields: ['required_field:invalid_type:undefined'],- $mcp_validation_input_keys: ['requiredField'],})})@@ -461,6 +472,83 @@ describe('ToolExecutor metrics', () => {})})+ // The shape is read from the raw input, before preprocess folds the alias away.+ it('stamps the input keys and the alias used on a successful direct call', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue({+ name: 'alias-tool',+ build() {+ return this.base+ },+ base: {+ schema: z.preprocess(normalizeParamAliases({ id: ['experimentId'] }), z.object({ id: z.number() })),+ handler: vi.fn().mockResolvedValue('ok'),+ _meta: undefined,+ },+ } as any)++ await executor.handleToolCall(+ { name: 'alias-tool', arguments: { experimentId: 29, llm_model: 'claude', context: {} } },+ makeState([{ name: 'alias-tool' }])+ )++ const call = mockTrackToolCall.mock.calls.find((c) => c[0] === 'alias-tool')!+ expect(call[2]).toBe(false)+ expect(call[4]).toMatchObject({+ // SDK-injected arguments are not something the agent chose to send.+ $mcp_input_keys: ['experimentId'],+ $mcp_input_aliases_used: ['experimentId:id'],+ })+ expect(JSON.stringify(call[4])).not.toContain('29')+ })++ // `params.arguments` is whatever JSON arrived. A string or array is rejected by+ // the schema, and must not be walked as if it were an argument object first.+ it('records no input keys when arguments is not an object', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('ok-tool') as any)++ await executor.handleToolCall(+ { name: 'ok-tool', arguments: 'x'.repeat(10_000) as unknown as Record<string, unknown> },+ makeState([{ name: 'ok-tool' }])+ )++ const call = mockTrackToolCall.mock.calls.find((c) => c[0] === 'ok-tool')!+ expect(call[2]).toBe(true)+ expect(call[4]).not.toHaveProperty('$mcp_input_keys')+ })++ it('stamps the input keys on a rejected direct call, without an alias property', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue({+ name: 'strict-tool',+ build() {+ return this.base+ },+ base: { schema: z.object({ required_field: z.string() }), handler: vi.fn(), _meta: undefined },+ } as any)++ await executor.handleToolCall(+ { name: 'strict-tool', arguments: { requiredField: 'x' } },+ makeState([{ name: 'strict-tool' }])+ )++ const extras = trackToolCallExtras('strict-tool')+ expect(extras).toMatchObject({ $mcp_input_keys: ['[redacted]'] })+ expect(extras).not.toHaveProperty('$mcp_input_aliases_used')+ })++ it('returns the structured tool error when the session lookup fails', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(+ makeFakeTool('failing-tool', async () => {+ throw new Error('boom')+ }) as any+ )+ const state = makeState([{ name: 'failing-tool' }])+ vi.mocked(state.reqCtx.getEffectiveSessionUuid).mockRejectedValue(new Error('redis down'))++ const result = await executor.handleToolCall({ name: 'failing-tool', arguments: {} }, state)++ expect((result as any).isError).toBe(true)+ })+it('records error for unknown tool', async () => {await executor.handleToolCall({ name: 'nonexistent', arguments: {} }, makeToolExecutorState([]))@@ -530,6 +618,38 @@ describe('ToolExecutor metrics', () => {expect(extras).not.toHaveProperty('mcp_discovery_hint')})+ // In exec mode the inner arguments are JSON inside `command`, so the direct+ // path's wiring alone would record nothing about the shape of nearly every call.+ it('stamps the inner input keys and alias on an exec call', async () => {+ await executor.handleToolCall(+ {+ name: 'exec',+ arguments: { command: 'call feature-flag-get-definition-by-key {"flagKey": "checkout-v2"}' },+ },+ execState()+ )++ const extras = mockTrackToolCall.mock.calls.at(-1)?.[4]+ expect(extras).toMatchObject({+ $mcp_exec_verb: 'call',+ $mcp_input_keys: ['flagKey'],+ $mcp_input_aliases_used: ['flagKey:key'],+ })+ expect(JSON.stringify(extras)).not.toContain('checkout-v2')+ })++ it.each([+ ['info docs-search'],+ ['schema docs-search query'],+ ['tools'],+ // An unparseable body carries no keys either.+ ['call docs-search {not json'],+ ])('stamps no input keys for "%s"', async (command) => {+ await executor.handleToolCall({ name: 'exec', arguments: { command } }, execState())++ expect(mockTrackToolCall.mock.calls.at(-1)?.[4]).not.toHaveProperty('$mcp_input_keys')+ })+// A name a feature flag retired is one we own, so it is recordable like any// other. Recorded as unrecognized instead, the `gated_tool` class counts the// wasted round trips without naming the rename that caused them.@@ -634,6 +754,21 @@ describe('ToolExecutor metrics', () => {})})+ it('emits an errored event when the exec wrapper schema rejects the arguments', async () => {+ const result = await executor.handleToolCall({ name: 'exec', arguments: { cmd: 'tools' } }, execState())++ expect((result as any).isError).toBe(true)+ expect(callsFor(mockToolCallsInc, 'exec')).toEqual([{ tool: 'exec', status: 'validation_error' }])+ const call = mockTrackToolCall.mock.calls.find((c) => c[0] === 'exec')+ expect(call?.[1]).toBe(0)+ expect(call?.[2]).toBe(true)+ expect(call?.[4]).toMatchObject({+ $mcp_input_keys: ['[redacted]'],+ $mcp_error_type: 'validation',+ })+ expect(call?.[4]).not.toHaveProperty('$mcp_exec_verb')+ })+// Reading a stored skill is one of the most common tool calls, and nearly all of// them arrive here, as JSON inside a command string rather than as tool arguments.// Without this the event records that *a* skill was read but never which one.@@ -790,4 +925,29 @@ describe('ToolExecutor metrics', () => {})})})++ describe('render-ui', () => {+ const uiAppTool = {+ name: 'survey-get',+ annotations: { readOnlyHint: true },+ _meta: { ui: { resourceUri: URI_MAP['survey'] } },+ }++ it('emits an errored event when the wrapper schema rejects the arguments', async () => {+ const result = await executor.handleToolCall(+ { name: 'render-ui', arguments: { toolName: 'survey-get' } },+ makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })+ )++ expect((result as any).isError).toBe(true)+ expect(callsFor(mockToolCallsInc, 'render-ui')).toEqual([{ tool: 'render-ui', status: 'validation_error' }])+ const call = mockTrackToolCall.mock.calls.find((c) => c[0] === 'render-ui')+ expect(call?.[1]).toBe(0)+ expect(call?.[2]).toBe(true)+ expect(call?.[4]).toMatchObject({+ $mcp_input_keys: ['[redacted]'],+ $mcp_error_type: 'validation',+ })+ })+ })})diff --git a/services/mcp/tests/unit/cast-helpers.test.ts b/services/mcp/tests/unit/cast-helpers.test.tsindex 8e2910cd688c..476215974816 100644--- a/services/mcp/tests/unit/cast-helpers.test.ts+++ b/services/mcp/tests/unit/cast-helpers.test.ts@@ -10,7 +10,12 @@import { describe, expect, it } from 'vitest'import { z } from 'zod'-import { castBooleanToString, castStringToInt } from '../../src/tools/cast-helpers'+import {+ castBooleanToString,+ castStringToInt,+ normalizeParamAliases,+ readParamAliases,+} from '../../src/tools/cast-helpers'describe('castStringToInt', () => {const schema = z.preprocess(castStringToInt, z.number().int())@@ -79,3 +84,37 @@ describe('castBooleanToString', () => {expect(() => schema.parse(input)).toThrow()})})++describe('readParamAliases', () => {+ it('reads the alias map back off a preprocess-wrapped schema', () => {+ const schema = z.preprocess(+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),+ z.object({ id: z.number() })+ )++ expect(readParamAliases(schema)).toEqual({ id: ['experimentId', 'experiment_id'] })+ })++ it('merges the maps of nested preprocess layers', () => {+ const inner = z.preprocess(+ normalizeParamAliases({ id: ['experimentId'] }),+ z.object({ id: z.number(), key: z.string() })+ )+ const outer = z.preprocess(normalizeParamAliases({ key: ['flagKey'] }), inner)++ expect(readParamAliases(outer)).toEqual({ id: ['experimentId'], key: ['flagKey'] })+ })++ it('keeps the aliases of every layer that declares the same canonical, outer first', () => {+ const inner = z.preprocess(normalizeParamAliases({ id: ['experiment_id'] }), z.object({ id: z.number() }))+ const outer = z.preprocess(normalizeParamAliases({ id: ['experimentId'] }), inner)++ expect(readParamAliases(outer)).toEqual({ id: ['experimentId', 'experiment_id'] })+ })++ it('returns undefined for a schema that declares no aliases', () => {+ expect(readParamAliases(z.object({ id: z.number() }))).toBeUndefined()+ // A preprocess that is not an alias normaliser is not mistaken for one.+ expect(readParamAliases(z.preprocess((value) => value, z.object({ id: z.number() })))).toBeUndefined()+ })+})diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex a7f1460739a8..1c59ed32af3e 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -11,10 +11,12 @@ import { InstructionsFormatter } from '@/lib/instructions-formatter'import { formatResponse } from '@/lib/response'import { SessionManager } from '@/lib/SessionManager'import { getToolsFromContext } from '@/tools'+import { normalizeParamAliases } from '@/tools/cast-helpers'import {createExecTool,describeApiValidationError,describeExecCommand,+ describeInputShape,describeValidationError,type ExecCommandMeta,type ExecInnerCallProperties,@@ -2059,29 +2061,108 @@ describe('exec tool', () => {})})- describe('describeValidationError', () => {- it('surfaces the unaccepted top-level key on a union rejection without leaking values', () => {- // The switch-organization regression shape: a union rejection carries an- // empty issue path, so `inputKeys` is what makes the wrong alias diagnosable.- const schema = z.union([z.object({ orgId: z.string() }), z.object({ id: z.string() })])- const input = { organizationId: 'super-secret-org-uuid' }- const result = schema.safeParse(input, { reportInput: true })- expect(result.success).toBe(false)+ describe('describeInputShape', () => {+ const inputKeys = (input: unknown, schema?: z.ZodType): unknown =>+ describeInputShape(input, schema).$mcp_input_keys- const detail = describeValidationError(result.error!, input, schema)+ it('lists the top-level keys sorted, without values', () => {+ const schema = z.object({ zeta: z.string(), alpha: z.number(), mid: z.object({ nested: z.string() }) })+ const keys = inputKeys({ zeta: 'secret-value', alpha: 1, mid: { nested: 'also-secret' } }, schema)- expect(detail.inputKeys).toEqual(['organizationId'])- // Never record input values — the raw uuid must not appear anywhere.- expect(JSON.stringify(detail)).not.toContain('super-secret-org-uuid')+ expect(keys).toEqual(['alpha', 'mid', 'zeta'])+ expect(JSON.stringify(keys)).not.toContain('secret')})+ it('caps the count at 20 and masks a key longer than 64 characters', () => {+ const wide = Object.fromEntries(Array.from({ length: 30 }, (_, i) => [`k${String(i).padStart(2, '0')}`, i]))+ const schema = z.object(Object.fromEntries(Object.keys(wide).map((key) => [key, z.number()])))+ expect(inputKeys(wide, schema)).toHaveLength(20)++ // A 100-character key is not a parameter spelling; it is recorded as masked, not truncated.+ const long = 'x'.repeat(100)+ expect(inputKeys({ [long]: 1 })).toEqual(['[redacted]'])+ })++ // `params.arguments` is an unvalidated cast until the schema runs; a string or+ // array there is not an argument object, and walking one builds an entry per+ // character or element.+ it('records nothing for input that is not a plain object', () => {+ expect(inputKeys('a'.repeat(1000))).toBeUndefined()+ expect(inputKeys(['a', 'b'])).toBeUndefined()+ expect(inputKeys(null)).toBeUndefined()+ })++ it('drops SDK-injected keys and masks a key that is not identifier-shaped', () => {+ expect(+ inputKeys({ context: {}, llm_model: 'x', conversation_id: 'c', id: 1 }, z.object({ id: z.number() }))+ ).toEqual(['id'])+ expect(inputKeys({ context: {}, id: 1 }, z.object({ context: z.string(), id: z.number() }))).toEqual([+ 'context',+ 'id',+ ])+ // Free text in a key name is caller text; the property records names only.+ expect(inputKeys({ 'drop table users; --': 1, ok_key: 2 }, z.object({ ok_key: z.number() }))).toEqual([+ 'ok_key',+ '[redacted]',+ ])+ })++ it('records declared names before misspelled ones when the limit is reached', () => {+ const declared = Object.fromEntries(+ Array.from({ length: 20 }, (_, i) => [`d${String(i).padStart(2, '0')}`, i])+ )+ const schema = z.preprocess(+ (value) => value,+ z.object(Object.fromEntries(Object.keys(declared).map((key) => [key, z.number()])))+ )+ const keys = inputKeys({ aaa_misspelled: 1, ...declared }, schema)+ expect(keys).toEqual(Object.keys(declared))+ })++ describe('aliases', () => {+ const schema = z.preprocess(+ normalizeParamAliases({ id: ['experimentId', 'experiment_id'] }),+ z.preprocess(normalizeParamAliases({ key: ['flagKey'] }), z.object({ id: z.number(), key: z.string() }))+ )++ it('records each alias the normaliser relied on, from every alias layer', () => {+ expect(describeInputShape({ flagKey: 'k', experimentId: 1 }, schema)).toEqual({+ $mcp_input_keys: ['experimentId', 'flagKey'],+ $mcp_input_aliases_used: ['experimentId:id', 'flagKey:key'],+ })+ })++ // Mirrors the normaliser: a canonical the input already carries is never filled+ // from an alias, and only the first alias in map order fills it. Recording the+ // rest would count rescues that never happened.+ it('records only the alias the normaliser relied on', () => {+ expect(describeInputShape({ id: 5, experimentId: 5 }, schema)).not.toHaveProperty(+ '$mcp_input_aliases_used'+ )+ expect(describeInputShape({ experimentId: 1, experiment_id: 2 }, schema)).toMatchObject({+ $mcp_input_aliases_used: ['experimentId:id'],+ })+ expect(describeInputShape({ experimentId: 1 }, z.object({ id: z.number() }))).toEqual({+ $mcp_input_keys: ['[redacted]'],+ })+ })++ it('never includes input values', () => {+ expect(JSON.stringify(describeInputShape({ experimentId: 'secret-value' }, schema))).not.toContain(+ 'secret-value'+ )+ })+ })+ })++ describe('describeValidationError', () => {it('records field path + issue code for a wrong-typed field, still without values', () => {const schema = z.object({ projectId: z.number() })const input = { projectId: 'not-a-number' }const result = schema.safeParse(input, { reportInput: true })expect(result.success).toBe(false)- const detail = describeValidationError(result.error!, input, schema)+ const detail = describeValidationError(result.error!, schema)expect(detail.fields).toContain('projectId:invalid_type:string')expect(JSON.stringify(detail)).not.toContain('not-a-number')@@ -2102,9 +2183,7 @@ describe('exec tool', () => {const result = schema.safeParse(input, { reportInput: true })expect(result.success).toBe(false)- expect(describeValidationError(result.error!, input as Record<string, unknown>, schema).fields).toEqual([- expected,- ])+ expect(describeValidationError(result.error!, schema).fields).toEqual([expected])})// The received type is only meaningful for the type-shaped codes; appending it@@ -2115,7 +2194,7 @@ describe('exec tool', () => {const result = schema.safeParse(input, { reportInput: true })expect(result.success).toBe(false)- expect(describeValidationError(result.error!, input, schema).fields).toEqual(['description:too_big'])+ expect(describeValidationError(result.error!, schema).fields).toEqual(['description:too_big'])})// A malformed array produces one issue per element. Collapsing indices keeps@@ -2134,7 +2213,7 @@ describe('exec tool', () => {const result = schema.safeParse(input, { reportInput: true })expect(result.success).toBe(false)- const { fields } = describeValidationError(result.error!, input as Record<string, unknown>, schema)+ const { fields } = describeValidationError(result.error!, schema)expect(fields).toEqual(['series.N.event:invalid_type:number', 'dateRange:invalid_type:number'])})@@ -2152,7 +2231,7 @@ describe('exec tool', () => {const result = schema.safeParse(input, { reportInput: true })expect(result.success).toBe(false)- const detail = describeValidationError(result.error!, input as Record<string, unknown>, schema)+ const detail = describeValidationError(result.error!, schema)expect(detail.fields).toEqual(['params.*:invalid_type:number'])expect(JSON.stringify(detail)).not.toContain('sk-live-abc123')@@ -2167,7 +2246,7 @@ describe('exec tool', () => {const result = schema.safeParse(input, { reportInput: true })expect(result.success).toBe(false)- expect(describeValidationError(result.error!, input, schema).fields).toEqual(['query.kind:invalid_value'])+ expect(describeValidationError(result.error!, schema).fields).toEqual(['query.kind:invalid_value'])})})diff --git a/services/mcp/tests/unit/mcp-property-taxonomy.test.ts b/services/mcp/tests/unit/mcp-property-taxonomy.test.tsnew file mode 100644index 000000000000..1666140fcfd0--- /dev/null+++ b/services/mcp/tests/unit/mcp-property-taxonomy.test.ts@@ -0,0 +1,74 @@+import { readdirSync, readFileSync } from 'node:fs'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { describe, expect, it } from 'vitest'++import { PostHogMCPAnalyticsProperty } from '@posthog/mcp-analytics'++const REPO_ROOT = fileURLToPath(new URL('../../../../', import.meta.url))+const MCP_SOURCE = join(REPO_ROOT, 'services/mcp/src')+const TAXONOMY_PATH = join(REPO_ROOT, 'frontend/src/taxonomy/core-filter-definitions-by-group.json')++// These properties need taxonomy work. This list keeps existing gaps explicit and rejects new gaps.+const KNOWN_UNREGISTERED_MCP_PROPERTIES = new Set([+ '$mcp_skill_lookup_miss_kind',+ '$mcp_app_name',+ '$mcp_app_version',+ '$mcp_app_instance_id',+ '$mcp_feedback_details',+ '$mcp_feedback_friction_points',+ '$mcp_feedback_sentiment',+ '$mcp_feedback_suggested_improvement',+ '$mcp_feedback_summary',+ '$mcp_feedback_task_completed',+ '$mcp_feedback_tool',+ '$mcp_feedback_type',+])++function typescriptFiles(directory: string): string[] {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const path = join(directory, entry.name)+ if (entry.isDirectory()) {+ return typescriptFiles(path)+ }+ return entry.name.endsWith('.ts') || entry.name.endsWith('.tsx') ? [path] : []+ })+}++function stampedServerProperties(): Set<string> {+ const properties = new Set<string>()+ for (const path of typescriptFiles(MCP_SOURCE)) {+ for (const match of readFileSync(path, 'utf8').matchAll(/\$mcp_[a-z0-9_]+(?=\s*:)/g)) {+ properties.add(match[0])+ }+ }+ return properties+}++function registeredProperties(): Set<string> {+ const taxonomy = JSON.parse(readFileSync(TAXONOMY_PATH, 'utf8')) as {+ event_properties: Record<string, unknown>+ }+ return new Set(Object.keys(taxonomy.event_properties))+}++describe('MCP property taxonomy', () => {+ it('registers properties from the server and SDK', () => {+ const stamped = stampedServerProperties()+ for (const property of Object.values(PostHogMCPAnalyticsProperty)) {+ if (property.startsWith('$mcp_')) {+ stamped.add(property)+ }+ }+ expect(stamped.size).toBeGreaterThan(20)++ const registered = registeredProperties()+ const unregistered = [...stamped].filter(+ (property) => !registered.has(property) && !KNOWN_UNREGISTERED_MCP_PROPERTIES.has(property)+ )+ expect(unregistered.sort()).toEqual([])++ const staleExceptions = [...KNOWN_UNREGISTERED_MCP_PROPERTIES].filter((property) => registered.has(property))+ expect(staleExceptions.sort()).toEqual([])+ })+})diff --git a/services/mcp/tests/unit/posthog/server-build.test.ts b/services/mcp/tests/unit/posthog/server-build.test.tsnew file mode 100644index 000000000000..1758f389754c--- /dev/null+++ b/services/mcp/tests/unit/posthog/server-build.test.ts@@ -0,0 +1,57 @@+import { readFileSync } from 'node:fs'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { PostHogMCP } from '@posthog/mcp-analytics'++vi.mock('node:fs', () => ({ readFileSync: vi.fn() }))+vi.mock('@posthog/mcp-analytics', () => ({ PostHogMCP: vi.fn() }))+vi.mock('@/lib/env', () => ({+ env: {+ POSTHOG_ANALYTICS_API_KEY: 'phc_test',+ POSTHOG_ANALYTICS_HOST: 'https://example.com',+ },+}))++import { getMCPServerBuild, getPostHogClient } from '@/lib/posthog/client'++const mockReadFileSync = vi.mocked(readFileSync)+const mockPostHogMCP = vi.mocked(PostHogMCP)++describe('getMCPServerBuild', () => {+ beforeEach(() => {+ mockReadFileSync.mockReset()+ })++ it('returns the deployed commit SHA', () => {+ mockReadFileSync.mockReturnValue('b3b941584bae0123\n')++ expect(getMCPServerBuild()).toBe('b3b941584bae0123')+ })++ it.each(['', 'unknown'])('omits an unavailable build value: %j', (build) => {+ mockReadFileSync.mockReturnValue(build)++ expect(getMCPServerBuild()).toBeUndefined()+ })++ it('omits the build when the file does not exist', () => {+ mockReadFileSync.mockImplementation(() => {+ throw new Error('missing')+ })++ expect(getMCPServerBuild()).toBeUndefined()+ })+})++describe('getPostHogClient', () => {+ it('passes the deployed build to the MCP analytics SDK', () => {+ mockReadFileSync.mockReturnValue('b3b941584bae0123\n')++ getPostHogClient()++ expect(mockPostHogMCP).toHaveBeenCalledWith(+ 'phc_test',+ expect.objectContaining({ serverBuild: 'b3b941584bae0123' })+ )+ })+})