: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): name the nesting mistake when a required object param is flattened (#90496)
Daniel Viscaf779f9fe8626
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex a42ef0598971..525d5980f948 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -234,7 +234,7 @@ export class ToolExecutor {const validation = tool.schema.safeParse(toolArgs, { reportInput: true })if (!validation.success) {toolCallsTotal.inc({ tool: tool.name, status: 'validation_error' })- const message = formatInputValidationError(tool.name, validation.error)+ const message = formatInputValidationError(tool.name, validation.error, toolArgs, tool.schema)// Emit the same errored `$mcp_tool_call` the exec path emits for an// identical rejection. Without it, direct-mode ('tools') schema// rejections are absent from analytics entirely — so everydiff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex eb1de004ed4e..7e98f6ba35da 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -339,6 +339,47 @@ const DEPRECATED_TOOL_REDIRECTS: Record<string, (allTools: Tool<ZodObjectAny>[])},}+/**+ * Detects the caller sending a required object parameter's *contents* in place of+ * the parameter itself — `{dateRange, limit}` where `{query: {dateRange, limit}}`+ * was wanted. Zod strips the misplaced keys, so an unwrapped payload and an empty+ * one both surface as the same bare `missing required parameter`, and the caller+ * has no way to tell which mistake it made.+ *+ * Decided by re-parsing rather than by reading the schema, so it holds for any+ * wrapper shape: nest the input under the missing key and see whether the schema+ * accepts it. Confident when the wrapped value either parses to something+ * non-empty, or fails only on paths *inside* the wrapper — both mean the nested+ * schema recognized the content. A payload of undeclared keys parses to `{}` and+ * is correctly rejected, as is a caller that sent nothing at all.+ */+function looksLikeUnwrappedPayload(+ issuePath: ReadonlyArray<PropertyKey>,+ input: unknown,+ schema: ZodObjectAny | undefined+): boolean {+ if (!schema || issuePath.length !== 1) {+ return false+ }+ const key = String(issuePath[0])+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {+ return false+ }+ const keys = Object.keys(input)+ if (keys.length === 0 || keys.includes(key)) {+ return false+ }++ const wrapped = schema.safeParse({ [key]: input })+ if (wrapped.success) {+ const nested = (wrapped.data as Record<string, unknown>)[key]+ return typeof nested === 'object' && nested !== null && Object.keys(nested).length > 0+ }+ // Every remaining complaint sits under the wrapper: the nested schema read the+ // content and rejected specific fields, so the nesting itself was the mistake.+ return wrapped.error.issues.every((issue) => issue.path.length > 1 && String(issue.path[0]) === key)+}+/** 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@@ -350,11 +391,19 @@ const DEPRECATED_TOOL_REDIRECTS: Record<string, (allTools: Tool<ZodObjectAny>[])* 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 {+export function formatInputValidationError(+ toolName: string,+ error: z.ZodError,+ input?: unknown,+ schema?: ZodObjectAny+): 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) {+ if (looksLikeUnwrappedPayload(issue.path, input, schema)) {+ return `missing required parameter: ${path}; the fields you sent belong inside it, so resend them as {"${path}": {...}}`+ }return `missing required parameter: ${path}`}return `parameter "${path}" must be of type ${issue.expected}`@@ -934,7 +983,7 @@ export function createExecTool(// field. Dispatch the parsed output so coerced values and defaults apply.const validation = toolSchema.safeParse(input, { reportInput: true })if (!validation.success) {- const message = formatInputValidationError(tool.name, validation.error)+ const message = formatInputValidationError(tool.name, validation.error, input, tool.schema)trackInnerCall?.(tool.name, {duration_ms: 0,success: false,diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 695e08ef6663..e35bc7372a66 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -21,6 +21,7 @@ import {parseExecCallInnerToolName,} from '@/tools/exec'import { ExecHelpCatalog } from '@/tools/exec-help'+import { GENERATED_TOOL_MAP } from '@/tools/generated'import { withInformationalResponse } from '@/tools/tool-utils'import { getToolDefinition } from '@/tools/toolDefinitions'import {@@ -1561,5 +1562,77 @@ describe('exec tool', () => {expect(message).toMatch(/parameter "tags": /)expect(message).not.toContain('undefined')})++ // A tool whose whole payload sits under one required object is the shape+ // agents flatten most often, and zod strips the misplaced keys — so+ // "sent everything, unwrapped" and "sent nothing" both arrive as a bare+ // `missing required parameter`. These lock in the disambiguation.+ describe('a required object parameter the caller flattened', () => {+ const wrapperSchema = z.object({+ query: z.object({+ dateRange: z.object({ date_from: z.string() }).optional(),+ orderBy: z.enum(['latest', 'earliest']).optional(),+ limit: z.number().optional(),+ }),+ })++ const formatFor = (input: unknown): string => {+ const result = wrapperSchema.safeParse(input, { reportInput: true })+ expect(result.success).toBe(false)+ return formatInputValidationError('query-logs', result.error!, input, wrapperSchema)+ }++ it('tells the caller to nest the fields it sent at the top level', () => {+ const message = formatFor({ dateRange: { date_from: '-1h' }, limit: 10 })++ expect(message).toBe(+ 'Invalid input for "query-logs": missing required parameter: query; the fields you sent belong inside it, so resend them as {"query": {...}}'+ )+ })++ it('still identifies the nesting when the nested fields have their own errors', () => {+ // Without this the caller fixes `orderBy`, resends flattened, and+ // fails again on the same ambiguous message.+ const message = formatFor({ orderBy: 'newest', limit: 10 })++ expect(message).toContain('resend them as {"query": {...}}')+ })++ it.each([+ ['an empty input, which is a caller that sent nothing', {}],+ ['keys the nested schema does not declare', { nonsense: 1, alsoNonsense: 2 }],+ ['a non-object input', 'just a string'],+ ])('does not claim a nesting mistake for %s', (_label, input) => {+ expect(formatFor(input)).not.toContain('resend them')+ })++ it('names only schema-declared fields, never the values the caller sent', () => {+ const message = formatFor({ dateRange: { date_from: 'secret-value' } })++ expect(message).not.toContain('secret-value')+ })++ it('keeps the bare message when the caller gives no input or schema to compare', () => {+ const input = { dateRange: { date_from: '-1h' } }+ const result = wrapperSchema.safeParse(input, { reportInput: true })++ expect(formatInputValidationError('query-logs', result.error!)).toBe(+ 'Invalid input for "query-logs": missing required parameter: query'+ )+ })++ it('fires for the real generated query-logs tool, not just a stand-in schema', () => {+ // Guards the assumption behind this whole branch: that the shipped+ // tool really does wrap its payload in one required `query` object.+ const tool = GENERATED_TOOL_MAP['query-logs']!()+ const input = { dateRange: { date_from: '-1h' }, limit: 10 }+ const result = tool.schema.safeParse(input, { reportInput: true })+ expect(result.success).toBe(false)++ expect(formatInputValidationError('query-logs', result.error!, input, tool.schema)).toContain(+ 'resend them as {"query": {...}}'+ )+ })+ })})})