: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): report ignored input keys and cap tool schema growth (#111786)
Julian Bezf0d58eb81a14
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 30f2c279ad66..aac3619038bb 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -23,6 +23,7 @@ import {} from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { resolveGatewayTools } from '@/lib/gateway-tools'+import { findIgnoredInputKeys, withIgnoredInputKeys } from '@/lib/ignored-input-keys'import { getPostHogClient } from '@/lib/posthog'import { isPrivateScoutTrialTool } from '@/lib/tool-privacy'import {@@ -401,9 +402,11 @@ export class ToolExecutor {? await state.reqCtx.safelyGetAnalyticsContext(state.context): undefined- const handlerResult = markNoncanonicalMetricRun(- tool.name,- await tool.handler(state.context, validation.data)+ // Computed before the handler runs, so a failure here cannot follow a write that succeeded.+ const ignoredKeys = findIgnoredInputKeys(toolArgs, validation.data, tool.schema)+ const handlerResult = withIgnoredInputKeys(+ markNoncanonicalMetricRun(tool.name, await tool.handler(state.context, validation.data)),+ ignoredKeys)if (isContextSwitch) {diff --git a/services/mcp/src/lib/constants.ts b/services/mcp/src/lib/constants.tsindex 89e50dbcd97a..a935f491a254 100644--- a/services/mcp/src/lib/constants.ts+++ b/services/mcp/src/lib/constants.ts@@ -42,3 +42,6 @@ export const MCP_CLAUDE_TOOL_DOMAINS_CHAR_BUDGET = 1536// Gates reaching third-party MCP servers connected through the MCP gateway. Same flag as// the gateway's own UI in the main app, so a team gets the tools when it gets the gateway.export const MCP_GATEWAY_FLAG = 'mcp-gateway'++// claude.ai silently drops a tool whose serialized `inputSchema` reaches this many characters.+export const CLAUDE_REGISTRY_INPUT_SCHEMA_CHAR_LIMIT = 16_384diff --git a/services/mcp/src/lib/ignored-input-keys.ts b/services/mcp/src/lib/ignored-input-keys.tsnew file mode 100644index 000000000000..d9d556caed6a--- /dev/null+++ b/services/mcp/src/lib/ignored-input-keys.ts@@ -0,0 +1,119 @@+import type { z } from 'zod'++import { isToolCallPayload } from '@/lib/build-tool-result'+import { readParamAliases, reshapesInputBeyondAliases } from '@/tools/cast-helpers'+import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, POSTHOG_INFORMATIONAL_RESPONSE_KEY } from '@/tools/types'++const MAX_IGNORED_KEYS = 20+const MAX_KEY_LENGTH = 100+// Bound the walk so a deeply nested or very wide input stays cheap to diff.+const MAX_DEPTH = 12+const MAX_COLLECTED_KEYS = 100+const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/g++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value)+}++function collectIgnoredKeys(+ sent: unknown,+ kept: unknown,+ path: string,+ topLevelAliases: ReadonlySet<string>,+ into: string[],+ depth = 0+): void {+ if (depth > MAX_DEPTH || into.length >= MAX_COLLECTED_KEYS) {+ return+ }+ if (Array.isArray(sent) && Array.isArray(kept)) {+ sent.forEach((item, index) => {+ collectIgnoredKeys(+ item,+ kept[index],+ path ? `${path}.${index}` : String(index),+ topLevelAliases,+ into,+ depth + 1+ )+ })+ return+ }+ if (!isPlainObject(sent) || !isPlainObject(kept)) {+ return+ }+ for (const [key, value] of Object.entries(sent)) {+ if (value === undefined) {+ continue+ }+ const isTopLevel = path === ''+ const keyPath = isTopLevel ? key : `${path}.${key}`+ if (!Object.prototype.hasOwnProperty.call(kept, key)) {+ // The schema folds an alias into its canonical key, so it is not ignored.+ if (!(isTopLevel && topLevelAliases.has(key)) && into.length < MAX_COLLECTED_KEYS) {+ into.push(keyPath)+ }+ continue+ }+ collectIgnoredKeys(value, kept[key], keyPath, topLevelAliases, into, depth + 1)+ }+}++/**+ * Dotted paths of the sent keys that the validated arguments no longer contain.+ * Zod strips unknown keys without an error, so a misnamed field would otherwise look like a successful call.+ * Transforms that rename keys below the root are not detected.+ */+export function findIgnoredInputKeys(sent: unknown, parsed: unknown, schema: z.ZodType): string[] {+ if (reshapesInputBeyondAliases(schema)) {+ return []+ }+ const aliases = new Set(Object.values(readParamAliases(schema) ?? {}).flat())+ const ignored: string[] = []+ collectIgnoredKeys(sent, parsed, '', aliases, ignored)+ return ignored+}++function ignoredKeysNotice(ignoredKeys: string[], omitted: number): string {+ const more = omitted > 0 ? ` (and ${omitted} more)` : ''+ // JSON-encode each key so a caller-chosen name stays inside quotes and cannot read as an instruction.+ return `Ignored input keys: ${ignoredKeys.map((key) => JSON.stringify(key)).join(', ')}${more}. These keys are not part of the tool's input schema, so the tool did not use them.`+}++// The notice also goes into the formatted text override, because the agent sees that text instead of the object.+export function withIgnoredInputKeys(result: unknown, ignoredKeys: string[]): unknown {+ if (ignoredKeys.length === 0 || result === null || result === undefined) {+ return result+ }+ // Key names come from the caller. Mask control characters so they cannot fake lines in a server message.+ const keys = ignoredKeys+ .slice(0, MAX_IGNORED_KEYS)+ .map((key) => key.slice(0, MAX_KEY_LENGTH).replace(CONTROL_CHARACTERS, '?'))+ const omitted = ignoredKeys.length - keys.length+ const notice = ignoredKeysNotice(keys, omitted)++ if (typeof result === 'string') {+ return `${result}\n\n${notice}`+ }+ if (typeof result !== 'object' || isToolCallPayload(result)) {+ return result+ }++ // The marker properties live on the original value, not on the array wrapper.+ const markers = result as Record<string, unknown>+ const source = Array.isArray(result) ? { results: result } : markers+ const wrapped: Record<string, unknown> = { ...source, _ignoredKeys: keys, _ignoredKeysNote: notice }++ // Non-enumerable keys do not survive the spread above.+ const formatted = markers[POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]+ if (typeof formatted === 'string') {+ Object.defineProperty(wrapped, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, {+ value: `${formatted}\n\n${notice}`,+ enumerable: false,+ })+ }+ if (markers[POSTHOG_INFORMATIONAL_RESPONSE_KEY] === true) {+ Object.defineProperty(wrapped, POSTHOG_INFORMATIONAL_RESPONSE_KEY, { value: true, enumerable: false })+ }+ return wrapped+}diff --git a/services/mcp/src/tools/cast-helpers.ts b/services/mcp/src/tools/cast-helpers.tsindex 5f47a55b95dc..f6ff7a27206b 100644--- a/services/mcp/src/tools/cast-helpers.ts+++ b/services/mcp/src/tools/cast-helpers.ts@@ -130,3 +130,23 @@ export function readParamAliases(schema: z.ZodType): Record<string, readonly str}return merged}++// A schema that transforms its input (other than alias folding) consumes keys on purpose,+// so comparing sent keys to the parsed result would report them as ignored.+export function reshapesInputBeyondAliases(schema: z.ZodType): boolean {+ let current: unknown = schema+ for (let depth = 0; depth < MAX_PREPROCESS_DEPTH && current instanceof z.ZodPipe; depth++) {+ const input = current.in as { def?: { transform?: unknown } }+ if (current.in instanceof z.ZodTransform) {+ const transform = input.def?.transform+ if (typeof transform !== 'function' || !ALIAS_MAPS.has(transform as (input: unknown) => unknown)) {+ return true+ }+ }+ if (current.out instanceof z.ZodTransform) {+ return true+ }+ current = current.out+ }+ return current instanceof z.ZodUnion+}diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 1ff45315e2e0..5bdd274f2eb4 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -16,6 +16,7 @@ import {} from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { GATEWAY_TOOL_SEPARATOR, isGatewayToolName } from '@/lib/gateway-tools'+import { findIgnoredInputKeys, withIgnoredInputKeys } from '@/lib/ignored-input-keys'import { formatResponse } from '@/lib/response'import { API_KEY_CACHE_TTL_MS } from '@/lib/StateManager'import { APP_DATA_META_KEY } from '@/ui-apps/types'@@ -2006,12 +2007,16 @@ export function createExecTool(describeValidationError(validation.error, toolSchema))}+ const ignoredKeys = findIgnoredInputKeys(input, validation.data, toolSchema)input = validation.data as Record<string, unknown>const startedAt = Date.now()let result: unknowntry {- result = markNoncanonicalMetricRun(tool.name, await tool.handler(context, input))+ result = withIgnoredInputKeys(+ markNoncanonicalMetricRun(tool.name, await tool.handler(context, input)),+ ignoredKeys+ )} catch (err) {// PostHogValidationError is the API's 400 validation_error body.const apiError = findRecoverableApiError(err)diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex d7b2b6f874e7..ee0617941d8e 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -832,4 +832,37 @@ describe('ToolExecutor', () => {expect(result.content[0].text.includes('NONCANONICAL')).toBe(marked)})})++ describe('ignored input keys in tools mode', () => {+ let getToolByNameSpy: MockInstance | undefined++ afterEach(() => {+ getToolByNameSpy?.mockRestore()+ getToolByNameSpy = undefined+ })++ it.each([+ { label: 'an unknown top-level key', args: { name: 'a', title: 'b' }, reported: true },+ { label: 'an unknown nested key', args: { name: 'a', query: { kind: 'x', extra: 1 } }, reported: true },+ { label: 'only declared keys', args: { name: 'a', query: { kind: 'x' } }, reported: false },+ ])('$label: reported is $reported', async ({ args, reported }) => {+ getToolByNameSpy = vi.spyOn(catalog, 'getToolByName').mockReturnValue({+ build() {+ return this.base+ },+ base: {+ schema: z.object({ name: z.string(), query: z.object({ kind: z.string() }).optional() }),+ handler: async () => ({ ok: true }),+ },+ } as any)++ const result = (await executor.handleToolCall(+ { name: 'mock-tool', arguments: args },+ makeToolExecutorState([{ name: 'mock-tool' }], { useSingleExec: false })+ )) as any++ expect(result.isError).toBeFalsy()+ expect(result.content[0].text.includes('Ignored input keys')).toBe(reported)+ })+ })})diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 1371484e9755..361fd5761388 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -10,6 +10,7 @@ import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructionimport { InstructionsFormatter } from '@/lib/instructions-formatter'import { formatResponse } from '@/lib/response'import { SessionManager } from '@/lib/SessionManager'+import { OrganizationSetActiveSchema, ReadDataSchemaSchema } from '@/schema/tool-inputs'import { getToolsFromContext } from '@/tools'import { normalizeParamAliases } from '@/tools/cast-helpers'import {@@ -1149,6 +1150,95 @@ describe('exec tool', () => {})})+ describe('ignored input keys', () => {+ const ignoredKeysTool = makeMockTool({+ schema: z.preprocess(+ normalizeParamAliases({ id: ['insightId'] }),+ z.object({+ id: z.string().optional(),+ name: z.string().optional(),+ query: z.object({ kind: z.string() }).optional(),+ series: z.array(z.object({ event: z.string() })).optional(),+ })+ ) as unknown as ZodObjectAny,+ handler: async () => ({ ok: true }),+ })++ it.each([+ ['an unknown top-level key', '{"title":"x"}', ['title']],+ ['an unknown nested key', '{"query":{"kind":"a","serie":1}}', ['query.serie']],+ [+ 'an unknown key inside an array item',+ '{"series":[{"event":"a"},{"event":"b","extra":1}]}',+ ['series.1.extra'],+ ],+ ['several unknown keys', '{"title":"x","name":"y","other":1}', ['title', 'other']],+ ['a key name with a newline', '{"a\\nb":1}', ['a?b']],+ ['an undeclared key named like an inherited property', '{"constructor":"x"}', ['constructor']],+ ['a declared alias that the schema folds', '{"insightId":"abc"}', undefined],+ ['only declared keys', '{"id":"abc","name":"y"}', undefined],+ ])('reports %s', async (_label, input, expected) => {+ const exec = createExec([ignoredKeysTool])+ const result = (await exec.handler(mockContext, {+ command: `call --json mock-tool ${input}`,+ })) as string+ const parsed = JSON.parse(result)+ expect(parsed._ignoredKeys).toEqual(expected)+ expect(parsed._ignoredKeysNote === undefined).toBe(expected === undefined)+ })++ it.each([+ ['read-data-schema folding its own aliases', ReadDataSchemaSchema, '{"event":"$pageview"}'],+ ['a union schema that normalizes with a transform', OrganizationSetActiveSchema, '{"id":"abc"}'],+ [+ 'a root transform that renames a key',+ z.object({ a: z.string() }).transform((v) => ({ b: v.a })),+ '{"a":"x"}',+ ],+ ])('reports nothing for %s', async (_label, schema, input) => {+ const exec = createExec([+ makeMockTool({ schema: schema as unknown as ZodObjectAny, handler: async () => ({ ok: true }) }),+ ])+ const result = (await exec.handler(mockContext, {+ command: `call --json mock-tool ${input}`,+ })) as string+ expect(JSON.parse(result)).toEqual({ ok: true })+ })++ it('appends the notice to the formatted text the agent reads', async () => {+ const tool = makeMockTool({+ schema: z.object({ name: z.string().optional() }),+ handler: async () => ({+ results: [1],+ [POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY]: 'table',+ }),+ })+ const exec = createExec([tool])+ const result = (await exec.handler(mockContext, { command: 'call mock-tool {"title":"x"}' })) as string+ expect(result).toContain('table')+ expect(result).toContain('Ignored input keys: "title".')+ })++ it('keeps the informational wrapper on an array result and quotes key names in the notice', async () => {+ const tool = makeMockTool({+ schema: z.object({ name: z.string().optional() }),+ handler: async () => withInformationalResponse([{ id: 1 }], 'rows'),+ })+ const exec = createExec([tool])+ const result = (await exec.handler(mockContext, {+ command: 'call mock-tool {"bad\\nkey":"x"}',+ })) as string+ expect(result).toContain('<rows informational="true"')+ expect(result).toContain('Ignored input keys: "bad?key".')+ })++ it('leaves a clean call without a notice in text mode', async () => {+ const exec = createExec([ignoredKeysTool])+ const result = (await exec.handler(mockContext, { command: 'call mock-tool {"name":"x"}' })) as string+ expect(result).not.toContain('Ignored input keys')+ })+ })+describe('output_format suppression', () => {// Mirrors the generated query wrappers / insight-query: `output_format`// toggles whether the handler surfaces the server-side formatted table.diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.tsindex bac16c701663..1ba8f59b9a14 100644--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts@@ -5,10 +5,12 @@ import { format } from 'oxfmt'import { describe, expect, it } from 'vitest'import { z } from 'zod'-import { OAUTH_SCOPES_HIDDEN } from '@/lib/constants'+import { PostHogMCP } from '@posthog/mcp-analytics'++import { CLAUDE_REGISTRY_INPUT_SCHEMA_CHAR_LIMIT, OAUTH_SCOPES_HIDDEN } from '@/lib/constants'import { SessionManager } from '@/lib/SessionManager'import { getToolsFromContext } from '@/tools'-import type { Context } from '@/tools/types'+import type { Context, Tool, ZodObjectAny } from '@/tools/types'function createMockContext(): Context {return {@@ -82,33 +84,36 @@ async function formatSnapshotJson(snapshotPath: string, schema: unknown): Promisreturn result.code}+async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {+ // Enable flag-gated tools we snapshot here: tracing (APM spans), tasks, loops,+ // dashboard-widgets and experiment setup context. Other flag-gated tools (logs-alerts,+ // visual-review, etc.) stay off to keep the surface stable.+ // agent-feedback is always_available and no longer flag-gated, so it appears regardless.+ const featureFlags = {+ tracing: true,+ tasks: true,+ 'tasks-mcp-agent-run-start': true,+ loops: true,+ 'dashboard-widgets': true,+ 'agent-platform': true,+ 'billing-alerts': true,+ 'experiment-setup-context': true,+ 'scout-trials': true,+ 'signals-report-checks-replace': true,+ 'ai-observability-offline-evaluations': true,+ }+ return [...(await getToolsFromContext(createMockContext(), { featureFlags }))].sort((a, b) =>+ a.name.localeCompare(b.name)+ )+}+describe('Tool schema snapshots', () => {const __filename = fileURLToPath(import.meta.url)const __dirname = path.dirname(__filename)- const context = createMockContext()it('snapshots runtime tool schemas', async () => {const shouldUpdateSnapshots = isSnapshotUpdateAll()const root = path.resolve(__dirname, '__snapshots__', 'tool-schemas')- // Enable flag-gated tools we snapshot here: tracing (APM spans), tasks, loops,- // dashboard-widgets and experiment setup context. Other flag-gated tools (logs-alerts,- // visual-review, etc.) stay off to keep the surface stable.- // agent-feedback is always_available and no longer flag-gated, so it appears regardless.- const featureFlags = {- tracing: true,- tasks: true,- 'tasks-mcp-agent-run-start': true,- loops: true,- 'dashboard-widgets': true,- 'agent-platform': true,- 'billing-alerts': true,- 'experiment-setup-context': true,- 'scout-trials': true,- 'signals-report-checks-replace': true,- 'ai-observability-offline-evaluations': true,- }- const tools = [...(await getToolsFromContext(context, { featureFlags }))].sort((a, b) =>- a.name.localeCompare(b.name)- )+ const tools = await loadSnapshotTools()expect(tools.length).toBeGreaterThan(0)@@ -139,4 +144,100 @@ describe('Tool schema snapshots', () => {)}})++ describe('schema budgets', () => {+ // Ratchet: the number of oversized tool schemas may only go down.+ const OVERSIZED_SCHEMA_COUNT = 44+ // Ratchet: the share of nested properties with a description may only go up.+ const NESTED_DESCRIPTION_COVERAGE_FLOOR_PERCENT = 55++ interface DescriptionCoverage {+ described: number+ total: number+ }++ function schemaChildren(schema: Record<string, unknown>): Record<string, unknown>[] {+ const branches = [schema.anyOf, schema.oneOf, schema.allOf].flatMap((group) =>+ Array.isArray(group) ? (group as Record<string, unknown>[]) : []+ )+ const items =+ schema.items && typeof schema.items === 'object' ? [schema.items as Record<string, unknown>] : []+ return [...branches, ...items]+ }++ function countNestedProperties(schema: unknown, depth: number, into: DescriptionCoverage): void {+ if (!schema || typeof schema !== 'object') {+ return+ }+ const node = schema as Record<string, unknown>+ const properties = node.properties as Record<string, Record<string, unknown>> | undefined+ for (const property of Object.values(properties ?? {})) {+ if (depth > 0) {+ into.total += 1+ if (typeof property.description === 'string' && property.description.length > 0) {+ into.described += 1+ }+ }+ countNestedProperties(property, depth + 1, into)+ }+ for (const child of schemaChildren(node)) {+ countNestedProperties(child, depth, into)+ }+ }++ function percent({ described, total }: DescriptionCoverage): number {+ return total === 0 ? 100 : (described / total) * 100+ }++ it('keeps the number of tool schemas over the claude.ai registry limit from growing', async () => {+ const tools = await loadSnapshotTools()+ // The analytics SDK adds a `context` property at registration, so measure the registered shape.+ const posthog = new PostHogMCP('phc_test', { disabled: true })+ const registered = posthog.prepareToolList(+ tools.map((tool) => ({+ name: tool.name,+ description: tool.description,+ inputSchema: z.toJSONSchema(tool.schema, { io: 'input', reused: 'inline' }) as {+ type: 'object'+ [key: string]: unknown+ },+ }))+ )+ const oversized = registered+ .map((entry) => ({ name: entry.name, size: JSON.stringify(entry.inputSchema).length }))+ .filter(({ size }) => size >= CLAUDE_REGISTRY_INPUT_SCHEMA_CHAR_LIMIT)+ .sort((a, b) => b.size - a.size)++ const offenders = oversized.map(({ name, size }) => `- ${name}: ${size} chars`).join('\n')++ expect(+ oversized.length,+ `${oversized.length} tool schemas are at or over ${CLAUDE_REGISTRY_INPUT_SCHEMA_CHAR_LIMIT} chars, ` ++ `above the ratchet of ${OVERSIZED_SCHEMA_COUNT}. Claude web and desktop silently drop such tools in tools mode. ` ++ `Shrink the schema with exclude_params, include_params or param_overrides in the product tools.yaml, ` ++ `or shorten serializer help_text. Largest schemas:\n${offenders}`+ ).toBeLessThanOrEqual(OVERSIZED_SCHEMA_COUNT)+ expect(+ oversized.length,+ `Only ${oversized.length} tool schemas are at or over the limit. Lower OVERSIZED_SCHEMA_COUNT ` ++ `from ${OVERSIZED_SCHEMA_COUNT} to ${oversized.length} so the count only goes down.`+ ).toBe(OVERSIZED_SCHEMA_COUNT)+ })++ it('keeps description coverage of nested tool properties from dropping', async () => {+ const tools = await loadSnapshotTools()+ const nested: DescriptionCoverage = { described: 0, total: 0 }+ for (const tool of tools) {+ const schema = z.toJSONSchema(tool.schema, { io: 'input', reused: 'inline' })+ countNestedProperties(schema, 0, nested)+ }+ expect(+ percent(nested),+ `Only ${percent(nested).toFixed(1)}% of nested tool properties have a description ` ++ `(${nested.described} of ${nested.total}), below the floor of ${NESTED_DESCRIPTION_COVERAGE_FLOOR_PERCENT}%. ` ++ `Add help_text to the serializer fields behind the new properties and regenerate with hogli build:openapi, ` ++ `or drop the properties with exclude_params.`+ ).toBeGreaterThanOrEqual(NESTED_DESCRIPTION_COVERAGE_FLOOR_PERCENT)+ })+ })})