Skip to content

: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.

feat(mcp): close telemetry gaps in tool validation failures (#77473)

Georgiy Tarasovc8b3f00c71cb
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 1159e390d0df..5d771f170371 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -19,7 +19,14 @@ import {
} from '@/lib/errors'
import { estimateTokens } from '@/lib/estimate-tokens'
import { getPostHogClient } from '@/lib/posthog'
-import { createExecTool, formatInputValidationError, type ExecInnerCallTracker } from '@/tools/exec'
+import {
+ createExecTool,
+ describeApiValidationError,
+ describeExecCommand,
+ describeValidationError,
+ formatInputValidationError,
+ type ExecInnerCallTracker,
+} from '@/tools/exec'
import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'
import { createRenderUiTool } from '@/tools/render-ui'
import type { Context, ZodObjectAny } from '@/tools/types'
@@ -189,8 +196,28 @@ 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)
+ // 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 every
+ // exec-vs-direct comparison silently flatters direct mode, and
+ // clients registered individually look error-free when they aren't.
+ // Duration is 0: no handler ran (see `trackInnerCall`, same rule).
+ const rejection = new ToolInputValidationError(
+ message,
+ describeValidationError(validation.error, toolArgs, tool.schema)
+ )
+ void trackToolCall(
+ tool.name,
+ 0,
+ true,
+ state,
+ errorAnalyticsProperties(classifyToolError(rejection, tool.name), rejection),
+ intentMeta,
+ this.servedToolDescription(tool.name, state)
+ )
return {
- content: [{ type: 'text', text: formatInputValidationError(tool.name, validation.error) }],
+ content: [{ type: 'text', text: message }],
isError: true,
}
}
@@ -335,6 +362,12 @@ export class ToolExecutor {
// attributed to `exec`.
const execToolName = (): string => execMetrics.innerToolName ?? 'exec'
+ // Which verb ran and which tool it targeted. Stamped on every exec event —
+ // success and failure alike — so the discovery verbs stop collapsing into
+ // one opaque `exec` bucket and an `info <tool>` can be linked to the
+ // `call <tool>` that follows it.
+ const execShape = execCommandAnalyticsProperties(validation.data, state)
+
try {
const handlerResult = await resolved.handler(state.context, validation.data)
const duration = Date.now() - startMs
@@ -356,6 +389,7 @@ export class ToolExecutor {
false,
state,
{
+ ...execShape,
input_tokens: estimateTokens(validation.data),
output_tokens: estimateResponseTokens(response),
},
@@ -378,7 +412,7 @@ export class ToolExecutor {
Date.now() - startMs,
true,
state,
- errorAnalyticsProperties(classification, error),
+ { ...execShape, ...errorAnalyticsProperties(classification, error) },
intentMeta,
this.servedToolDescription(metricTool, state)
)
@@ -586,8 +620,13 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassification
if (apiError instanceof PostHogValidationError) {
const errorCode = apiError.code ? sanitizeErrorToken(apiError.code) : undefined
const errorField = apiError.attr ? normalizeErrorField(apiError.attr) : undefined
+ // Same descriptor property and format as a local schema rejection, so one
+ // query covers both layers. There is no `validationInputKeys` counterpart:
+ // the request body reached the API, so the keys it carried aren't ours to
+ // reconstruct here.
return {
errorType: 'validation',
+ validationFields: describeApiValidationError(apiError.attr, apiError.code),
...(errorCode ? { errorCode } : {}),
...(errorField ? { errorField } : {}),
}
@@ -721,3 +760,31 @@ function errorAnalyticsProperties(classification: ToolErrorClassification, error
...(message !== undefined ? { $mcp_error_message: message } : {}),
}
}
+
+/**
+ * Properties describing the exec command itself: `$mcp_exec_verb` (which
+ * dispatcher verb ran) and `$mcp_exec_target_tool` (the tool `info`/`schema`/
+ * `call` named).
+ *
+ * `$mcp_tool_name` already carries the inner tool for a successful `call`, but
+ * it reads `exec` for every other verb and for a `call` that never resolved — so
+ * schema discovery, tool search, and a mistyped verb are indistinguishable, and
+ * an `unknown_tool` rejection records nothing about what was attempted. Both
+ * values are value-free by construction (see `describeExecCommand`): the verb comes
+ * from the closed grammar and the target from this connection's own catalog, so a
+ * token outside either is recorded as unrecognized rather than echoed.
+ */
+function execCommandAnalyticsProperties(execArgs: unknown, state: ResolvedState): Record<string, unknown> {
+ const command = (execArgs as { command?: unknown } | undefined)?.command
+ if (typeof command !== 'string') {
+ return {}
+ }
+ const { verb, targetTool } = describeExecCommand(
+ command,
+ (name) => state.allTools.some((t) => t.name === name) || state.scopeGatedTools.some((t) => t.name === name)
+ )
+ return {
+ ...(verb !== undefined ? { $mcp_exec_verb: verb } : {}),
+ ...(targetTool !== undefined ? { $mcp_exec_target_tool: targetTool } : {}),
+ }
+}
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 27f2f97a4fed..0bf079cdacdf 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -126,6 +126,83 @@ export function parseExecCallInnerToolName(command: string): string | undefined
return innerName || undefined
}
+/** Verbs the dispatcher grammar accepts. A verb outside this set is what the
+ * `unknown_command` rejection fires on, and is recorded as unrecognized. */
+const KNOWN_EXEC_VERBS = new Set(['learn', 'tools', 'search', 'info', 'schema', 'call'])
+
+/** Verbs whose first positional argument names a tool. */
+const TOOL_TARGETING_VERBS = new Set(['info', 'schema', 'call'])
+
+/**
+ * Recorded in place of a verb or tool name the server doesn't recognize. A token
+ * the grammar rejected is caller text, and bounding its charset does not make it
+ * value-free — an identifier-shaped secret survives sanitization intact. This file
+ * already withholds `ExecCommandError`'s message from analytics for exactly this
+ * reason (it echoes the caller's tool name); the rejection reason on the event says
+ * which of the two failed, so the sentinel loses only the misspelling itself.
+ */
+const UNRECOGNIZED_EXEC_TOKEN = 'unrecognized'
+
+export interface ExecCommandShape {
+ /** The dispatcher verb, or `unrecognized` when it isn't one we accept. */
+ verb?: string
+ /** The tool `info`/`schema`/`call` targeted, or `unrecognized` when the name
+ * resolves to nothing in our catalog. */
+ targetTool?: string
+}
+
+/**
+ * Describes an exec command for analytics: which verb ran, and which tool it
+ * targeted. Both are value-free by construction — a verb from the closed grammar
+ * and a tool name from our own catalog, never the caller's token (see
+ * `describeValidationError` for the same constraint applied to schema rejections).
+ *
+ * Without this, every non-`call` verb lands in one undifferentiated `exec`
+ * bucket: schema discovery is indistinguishable from tool search, and an
+ * `unknown_command` rejection records no verb to diagnose. `targetTool` is what
+ * links an `info <tool>` to the `call <tool>` that follows it.
+ *
+ * `isKnownToolName` decides whether a target resolves against the catalog this
+ * connection can see; anything it rejects is recorded as
+ * `UNRECOGNIZED_EXEC_TOKEN`.
+ */
+export function describeExecCommand(command: string, isKnownToolName: (name: string) => boolean): ExecCommandShape {
+ const { verb: rawVerb, rest } = parseCommand(command)
+ if (!rawVerb) {
+ return {}
+ }
+ const verb = KNOWN_EXEC_VERBS.has(rawVerb) ? rawVerb : UNRECOGNIZED_EXEC_TOKEN
+ if (!TOOL_TARGETING_VERBS.has(rawVerb) || !rest) {
+ return { verb }
+ }
+ // The target must be parsed exactly as the dispatcher looks it up, or a
+ // rejected command gets attributed to a valid tool. `call` strips its flags
+ // then takes the first token; `schema` takes the first token. `info` is the
+ // exception: it hands the entire remaining argument to `findTool` as an exact
+ // name (after an optional `--json`), so `info execute-sql extra` looks up
+ // "execute-sql extra", resolves to nothing, and records `unrecognized` — not
+ // the `execute-sql` its first token would suggest.
+ let target: string
+ if (rawVerb === 'call') {
+ target = parseCommand(parseCallFlags(rest).rest).verb
+ } else if (rawVerb === 'info') {
+ target = rest.replace(/^--json(\s+|$)/, '').trim()
+ } else {
+ target = parseCommand(rest).verb
+ }
+ if (!target) {
+ return { verb }
+ }
+ return { verb, targetTool: isRecordableToolName(target, isKnownToolName) ? target : UNRECOGNIZED_EXEC_TOKEN }
+}
+
+/** Tool names we own, and can therefore record: the ones this connection can see,
+ * plus the removed ones kept only to redirect a call. A name outside both is the
+ * caller's own text. */
+function isRecordableToolName(name: string, isKnownToolName: (name: string) => boolean): boolean {
+ return isKnownToolName(name) || Object.prototype.hasOwnProperty.call(DEPRECATED_TOOL_REDIRECTS, name)
+}
+
// Resolves the inner tool an `exec` call targets: given a request, return the
// inner tool's { name, description } when the agent invoked it via
// `call <tool> ...`, or undefined otherwise. Lives here (alongside
@@ -223,31 +300,170 @@ export function formatInputValidationError(toolName: string, error: z.ZodError):
const MAX_VALIDATION_DESCRIPTORS = 20
const MAX_KEY_LENGTH = 64
+/**
+ * Issue codes where the type of the rejected value is the diagnostic signal: a
+ * parameter that is absent and one that is present under the right name but the
+ * wrong shape are different bugs with different fixes, and both otherwise read as
+ * a bare `invalid_type`.
+ */
+const TYPE_REVEALING_CODES = new Set(['invalid_type', 'invalid_union'])
+
+/**
+ * Recorded in place of a path segment the schema never declared. An open record
+ * (`generate-app-url`'s `params: z.record(z.string(), z.string())`) puts the
+ * caller's own key in the issue path, so recording the path verbatim would carry
+ * caller text into analytics. Which field held the bad value is preserved; only
+ * the key inside it is masked.
+ */
+const UNDECLARED_PATH_SEGMENT = '*'
+
+/** Defensive bound on the JSON Schema walk behind `declaredPropertyNames`. */
+const MAX_SCHEMA_WALK_DEPTH = 20
+
+/**
+ * Joins an issue path into a descriptor, collapsing array indices to `N` and
+ * masking any segment `declaredNames` doesn't cover.
+ *
+ * `series.0.event` and `series.1.event` describe one defect. Without the collapse
+ * a malformed 50-element array yields 50 distinct descriptors that fill
+ * `MAX_VALIDATION_DESCRIPTORS` with restatements of itself — and because the cap
+ * truncates in schema-traversal order, it evicts genuinely different fields that
+ * failed later. The dedupe is what keeps the cap meaningful.
+ *
+ * `declaredNames` is omitted only where every segment is ours by construction
+ * (`describeApiValidationError`, whose `attr` is a serializer field name).
+ */
+function normalizeDescriptorPath(segments: readonly PropertyKey[], declaredNames?: ReadonlySet<string>): string {
+ if (!segments.length) {
+ return '(root)'
+ }
+ return segments
+ .map((segment) => {
+ if (typeof segment === 'number' || /^\d+$/.test(String(segment))) {
+ return 'N'
+ }
+ const name = String(segment)
+ if (declaredNames && !declaredNames.has(name)) {
+ return UNDECLARED_PATH_SEGMENT
+ }
+ return name
+ })
+ .join('.')
+ .slice(0, MAX_KEY_LENGTH)
+}
+
+const declaredPropertyNamesCache = new WeakMap<object, ReadonlySet<string>>()
+
+/**
+ * Every property name a tool's schema declares, at any depth. A path segment
+ * outside this set came from an open record or a catchall, which means the caller
+ * chose it.
+ *
+ * Read off the JSON Schema exec already generates for `info`, so this depends on
+ * no Zod internals. A schema that can't be converted yields an empty set: more
+ * masking than strictly needed, never less.
+ */
+function declaredPropertyNames(schema: z.ZodType): ReadonlySet<string> {
+ const cached = declaredPropertyNamesCache.get(schema)
+ if (cached) {
+ return cached
+ }
+ const names = new Set<string>()
+ try {
+ collectDeclaredPropertyNames(z.toJSONSchema(schema, { io: 'input' }), names)
+ } catch {
+ // Telemetry must never break a tool call; an empty set only costs detail.
+ }
+ declaredPropertyNamesCache.set(schema, names)
+ return names
+}
+
+function collectDeclaredPropertyNames(node: unknown, into: Set<string>, depth = 0): void {
+ if (depth > MAX_SCHEMA_WALK_DEPTH || typeof node !== 'object' || node === null) {
+ return
+ }
+ if (Array.isArray(node)) {
+ for (const child of node) {
+ collectDeclaredPropertyNames(child, into, depth + 1)
+ }
+ return
+ }
+ for (const [key, value] of Object.entries(node)) {
+ // Only a `properties` map is keyed by field names. `patternProperties`,
+ // `additionalProperties` and `$defs` are keyed by pattern or definition name,
+ // so descend into their values without recording the keys.
+ if (key === 'properties' && typeof value === 'object' && value !== null && !Array.isArray(value)) {
+ for (const [name, child] of Object.entries(value)) {
+ into.add(name)
+ collectDeclaredPropertyNames(child, into, depth + 1)
+ }
+ continue
+ }
+ collectDeclaredPropertyNames(value, into, depth + 1)
+ }
+}
+
+/** The JSON-shaped type of a rejected value — never the value, never its length. */
+function describeReceivedType(value: unknown): string {
+ if (value === null) {
+ return 'null'
+ }
+ if (Array.isArray(value)) {
+ return 'array'
+ }
+ return typeof value
+}
+
+/**
+ * Builds a descriptor in the same `path:code[:received]` shape
+ * `describeValidationError` emits, for a rejection that came from the PostHog API
+ * rather than the local schema — so both kinds of validation failure answer one
+ * query instead of requiring `$mcp_error_message` to be string-parsed.
+ *
+ * `attr` is one of our own serializer field names and `code` a DRF code; neither
+ * carries caller input, unlike the API's free-text `detail`.
+ */
+export function describeApiValidationError(attr: string | undefined, code: string | undefined): string[] {
+ const path = normalizeDescriptorPath((attr ?? '').split('.').filter(Boolean))
+ return [`${path}:${code ?? 'unknown'}`]
+}
+
/**
* Derives a value-free descriptor of a validation failure for telemetry, so a
* contract regression (agents sending a field name the schema doesn't accept) is
* diagnosable from the `$mcp_tool_call` event alone — without ever recording the
* request payload.
*
- * `fields` are the offending top-level field + issue code (e.g. `orgId:invalid_type`);
- * for a union rejection the path is empty and it reads `(root):invalid_union`, which
- * is why `inputKeys` — the top-level keys the caller actually sent — carries the real
- * signal there (it surfaces the unaccepted alias, e.g. `organizationId`).
+ * `fields` are the offending field path + issue code, plus the received type where
+ * that distinguishes the bug (e.g. `id:invalid_type:undefined` for an omitted
+ * parameter vs `query:invalid_union:string` for an envelope the agent flattened).
+ * `inputKeys` — the top-level keys the caller actually sent — is what surfaces an
+ * unaccepted alias (e.g. `organizationId` where the schema wants `orgId`).
*
- * Records only structural information (field names, issue codes). It never touches
- * input VALUES: the ZodError embeds raw values in `issue.input` and `.message` (see
- * `formatInputValidationError`), so we read `issue.path[0]`/`issue.code` and the
- * input's own key names only.
+ * Records only structural information: field names, issue codes, and the TYPE of a
+ * rejected value. It never records input VALUES — the ZodError embeds those in
+ * `issue.input` and in `.message` (see `formatInputValidationError`), so this reads
+ * `typeof issue.input` and never the value behind it. `schema` is what keeps that
+ * true of the field paths as well: a key the schema never declared belongs to the
+ * caller, so it is masked rather than recorded (see `normalizeDescriptorPath`).
*/
export function describeValidationError(
error: z.ZodError,
- input: Record<string, unknown>
+ input: Record<string, unknown>,
+ schema: z.ZodType
): { fields: string[]; inputKeys: string[] } {
+ const declaredNames = declaredPropertyNames(schema)
const fields = [
...new Set(
error.issues.map((issue) => {
- const top = issue.path.length ? String(issue.path[0]) : '(root)'
- return `${top.slice(0, MAX_KEY_LENGTH)}:${issue.code}`
+ const descriptor = `${normalizeDescriptorPath(issue.path, declaredNames)}:${issue.code}`
+ // `input` is only present under `safeParse(..., { reportInput: true })`;
+ // without it there is no type to report, and an absent value and an
+ // unreported one must not both read as `undefined`.
+ if (!TYPE_REVEALING_CODES.has(issue.code) || !('input' in issue)) {
+ return descriptor
+ }
+ return `${descriptor}:${describeReceivedType(issue.input)}`
})
),
].slice(0, MAX_VALIDATION_DESCRIPTORS)
@@ -606,7 +822,10 @@ export function createExecTool(
// classifies it as `validation`, not `internal`. The value-free
// descriptor rides along so the errored `$mcp_tool_call` records
// which field/alias was rejected — without the payload.
- throw new ToolInputValidationError(message, describeValidationError(validation.error, input))
+ throw new ToolInputValidationError(
+ message,
+ describeValidationError(validation.error, input, tool.schema)
+ )
}
input = validation.data as Record<string, unknown>
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
index 8f0b75b583e1..d07144a4f8c4 100644
--- a/services/mcp/tests/hono/tool-executor-intent.test.ts
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -136,11 +136,12 @@ describe('ToolExecutor intent capture', () => {
})
// A native (non-exec) tool call with context: proves the native callTool path
- // strips context and forwards intent. captureToolCall only fires *after*
- // validation passes (the validation-error path returns before tracking), so its
- // being called with the intent proves context was stripped before validation.
- // (projects-get hits the API, which the harness can't fulfill, so we assert on
- // the captured analytics, not the tool's own result.)
+ // strips context and forwards intent. The native path now also tracks schema
+ // rejections, so "captureToolCall fired" alone no longer implies validation
+ // passed — assert the absence of a validation error explicitly, otherwise an
+ // unstripped `context` (rejected as an unrecognized key) would satisfy this
+ // test. (projects-get hits the API, which the harness can't fulfill, so we
+ // assert on the captured analytics, not the tool's own result.)
it('strips context before a native tool validates and still forwards intent', async () => {
const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})
@@ -150,8 +151,10 @@ describe('ToolExecutor intent capture', () => {
)
expect(captureSpy).toHaveBeenCalledTimes(1)
- expect(captureSpy.mock.calls[0]![0].toolName).toBe('projects-get')
- expect(captureSpy.mock.calls[0]![0].intent).toBe('looking up the current user')
+ const arg = captureSpy.mock.calls[0]![0]
+ expect(arg.toolName).toBe('projects-get')
+ expect(arg.intent).toBe('looking up the current user')
+ expect(arg.properties?.$mcp_error_type).not.toBe('validation')
captureSpy.mockRestore()
})
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index d103f0cbff34..feebae86fad6 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -274,6 +274,35 @@ describe('ToolExecutor metrics', () => {
expect(trackToolCallExtras('fail-tool')).toMatchObject({ $mcp_error_message: expected })
})
+ // An API-layer rejection used to carry no structured field, so it was only
+ // reachable by string-parsing $mcp_error_message. It now populates the same
+ // property a local schema rejection does — the API's free-text `detail` still
+ // never reaches analytics.
+ it('stamps $mcp_validation_fields for an API validation error, without the detail body', async () => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue(
+ makeFakeTool('fail-tool', async () => {
+ throw new PostHogValidationError({
+ detail: 'Unable to resolve field: SECRET=sk_live_abc123',
+ attr: 'series.0.event',
+ code: 'invalid_input',
+ extra: undefined,
+ url: 'https://us.posthog.com/api/environments/2/query/',
+ 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',
+ // Array indices collapse here too, matching the schema path.
+ $mcp_validation_fields: ['series.N.event:invalid_input'],
+ })
+ expect(JSON.stringify(extras)).not.toContain('sk_live_abc123')
+ })
+
it('rebuilds PostHogApiError messages from status + path, never the response body or query string', async () => {
vi.spyOn(catalog, 'getToolByName').mockReturnValue(
makeFakeTool('fail-tool', async () => {
@@ -381,6 +410,39 @@ describe('ToolExecutor metrics', () => {
expect(mockToolDurationStartTimer).not.toHaveBeenCalled()
})
+ // The direct path used to return before tracking, so a schema rejection in
+ // 'tools' mode produced no `$mcp_tool_call` at all — leaving every
+ // exec-vs-direct error comparison silently flattering direct mode. Pin both
+ // the event and the value-free diagnostics that make it actionable.
+ it('emits an errored analytics event with the rejected fields on a schema rejection', async () => {
+ vi.spyOn(catalog, 'getToolByName').mockReturnValue({
+ name: 'strict-tool',
+ base: { schema: z.object({ required_field: z.string() }), handler: vi.fn(), _meta: undefined },
+ } as any)
+
+ await executor.handleToolCall(
+ { name: 'strict-tool', arguments: { requiredField: 'sent under the wrong name' } },
+ makeState([{ name: 'strict-tool' }])
+ )
+
+ // Exactly one event: the rejection returns before the handler runs, so
+ // neither the success nor the catch tracker can also fire. A second emit
+ // here would double-count the call in every error-rate metric.
+ const calls = mockTrackToolCall.mock.calls.filter((c) => c[0] === 'strict-tool')
+ expect(calls).toHaveLength(1)
+ const call = calls[0]!
+ expect(call[2]).toBe(true)
+ // No handler ran, so the call carries no duration (mirrors the exec path).
+ expect(call[1]).toBe(0)
+ expect(trackToolCallExtras('strict-tool')).toMatchObject({
+ $mcp_error_type: 'validation',
+ // `:undefined` is the received type — the param was absent, not
+ // mistyped, which is what separates an alias slip from a coercion bug.
+ $mcp_validation_fields: ['required_field:invalid_type:undefined'],
+ $mcp_validation_input_keys: ['requiredField'],
+ })
+ })
+
it('records error for unknown tool', async () => {
await executor.handleToolCall({ name: 'nonexistent', arguments: {} }, makeState([]))
@@ -413,6 +475,26 @@ describe('ToolExecutor metrics', () => {
expect(callsFor(mockToolDurationStartTimer, 'exec')).toHaveLength(0)
})
+ // Without the verb, every non-`call` command lands in one undifferentiated
+ // `exec` bucket — schema discovery, tool search and a mistyped verb become
+ // indistinguishable, and `unknown_command` records nothing to diagnose.
+ // `$mcp_exec_target_tool` is what links an `info <tool>` to the `call <tool>`
+ // that follows it, and is the only trace of an attempted unknown tool.
+ it.each([
+ ['tools', { $mcp_exec_verb: 'tools' }],
+ ['info docs-search', { $mcp_exec_verb: 'info', $mcp_exec_target_tool: 'docs-search' }],
+ ['schema docs-search query', { $mcp_exec_verb: 'schema', $mcp_exec_target_tool: 'docs-search' }],
+ // A verb or tool name we don't recognize is caller text, so the event
+ // records that it was unrecognized rather than the token itself.
+ ['frobnicate whatever', { $mcp_exec_verb: 'unrecognized' }],
+ ['call not-a-real-tool {}', { $mcp_exec_verb: 'call', $mcp_exec_target_tool: 'unrecognized' }],
+ ])('stamps the exec verb and target for "%s"', async (command, expected) => {
+ await executor.handleToolCall({ name: 'exec', arguments: { command } }, execState())
+
+ const call = mockTrackToolCall.mock.calls.at(-1)
+ expect(call?.[4]).toMatchObject(expected)
+ })
+
it('emits inner tool name for counter and duration on inner tool call', async () => {
await executor.handleToolCall(
{ name: 'exec', arguments: { command: 'call docs-search {"query": "test"}' } },
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index 0ca510132162..695e08ef6663 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -12,6 +12,8 @@ import { SessionManager } from '@/lib/SessionManager'
import { getToolsFromContext } from '@/tools'
import {
createExecTool,
+ describeApiValidationError,
+ describeExecCommand,
describeValidationError,
type ExecInnerCallProperties,
type ExecToolOptions,
@@ -1256,6 +1258,56 @@ describe('exec tool', () => {
})
})
+ describe('describeExecCommand', () => {
+ const isKnownToolName = (name: string): boolean => ['execute-sql', 'query-trends', 'my-tool'].includes(name)
+
+ // The verb/target pair is what separates schema discovery from tool search
+ // from a mistyped verb in analytics. Flag handling differs per verb, so a
+ // parser regression silently collapses the funnel back into one bucket.
+ it.each([
+ ['tools', 'tools', undefined],
+ ['search query-', 'search', undefined],
+ ['info execute-sql', 'info', 'execute-sql'],
+ ['info --json execute-sql', 'info', 'execute-sql'],
+ ['schema query-trends series', 'schema', 'query-trends'],
+ // `info` matches the whole remainder as an exact tool name, so a
+ // trailing token makes the lookup fail — telemetry must mirror the
+ // dispatcher's rejection, not credit the valid first token.
+ ['info execute-sql extra', 'info', 'unrecognized'],
+ ['call my-tool {"a":1}', 'call', 'my-tool'],
+ ['call --json --confirm my-tool {}', 'call', 'my-tool'],
+ [' info execute-sql ', 'info', 'execute-sql'],
+ // A removed tool is still one of our own names, so the redirect it
+ // triggers stays diagnosable.
+ ['call query-run {}', 'call', 'query-run'],
+ // Verb present, target absent: nothing to record for the tool, but the
+ // verb still is.
+ ['info', 'info', undefined],
+ ['call', 'call', undefined],
+ ['', undefined, undefined],
+ ])('describes "%s" as verb=%s target=%s', (command, expectedVerb, expectedTarget) => {
+ expect(describeExecCommand(command, isKnownToolName)).toEqual({
+ verb: expectedVerb,
+ ...(expectedTarget !== undefined ? { targetTool: expectedTarget } : {}),
+ })
+ })
+
+ // Both fields reach analytics, and a token the grammar rejected is caller
+ // text — sanitizing its charset would leave an identifier-shaped secret
+ // intact, so it is replaced outright. Same value-free constraint
+ // `describeValidationError` holds for schema rejections.
+ it.each([
+ ['an unknown verb', 'sk-live-abc123 {"a":1}', { verb: 'unrecognized' }],
+ ['an unresolvable call target', 'call sk-live-abc123 {}', { verb: 'call', targetTool: 'unrecognized' }],
+ ['an unresolvable info target', 'info sk-live-abc123', { verb: 'info', targetTool: 'unrecognized' }],
+ ])('records a sentinel instead of %s', (_label, command, expected) => {
+ const shape = describeExecCommand(command, isKnownToolName)
+
+ expect(shape).toEqual(expected)
+ expect(JSON.stringify(shape)).not.toContain('sk-live-abc123')
+ })
+ })
+
describe('exec tool description', () => {
function createExecContext(): Context {
return {
@@ -1362,7 +1414,7 @@ describe('exec tool', () => {
const result = schema.safeParse(input, { reportInput: true })
expect(result.success).toBe(false)
- const detail = describeValidationError(result.error!, input)
+ const detail = describeValidationError(result.error!, input, schema)
expect(detail.inputKeys).toEqual(['organizationId'])
// Never record input values — the raw uuid must not appear anywhere.
@@ -1375,11 +1427,112 @@ describe('exec tool', () => {
const result = schema.safeParse(input, { reportInput: true })
expect(result.success).toBe(false)
- const detail = describeValidationError(result.error!, input)
+ const detail = describeValidationError(result.error!, input, schema)
- expect(detail.fields).toContain('projectId:invalid_type')
+ expect(detail.fields).toContain('projectId:invalid_type:string')
expect(JSON.stringify(detail)).not.toContain('not-a-number')
})
+
+ // `invalid_type` alone conflates an omitted parameter with one sent under the
+ // right name but the wrong shape — the two dominant rejection classes, and
+ // they need different fixes (aliasing vs coercion/envelope). The received
+ // type is what separates them.
+ it.each([
+ ['omitted entirely', {}, 'id:invalid_type:undefined'],
+ ['sent as the wrong primitive', { id: 42 }, 'id:invalid_type:number'],
+ ['sent as an envelope object', { id: { value: 'x' } }, 'id:invalid_type:object'],
+ ['sent as an array', { id: ['x'] }, 'id:invalid_type:array'],
+ ['sent as null', { id: null }, 'id:invalid_type:null'],
+ ])('distinguishes a required param %s', (_label, input, expected) => {
+ const schema = z.object({ id: z.string() })
+ const result = schema.safeParse(input, { reportInput: true })
+ expect(result.success).toBe(false)
+
+ expect(describeValidationError(result.error!, input as Record<string, unknown>, schema).fields).toEqual([
+ expected,
+ ])
+ })
+
+ // The received type is only meaningful for the type-shaped codes; appending it
+ // to every code would bloat the descriptor and say nothing (`too_big:string`).
+ it('omits the received type for a code the type does not explain', () => {
+ const schema = z.object({ description: z.string().max(3) })
+ const input = { description: 'far too long' }
+ const result = schema.safeParse(input, { reportInput: true })
+ expect(result.success).toBe(false)
+
+ expect(describeValidationError(result.error!, input, schema).fields).toEqual(['description:too_big'])
+ })
+
+ // A malformed array produces one issue per element. Collapsing indices keeps
+ // them a single descriptor — otherwise they fill the 20-descriptor cap with
+ // restatements of one defect and evict the genuinely different field that
+ // failed after them, which is the information the event exists to carry.
+ it('collapses array indices so one bad array cannot evict other failed fields', () => {
+ const schema = z.object({
+ series: z.array(z.object({ event: z.string() })),
+ dateRange: z.string(),
+ })
+ const input = {
+ series: Array.from({ length: 50 }, () => ({ event: 123 })),
+ dateRange: 456,
+ }
+ const result = schema.safeParse(input, { reportInput: true })
+ expect(result.success).toBe(false)
+
+ const { fields } = describeValidationError(result.error!, input as Record<string, unknown>, schema)
+
+ expect(fields).toEqual(['series.N.event:invalid_type:number', 'dateRange:invalid_type:number'])
+ })
+
+ // The full issue path is what distinguishes a flattened envelope from a bad
+ // discriminator, but under an open record (`generate-app-url`'s `params`) the
+ // path's own segments are the caller's keys. Masking them keeps the field that
+ // held the bad value visible without recording anything the caller chose.
+ it('masks a path segment the schema never declared', () => {
+ const schema = z.object({
+ url: z.string(),
+ params: z.record(z.string(), z.string()),
+ })
+ const input = { url: '/project/2', params: { 'sk-live-abc123': 42 } }
+ const result = schema.safeParse(input, { reportInput: true })
+ expect(result.success).toBe(false)
+
+ const detail = describeValidationError(result.error!, input as Record<string, unknown>, schema)
+
+ expect(detail.fields).toEqual(['params.*:invalid_type:number'])
+ expect(JSON.stringify(detail)).not.toContain('sk-live-abc123')
+ })
+
+ // Nested schema fields are ours, so they must survive the mask — otherwise
+ // every descriptor collapses to `*` and the reason the PR widened the path
+ // (telling `query:invalid_union` apart from `query.kind:invalid_type`) is lost.
+ it('keeps a declared nested path intact', () => {
+ const schema = z.object({ query: z.object({ kind: z.literal('TrendsQuery') }) })
+ const input = { query: { kind: 'trends' } }
+ const result = schema.safeParse(input, { reportInput: true })
+ expect(result.success).toBe(false)
+
+ expect(describeValidationError(result.error!, input, schema).fields).toEqual(['query.kind:invalid_value'])
+ })
+ })
+
+ describe('describeApiValidationError', () => {
+ // API-layer rejections carried no structured field at all, so they could only
+ // be reached by string-parsing $mcp_error_message. Same format as the schema
+ // path so a single query spans both.
+ it.each([
+ ['name', 'required', 'name:required'],
+ ['series.0.event', 'invalid', 'series.N.event:invalid'],
+ [undefined, 'invalid', '(root):invalid'],
+ ['name', undefined, 'name:unknown'],
+ ])('describes attr=%s code=%s as %s', (attr, code, expected) => {
+ expect(describeApiValidationError(attr, code)).toEqual([expected])
+ })
+
+ it('bounds an over-long attr to the shared key-length cap', () => {
+ expect(describeApiValidationError('a'.repeat(200), 'invalid')[0]).toBe(`${'a'.repeat(64)}:invalid`)
+ })
})
describe('formatInputValidationError', () => {