: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): stamp failure reason on $mcp_tool_call events (#67221)
Lucas Faria145e5743b214
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex f55fbc9b723b..18f9901247e7 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -2103,6 +2103,30 @@"label": "MCP duration (ms)","type": "Numeric"},+ "$mcp_error_message": {+ "description": "Error message for a failed MCP tool call, truncated. Present when the server passes the thrown error to the SDK; PostHog's own server omits it to avoid capturing query content. Only set when $mcp_is_error is true.",+ "label": "MCP error message"+ },+ "$mcp_error_status": {+ "description": "Upstream HTTP status code when an MCP tool call failed against a PostHog API (e.g. 429, 500). Only set for API-originated failures.",+ "examples": [+ 429,+ 500,+ 403+ ],+ "label": "MCP error status",+ "type": "Numeric"+ },+ "$mcp_error_type": {+ "description": "Failure category for an errored MCP tool call, for breaking failures down by reason. PostHog's server emits a semantic bucket (missing_context, validation, permission, timeout, rate_limited, api_4xx, api_5xx, internal); external servers using the SDK fall back to the thrown error's type. Only set when $mcp_is_error is true.",+ "examples": [+ "rate_limited",+ "validation",+ "timeout",+ "api_4xx"+ ],+ "label": "MCP error type"+ },"$mcp_exec_inner_tool_names": {"description": "Array of every inner tool name available to the agent at the time of a tools/list request. Stored as a JSON array \u2014 filter with `contains` against a single tool name (e.g. 'execute-sql'). Only stamped on mcp_tools_list events when running in single-exec mode (in multi-tool mode the SDK's $mcp_listed_tool_names already carries the catalog). Lets you compute zombie tools by diffing against $mcp_exec_tool_call_name from mcp_tool_call events.","examples": [@@ -6597,6 +6621,30 @@"label": "MCP duration (ms)","type": "Numeric"},+ "$mcp_error_message": {+ "description": "Error message for a failed MCP tool call, truncated. Present when the server passes the thrown error to the SDK; PostHog's own server omits it to avoid capturing query content. Only set when $mcp_is_error is true.",+ "label": "MCP error message"+ },+ "$mcp_error_status": {+ "description": "Upstream HTTP status code when an MCP tool call failed against a PostHog API (e.g. 429, 500). Only set for API-originated failures.",+ "examples": [+ 429,+ 500,+ 403+ ],+ "label": "MCP error status",+ "type": "Numeric"+ },+ "$mcp_error_type": {+ "description": "Failure category for an errored MCP tool call, for breaking failures down by reason. PostHog's server emits a semantic bucket (missing_context, validation, permission, timeout, rate_limited, api_4xx, api_5xx, internal); external servers using the SDK fall back to the thrown error's type. Only set when $mcp_is_error is true.",+ "examples": [+ "rate_limited",+ "validation",+ "timeout",+ "api_4xx"+ ],+ "label": "MCP error type"+ },"$mcp_exec_inner_tool_names": {"description": "Array of every inner tool name available to the agent at the time of a tools/list request. Stored as a JSON array \u2014 filter with `contains` against a single tool name (e.g. 'execute-sql'). Only stamped on mcp_tools_list events when running in single-exec mode (in multi-tool mode the SDK's $mcp_listed_tool_names already carries the catalog). Lets you compute zombie tools by diffing against $mcp_exec_tool_call_name from mcp_tool_call events.","examples": [diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 660db20fd500..267d17678fe8 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -2699,6 +2699,21 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"label": "MCP is error","description": "Whether the MCP tool call failed. True if the tool returned an error result or threw an exception.",},+ "$mcp_error_type": {+ "label": "MCP error type",+ "description": "Failure category for an errored MCP tool call, for breaking failures down by reason. PostHog's server emits a semantic bucket (missing_context, validation, permission, timeout, rate_limited, api_4xx, api_5xx, internal); external servers using the SDK fall back to the thrown error's type. Only set when $mcp_is_error is true.",+ "examples": ["rate_limited", "validation", "timeout", "api_4xx"],+ },+ "$mcp_error_status": {+ "label": "MCP error status",+ "description": "Upstream HTTP status code when an MCP tool call failed against a PostHog API (e.g. 429, 500). Only set for API-originated failures.",+ "type": "Numeric",+ "examples": [429, 500, 403],+ },+ "$mcp_error_message": {+ "label": "MCP error message",+ "description": "Error message for a failed MCP tool call, truncated. Present when the server passes the thrown error to the SDK; PostHog's own server omits it to avoid capturing query content. Only set when $mcp_is_error is true.",+ },"$mcp_server_name": {"label": "MCP server name","description": "The advertised name of the MCP server that handled the request.",diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 43b25805fe30..0b04e5ff9979 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -229,9 +229,16 @@ export class ToolExecutor {} catch (error: unknown) {toolCallsTotal.inc({ tool: tool.name, status: 'error' })stop({ status: 'error' })- classifyToolError(error, tool.name)+ const classification = classifyToolError(error, tool.name)- void trackToolCall(tool.name, Date.now() - startMs, true, state, undefined, intentMeta)+ void trackToolCall(+ tool.name,+ Date.now() - startMs,+ true,+ state,+ errorAnalyticsProperties(classification),+ intentMeta+ )const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)return handleToolError(error, tool.name, state.distinctId, sessionUuid)@@ -301,9 +308,16 @@ export class ToolExecutor {if (!execMetrics.innerToolName) {toolCallsTotal.inc({ tool: 'exec', status: 'error' })}- classifyToolError(error, metricTool)+ const classification = classifyToolError(error, metricTool)- void trackToolCall(metricTool, Date.now() - startMs, true, state, undefined, intentMeta)+ void trackToolCall(+ metricTool,+ Date.now() - startMs,+ true,+ state,+ errorAnalyticsProperties(classification),+ intentMeta+ )const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)// Attribute the failure to the inner tool that actually ran (e.g. `query-logs`),@@ -397,35 +411,89 @@ export class ToolExecutor {} catch (error: unknown) {toolCallsTotal.inc({ tool: 'render-ui', status: 'error' })stop({ status: 'error' })- classifyToolError(error, 'render-ui')- void trackToolCall('render-ui', Date.now() - startMs, true, state, undefined, intentMeta)+ const classification = classifyToolError(error, 'render-ui')+ void trackToolCall(+ 'render-ui',+ Date.now() - startMs,+ true,+ state,+ errorAnalyticsProperties(classification),+ intentMeta+ )const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)return handleToolError(error, 'render-ui', state.distinctId, sessionUuid)}}}-function classifyToolError(error: unknown, toolName: string): void {+type ToolErrorType =+ | 'missing_context'+ | 'validation'+ | 'permission'+ | 'timeout'+ | 'rate_limited'+ | 'api_5xx'+ | 'api_4xx'+ | 'internal'++interface ToolErrorClassification {+ errorType: ToolErrorType+ /** Upstream HTTP status, when the failure came from a PostHog API error. */+ status?: number+}++/**+ * Buckets a thrown tool error into a low-cardinality category, increments the+ * Prometheus counter, and returns the classification so the caller can also+ * surface it on the `$mcp_tool_call` event (`$mcp_error_type` / `$mcp_error_status`).+ * Without that, the MCP analytics dashboard only sees the `$mcp_is_error`+ * boolean and can't break failures down by reason.+ */+function classifyToolError(error: unknown, toolName: string): ToolErrorClassification {+ const classification = resolveToolErrorClassification(error)+ toolErrorsTotal.inc({ tool: toolName, error_type: classification.errorType })+ return classification+}++function resolveToolErrorClassification(error: unknown): ToolErrorClassification {if (error instanceof MissingProjectContextError || error instanceof MissingOrganizationContextError) {- toolErrorsTotal.inc({ tool: toolName, error_type: 'missing_context' })- } else if (error instanceof ToolInputValidationError) {- toolErrorsTotal.inc({ tool: toolName, error_type: 'validation' })- } else if (findPostHogPermissionError(error)) {- toolErrorsTotal.inc({ tool: toolName, error_type: 'permission' })- } else if (error instanceof Error && error.name === 'TimeoutError') {- toolErrorsTotal.inc({ tool: toolName, error_type: 'timeout' })- } else {- const apiError = findRecoverableApiError(error)- if (apiError instanceof PostHogValidationError) {- toolErrorsTotal.inc({ tool: toolName, error_type: 'validation' })- } else if (apiError instanceof PostHogApiError && apiError.status === 429) {- toolErrorsTotal.inc({ tool: toolName, error_type: 'rate_limited' })- } else if (apiError instanceof PostHogApiError && apiError.status >= 500) {- toolErrorsTotal.inc({ tool: toolName, error_type: 'api_5xx' })- } else if (apiError instanceof PostHogApiError) {- toolErrorsTotal.inc({ tool: toolName, error_type: 'api_4xx' })- } else {- toolErrorsTotal.inc({ tool: toolName, error_type: 'internal' })- }+ return { errorType: 'missing_context' }+ }+ if (error instanceof ToolInputValidationError) {+ return { errorType: 'validation' }+ }+ if (findPostHogPermissionError(error)) {+ return { errorType: 'permission' }+ }+ if (error instanceof Error && error.name === 'TimeoutError') {+ return { errorType: 'timeout' }+ }++ const apiError = findRecoverableApiError(error)+ if (apiError instanceof PostHogValidationError) {+ return { errorType: 'validation' }+ }+ if (apiError instanceof PostHogApiError && apiError.status === 429) {+ return { errorType: 'rate_limited', status: apiError.status }+ }+ if (apiError instanceof PostHogApiError && apiError.status >= 500) {+ return { errorType: 'api_5xx', status: apiError.status }+ }+ if (apiError instanceof PostHogApiError) {+ return { errorType: 'api_4xx', status: apiError.status }+ }+ return { errorType: 'internal' }+}++/**+ * 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+ * SDK derives a generic type from the thrown error when none is supplied, and an+ * explicit value here overrides it.+ */+function errorAnalyticsProperties(classification: ToolErrorClassification): Record<string, unknown> {+ return {+ $mcp_error_type: classification.errorType,+ ...(classification.status !== undefined ? { $mcp_error_status: classification.status } : {}),}}diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 57477259ff64..d755cecf11c1 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -36,11 +36,20 @@ vi.mock('@/resources', () => ({import { z } from 'zod'-import { PostHogRateLimitError, wrapError } from '@/lib/errors'+import { trackToolCall } from '@/hono/analytics'import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'+import { PostHogRateLimitError, wrapError } from '@/lib/errors'++const mockTrackToolCall = vi.mocked(trackToolCall)++/** Extra-properties bag passed to the 5th arg of `trackToolCall` for a given tool. */+function trackToolCallExtras(tool: string): Record<string, unknown> | undefined {+ const call = mockTrackToolCall.mock.calls.find((c) => c[0] === tool)+ return call?.[4]+}function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {return {@@ -114,6 +123,7 @@ describe('ToolExecutor metrics', () => {mockToolDurationObserve.mockClear()mockToolDurationStartTimer.mockClear()mockToolErrorsInc.mockClear()+ mockTrackToolCall.mockClear()catalog = new ToolCatalog()await catalog.warmup()@@ -145,6 +155,38 @@ describe('ToolExecutor metrics', () => {expect(mockToolDurationStartTimer.mock.results[0]!.value).toHaveBeenCalledWith({ status: 'error' })})+ it('stamps $mcp_error_type on the analytics event so the dashboard can slice failures by reason', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(+ makeFakeTool('fail-tool', async () => {+ throw new Error('boom')+ }) as any+ )++ await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))++ expect(trackToolCallExtras('fail-tool')).toMatchObject({ $mcp_error_type: 'internal' })+ })++ it('carries the upstream status alongside the error type for API failures', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(+ makeFakeTool('execute-sql', async () => {+ throw new PostHogRateLimitError({+ body: '{}',+ url: 'https://us.posthog.com/api/environments/2/mcp_tools/execute_sql/',+ method: 'POST',+ retryAfterSeconds: 5,+ })+ }) as any+ )++ await executor.handleToolCall({ name: 'execute-sql', arguments: {} }, makeState([{ name: 'execute-sql' }]))++ expect(trackToolCallExtras('execute-sql')).toMatchObject({+ $mcp_error_type: 'rate_limited',+ $mcp_error_status: 429,+ })+ })+it('classifies a downstream 429 as rate_limited, keeping it out of the error rate', async () => {vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('execute-sql', async () => {diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.tsindex 27c4e090e88d..cf161d89cd90 100644--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts@@ -165,7 +165,10 @@ describe('ToolExecutor token estimates', () => {const [toolName, , isError, , extra] = mockTrackToolCall.mock.calls[0]!expect(toolName).toBe('fail-tool')expect(isError).toBe(true)- expect(extra).toBeUndefined()+ // The error path carries the failure classification ($mcp_error_type) but+ // never token estimates — those only make sense on a successful call.+ expect(extra).not.toHaveProperty('input_tokens')+ expect(extra).not.toHaveProperty('output_tokens')})})