: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 machine-readable error code on failed tool calls (#78185)
Harley Alexander8d4044841546
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex 12168c9b0a4b..68425feaff8b 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -2112,6 +2112,24 @@"label": "MCP duration (ms)","type": "Numeric"},+ "$mcp_error_code": {+ "description": "Machine-readable code for the leaf failure mode of an errored MCP tool call: the API's validation error code, or the exec dispatcher's rejection reason. Carries error codes only, never caller-supplied values. Only set when $mcp_is_error is true.",+ "examples": [+ "invalid",+ "required",+ "unknown_tool",+ "invalid_json"+ ],+ "label": "MCP error code"+ },+ "$mcp_error_field": {+ "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"+ ],+ "label": "MCP error field"+ },"$mcp_error_message": {"description": "Short, sanitized summary of why a failed MCP tool call errored: a validation code and field, or an HTTP status and path. Never includes caller-supplied input, query text, or upstream response bodies. Truncated to 2048 characters. Only set when $mcp_is_error is true.","label": "MCP error message"@@ -4225,6 +4243,24 @@"label": "MCP duration (ms)","type": "Numeric"},+ "$mcp_error_code": {+ "description": "Machine-readable code for the leaf failure mode of an errored MCP tool call: the API's validation error code, or the exec dispatcher's rejection reason. Carries error codes only, never caller-supplied values. Only set when $mcp_is_error is true.",+ "examples": [+ "invalid",+ "required",+ "unknown_tool",+ "invalid_json"+ ],+ "label": "MCP error code"+ },+ "$mcp_error_field": {+ "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"+ ],+ "label": "MCP error field"+ },"$mcp_error_message": {"description": "Short, sanitized summary of why a failed MCP tool call errored: a validation code and field, or an HTTP status and path. Never includes caller-supplied input, query text, or upstream response bodies. Truncated to 2048 characters. Only set when $mcp_is_error is true.","label": "MCP error message"@@ -6915,6 +6951,24 @@"label": "MCP duration (ms)","type": "Numeric"},+ "$mcp_error_code": {+ "description": "Machine-readable code for the leaf failure mode of an errored MCP tool call: the API's validation error code, or the exec dispatcher's rejection reason. Carries error codes only, never caller-supplied values. Only set when $mcp_is_error is true.",+ "examples": [+ "invalid",+ "required",+ "unknown_tool",+ "invalid_json"+ ],+ "label": "MCP error code"+ },+ "$mcp_error_field": {+ "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"+ ],+ "label": "MCP error field"+ },"$mcp_error_message": {"description": "Short, sanitized summary of why a failed MCP tool call errored: a validation code and field, or an HTTP status and path. Never includes caller-supplied input, query text, or upstream response bodies. Truncated to 2048 characters. Only set when $mcp_is_error is true.","label": "MCP error message"diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex b47214c3f6e2..44900e598f2e 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -2728,6 +2728,16 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"type": "Numeric","examples": [429, 500, 403],},+ "$mcp_error_code": {+ "label": "MCP error code",+ "description": "Machine-readable code for the leaf failure mode of an errored MCP tool call: the API's validation error code, or the exec dispatcher's rejection reason. Carries error codes only, never caller-supplied values. Only set when $mcp_is_error is true.",+ "examples": ["invalid", "required", "unknown_tool", "invalid_json"],+ },+ "$mcp_error_field": {+ "label": "MCP error field",+ "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_error_message": {"label": "MCP error message","description": "Short, sanitized summary of why a failed MCP tool call errored: a validation code and field, or an HTTP status and path. Never includes caller-supplied input, query text, or upstream response bodies. Truncated to 2048 characters. Only set when $mcp_is_error is true.",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 366584bba24f..f654e2d5feec 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@@ -65,10 +65,7 @@ server, so never rely on them in customer-facing queries or docs without checkinnon-`$`-prefixed `mcp_runtime` (`hono`) and `mcp_vendor_client` — the last of which is the**top-priority harness signal**, so it appears inside harness SQL.-Per-event additions: `$mcp_error_status` (upstream HTTP status, 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`. `execute-sql` calls additionally emit a separate `$ai_generation` event+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`. `execute-sql` calls additionally emit a separate `$ai_generation` eventcarrying `$ai_trace_id`, `$ai_input`, `$ai_output_choices`, and `$ai_latency`.## Exec-mode propertiesdiff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 00cac4207629..1159e390d0df 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -536,6 +536,10 @@ interface ToolErrorClassification {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`. */+ errorField?: string}/**@@ -566,7 +570,10 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassification// ops alerts on. `missing_scope` is the exception: no input the agent sends// fixes it, the connection has to be reauthorized.if (error instanceof ExecCommandError) {- return { errorType: error.reason === 'missing_scope' ? 'permission' : 'validation' }+ return {+ errorType: error.reason === 'missing_scope' ? 'permission' : 'validation',+ errorCode: error.reason,+ }}if (findPostHogPermissionError(error)) {return { errorType: 'permission' }@@ -577,7 +584,13 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassificationconst apiError = findRecoverableApiError(error)if (apiError instanceof PostHogValidationError) {- return { errorType: 'validation' }+ const errorCode = apiError.code ? sanitizeErrorToken(apiError.code) : undefined+ const errorField = apiError.attr ? normalizeErrorField(apiError.attr) : undefined+ return {+ errorType: 'validation',+ ...(errorCode ? { errorCode } : {}),+ ...(errorField ? { errorField } : {}),+ }}if (apiError instanceof PostHogApiError && apiError.status === 429) {return { errorType: 'rate_limited', status: apiError.status }@@ -595,6 +608,31 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassification// the bound external servers get when they pass `error` to the SDK.const MAX_ERROR_MESSAGE_LENGTH = 2048+// Matches the truncation the MCP analytics queries apply to `$mcp_error_type`.+const MAX_ERROR_TOKEN_LENGTH = 200++/**+ * DRF error codes and attrs are server-generated (field names and error codes,+ * never caller values), but they cross a network boundary — strip control+ * characters and cap length so a malformed body can't pollute the property.+ */+function sanitizeErrorToken(token: string): string | undefined {+ const sanitized = token+ .replace(/[\x00-\x1f\x7f]/g, '')+ .trim()+ .slice(0, MAX_ERROR_TOKEN_LENGTH)+ return sanitized || undefined+}++/**+ * Collapses array indexes in a DRF attr path (`actions__2__inputs__email`) to+ * `N` so one leaf failure mode groups to one value regardless of where in the+ * payload it occurred.+ */+function normalizeErrorField(attr: string): string | undefined {+ return sanitizeErrorToken(attr.replace(/(^|__)\d+(?=__|$)/g, '$1N'))+}+/*** Extracts a capturable message from a thrown value, restricted to an allowlist* of error classes whose message shape we control. `$mcp_error_message` is@@ -665,6 +703,9 @@ function safeUrlPath(url: string): string {* explicit value here overrides it. `$mcp_error_message` carries a sanitized,* allowlisted summary of the failure (see `extractErrorMessage`) so tool-quality* drill-downs can show what went wrong without persisting caller-derived text.+ * `$mcp_error_code` / `$mcp_error_field` carry the machine-readable leaf failure+ * mode (error code + normalized field path, never values) so validation failures+ * are measurable per field instead of one undifferentiated `validation` bucket.*/function errorAnalyticsProperties(classification: ToolErrorClassification, error: unknown): Record<string, unknown> {const message = extractErrorMessage(error)@@ -675,6 +716,8 @@ function errorAnalyticsProperties(classification: ToolErrorClassification, error...(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/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 1e06ef90699e..d103f0cbff34 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -200,6 +200,37 @@ describe('ToolExecutor metrics', () => {const extras = trackToolCallExtras('fail-tool')expect(extras).toMatchObject({ $mcp_error_type: 'internal' })expect(extras).not.toHaveProperty('$mcp_error_message')+ expect(extras).not.toHaveProperty('$mcp_error_code')+ expect(extras).not.toHaveProperty('$mcp_error_field')+ })++ // The code and normalized field path are what make leaf failure modes measurable:+ // $mcp_error_message is free text, so dashboards can't group on it, and the raw+ // attr fragments per array index ("actions__0__...", "actions__3__...").+ it('stamps $mcp_error_code and index-normalized $mcp_error_field for a PostHogValidationError', async () => {+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(+ makeFakeTool('fail-tool', async () => {+ throw new PostHogValidationError({+ detail: "Email input must contain a 'from' property",+ attr: 'actions__2__inputs__email',+ code: 'invalid_input',+ extra: undefined,+ url: 'https://us.posthog.com/api/environments/2/hog_flows/',+ method: 'POST',+ })+ }) as any+ )++ await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))++ const extras = trackToolCallExtras('fail-tool')+ expect(extras).toMatchObject({+ $mcp_error_type: 'validation',+ $mcp_error_code: 'invalid_input',+ $mcp_error_field: 'actions__N__inputs__email',+ })+ // The detail body echoes caller input, so it must never ride along.+ expect(JSON.stringify(extras)).not.toContain("'from' property")})it.each([@@ -447,6 +478,7 @@ describe('ToolExecutor metrics', () => {expect(callsFor(mockToolErrorsInc, 'exec')).toEqual([{ tool: 'exec', error_type: 'validation' }])expect(trackToolCallExtras('exec')).toMatchObject({$mcp_error_type: 'validation',+ $mcp_error_code: reason,$mcp_error_message: `Exec command rejected: ${reason}`,})})