: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): classify exec dispatcher rejections as validation, not internal (#73749)
Marce Coll1344fa4727b4
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex aa26e3f667cd..3b0b33ff4805 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -7,6 +7,7 @@ import {type ToolResultPayload,} from '@/lib/build-tool-result'import {+ ExecCommandError,handleToolError,MissingOrganizationContextError,MissingProjectContextError,@@ -330,10 +331,12 @@ export class ToolExecutor {return response} catch (error: unknown) {const metricTool = execToolName()+ const classification = classifyToolError(error, metricTool)if (!execMetrics.innerToolName) {- toolCallsTotal.inc({ tool: 'exec', status: 'error' })+ // Match the inner-tool path, which labels rejected input `validation_error`.+ const status = classification.errorType === 'validation' ? 'validation_error' : 'error'+ toolCallsTotal.inc({ tool: 'exec', status })}- const classification = classifyToolError(error, metricTool)void trackToolCall(metricTool,@@ -516,6 +519,12 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassification...(error.inputKeys.length ? { validationInputKeys: error.inputKeys } : {}),}}+ // Agent-recoverable command mistakes, so keep them out of the `internal` rate+ // 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' }+ }if (findPostHogPermissionError(error)) {return { errorType: 'permission' }}@@ -574,6 +583,11 @@ function resolveSafeErrorMessage(error: unknown): string | undefined {if (error instanceof ToolInputValidationError) {return error.message}+ // Value-free: the reason enum only. The dispatcher's human message can echo the+ // caller's tool name or a JSON-parser fragment, so it's never captured.+ if (error instanceof ExecCommandError) {+ return `Exec command rejected: ${error.reason}`+ }if (error instanceof Error && error.name === 'TimeoutError') {return 'Tool call timed out'}diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex 9da6141e62cb..f3bfe6fd585c 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -143,6 +143,36 @@ export class ToolInputValidationError extends Error {}}+export type ExecCommandErrorReason =+ | 'unknown_command'+ | 'unknown_tool'+ | 'deprecated_tool'+ | 'missing_scope'+ | 'invalid_json'+ | 'usage'+ | 'invalid_regex'+ | 'unknown_learn_topic'+ | 'needs_confirmation'++/**+ * Thrown by the `exec` dispatcher when it rejects a command before any inner+ * tool runs. Typed so these classify as agent mistakes rather than falling+ * through to the `internal` bucket ops alerts on.+ *+ * `message` goes back to the agent verbatim so it can self-correct, but is+ * never captured into analytics — it can echo the caller's tool name or a JSON+ * parser fragment. `$mcp_error_message` is derived from the `reason` enum.+ */+export class ExecCommandError extends Error {+ public readonly reason: ExecCommandErrorReason++ constructor(message: string, reason: ExecCommandErrorReason) {+ super(message)+ this.name = 'ExecCommandError'+ this.reason = reason+ }+}+export interface PostHogApiErrorOptions {status: numberstatusText: string@@ -404,25 +434,16 @@ export function findRecoverableApiError(error: unknown): PostHogApiError | PostHexport function handleToolError(error: any, tool?: string, distinctId?: string, sessionUuid?: string): CallToolResult {const toolName = tool || 'unknown'- // Recoverable: agent can fix it via switch-project / projects-get. Skip- // exception capture (this is expected user state, not a bug) and return the- // typed error's pre-formatted multi-line message verbatim.- if (error instanceof MissingProjectContextError || error instanceof MissingOrganizationContextError) {- return {- content: [- {- type: 'text',- text: `Error: [${toolName}]: ${error.message}`,- },- ],- isError: true,- }- }-- // Recoverable: input rejected by the tool's schema before any handler ran —- // an agent slip-up, not a bug. The message already names the offending- // field(s); skip exception capture like the API 4xx branch below.- if (error instanceof ToolInputValidationError) {+ // Recoverable: expected agent or user state, not a bug — no project picked,+ // input the schema rejected, a mistyped exec command. Each of these classes+ // pre-formats a message the agent can self-correct from, so return it verbatim+ // and skip exception capture, which would mint an issue per slip-up.+ if (+ error instanceof MissingProjectContextError ||+ error instanceof MissingOrganizationContextError ||+ error instanceof ToolInputValidationError ||+ error instanceof ExecCommandError+ ) {return {content: [{diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 119e98649f6d..df57878a61e0 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -3,7 +3,7 @@ import { z } from 'zod'import { markExecPayload, buildToolResultPayload, estimateResponseTokens } from '@/lib/build-tool-result'import { isPostHogCodeConsumer } from '@/lib/client-detection'-import { findRecoverableApiError, PostHogApiError, ToolInputValidationError } from '@/lib/errors'+import { ExecCommandError, findRecoverableApiError, PostHogApiError, ToolInputValidationError } from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { formatResponse } from '@/lib/response'@@ -285,16 +285,18 @@ function findTool(tools: Tool<ZodObjectAny>[], scopeGatedTools: ScopeGatedTool[]if (!tool) {const redirect = DEPRECATED_TOOL_REDIRECTS[name]if (redirect) {- throw new Error(redirect(tools))+ throw new ExecCommandError(redirect(tools), 'deprecated_tool')}const scopeGatedTool = scopeGatedTools.find((candidate) => candidate.name === name)if (scopeGatedTool) {- throw new Error(- `Tool "${name}" exists, but this MCP connection is missing the required scope(s): ${scopeGatedTool.missingScopes.join(', ')}. Reconnect or reauthorize the PostHog MCP connection and approve these scopes. Logging in to PostHog in a browser does not update MCP permissions.`+ throw new ExecCommandError(+ `Tool "${name}" exists, but this MCP connection is missing the required scope(s): ${scopeGatedTool.missingScopes.join(', ')}. Reconnect or reauthorize the PostHog MCP connection and approve these scopes. Logging in to PostHog in a browser does not update MCP permissions.`,+ 'missing_scope')}- throw new Error(- `Unknown tool: "${name}". Run "search ${name}" to find the current tool name before claiming the capability is unavailable.`+ throw new ExecCommandError(+ `Unknown tool: "${name}". Run "search ${name}" to find the current tool name before claiming the capability is unavailable.`,+ 'unknown_tool')}return tool@@ -331,7 +333,12 @@ export function createExecTool(case 'learn': {const helpCatalog = options.helpCatalogif (!helpCatalog) {- throw new Error('The learning catalog is not available for this client.')+ // `learn` is only advertised when a catalog exists, so without one+ // it's an unsupported verb rather than a misuse of a real command.+ throw new ExecCommandError(+ 'The learning catalog is not available for this client.',+ 'unknown_command'+ )}if (!rest) {return JSON.stringify(helpCatalog.list())@@ -344,11 +351,11 @@ export function createExecTool(.list().map((item) => item.id).join(', ')- if (unknownTopicIds.length === 1) {- throw new Error(`Unknown learning topic: "${unknownTopicIds[0]}". Available: ${available}`)- }const unknownTopics = unknownTopicIds.map((topicId) => `"${topicId}"`).join(', ')- throw new Error(`Unknown learning topics: ${unknownTopics}. Available: ${available}`)+ throw new ExecCommandError(+ `Unknown learning topic${unknownTopicIds.length === 1 ? '' : 's'}: ${unknownTopics}. Available: ${available}`,+ 'unknown_learn_topic'+ )}const resolvedEntries = entries.filter((entry) => entry !== undefined)if (resolvedEntries.length === 1) {@@ -363,13 +370,14 @@ export function createExecTool(case 'search': {if (!rest) {- throw new Error('Usage: search <words or regex_pattern>')+ throw new ExecCommandError('Usage: search <words or regex_pattern>', 'usage')}// Bound the user-supplied pattern length to limit the blast// radius of a pathological (catastrophic-backtracking) regex.if (rest.length > MAX_SEARCH_PATTERN_LENGTH) {- throw new Error(- `Search pattern too long (${rest.length} chars, max ${MAX_SEARCH_PATTERN_LENGTH}). Use a shorter, more targeted pattern.`+ throw new ExecCommandError(+ `Search pattern too long (${rest.length} chars, max ${MAX_SEARCH_PATTERN_LENGTH}). Use a shorter, more targeted pattern.`,+ 'usage')}@@ -385,7 +393,7 @@ export function createExecTool(matches = searchToolsRegex(allTools, rest).map((t) => t.name)gatedMatches = searchToolsRegex(scopeGatedTools, rest)} catch {- throw new Error(`Invalid regex pattern: "${rest}"`)+ throw new ExecCommandError(`Invalid regex pattern: "${rest}"`, 'invalid_regex')}} else {const ranked = searchToolsRanked(allTools, rest)@@ -430,12 +438,12 @@ export function createExecTool(case 'info': {if (!rest) {- throw new Error('Usage: info [--json] <tool_name>')+ throw new ExecCommandError('Usage: info [--json] <tool_name>', 'usage')}const forceJson = rest.startsWith('--json ') || rest === '--json'const infoArgs = forceJson ? rest.slice('--json'.length).trim() : restif (!infoArgs) {- throw new Error('Usage: info [--json] <tool_name>')+ throw new ExecCommandError('Usage: info [--json] <tool_name>', 'usage')}const tool = findTool(allTools, scopeGatedTools, infoArgs)// `io: 'input'` mirrors the advertised `tools/list` schema and the executor's@@ -477,7 +485,7 @@ export function createExecTool(case 'schema': {if (!rest) {- throw new Error('Usage: schema <tool_name> [field_path]')+ throw new ExecCommandError('Usage: schema <tool_name> [field_path]', 'usage')}const { verb: schemaToolName, rest: fieldPath } = parseCommand(rest)const schemaTool = findTool(allTools, scopeGatedTools, schemaToolName)@@ -497,7 +505,10 @@ export function createExecTool(const resolved = resolveSchemaPath(fullJsonSchema, fieldPath)if (!resolved) {const available = listAvailablePaths(fullJsonSchema)- throw new Error(`Unknown path "${fieldPath}". Available: ${available.join(', ')}`)+ throw new ExecCommandError(+ `Unknown path "${fieldPath}". Available: ${available.join(', ')}`,+ 'usage'+ )}const serialized = JSON.stringify({@@ -520,20 +531,23 @@ export function createExecTool(case 'call': {if (!rest) {- throw new Error('Usage: call [--json] [--confirm] <tool_name> <json_input>')+ throw new ExecCommandError('Usage: call [--json] [--confirm] <tool_name> <json_input>', 'usage')}if (!context) {+ // Deliberately untyped: a wiring fault, not an agent mistake, so it+ // belongs in the `internal` bucket its siblings are kept out of.throw new Error('Cannot call PostHog tools without an API context')}const { forceJson, confirmed, rest: callArgs } = parseCallFlags(rest)if (!callArgs) {- throw new Error('Usage: call [--json] [--confirm] <tool_name> <json_input>')+ throw new ExecCommandError('Usage: call [--json] [--confirm] <tool_name> <json_input>', 'usage')}const { verb: toolName, rest: jsonBody } = parseCommand(callArgs)const tool = findTool(allTools, scopeGatedTools, toolName)if (options.requireDestructiveConfirmation && tool.annotations.destructiveHint && !confirmed) {- throw new Error(- `Tool "${tool.name}" is destructive. Re-run with "call --confirm ${tool.name} ..." after verifying the target IDs. Use "info ${tool.name}" to inspect the tool first.`+ throw new ExecCommandError(+ `Tool "${tool.name}" is destructive. Re-run with "call --confirm ${tool.name} ..." after verifying the target IDs. Use "info ${tool.name}" to inspect the tool first.`,+ 'needs_confirmation')}let input: Record<string, unknown>@@ -544,7 +558,7 @@ export function createExecTool(input = JSON.parse(jsonBody) as Record<string, unknown>} catch (err) {const detail = err instanceof Error ? err.message : String(err)- throw new Error(`Invalid JSON input: ${detail}`)+ throw new ExecCommandError(`Invalid JSON input: ${detail}`, 'invalid_json')}}@@ -696,8 +710,9 @@ export function createExecTool(}default:- throw new Error(- `Unknown command: "${verb}". Supported commands: ${options.helpCatalog ? 'learn, ' : ''}tools, search, info, schema, call`+ throw new ExecCommandError(+ `Unknown command: "${verb}". Supported commands: ${options.helpCatalog ? 'learn, ' : ''}tools, search, info, schema, call`,+ 'unknown_command')}},diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 2fe87e3cef6e..8c51ed55781d 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -431,17 +431,37 @@ describe('ToolExecutor metrics', () => {expect(callsFor(mockToolErrorsInc, 'exec')).toHaveLength(0)})- it('emits exec-level error for framework failures before inner dispatch', async () => {- await executor.handleToolCall(- { name: 'exec', arguments: { command: 'call nonexistent-tool-xyz {}' } },- execState()- )+ // Dispatcher rejections are agent mistakes, not server faults: they must not+ // land in the `internal` bucket the error-rate alert watches, they stay+ // attributed to `exec` (no inner tool ran), and they must carry a value-free+ // message so the failure is debuggable from analytics.+ it.each([+ ['call nonexistent-tool-xyz {}', 'unknown_tool'],+ ['frobnicate', 'unknown_command'],+ ['call docs-search {not json}', 'invalid_json'],+ ])('classifies %s as validation', async (command, reason) => {+ await executor.handleToolCall({ name: 'exec', arguments: { command } }, execState())++ expect(callsFor(mockToolCallsInc, 'exec')).toEqual([{ tool: 'exec', status: 'validation_error' }])+ expect(callsFor(mockToolErrorsInc, 'exec')).toEqual([{ tool: 'exec', error_type: 'validation' }])+ expect(trackToolCallExtras('exec')).toMatchObject({+ $mcp_error_type: 'validation',+ $mcp_error_message: `Exec command rejected: ${reason}`,+ })+ })- const execErrors = callsFor(mockToolCallsInc, 'exec')- expect(execErrors.length).toBeGreaterThan(0)- expect(execErrors[0].status).toBe('error')+ it('classifies a scope-gated tool as permission, not validation', async () => {+ // The agent can't fix this by sending different input — the connection has+ // to be reauthorized, which is what the permission-rate alert watches for.+ const state = execState()+ state.scopeGatedTools = [{ name: 'gated-tool', missingScopes: ['insight:read'] }] as any- expect(callsFor(mockToolErrorsInc, 'exec').length).toBeGreaterThan(0)+ await executor.handleToolCall({ name: 'exec', arguments: { command: 'info gated-tool' } }, state)++ expect(callsFor(mockToolErrorsInc, 'exec')).toEqual([{ tool: 'exec', error_type: 'permission' }])+ expect(trackToolCallExtras('exec')).toMatchObject({+ $mcp_error_message: 'Exec command rejected: missing_scope',+ })})})})