:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): attribute single-exec tool calls to the real inner tool (#66144)
Lucas Fariaf40af8c68343
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 5fe729f1e9a1..1014f2953e64 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -18,10 +18,8 @@ import {} from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { getPostHogClient } from '@/lib/posthog'-import { AnalyticsEvent } from '@/lib/posthog/analytics'import { createExecTool, formatInputValidationError, type ExecInnerCallTracker } from '@/tools/exec'import { createRenderUiTool } from '@/tools/render-ui'-import { getToolCategory } from '@/tools/toolDefinitions'import type { Context, ZodObjectAny } from '@/tools/types'import { trackToolCall, trackToolsList, type ToolCallIntentMeta } from './analytics'@@ -257,6 +255,16 @@ export class ToolExecutor {const startMs = Date.now()+ // In single-exec mode every transport-level call is `exec`, so `$mcp_tool_name`+ // would always read `exec` and hide which tool the agent actually invoked.+ // Attribute the canonical event to the inner tool that dispatched (captured by+ // `trackInnerCall` above) — keeping the same standard `$mcp_tool_name` the SDK+ // emits for direct calls, so exec-routed and direct calls share one vocabulary.+ // `$mcp_mode` already distinguishes single-exec from direct for anyone who needs+ // it. Non-`call` verbs (tools/info/search/schema) resolve no inner tool and stay+ // attributed to `exec`.+ const execToolName = (): string => execMetrics.innerToolName ?? 'exec'+try {const handlerResult = await resolved.handler(state.context, validation.data)const duration = Date.now() - startMs@@ -273,7 +281,7 @@ export class ToolExecutor {})void trackToolCall(- 'exec',+ execToolName(),duration,false,state,@@ -286,13 +294,13 @@ export class ToolExecutor {return response} catch (error: unknown) {- const metricTool = execMetrics.innerToolName ?? 'exec'+ const metricTool = execToolName()if (!execMetrics.innerToolName) {toolCallsTotal.inc({ tool: 'exec', status: 'error' })}classifyToolError(error, metricTool)- void trackToolCall('exec', Date.now() - startMs, true, state, undefined, intentMeta)+ void trackToolCall(metricTool, Date.now() - startMs, true, state, undefined, intentMeta)const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)// Attribute the failure to the inner tool that actually ran (e.g. `query-logs`),@@ -307,6 +315,11 @@ export class ToolExecutor {const commandReference = this.instructionsBuilder.buildExecCommandReference(state)const trackInnerCall: ExecInnerCallTracker = (toolName, properties) => {+ // Record which inner tool actually dispatched so `callExecTool` can attribute+ // the canonical `$mcp_tool_call` event to the real tool instead of the `exec`+ // dispatcher. The PostHog event is intentionally NOT emitted here: the wrapper+ // event (now relabelled to the inner tool name, with the inner tool's category+ // derived from it) already carries this call, so a second emit would double-count.execMetrics.innerToolName = toolNameconst status = properties.success ? 'success' : properties.validation_error ? 'validation_error' : 'error'toolCallsTotal.inc({ tool: toolName, status })@@ -316,25 +329,6 @@ export class ToolExecutor {if (!properties.validation_error) {toolCallDurationSeconds.observe({ tool: toolName, status }, properties.duration_ms / 1000)}-- // Mirror the native path: stamp the inner tool's category so exec-routed- // calls share the dashboard's `$mcp_tool_category` grouping dimension.- const toolCategory = getToolCategory(toolName)-- void (async () => {- const freshContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)- await state.reqCtx.trackEvent(- AnalyticsEvent.MCP_TOOL_CALL,- {- tool_name: toolName,- ...(toolCategory ? { $mcp_tool_category: toolCategory } : {}),- ...properties,- },- freshContext,- undefined,- state.distinctId- )- })().catch(() => {})}const clientContext = getEffectiveMCPClientContext(state.requestContext, state.sessionContext)diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.tsindex 46791b5dbab0..27c4e090e88d 100644--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts@@ -186,5 +186,40 @@ describe('ToolExecutor token estimates', () => {expect(execCall[4].output_tokens).toBe(estimateTokens(joinedText(response)))expect(execCall[4].output_tokens).not.toBe(estimateTokens(response))})++ it('attributes the canonical event to the inner tool via the standard $mcp_tool_name', async () => {+ // Full catalog tools (real names, so the instructions builder resolves them),+ // with the target handler stubbed to keep dispatch offline + deterministic.+ const tools = catalog.getPreBuiltEntries().map((entry) => {+ const preBuilt = catalog.getToolByName(entry.name)!+ return {+ ...preBuilt.base,+ title: entry.title,+ description: entry.description ?? '',+ annotations: entry.annotations,+ scopes: [],+ }+ })+ const target = tools.find((t) => t.name === 'docs-search')! as any+ target.handler = vi.fn(async () => 'inner-ok')+ const state = makeState(tools as any, { useSingleExec: true })++ await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'call docs-search {"query":"hi"}' } },+ state+ )++ // The canonical event is attributed to the real inner tool — the same standard+ // property the SDK emits for direct calls — never the `exec` dispatcher.+ const innerCall = mockTrackToolCall.mock.calls.find((call) => call[0] === 'docs-search')!+ expect(innerCall).toBeTruthy()+ expect(innerCall[2]).toBe(false)+ expect(mockTrackToolCall.mock.calls.some((call) => call[0] === 'exec')).toBe(false)++ // Regression: the inner dispatch must not ALSO emit its own `mcp_tool_call`+ // event — that would double-count the inner tool on the legacy event.+ const trackEvent = state.reqCtx.trackEvent as ReturnType<typeof vi.fn>+ expect(trackEvent.mock.calls.some((call) => call[0] === 'mcp_tool_call')).toBe(false)+ })})})