: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): capture model identity in dogfood analytics (#94630)
Lucas Faria77b52dcd9ce8
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts b/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.tsindex 3003fb838255..36ded9a9c5d8 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/utils/mcpProperties.test.ts@@ -26,6 +26,8 @@ describe('mcpProperties', () => {// Non-priority schema properties come from the taxonomy-derived group, so new// $mcp_* taxonomy entries surface without touching this module.expect(options).toContain('$mcp_transport')+ expect(options).toContain('$mcp_llm_model')+ expect(options).toContain('$mcp_llm_model_source')expect(options.every((key) => key.startsWith('$mcp_'))).toBe(true)expect(new Set(options).size).toBe(options.length)})diff --git a/frontend/src/scenes/activity/explore/MCPEventView.tsx b/frontend/src/scenes/activity/explore/MCPEventView.tsxindex 10929cc40f5a..5cb0893f22ae 100644--- a/frontend/src/scenes/activity/explore/MCPEventView.tsx+++ b/frontend/src/scenes/activity/explore/MCPEventView.tsx@@ -87,6 +87,8 @@ const MCP_PROPERTY_ORDER: readonly string[] = ['$mcp_client_name','$mcp_client_version','$mcp_client_user_agent',+ '$mcp_llm_model',+ '$mcp_llm_model_source',// Server'$mcp_server_name','$mcp_server_version',@@ -226,6 +228,8 @@ export function MCPEventView({ properties }: MCPEventViewProps): JSX.Element {const isError = rawIsError === true || rawIsError === 'true'const durationMs = mcpProps['$mcp_duration_ms']const clientName = mcpProps['$mcp_client_name']+ const llmModel = mcpProps['$mcp_llm_model']+ const llmModelSource = mcpProps['$mcp_llm_model_source']const serverName = mcpProps['$mcp_server_name']const intent = mcpProps['$mcp_intent']const intentSource = mcpProps['$mcp_intent_source']@@ -234,6 +238,7 @@ export function MCPEventView({ properties }: MCPEventViewProps): JSX.Element {Boolean(displayName && displayKind) ||(durationMs !== undefined && durationMs !== null) ||Boolean(clientName) ||+ Boolean(llmModel) ||Boolean(serverName) ||Boolean(intent)@@ -297,6 +302,11 @@ export function MCPEventView({ properties }: MCPEventViewProps): JSX.Element {<Stat label="Duration">{String(durationMs)} ms</Stat>) : null}{clientName ? <Stat label="Client">{String(clientName)}</Stat> : null}+ {llmModel ? (+ <Stat label={llmModelSource ? `Model (${String(llmModelSource).replace(/_/g, ' ')})` : 'Model'}>+ {String(llmModel)}+ </Stat>+ ) : null}{serverName ? <Stat label="Server">{String(serverName)}</Stat> : null}{intent ? (<div className="basis-full">diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex 098105dd45d5..7a1491cbd815 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -2272,6 +2272,22 @@],"label": "MCP listed tool names"},+ "$mcp_llm_model": {+ "description": "The model used by the MCP client for this tool call. Taken from recognized client metadata when available, otherwise from the agent's self-reported llm_model argument. MCP does not attest model identity, so use this for analytics rather than billing or access control.",+ "examples": [+ "claude-sonnet-5",+ "gpt-5.6-sol"+ ],+ "label": "MCP model"+ },+ "$mcp_llm_model_source": {+ "description": "How the model identifier was obtained. client_metadata means the MCP client supplied recognized metadata. self_reported means the agent filled the injected llm_model argument. Both sources are unverified.",+ "examples": [+ "client_metadata",+ "self_reported"+ ],+ "label": "MCP model source"+ },"$mcp_missing_scope": {"description": "The API scope the PostHog API said was missing when it refused an MCP request. Only set on $mcp_auth_failed with reason insufficient_scope, and only when the API named a specific scope.","examples": [@@ -4560,6 +4576,22 @@],"label": "MCP listed tool names"},+ "$mcp_llm_model": {+ "description": "The model used by the MCP client for this tool call. Taken from recognized client metadata when available, otherwise from the agent's self-reported llm_model argument. MCP does not attest model identity, so use this for analytics rather than billing or access control.",+ "examples": [+ "claude-sonnet-5",+ "gpt-5.6-sol"+ ],+ "label": "MCP model"+ },+ "$mcp_llm_model_source": {+ "description": "How the model identifier was obtained. client_metadata means the MCP client supplied recognized metadata. self_reported means the agent filled the injected llm_model argument. Both sources are unverified.",+ "examples": [+ "client_metadata",+ "self_reported"+ ],+ "label": "MCP model source"+ },"$mcp_missing_scope": {"description": "The API scope the PostHog API said was missing when it refused an MCP request. Only set on $mcp_auth_failed with reason insufficient_scope, and only when the API named a specific scope.","examples": [@@ -7382,6 +7414,22 @@],"label": "MCP listed tool names"},+ "$mcp_llm_model": {+ "description": "The model used by the MCP client for this tool call. Taken from recognized client metadata when available, otherwise from the agent's self-reported llm_model argument. MCP does not attest model identity, so use this for analytics rather than billing or access control.",+ "examples": [+ "claude-sonnet-5",+ "gpt-5.6-sol"+ ],+ "label": "MCP model"+ },+ "$mcp_llm_model_source": {+ "description": "How the model identifier was obtained. client_metadata means the MCP client supplied recognized metadata. self_reported means the agent filled the injected llm_model argument. Both sources are unverified.",+ "examples": [+ "client_metadata",+ "self_reported"+ ],+ "label": "MCP model source"+ },"$mcp_missing_scope": {"description": "The API scope the PostHog API said was missing when it refused an MCP request. Only set on $mcp_auth_failed with reason insufficient_scope, and only when the API named a specific scope.","examples": [diff --git a/frontend/src/taxonomy/taxonomy.tsx b/frontend/src/taxonomy/taxonomy.tsxindex c8621daa30ab..b8b62f010ea9 100644--- a/frontend/src/taxonomy/taxonomy.tsx+++ b/frontend/src/taxonomy/taxonomy.tsx@@ -121,6 +121,7 @@ export const POSTHOG_EVENT_PROMOTED_PROPERTIES = {'$mcp_error_type','$mcp_duration_ms','$mcp_client_name',+ '$mcp_llm_model','$mcp_intent',],}diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 51eb6d6c66f8..4e5d99b11c35 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -2911,6 +2911,16 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"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": ["ClaudeCode", "ClaudeAI", "Cowork"],},+ "$mcp_llm_model": {+ "label": "MCP model",+ "description": "The model used by the MCP client for this tool call. Taken from recognized client metadata when available, otherwise from the agent's self-reported llm_model argument. MCP does not attest model identity, so use this for analytics rather than billing or access control.",+ "examples": ["claude-sonnet-5", "gpt-5.6-sol"],+ },+ "$mcp_llm_model_source": {+ "label": "MCP model source",+ "description": "How the model identifier was obtained. client_metadata means the MCP client supplied recognized metadata. self_reported means the agent filled the injected llm_model argument. Both sources are unverified.",+ "examples": ["client_metadata", "self_reported"],+ },"$mcp_intent": {"label": "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 — if none was supplied — from an intentFallback the MCP server provides.",diff --git a/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.md b/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.mdindex 4e684409112c..34dd5c781082 100644--- a/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.md+++ b/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.md@@ -48,6 +48,8 @@ On `$mcp_tool_call` unless noted. These are the properties any instrumented serv| `$mcp_error_message` | Since TS 0.8.0. Redacted automatically as of TS 0.10.2. || `$mcp_client_name` / `$mcp_client_version` | The calling client as _it_ reported itself. One mid-priority input to harness resolution — not the harness label. || `$mcp_client_user_agent` / `$mcp_vendor_client` | Since TS 0.11.0 / Python 7.42.0. The raw `User-Agent` and vendor header (e.g. `x-anthropic-client`) — `clientInfo.name` can't tell one vendor surface from another (`claude-code` is the CLI, the Agent SDK, the VS Code extension, and the desktop app alike). HTTP transports only; stdio and in-memory servers carry no headers. Captured raw and resolved to labels at query time. Together with `$mcp_client_name` these are the **only** properties `HARNESS_TOKEN_SQL` reads — `$mcp_vendor_client` is its top-priority signal (the legacy server-stamped non-`$` `mcp_vendor_client` is coalesced behind it for historical rows). |+| `$mcp_llm_model` | The model identifier captured for the tool call. Recognized client metadata takes priority; otherwise the SDK can inject an `llm_model` tool argument for the agent to self-report. MCP does not attest model identity, so use this for analytics rather than billing or access control. |+| `$mcp_llm_model_source` | `client_metadata` when recognized client metadata supplied the model, or `self_reported` when it came from the injected `llm_model` argument. Both sources are unverified. || `$mcp_server_name` / `$mcp_server_version` | The instrumented server's own identity. || `$mcp_protocol_version` | Since TS 0.10.0. The negotiated MCP spec version. On legacy `initialize`-handshake sessions it is stamped on `$mcp_initialize` and every subsequent event of that session; under the 2026-07-28 revision it is **per request**, so one `$session_id` can legitimately span more than one value — don't treat it as a session constant. See [stateless-and-sessions.md](stateless-and-sessions.md). || `$mcp_conversation_id` | The conversation handle: **server-minted on the first call, agent-echoed thereafter** (an invented value is rejected and replaced). **Survives reconnects, but only when the server sets `enableConversationId`** (off by default) — see identifiers below and [stateless-and-sessions.md](stateless-and-sessions.md). |diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.mdindex 6c7c92b6b0a2..e678bfb4a884 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md@@ -62,6 +62,8 @@ And two tools cover what SQL can't express at all: `posthog:mcp-analytics-intent| `$mcp_response` | SDK | The response the MCP server returned, redacted the same way as `$mcp_parameters`. Stays empty on PostHog's hosted server. || `$mcp_client_name` | SDK | Raw client string (e.g. `claude-code/1.2.3`). Bucketed into harnesses **server-side** by `products/mcp_analytics/backend/mcp_harness.py` (`HARNESS_TOKEN_SQL` / `harness_label_sql`) — the single source of truth. The frontend only maps the resolved label to a logo. There is no `category` column. || `$mcp_client_version` | SDK | Version of the MCP client that initiated the connection. |+| `$mcp_llm_model` | SDK | Model identifier captured for the tool call. Recognized client metadata takes priority; otherwise the SDK can inject an `llm_model` argument for the agent to self-report. MCP does not attest model identity, so use this for analytics rather than billing or access control. |+| `$mcp_llm_model_source` | SDK | How the model was obtained: `client_metadata` from recognized client metadata, or `self_reported` from the injected `llm_model` argument. Both sources are unverified. || `$mcp_tool_category` | server | Tool category, when tagged. Stamped from PostHog's tool catalog; external servers can declare one per tool. || `$mcp_tool_description` | SDK | Tool description as seen by the agent (revisions over time), clipped to 512 chars on capture. Gap warning: the hono migration silently dropped this stamp, so there is a window (roughly Jun-Jul 2026) with no descriptions on PostHog's hosted server; `notEmpty(...)` filters are mandatory. || `$mcp_listed_tool_names` | SDK | Every tool name advertised on a `tools/list` call, in multi-tool mode (JSON array; filter with `contains`). Diff against `$mcp_tool_name` to find zombie tools (advertised, never called). In single-exec mode, `$mcp_exec_inner_tool_names` carries the catalog instead. |diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 2cb64e76b5b4..2f1d0d5d46e5 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -1,6 +1,6 @@import { randomUUID } from 'node:crypto'-import type { MCPAnalyticsIntentSource } from '@posthog/mcp-analytics'+import type { MCPAnalyticsIntentSource, MCPAnalyticsModelSource } from '@posthog/mcp-analytics'import type { McpAuthFailure } from '@/lib/auth-errors'import { classifyAuthMethod } from '@/lib/auth-method'@@ -118,11 +118,15 @@ export async function trackInitEvent(state: ResolvedState): Promise<void> {}}-export interface ToolCallIntentMeta {+export interface ToolCallAnalyticsMeta {/** The agent's stated intent (the injected `context` arg) → `$mcp_intent`. */intent?: string/** Where it came from → `$mcp_intent_source`. */intentSource?: MCPAnalyticsIntentSource+ /** The calling model -> `$mcp_llm_model`. */+ llmModel?: string+ /** Where the model identifier came from -> `$mcp_llm_model_source`. */+ llmModelSource?: MCPAnalyticsModelSource}export async function trackToolCall(@@ -131,7 +135,7 @@ export async function trackToolCall(isError: boolean,state: ResolvedState,extraProperties?: Record<string, unknown>,- intentMeta?: ToolCallIntentMeta,+ analyticsMeta?: ToolCallAnalyticsMeta,servedDescription?: string): Promise<void> {try {@@ -171,8 +175,10 @@ export async function trackToolCall(distinctId: state.distinctId,groups,...(sessionUuid ? { sessionId: sessionUuid } : {}),- ...(intentMeta?.intent ? { intent: intentMeta.intent } : {}),- ...(intentMeta?.intentSource ? { intentSource: intentMeta.intentSource } : {}),+ ...(analyticsMeta?.intent ? { intent: analyticsMeta.intent } : {}),+ ...(analyticsMeta?.intentSource ? { intentSource: analyticsMeta.intentSource } : {}),+ ...(analyticsMeta?.llmModel ? { llmModel: analyticsMeta.llmModel } : {}),+ ...(analyticsMeta?.llmModelSource ? { llmModelSource: analyticsMeta.llmModelSource } : {}),properties: {...properties,tool_name: toolName,@@ -207,7 +213,7 @@ export async function trackExecuteSqlGeneration(args: unknown,state: ResolvedState,meta: ExecuteSqlGenerationMeta,- intentMeta?: ToolCallIntentMeta+ analyticsMeta?: ToolCallAnalyticsMeta): Promise<void> {if (toolName !== EXECUTE_SQL_TOOL_NAME) {return@@ -230,7 +236,7 @@ export async function trackExecuteSqlGeneration(...(sessionUuid ? { $session_id: sessionUuid } : {}),$ai_trace_id: sessionUuid ?? randomUUID(),$ai_span_name: EXECUTE_SQL_TOOL_NAME,- $ai_input: [{ role: 'user', content: intentMeta?.intent ?? '' }],+ $ai_input: [{ role: 'user', content: analyticsMeta?.intent ?? '' }],$ai_output_choices: [{ role: 'assistant', content: query }],$ai_latency: meta.durationMs / 1000,$ai_is_error: meta.isError,diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex a1dfb8599967..af01af8e6e7d 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -42,7 +42,7 @@ import {trackToolCall,trackToolSpan,trackToolsList,- type ToolCallIntentMeta,+ type ToolCallAnalyticsMeta,} from './analytics'import type { InstructionsBuilder } from './instructions'import { getEffectiveMCPClientContext } from './mcp-context'@@ -110,7 +110,7 @@ export class ToolExecutor {}async handleToolsList(state: ResolvedState): Promise<ListToolsResult> {- const tools = this.injectContext(this.buildAdvertisedTools(state))+ const tools = this.injectAnalyticsParameters(this.buildAdvertisedTools(state))void trackToolsList(tools.map((t) => t.name),@@ -120,12 +120,8 @@ export class ToolExecutor {return { tools }}- // Inject the `context` argument into every advertised tool so agents can state- // what they're trying to do (`handleToolCall` strips it before validation and- // surfaces it as `$mcp_intent` — the same injection `instrument()` does for- // SDK-wrapped servers). Guarded: analytics must never break `tools/list`, so- // any failure falls back to the un-augmented tools.- private injectContext(tools: ListToolsResult['tools']): ListToolsResult['tools'] {+ // Guarded because analytics must never break `tools/list`.+ private injectAnalyticsParameters(tools: ListToolsResult['tools']): ListToolsResult['tools'] {try {return getPostHogClient().prepareToolList(tools)} catch {@@ -153,17 +149,38 @@ export class ToolExecutor {})}+ private findOriginalTool(toolName: string, state: ResolvedState): ListToolsResult['tools'][number] | undefined {+ if (state.useSingleExec) {+ if (toolName === 'exec') {+ return this.instructionsBuilder.buildExecToolEntry(state)+ }+ if (toolName === 'render-ui' && state.renderUiEnabled) {+ return this.instructionsBuilder.buildRenderUiToolEntry(state) ?? undefined+ }+ return undefined+ }++ return this.buildAdvertisedTools(state).find((tool) => tool.name === toolName)+ }+async handleToolCall(params: Record<string, unknown> | undefined, state: ResolvedState): Promise<unknown> {const toolName = params?.name as stringif (!toolName) {return { content: [{ type: 'text', text: 'Missing tool name' }], isError: true }}- const { intentMeta, args } = this.extractIntent(toolName, (params?.arguments ?? {}) as Record<string, unknown>)+ const rawArgs = (params?.arguments ?? {}) as Record<string, unknown>+ const originalTool = this.findOriginalTool(toolName, state)+ const rawRequestMeta = params?._meta+ const requestMeta =+ rawRequestMeta && typeof rawRequestMeta === 'object' && !Array.isArray(rawRequestMeta)+ ? (rawRequestMeta as Record<string, unknown>)+ : undefined+ const { analyticsMeta, args } = this.extractAnalyticsMetadata(toolName, rawArgs, originalTool, requestMeta)const callParams = { ...params, arguments: args }if (toolName === 'exec') {- return this.callExecTool(callParams, state, intentMeta)+ return this.callExecTool(callParams, state, analyticsMeta)}if (toolName === 'render-ui') {@@ -172,7 +189,7 @@ export class ToolExecutor {toolCallsTotal.inc({ tool: toolName, status: 'error' })return { content: [{ type: 'text', text: `Tool ${toolName} not found` }], isError: true }}- return this.callRenderUiTool(callParams, state, intentMeta)+ return this.callRenderUiTool(callParams, state, analyticsMeta)}if (!state.allTools.some((t) => t.name === toolName)) {@@ -196,7 +213,7 @@ export class ToolExecutor {},callParams,state,- intentMeta+ analyticsMeta)}@@ -212,23 +229,27 @@ export class ToolExecutor {return undefined}- // Pull the agent's stated intent off the injected `context` arg and strip it so- // tool schemas/handlers never see it (validation is `.strict()` in places). The- // intent rides through to `$mcp_intent` on the captured event. Guarded: analytics- // must never break `tools/call`, so on failure we fall back to the raw args —- // safe because `context` is only present when the matching injection succeeded.- private extractIntent(+ // Guarded because analytics must never break `tools/call`. The SDK only strips+ // fields whose ownership it recorded while preparing the tool list.+ private extractAnalyticsMetadata(toolName: string,- rawArgs: Record<string, unknown>- ): { intentMeta: ToolCallIntentMeta; args: Record<string, unknown> } {+ rawArgs: Record<string, unknown>,+ originalTool: ListToolsResult['tools'][number] | undefined,+ requestMeta: Record<string, unknown> | undefined+ ): { analyticsMeta: ToolCallAnalyticsMeta; args: Record<string, unknown> } {try {- const prepared = getPostHogClient().prepareToolCall(toolName, rawArgs)+ const prepared = getPostHogClient().prepareToolCall(toolName, rawArgs, { originalTool, requestMeta })return {- intentMeta: { intent: prepared.intent, intentSource: prepared.intentSource },+ analyticsMeta: {+ intent: prepared.intent,+ intentSource: prepared.intentSource,+ llmModel: prepared.llmModel,+ llmModelSource: prepared.llmModelSource,+ },args: prepared.args ?? rawArgs,}} catch {- return { intentMeta: {}, args: rawArgs }+ return { analyticsMeta: {}, args: rawArgs }}}@@ -236,7 +257,7 @@ export class ToolExecutor {tool: ResolvedTool,params: Record<string, unknown> | undefined,state: ResolvedState,- intentMeta?: ToolCallIntentMeta+ analyticsMeta?: ToolCallAnalyticsMeta): Promise<unknown> {const rawToolArgs = (params?.arguments ?? {}) as Record<string, unknown>const firstPass = tool.schema.safeParse(rawToolArgs, { reportInput: true })@@ -264,7 +285,7 @@ export class ToolExecutor {true,state,errorAnalyticsProperties(classifyToolError(rejection, tool.name), rejection),- intentMeta,+ analyticsMeta,this.servedToolDescription(tool.name))return {@@ -331,7 +352,7 @@ export class ToolExecutor {input_tokens: estimateTokens(validation.data),output_tokens: estimateResponseTokens(response),},- intentMeta,+ analyticsMeta,this.servedToolDescription(tool.name))@@ -341,7 +362,7 @@ export class ToolExecutor {validation.data,state,{ durationMs: duration, isError: false },- intentMeta+ analyticsMeta)}@@ -364,7 +385,7 @@ export class ToolExecutor {true,state,errorAnalyticsProperties(classification, error),- intentMeta,+ analyticsMeta,this.servedToolDescription(tool.name))@@ -378,7 +399,7 @@ export class ToolExecutor {isError: true,errorMessage: error instanceof Error ? error.message : String(error),},- intentMeta+ analyticsMeta)}@@ -397,10 +418,10 @@ export class ToolExecutor {private async callExecTool(params: Record<string, unknown> | undefined,state: ResolvedState,- intentMeta?: ToolCallIntentMeta+ analyticsMeta?: ToolCallAnalyticsMeta): Promise<unknown> {const execMetrics: ExecMetricState = { innerToolName: undefined, commandMeta: undefined }- const resolved = this.resolveExecTool(state, execMetrics, intentMeta)+ const resolved = this.resolveExecTool(state, execMetrics, analyticsMeta)const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>const validation = resolved.schema.safeParse(toolArgs, { reportInput: true })@@ -460,7 +481,7 @@ export class ToolExecutor {output_tokens: estimateResponseTokens(response),...execMetrics.commandMeta,},- intentMeta,+ analyticsMeta,this.servedToolDescription(execToolName()))@@ -480,7 +501,7 @@ export class ToolExecutor {true,state,{ ...execShape, ...errorAnalyticsProperties(classification, error), ...execMetrics.commandMeta },- intentMeta,+ analyticsMeta,this.servedToolDescription(metricTool))@@ -514,7 +535,7 @@ export class ToolExecutor {private resolveExecTool(state: ResolvedState,execMetrics: ExecMetricState,- intentMeta?: ToolCallIntentMeta+ analyticsMeta?: ToolCallAnalyticsMeta): ResolvedTool {const commandReference = this.instructionsBuilder.buildExecCommandReference(state)@@ -543,7 +564,7 @@ export class ToolExecutor {isError: !properties.success,errorMessage: properties.error_message,},- intentMeta+ analyticsMeta)}void trackToolSpan(toolName, state, {@@ -606,7 +627,7 @@ export class ToolExecutor {private async callRenderUiTool(params: Record<string, unknown> | undefined,state: ResolvedState,- intentMeta?: ToolCallIntentMeta+ analyticsMeta?: ToolCallAnalyticsMeta): Promise<unknown> {const renderUiTool = createRenderUiTool(state.allTools, state.context)if (!renderUiTool) {@@ -629,7 +650,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, intentMeta)+ void trackToolCall('render-ui', Date.now() - startMs, false, state, undefined, analyticsMeta)// The handler always returns an exec-built payload (UI resourceUri + structuredContent).return handlerResult} catch (error: unknown) {@@ -642,7 +663,7 @@ export class ToolExecutor {true,state,errorAnalyticsProperties(classification, error),- intentMeta+ analyticsMeta)const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)return handleToolError(error, 'render-ui', state.distinctId, sessionUuid)diff --git a/services/mcp/src/lib/posthog/client.ts b/services/mcp/src/lib/posthog/client.tsindex 6e49924eac79..57413ed91870 100644--- a/services/mcp/src/lib/posthog/client.ts+++ b/services/mcp/src/lib/posthog/client.ts@@ -19,6 +19,7 @@ export const getPostHogClient = (): PostHogMCP => {// Tool errors already surface as `$mcp_is_error: true`; keep the SDK// from fanning out a separate `$exception` event into Error Tracking.enableExceptionAutocapture: false,+ captureModel: true,})}diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.tsindex 875bc86cbd43..401f8f815915 100644--- a/services/mcp/tests/hono/tool-executor-intent.test.ts+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts@@ -17,7 +17,7 @@ vi.mock('@/resources', () => ({// not a stub.vi.mock('@/lib/posthog', async () => {const { PostHogMCP } = await import('@posthog/mcp-analytics')- const client = new PostHogMCP('phc_test', { disabled: true })+ const client = new PostHogMCP('phc_test', { disabled: true, captureModel: true })return { getPostHogClient: () => client }})@@ -79,7 +79,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>}}-describe('ToolExecutor intent capture', () => {+describe('ToolExecutor analytics capture', () => {let catalog: ToolCataloglet executor: ToolExecutor@@ -89,7 +89,7 @@ describe('ToolExecutor intent capture', () => {executor = new ToolExecutor(catalog, new InstructionsBuilder(''))})- it('injects the context argument into advertised tools', async () => {+ it('injects the analytics arguments into advertised tools', async () => {const state = makeState([], { useSingleExec: true })const result = await executor.handleToolsList(state)@@ -99,46 +99,76 @@ describe('ToolExecutor intent capture', () => {// The SDK injects `context` (required, to nudge the agent to state intent)// while leaving the existing `command` arg untouched.expect(properties).toHaveProperty('context')+ expect(properties).toHaveProperty('llm_model')expect(properties).toHaveProperty('command')expect(execEntry.inputSchema.required).toContain('context')+ expect(execEntry.inputSchema.required).toContain('llm_model')})it.each([{label: 'forwards the agent intent and strips context before the handler',- args: { command: 'tools', context: 'investigating signup drop' },+ args: {+ command: 'tools',+ context: 'investigating signup drop',+ llm_model: 'gpt-5.6-codex',+ },expectedIntent: 'investigating signup drop',expectedSource: 'context_parameter',+ expectedModel: 'gpt-5.6-codex',+ expectedModelSource: 'self_reported',+ },+ {+ label: 'prefers Codex request metadata over an unknown self-report',+ args: {+ command: 'tools',+ context: 'checking the available tools',+ llm_model: 'unknown',+ },+ requestMeta: { 'x-codex-turn-metadata': { model: 'gpt-5.6-sol' } },+ expectedIntent: 'checking the available tools',+ expectedSource: 'context_parameter',+ expectedModel: 'gpt-5.6-sol',+ expectedModelSource: 'client_metadata',},{label: 'captures no intent when the agent omits context',args: { command: 'tools' },expectedIntent: undefined,expectedSource: undefined,+ expectedModel: undefined,+ expectedModelSource: undefined,},- ])('exec call $label', async ({ args, expectedIntent, expectedSource }) => {- const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})+ ])(+ 'exec call $label',+ async ({ args, requestMeta, expectedIntent, expectedSource, expectedModel, expectedModelSource }) => {+ const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})- const filteredTools = catalog- .getFilteredTools({ scopes: ['*'] })- .filter((tool) => tool.name === 'execute-sql' || tool.name === 'organization-get')+ const filteredTools = catalog+ .getFilteredTools({ scopes: ['*'] })+ .filter((tool) => tool.name === 'execute-sql' || tool.name === 'organization-get')+ const state = makeState(filteredTools, { useSingleExec: true })+ await executor.handleToolsList(state)- const result = (await executor.handleToolCall(- { name: 'exec', arguments: args },- makeState(filteredTools, { useSingleExec: false })- )) as any+ const result = (await executor.handleToolCall(+ { name: 'exec', arguments: args, _meta: requestMeta },+ state+ )) as any- // context (when present) must not break exec validation — proves it was stripped.- expect(result.isError).toBeFalsy()+ // context (when present) must not break exec validation — proves it was stripped.+ expect(result.isError).toBeFalsy()- expect(captureSpy).toHaveBeenCalledTimes(1)- const arg = captureSpy.mock.calls[0]![0]- expect(arg.toolName).toBe('exec')- expect(arg.intent).toBe(expectedIntent)- expect(arg.intentSource).toBe(expectedSource)+ expect(captureSpy).toHaveBeenCalledTimes(1)+ const arg = captureSpy.mock.calls[0]![0]+ expect(arg.toolName).toBe('exec')+ expect(arg.intent).toBe(expectedIntent)+ expect(arg.intentSource).toBe(expectedSource)+ expect(arg.llmModel).toBe(expectedModel)+ expect(arg.llmModelSource).toBe(expectedModelSource)- captureSpy.mockRestore()- })+ captureSpy.mockRestore()+ }+ )// A native (non-exec) tool call with context: proves the native callTool path// strips context and forwards intent. The native path now also tracks schema@@ -147,18 +177,28 @@ describe('ToolExecutor intent capture', () => {// unstripped `context` (rejected as an unrecognized key) would satisfy this// test. (projects-get hits the API, which the harness can't fulfill, so we// assert on the captured analytics, not the tool's own result.)- it('strips context before a native tool validates and still forwards intent', async () => {+ it('strips analytics arguments before a native tool validates and forwards their values', async () => {+ const state = makeState([{ name: 'projects-get' }])+ await executor.handleToolsList(state)const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})await executor.handleToolCall(- { name: 'projects-get', arguments: { context: 'looking up the current user' } },- makeState([{ name: 'projects-get' }])+ {+ name: 'projects-get',+ arguments: {+ context: 'looking up the current user',+ llm_model: 'claude-sonnet-4-20250514',+ },+ },+ state)expect(captureSpy).toHaveBeenCalledTimes(1)const arg = captureSpy.mock.calls[0]![0]expect(arg.toolName).toBe('projects-get')expect(arg.intent).toBe('looking up the current user')+ expect(arg.llmModel).toBe('claude-sonnet-4-20250514')+ expect(arg.llmModelSource).toBe('self_reported')expect(arg.properties?.$mcp_error_type).not.toBe('validation')captureSpy.mockRestore()diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 6ab9026741e0..f2ae4cfa8d7f 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -494,17 +494,16 @@ describe('ToolExecutor', () => {const result = await executor.handleToolsList(state)expect(result.tools.map((t) => t.name)).toEqual(['exec', 'render-ui'])- // The advertised schema is derived from the zod validation schema —- // pin the contract the agent writes calls against. The analytics- // client injects a required `context` intent parameter into every- // advertised tool (surfaced as `$mcp_intent`).+ // Pin the complete advertised schema because clients generate+ // render-ui calls from this list response.const renderUiEntry = result.tools[1]!const properties = renderUiEntry.inputSchema.properties as Record<string, Record<string, unknown>>expect(properties.tool_name!.enum).toEqual(['survey-get'])expect(properties.tool_name!.description).toBeTruthy()expect(properties.tool_input!.description).toBeTruthy()expect(properties.context!.description).toBeTruthy()- expect(renderUiEntry.inputSchema.required).toEqual(['tool_name', 'context'])+ expect(properties.llm_model!.description).toBeTruthy()+ expect(renderUiEntry.inputSchema.required).toEqual(['tool_name', 'context', 'llm_model'])})it('omits render-ui when render-ui is disabled, even with a UI-app tool available', async () => {