: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): record safe undeclared argument names in $mcp_input_keys (#110274)
Jake Ruth2a32976ebdca
diff --git a/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md b/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.mdindex 02dc40be6e20..ddaf55736743 100644--- a/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md+++ b/.agents/skills/debugging-mcp-analytics/references/event-vocabulary.md@@ -96,7 +96,7 @@ A `$mcp_tool_call` that named a tool and its arguments (a direct-mode call, `renexec `call`) also carries the call's shape, stamped in `tool-executor.ts` from the raw input beforeany alias is folded away, by the `@posthog/mcp` SDK helper `getToolInputProperties`:`$mcp_input_keys` (the top-level argument names the caller sent, never values: declared names and-aliases first, capped at 20, with undeclared names recorded as one `[redacted]` entry; in exec mode parsed from the `call` command's JSON) and+aliases first, then undeclared names that look like parameter names (any other name becomes one `[redacted]` entry), capped at 20; in exec mode parsed from the `call` command's JSON) and`$mcp_input_aliases_used` (`alias:canonical` tokens such as `experimentId:id`, present only whenthe normaliser filled the canonical from that alias). Execdiscovery verbs (`tools`, `search`, `info`, `schema`) carry neither, so rate alias use against thediff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex dc4a666d3fee..87917dbddb31 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -1097,7 +1097,7 @@ function recordedTargetTool(execShape: Record<string, unknown>): string | undefi* live as JSON inside `command`, so they are parsed with the dispatcher's own parser.* Verbs other than `call` carry no arguments and get no keys. The schema is looked up* only among the tools this connection can see. A gated or retired target has no schema,- * so its keys become one `[redacted]` marker and its aliases stay absent.+ * so every key it sent counts as undeclared and its aliases stay absent.*/function execInputShapeAnalyticsProperties(execArgs: unknown,diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex d20c5ce45f28..55d9a37d6462 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -1,7 +1,7 @@import { stringify as stringifyYaml } from 'yaml'import { z } from 'zod'-import { getToolInputProperties } from '@posthog/mcp-analytics'+import { getToolInputProperties, type ShouldRecordInputKeyFn } from '@posthog/mcp-analytics'import { classifyAuthMethod } from '@/lib/auth-method'import { markExecPayload, buildToolResultPayload, estimateResponseTokens } from '@/lib/build-tool-result'@@ -1492,17 +1492,38 @@ export function describeValidationError(error: z.ZodError, schema: z.ZodType): {return { fields }}+const PARAMETER_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/+const DIGIT_RUN_PATTERN = /\d{5}/+const POSTHOG_TOKEN_PREFIX_PATTERN = /^ph[a-z]_/+const CREDENTIAL_SEGMENT_MIN_LENGTH = 16++function hasCredentialSegment(key: string): boolean {+ return key.split('_').some((segment) => segment.length >= CREDENTIAL_SEGMENT_MIN_LENGTH && /\d/.test(segment))+}++/**+ * Undeclared names come from the caller and can hold private data, so only parameter-shaped+ * ones are recorded. The digit checks keep out phone numbers, IDs, and most tokens. The prefix+ * check keeps out PostHog tokens, whose suffix can have no digits.+ */+const shouldRecordInputKey: ShouldRecordInputKeyFn = (key, { declared }) =>+ declared ||+ (PARAMETER_NAME_PATTERN.test(key) &&+ !DIGIT_RUN_PATTERN.test(key) &&+ !hasCredentialSegment(key) &&+ !POSTHOG_TOKEN_PREFIX_PATTERN.test(key))+/*** `$mcp_input_keys` and `$mcp_input_aliases_used` for one call, from the SDK helper, with no* values. The alias map comes from the schema's own `normalizeParamAliases` layers, so* alias names count as declared and each alias the normaliser relied on is recorded as* `alias:canonical`. The SDK owns the limits (20 names, 64 characters), declared-names-first* ordering, and dropping its injected `context`, `llm_model`, and `conversation_id` unless the- * schema declares them. Undeclared names become one `[redacted]` marker because caller-controlled- * names can contain credentials or personal data.+ * schema declares them. `shouldRecordInputKey` decides which undeclared names are recorded.*/export function describeInputShape(input: unknown, schema?: z.ZodType): Record<string, unknown> {return getToolInputProperties(input, schema, {+ shouldRecordInputKey,inputAliases: schema ? readParamAliases(schema) : undefined,})}diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex 2928413c4800..4d34b5233478 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -152,7 +152,7 @@ describe('ToolExecutor metrics', () => {// property exists for.expect(trackToolCallExtras('fail-tool')).toMatchObject({$mcp_error_type: 'internal',- $mcp_input_keys: ['[redacted]'],+ $mcp_input_keys: ['experimentId'],})})@@ -448,7 +448,7 @@ describe('ToolExecutor metrics', () => {expect(call[1]).toBe(0)expect(trackToolCallExtras('strict-tool')).toMatchObject({$mcp_error_type: 'validation',- $mcp_input_keys: ['[redacted]'],+ $mcp_input_keys: ['requiredField'],// `: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'],@@ -530,7 +530,7 @@ describe('ToolExecutor metrics', () => {)const extras = trackToolCallExtras('strict-tool')- expect(extras).toMatchObject({ $mcp_input_keys: ['[redacted]'] })+ expect(extras).toMatchObject({ $mcp_input_keys: ['requiredField'] })expect(extras).not.toHaveProperty('$mcp_input_aliases_used')})@@ -762,7 +762,7 @@ describe('ToolExecutor metrics', () => {expect(call?.[1]).toBe(0)expect(call?.[2]).toBe(true)expect(call?.[4]).toMatchObject({- $mcp_input_keys: ['[redacted]'],+ $mcp_input_keys: ['cmd'],$mcp_error_type: 'validation',})expect(call?.[4]).not.toHaveProperty('$mcp_exec_verb')@@ -944,7 +944,7 @@ describe('ToolExecutor metrics', () => {expect(call?.[1]).toBe(0)expect(call?.[2]).toBe(true)expect(call?.[4]).toMatchObject({- $mcp_input_keys: ['[redacted]'],+ $mcp_input_keys: ['toolName'],$mcp_error_type: 'validation',})})diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex ac67577931a6..435ed2115095 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -2147,6 +2147,25 @@ describe('exec tool', () => {])})+ it.each([+ ['a guessed spelling', 'requiredField', 'requiredField'],+ [+ 'a long settings field',+ 'session_recording_minimum_duration_milliseconds',+ 'session_recording_minimum_duration_milliseconds',+ ],+ ['an email', '[email protected]', '[redacted]'],+ ['a hostname', 'example.com', '[redacted]'],+ ['a phone number', 'tel_15555550100', '[redacted]'],+ ['a token', `ghp_${'aB3'.repeat(12)}`, '[redacted]'],+ ['a PostHog token without digits', `phx_${'aBc'.repeat(15)}`, '[redacted]'],+ ])('records an undeclared key that is %s', (_shape, key, recorded) => {+ const shape = describeInputShape({ [key]: 'secret-value', id: 1 }, z.object({ id: z.number() }))++ expect(shape.$mcp_input_keys).toEqual(['id', recorded])+ expect(JSON.stringify(shape)).not.toContain('secret-value')+ })+it('records declared names before misspelled ones when the limit is reached', () => {const declared = Object.fromEntries(Array.from({ length: 20 }, (_, i) => [`d${String(i).padStart(2, '0')}`, i])@@ -2183,7 +2202,7 @@ describe('exec tool', () => {$mcp_input_aliases_used: ['experimentId:id'],})expect(describeInputShape({ experimentId: 1 }, z.object({ id: z.number() }))).toEqual({- $mcp_input_keys: ['[redacted]'],+ $mcp_input_keys: ['experimentId'],})})