: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): validate exec call input against tool schema (#62617)
Georgiy Tarasov674eb6b87e8b
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 3f43eba4a202..5681b314ccdc 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -7,11 +7,12 @@ import {MissingProjectContextError,PostHogApiError,PostHogValidationError,+ ToolInputValidationError,findPostHogPermissionError,findRecoverableApiError,} from '@/lib/errors'import { AnalyticsEvent } from '@/lib/posthog/analytics'-import { createExecTool, type ExecInnerCallTracker } from '@/tools/exec'+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'@@ -112,10 +113,13 @@ export class ToolExecutor {state: ResolvedState): Promise<unknown> {const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>- const validation = tool.schema.safeParse(toolArgs)+ const validation = tool.schema.safeParse(toolArgs, { reportInput: true })if (!validation.success) {toolCallsTotal.inc({ tool: tool.name, status: 'validation_error' })- return { content: [{ type: 'text', text: `Invalid input: ${validation.error.message}` }], isError: true }+ return {+ content: [{ type: 'text', text: formatInputValidationError(tool.name, validation.error) }],+ isError: true,+ }}const stop = toolCallDurationSeconds.startTimer({ tool: tool.name })@@ -171,10 +175,13 @@ export class ToolExecutor {const resolved = this.resolveExecTool(state, execMetrics)const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>- const validation = resolved.schema.safeParse(toolArgs)+ const validation = resolved.schema.safeParse(toolArgs, { reportInput: true })if (!validation.success) {toolCallsTotal.inc({ tool: 'exec', status: 'validation_error' })- return { content: [{ type: 'text', text: `Invalid input: ${validation.error.message}` }], isError: true }+ return {+ content: [{ type: 'text', text: formatInputValidationError(resolved.name, validation.error) }],+ isError: true,+ }}const startMs = Date.now()@@ -219,9 +226,14 @@ export class ToolExecutor {const trackInnerCall: ExecInnerCallTracker = (toolName, properties) => {execMetrics.innerToolName = toolName- const status = properties.success ? 'success' : 'error'+ const status = properties.success ? 'success' : properties.validation_error ? 'validation_error' : 'error'toolCallsTotal.inc({ tool: toolName, status })- toolCallDurationSeconds.observe({ tool: toolName, status }, properties.duration_ms / 1000)+ // Mirror the native path: schema rejections never start a handler, so+ // they get no duration observation (`callTool` starts its timer only+ // after validation passes).+ 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.@@ -304,6 +316,8 @@ export class ToolExecutor {function classifyToolError(error: unknown, toolName: string): void {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') {diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex 6e36b2ed933f..8e45b27081ca 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -120,6 +120,21 @@ export class PostHogValidationError extends Error {}}+/**+ * Thrown when MCP-side schema validation rejects a tool call's input before+ * any handler runs (the exec `call` path). The message is pre-formatted by+ * `formatInputValidationError` and already names the offending field(s), so+ * `handleToolError` returns it verbatim — capturing it as an exception would+ * mint a per-tool error tracking issue for every agent slip-up, the same+ * noise problem the 4xx short-circuit exists to prevent.+ */+export class ToolInputValidationError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'ToolInputValidationError'+ }+}+export interface PostHogApiErrorOptions {status: numberstatusText: string@@ -353,6 +368,21 @@ export function handleToolError(error: any, tool?: string, distinctId?: string,}}+ // 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) {+ return {+ content: [+ {+ type: 'text',+ text: `Error: [${toolName}]: ${error.message}`,+ },+ ],+ isError: true,+ }+ }+// Recoverable: 4xx responses from the PostHog API (and validation errors)// are agent-input failures — the LLM passed a bad id, a stale UUID, or a// value the serializer rejected. Returning the typed error message to thediff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 39cfb343dcd5..af58700ed12f 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -3,6 +3,7 @@ import { z } from 'zod'import { markExecPayload, buildToolResultPayload } from '@/lib/build-tool-result'import { isPostHogCodeConsumer } from '@/lib/client-detection'+import { ToolInputValidationError } from '@/lib/errors'import { formatResponse } from '@/lib/response'import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'@@ -26,6 +27,8 @@ export interface ExecInnerCallProperties {success: booleanoutput_format: 'json' | 'text' | 'structured'error_message?: string+ /** Input rejected by the tool's schema before dispatch — no handler ran. */+ validation_error?: boolean}export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallProperties) => void@@ -108,6 +111,34 @@ const DEPRECATED_TOOL_REDIRECTS: Record<string, (allTools: Tool<ZodObjectAny>[])},}+/** Turns a Zod validation failure into a short, field-named message the model+ * can act on. Without it, a missing/`undefined` path segment slips through to+ * the HTTP layer and the API returns a generic 404 that reads as "entity does+ * not exist" — steering recovery toward re-checking the ID rather than the+ * malformed parameter.+ *+ * Callers must `safeParse(input, { reportInput: true })` so `issue.input`+ * distinguishes a missing required field from a present-but-wrong one (the+ * key is absent without the option, and the check degrades to the wrong-type+ * message). `reportInput` embeds raw input values in the ZodError, including+ * its `.message` — keep the error local; never log or capture it. */+export function formatInputValidationError(toolName: string, error: z.ZodError): string {+ const parts = error.issues.map((issue) => {+ const path = issue.path.map(String).join('.')+ if (issue.code === 'invalid_type') {+ if ('input' in issue && issue.input === undefined) {+ return `missing required parameter: ${path}`+ }+ return `parameter "${path}" must be of type ${issue.expected}`+ }+ if (issue.code === 'unrecognized_keys') {+ return `unexpected ${issue.keys.length > 1 ? 'properties' : 'property'}: ${issue.keys.join(', ')}`+ }+ return path ? `parameter "${path}": ${issue.message}` : issue.message+ })+ return `Invalid input for "${toolName}": ${[...new Set(parts)].join('; ')}`+}+function findTool(tools: Tool<ZodObjectAny>[], name: string): Tool<ZodObjectAny> {const tool = tools.find((t) => t.name === name)if (!tool) {@@ -301,6 +332,27 @@ export function createExecTool(}const useJson = forceJson || tool._meta?.[POSTHOG_META_KEY]?.outputFormat === 'json'++ // Same validation gate as the non-exec MCP path (`tool-executor.ts`) —+ // otherwise bad input reaches the HTTP layer and builds URLs like+ // `.../actions/undefined/`, a misleading 404 that hides the offending+ // field. Dispatch the parsed output so coerced values and defaults apply.+ const validation = tool.schema.safeParse(input, { reportInput: true })+ if (!validation.success) {+ const message = formatInputValidationError(tool.name, validation.error)+ trackInnerCall?.(tool.name, {+ duration_ms: 0,+ success: false,+ output_format: useJson ? 'json' : 'text',+ error_message: message,+ validation_error: true,+ })+ // Typed so the executor's catch skips exception capture and+ // classifies it as `validation`, not `internal`.+ throw new ToolInputValidationError(message)+ }+ input = validation.data as Record<string, unknown>+const startedAt = Date.now()let result: unknowntry {diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 679fef1c5f23..2f5c19d69aef 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -164,10 +164,20 @@ describe('ToolExecutor metrics', () => {describe('single-exec mode', () => {function execState(): ResolvedState {- return makeState(- catalog.getPreBuiltEntries().map((e) => ({ name: e.name })),- { useSingleExec: true }- )+ // Mirror getFilteredTools: full tool objects with real schemas and+ // handlers, so exec's inner dispatch (schema validation, handler+ // call) behaves as in production.+ 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: [],+ }+ })+ return makeState(tools as any, { useSingleExec: true })}it('emits no exec-labelled counter or timer on success', async () => {@@ -207,6 +217,26 @@ describe('ToolExecutor metrics', () => {expect(execClassifications).toHaveLength(0)})+ it('records inner validation_error without a duration observation', async () => {+ await executor.handleToolCall({ name: 'exec', arguments: { command: 'call docs-search {}' } }, execState())++ expect(callsFor(mockToolCallsInc, 'docs-search')).toEqual([+ { tool: 'docs-search', status: 'validation_error' },+ ])+ const innerDurations = mockToolDurationObserve.mock.calls.filter((c: any[]) => c[0]?.tool === 'docs-search')+ expect(innerDurations).toHaveLength(0)+ expect(callsFor(mockToolCallsInc, 'exec')).toHaveLength(0)+ })++ it('classifies inner validation failures as validation, not internal', async () => {+ await executor.handleToolCall({ name: 'exec', arguments: { command: 'call docs-search {}' } }, execState())++ expect(callsFor(mockToolErrorsInc, 'docs-search')).toEqual([+ { tool: 'docs-search', error_type: 'validation' },+ ])+ 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 {}' } },diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex bccfcb300f1d..22d73c5d1417 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'import { parse as parseYaml } from 'yaml'import { z } from 'zod'+import { ToolInputValidationError } from '@/lib/errors'import { buildQueryToolsBlock, buildToolDomainsBlock } from '@/lib/instructions'import { InstructionsFormatter } from '@/lib/instructions-formatter'import { SessionManager } from '@/lib/SessionManager'@@ -242,6 +243,68 @@ describe('exec tool', () => {).rejects.toThrow(/Invalid JSON input:/)})+ it.each([+ {+ case: 'a missing required parameter, naming the field',+ input: '{}',+ expected: /Invalid input for "action-get": missing required parameter: id/,+ },+ {+ case: 'a parameter of the wrong type, naming the expected type',+ input: '{"id":"not-a-number"}',+ expected: /parameter "id" must be of type number/,+ },+ {+ // Plain z.object strips unknown keys at parse time (Zod v4), so the+ // actionable signal is the absent required `id`, not the stray key.+ case: 'an unexpected property displacing the required field',+ input: '{"actionId":277664}',+ expected: /missing required parameter: id/,+ },+ ])('rejects a call with $case', async ({ input, expected }) => {+ const tool = makeMockTool({+ name: 'action-get',+ schema: z.object({ id: z.number() }),+ handler: async (_ctx, params) => params,+ })+ const exec = createExec([tool])+ const error: unknown = await exec.handler(mockContext, { command: `call action-get ${input}` }).then(+ () => null,+ (e: unknown) => e+ )+ // Typed rejection — the executor relies on it to skip exception+ // capture and classify the failure as `validation`.+ expect(error).toBeInstanceOf(ToolInputValidationError)+ expect((error as Error).message).toMatch(expected)+ })++ it('passes validated output — with defaults applied — to the inner handler', async () => {+ const tool = makeMockTool({+ schema: z.object({ id: z.number(), limit: z.number().default(10) }),+ handler: async (_ctx, params) => params,+ })+ const exec = createExec([tool])+ const result = await exec.handler(mockContext, { command: 'call --json mock-tool {"id":5}' })+ expect(JSON.parse(result as string)).toEqual({ id: 5, limit: 10 })+ })++ it('does not dispatch to the handler when validation fails', async () => {+ let called = false+ const tool = makeMockTool({+ name: 'action-get',+ schema: z.object({ id: z.number() }),+ handler: async () => {+ called = true+ return {}+ },+ })+ const exec = createExec([tool])+ await expect(exec.handler(mockContext, { command: 'call action-get {}' })).rejects.toThrow(+ /missing required parameter: id/+ )+ expect(called).toBe(false)+ })+it('invokes the inner-call tracker with success=false when the inner tool throws', async () => {const calls: { toolName: string; properties: ExecInnerCallProperties }[] = []const tracker = (toolName: string, properties: ExecInnerCallProperties): void => {@@ -266,6 +329,35 @@ describe('exec tool', () => {expect(calls[0]!.properties.error_message).toBe('boom')expect(calls[0]!.properties.output_format).toBe('text')})++ it('invokes the inner-call tracker with validation_error=true when input fails validation', async () => {+ const calls: { toolName: string; properties: ExecInnerCallProperties }[] = []+ const tracker = (toolName: string, properties: ExecInnerCallProperties): void => {+ calls.push({ toolName, properties })+ }+ const tool = makeMockTool({+ name: 'action-get',+ schema: z.object({ id: z.number() }),+ handler: async (_ctx, params) => params,+ })+ const exec = createExecTool(+ [tool],+ mockContext,+ 'test description',+ 'test command reference',+ undefined,+ tracker+ )+ await expect(exec.handler(mockContext, { command: 'call action-get {}' })).rejects.toThrow(+ /missing required parameter: id/+ )+ expect(calls).toHaveLength(1)+ expect(calls[0]!.toolName).toBe('action-get')+ expect(calls[0]!.properties.success).toBe(false)+ expect(calls[0]!.properties.validation_error).toBe(true)+ expect(calls[0]!.properties.duration_ms).toBe(0)+ expect(calls[0]!.properties.error_message).toMatch(/missing required parameter: id/)+ })})describe('info command', () => {diff --git a/services/mcp/tests/unit/tool-input-validation-error.test.ts b/services/mcp/tests/unit/tool-input-validation-error.test.tsnew file mode 100644index 000000000000..0eab26b2c14b--- /dev/null+++ b/services/mcp/tests/unit/tool-input-validation-error.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it, vi } from 'vitest'++import { handleToolError, ToolInputValidationError } from '@/lib/errors'++const captureException = vi.fn()+vi.mock('@/lib/posthog', () => ({+ getPostHogClient: () => ({ captureException }),+}))++describe('handleToolError with ToolInputValidationError', () => {+ it('returns the pre-formatted message verbatim without capturing an exception', () => {+ const error = new ToolInputValidationError('Invalid input for "action-get": missing required parameter: id')++ const result = handleToolError(error, 'action-get')++ expect(result.isError).toBe(true)+ const [content] = result.content as Array<{ type: string; text: string }>+ expect(content?.type).toBe('text')+ expect(content?.text).toBe(+ 'Error: [action-get]: Invalid input for "action-get": missing required parameter: id'+ )+ expect(captureException).not.toHaveBeenCalled()+ })+})