: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): accept more switch-organization id aliases + validation telemetry (#72053)
posthog[bot]392b3d60ad46
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 6853937f299b..47e5b283a070 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -530,6 +530,36 @@}},"required": ["id"]+ },+ {+ "type": "object",+ "properties": {+ "organizationId": {+ "type": "string",+ "description": "Alias for `orgId`. Accepts the `id` returned by `organizations-list` / `organization-get`."+ }+ },+ "required": ["organizationId"]+ },+ {+ "type": "object",+ "properties": {+ "organization_id": {+ "type": "string",+ "description": "Alias for `orgId`. Accepts the `id` returned by `organizations-list` / `organization-get`."+ }+ },+ "required": ["organization_id"]+ },+ {+ "type": "object",+ "properties": {+ "org_id": {+ "type": "string",+ "description": "Alias for `orgId`. Accepts the `id` returned by `organizations-list` / `organization-get`."+ }+ },+ "required": ["org_id"]}]},diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex c891f5c36c04..1f17f509a2fb 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -486,6 +486,10 @@ interface ToolErrorClassification {errorType: ToolErrorType/** Upstream HTTP status, when the failure came from a PostHog API error. */status?: number+ /** Value-free descriptors of a schema rejection (offending field+code). */+ validationFields?: string[]+ /** Top-level keys the caller sent — surfaces unaccepted aliases on a union rejection. */+ validationInputKeys?: string[]}/**@@ -506,7 +510,11 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassificationreturn { errorType: 'missing_context' }}if (error instanceof ToolInputValidationError) {- return { errorType: 'validation' }+ return {+ errorType: 'validation',+ ...(error.fields.length ? { validationFields: error.fields } : {}),+ ...(error.inputKeys.length ? { validationInputKeys: error.inputKeys } : {}),+ }}if (findPostHogPermissionError(error)) {return { errorType: 'permission' }@@ -541,5 +549,9 @@ function errorAnalyticsProperties(classification: ToolErrorClassification): Recoreturn {$mcp_error_type: classification.errorType,...(classification.status !== undefined ? { $mcp_error_status: classification.status } : {}),+ ...(classification.validationFields?.length ? { $mcp_validation_fields: classification.validationFields } : {}),+ ...(classification.validationInputKeys?.length+ ? { $mcp_validation_input_keys: classification.validationInputKeys }+ : {}),}}diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex 4ea79a0c60ed..e41a586369b9 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -129,9 +129,17 @@ export class PostHogValidationError extends Error {* noise problem the 4xx short-circuit exists to prevent.*/export class ToolInputValidationError extends Error {- constructor(message: string) {+ /** Value-free descriptors of the rejection for telemetry: offending+ * field paths + issue codes, and the top-level keys the caller sent. Never+ * includes input VALUES — see `describeValidationError`. */+ public readonly fields: string[]+ public readonly inputKeys: string[]++ constructor(message: string, detail?: { fields?: string[]; inputKeys?: string[] }) {super(message)this.name = 'ToolInputValidationError'+ this.fields = detail?.fields ?? []+ this.inputKeys = detail?.inputKeys ?? []}}diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 7f76dcde34ae..5789f0bc9032 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -312,13 +312,17 @@ export const AIObservabilityGetCostsSchema = z.object({days: z.number().optional(),})-// Accept both `orgId` and its `id` alias. `organizations-list` and-// `organization-get` return/accept the organization under an `id` key, so agents-// naturally reach for `id` here too. Requiring `orgId` alone made this the odd-// tool out and drove a stream of validation failures in exec mode. Modeled as a-// union so the advertised JSON schema expresses "exactly one identifier is-// required" (anyOf) rather than silently allowing an empty object; normalized to-// `orgId` so the handler stays simple.+// Accept `orgId` and the aliases agents reach for when composing the call from+// scratch. `organizations-list` / `organization-get` return the org under an `id`+// key, and in exec mode agents don't read the advertised schema — they+// reconstruct the field name from context, producing `id`, `organizationId`,+// `organization_id`, or `org_id`. Requiring a single spelling made this the odd+// tool out and drove a steady stream of exec-mode validation failures. Model each+// accepted key as its own single-field required branch so the advertised JSON+// schema (anyOf) enumerates every alias and still expresses "exactly one+// identifier is required"; normalize to `orgId` so the handler stays simple.+const orgIdAliasDescription =+ 'Alias for `orgId`. Accepts the `id` returned by `organizations-list` / `organization-get`.'export const OrganizationSetActiveSchema = z.union([@@ -329,17 +333,25 @@ export const OrganizationSetActiveSchema = z'The organization to switch to: the `id` returned by `organizations-list` (a UUID-like string, not the organization name). Use `organizations-list` to resolve a name to its id.'),}),- z.object({- id: z- .string()- .describe(- 'Alias for `orgId`. Accepts the `id` returned by `organizations-list` / `organization-get`.'- ),- }),+ z.object({ id: z.string().describe(orgIdAliasDescription) }),+ z.object({ organizationId: z.string().describe(orgIdAliasDescription) }),+ z.object({ organization_id: z.string().describe(orgIdAliasDescription) }),+ z.object({ org_id: z.string().describe(orgIdAliasDescription) }),],{ error: () => 'provide the organization id via "orgId" (get it from organizations-list)' })- .transform((data) => ({ orgId: 'orgId' in data ? data.orgId : data.id }))+ .transform((data) => ({+ orgId:+ 'orgId' in data+ ? data.orgId+ : 'id' in data+ ? data.id+ : 'organizationId' in data+ ? data.organizationId+ : 'organization_id' in data+ ? data.organization_id+ : data.org_id,+ }))export const ProjectGetAllSchema = z.object({})diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex d56ea4fb74bb..a534016fa0aa 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -193,6 +193,45 @@ export function formatInputValidationError(toolName: string, error: z.ZodError):return `Invalid input for "${toolName}": ${[...new Set(parts)].join('; ')}`}+/** Caps on what we record so a single failure can't blow up analytics cardinality. */+const MAX_VALIDATION_DESCRIPTORS = 20+const MAX_KEY_LENGTH = 64++/**+ * 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`).+ *+ * 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.+ */+export function describeValidationError(+ error: z.ZodError,+ input: Record<string, unknown>+): { fields: string[]; inputKeys: string[] } {+ 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}`+ })+ ),+ ].slice(0, MAX_VALIDATION_DESCRIPTORS)+ const inputKeys = Object.keys(input)+ .sort()+ .slice(0, MAX_VALIDATION_DESCRIPTORS)+ .map((key) => key.slice(0, MAX_KEY_LENGTH))+ return { fields, inputKeys }+}+/** Whether the tool's input schema declares an `output_format` field. */function schemaHasOutputFormat(schema: ZodObjectAny): boolean {return schema instanceof z.ZodObject && 'output_format' in schema.shape@@ -511,8 +550,10 @@ export function createExecTool(validation_error: true,})// Typed so the executor's catch skips exception capture and- // classifies it as `validation`, not `internal`.- throw new ToolInputValidationError(message)+ // 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))}input = validation.data as Record<string, unknown>diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/switch-organization.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/switch-organization.jsonindex 2c5447f80ba0..a57d012430db 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/switch-organization.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/switch-organization.json@@ -20,6 +20,36 @@},"required": ["id"],"type": "object"+ },+ {+ "properties": {+ "organizationId": {+ "description": "Alias for `orgId`. Accepts the `id` returned by `organizations-list` / `organization-get`.",+ "type": "string"+ }+ },+ "required": ["organizationId"],+ "type": "object"+ },+ {+ "properties": {+ "organization_id": {+ "description": "Alias for `orgId`. Accepts the `id` returned by `organizations-list` / `organization-get`.",+ "type": "string"+ }+ },+ "required": ["organization_id"],+ "type": "object"+ },+ {+ "properties": {+ "org_id": {+ "description": "Alias for `orgId`. Accepts the `id` returned by `organizations-list` / `organization-get`.",+ "type": "string"+ }+ },+ "required": ["org_id"],+ "type": "object"}]}diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex f2e889858d31..a48746573487 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -12,6 +12,7 @@ import { getToolsFromContext } from '@/tools'import { withInformationalResponse } from '@/tools/tool-utils'import {createExecTool,+ describeValidationError,type ExecInnerCallProperties,type ExecToolOptions,parseExecCallInnerToolName,@@ -1247,4 +1248,33 @@ describe('exec tool', () => {expect(commandDescription).toContain(queryToolsBlock)})})++ describe('describeValidationError', () => {+ it('surfaces the unaccepted top-level key on a union rejection without leaking values', () => {+ // The switch-organization regression shape: a union rejection carries an+ // empty issue path, so `inputKeys` is what makes the wrong alias diagnosable.+ const schema = z.union([z.object({ orgId: z.string() }), z.object({ id: z.string() })])+ const input = { organizationId: 'super-secret-org-uuid' }+ const result = schema.safeParse(input, { reportInput: true })+ expect(result.success).toBe(false)++ const detail = describeValidationError(result.error!, input)++ expect(detail.inputKeys).toEqual(['organizationId'])+ // Never record input values — the raw uuid must not appear anywhere.+ expect(JSON.stringify(detail)).not.toContain('super-secret-org-uuid')+ })++ it('records field path + issue code for a wrong-typed field, still without values', () => {+ const schema = z.object({ projectId: z.number() })+ const input = { projectId: 'not-a-number' }+ const result = schema.safeParse(input, { reportInput: true })+ expect(result.success).toBe(false)++ const detail = describeValidationError(result.error!, input)++ expect(detail.fields).toContain('projectId:invalid_type')+ expect(JSON.stringify(detail)).not.toContain('not-a-number')+ })+ })})diff --git a/services/mcp/tests/unit/organization-set-active-schema.test.ts b/services/mcp/tests/unit/organization-set-active-schema.test.tsindex fd0d89c2fd0f..c2f9e0ec909b 100644--- a/services/mcp/tests/unit/organization-set-active-schema.test.ts+++ b/services/mcp/tests/unit/organization-set-active-schema.test.ts@@ -5,9 +5,13 @@ import { OrganizationSetActiveSchema } from '@/schema/tool-inputs'describe('OrganizationSetActiveSchema', () => {it.each([['orgId', { orgId: 'org-123' }, 'org-123'],- // `organizations-list` / `organization-get` return the org under `id`; agents- // reach for it here too, so it must normalize to `orgId`.+ // `organizations-list` / `organization-get` return the org under `id`, and in+ // exec mode agents reconstruct the field name from context — every one of these+ // aliases must normalize to `orgId` or the exec-mode failures come back.['id alias', { id: 'org-456' }, 'org-456'],+ ['organizationId alias', { organizationId: 'org-789' }, 'org-789'],+ ['organization_id alias', { organization_id: 'org-abc' }, 'org-abc'],+ ['org_id alias', { org_id: 'org-def' }, 'org-def'],['orgId takes precedence over id', { orgId: 'org-123', id: 'org-456' }, 'org-123'],])('accepts %s and normalizes to orgId', (_label, input, expected) => {const result = OrganizationSetActiveSchema.safeParse(input)@@ -15,7 +19,7 @@ describe('OrganizationSetActiveSchema', () => {expect(result.data).toEqual({ orgId: expected })})- it('rejects input with neither orgId nor id', () => {+ it('rejects input with no recognized identifier', () => {const result = OrganizationSetActiveSchema.safeParse({})expect(result.success).toBe(false)expect(result.error?.issues[0]?.message).toContain('orgId')