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.

fix(mcp): accept insight id aliases across insight tools (#72809)

Thomas Obermüller48497aa64bdf
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yaml
index 309d825d7973..34dc4cdc8423 100644
--- a/products/product_analytics/mcp/tools.yaml
+++ b/products/product_analytics/mcp/tools.yaml
@@ -121,6 +121,13 @@ tools:
title: Delete insight
description: |
Soft-delete an insight by ID. The insight will be marked as deleted and no longer appear in lists.
+ param_overrides:
+ id:
+ aliases:
+ - insightId
+ - insight_id
+ - short_id
+ - shortId
soft_delete: true
insight-get:
operation: insights_retrieve
@@ -142,6 +149,13 @@ tools:
- format
- refresh
- from_dashboard
+ param_overrides:
+ id:
+ aliases:
+ - insightId
+ - insight_id
+ - short_id
+ - shortId
response:
exclude:
- result
@@ -175,6 +189,12 @@ tools:
- favorited
- dashboards
param_overrides:
+ id:
+ aliases:
+ - insightId
+ - insight_id
+ - short_id
+ - shortId
query:
schema_ref: InsightQuery
dashboards:
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 1cb631d74a2c..23a79f5ace4c 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -489,8 +489,15 @@
"type": "object",
"properties": {
"insightId": {
- "type": "string",
- "description": "The insight ID or short_id to run."
+ "description": "The insight to run: its numeric `id` or 8-character `short_id`.",
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "number"
+ }
+ ]
},
"output_format": {
"default": "optimized",
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index b9506bdbf904..aa8a31f14e50 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -468,6 +468,12 @@ interface SchemaComposition {
renamedFields: Record<string, string>
/** Maps param name → fallback key for optional params with state fallbacks */
paramFallbacks: Record<string, string>
+ /**
+ * Maps canonical param name → accepted alias keys, from `param_overrides.<param>.aliases`.
+ * `generateToolCode` wraps the composed schema with
+ * `z.preprocess(normalizeParamAliases(...), ...)` when non-empty.
+ */
+ paramAliases: Record<string, string[]>
}
function composeToolSchema(
@@ -654,10 +660,13 @@ function composeToolSchema(
// - description → wrap the existing Orval-derived field with .describe(...)
// - optional+fallback → make param optional and resolve from state when omitted
// - cast → wrap with z.preprocess(...) from @/tools/cast-helpers
+ // - aliases → collected here; generateToolCode wraps the finished schema
+ // with z.preprocess(normalizeParamAliases(...), ...)
const toolInputsImports: string[] = []
const castHelperImports = new Set<string>()
const schemaRefBlocks: string[] = []
const paramFallbacks: Record<string, string> = {}
+ const paramAliases: Record<string, string[]> = {}
// Fields added via param_overrides (input_schema/schema_ref) need to participate in
// the body builder for write ops — otherwise the override is in the schema but
// the handler never forwards the value to the API. On PATCH (partial update) the
@@ -673,6 +682,10 @@ function composeToolSchema(
paramFallbacks[paramName] = override.fallback
}
+ if (override.aliases?.length) {
+ paramAliases[paramName] = override.aliases
+ }
+
// An `optional` override must also surface as optional in the agent-facing
// JSON Schema. When combined with `cast` the field is wrapped in
// `z.preprocess(...)`, which doesn't propagate inner `.optional()` (zod 4
@@ -812,6 +825,7 @@ function composeToolSchema(
variantSpecificBodyFieldNames,
renamedFields,
paramFallbacks,
+ paramAliases,
}
}
@@ -1028,6 +1042,19 @@ function generateToolCode(
}
}
+ // `param_overrides.<param>.aliases` — normalize alias keys to the canonical
+ // param before validation. Outermost wrapper so the rename happens before any
+ // field schema or validator runs; zod 4 renders a preprocess as the wrapped
+ // schema in JSON Schema output, so the advertised schema is unchanged.
+ const aliasEntries = Object.entries(composition.paramAliases)
+ if (aliasEntries.length > 0) {
+ composition.castHelperImports.add('normalizeParamAliases')
+ const aliasMapLiteral = `{ ${aliasEntries
+ .map(([canonical, aliases]) => `${canonical}: [${aliases.map((a) => `'${a}'`).join(', ')}]`)
+ .join(', ')} }`
+ schemaExpr = `z.preprocess(normalizeParamAliases(${aliasMapLiteral}), ${schemaExpr})`
+ }
+
const schemaDecl = `const ${schemaName} = ${schemaExpr}`
const localVarParams = new Set(Object.keys(composition.paramFallbacks))
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index 04c3774c8719..f5841b7643f1 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -98,6 +98,17 @@ export const ToolConfigSchema = z
* fully replace the schema; cast composes with the existing one).
*/
cast: z.enum(['string-int']).optional(),
+ /**
+ * Alternate key names accepted for this param and normalized to it
+ * before validation — for identifier params agents guess different
+ * spellings for (e.g. `id` ← `insightId` / `short_id`). The
+ * canonical key wins on conflict, then the first-listed alias;
+ * alias keys never reach the handler. The advertised JSON schema
+ * still shows only the canonical param. Codegen wraps the composed
+ * tool schema with `z.preprocess(normalizeParamAliases(...), ...)`
+ * — see generate-tools.ts and @/tools/cast-helpers.
+ */
+ aliases: z.array(z.string()).optional(),
})
.strict()
.refine((data) => !(data.input_schema && data.schema_ref), {
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 2be665b59399..ceec517b6f79 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -1,8 +1,9 @@
import { z } from 'zod'
-// Relative (not `@/`) import: this module is loaded by the tsx schema-generation
-// script, and `playbookIds` is pure constants — no `.md` imports to choke on.
+// Relative (not `@/`) imports: this module is loaded by the tsx schema-generation
+// script, and both modules are pure constants/functions — no `.md` imports to choke on.
import { PLAYBOOK_IDS, PLAYBOOK_URI_PREFIX } from '../tools/agentPlatform/playbookIds'
+import { normalizeParamAliases } from '../tools/cast-helpers'
export const BusinessKnowledgeUrlSourceCreateSchema = z.object({
name: z
@@ -329,28 +330,40 @@ export const ExperimentResultsGetSchema = z.object({
.describe('Force refresh of results instead of using cached values. Defaults to false.'),
})
-export const InsightQueryInputSchema = z.object({
- insightId: z.string().describe('The insight ID or short_id to run.'),
- output_format: z
- .enum(['optimized', 'json'])
- .optional()
- .default('optimized')
- .describe(
- 'Output format. "optimized" returns a human-readable summary from server-side formatters (recommended for analysis). "json" returns the raw query results as JSON.'
- ),
- variables_override: z
- .union([z.string(), z.record(z.string(), z.unknown())])
- .optional()
- .describe(
- 'Object (or pre-encoded JSON string) to override the insight\'s HogQL variables for this run only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `insight-get` first, copy the matching entry from the response\'s query variables, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.'
- ),
- filters_override: z
- .union([z.string(), z.record(z.string(), z.unknown())])
- .optional()
- .describe(
- "Object (or pre-encoded JSON string) to override the insight's filters for this run only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token."
- ),
-})
+// Accept the identifier under the aliases agents reach for (`insight-get` &
+// friends return the insight under `id`; UI URLs surface `short_id`), and
+// accept a numeric id — production traces show both mistakes are common.
+// Same motivation as the `orgId` aliases on OrganizationSetActiveSchema below;
+// normalized via preprocess here because this schema has more fields than a
+// per-alias union can reasonably enumerate.
+export const InsightQueryInputSchema = z.preprocess(
+ normalizeParamAliases({ insightId: ['id', 'insight_id', 'short_id', 'shortId'] }),
+ z.object({
+ insightId: z
+ .union([z.string(), z.number()])
+ .transform((value) => String(value))
+ .describe('The insight to run: its numeric `id` or 8-character `short_id`.'),
+ output_format: z
+ .enum(['optimized', 'json'])
+ .optional()
+ .default('optimized')
+ .describe(
+ 'Output format. "optimized" returns a human-readable summary from server-side formatters (recommended for analysis). "json" returns the raw query results as JSON.'
+ ),
+ variables_override: z
+ .union([z.string(), z.record(z.string(), z.unknown())])
+ .optional()
+ .describe(
+ 'Object (or pre-encoded JSON string) to override the insight\'s HogQL variables for this run only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `insight-get` first, copy the matching entry from the response\'s query variables, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.'
+ ),
+ filters_override: z
+ .union([z.string(), z.record(z.string(), z.unknown())])
+ .optional()
+ .describe(
+ "Object (or pre-encoded JSON string) to override the insight's filters for this run only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token."
+ ),
+ })
+)
export const AIObservabilityGetCostsSchema = z.object({
projectId: z.number().int().positive(),
diff --git a/services/mcp/src/tools/cast-helpers.ts b/services/mcp/src/tools/cast-helpers.ts
index c2ce5a50289d..808e2a6580c4 100644
--- a/services/mcp/src/tools/cast-helpers.ts
+++ b/services/mcp/src/tools/cast-helpers.ts
@@ -29,3 +29,49 @@ export const castStringToInt = (v: unknown): unknown => {
}
return v
}
+
+/**
+ * Normalize alternate key spellings to a canonical param name before validation.
+ *
+ * Agents composing calls from scratch guess the identifier key from context —
+ * production traces show `insight-get` receiving `insightId` / `short_id` /
+ * `insight_id` / `shortId` where the schema requires `id`, and `insight-query`
+ * receiving the reverse. Same failure mode the `orgId` aliases in
+ * `OrganizationSetActiveSchema` exist for (see src/schema/tool-inputs.ts), but
+ * for schemas with additional fields where a union of per-alias branches
+ * doesn't scale.
+ *
+ * Compose via `z.preprocess(normalizeParamAliases({ id: ['insightId', ...] }), schema)`.
+ * The canonical key wins when present; otherwise the first-listed alias with a
+ * value wins. Alias keys are always removed so they never reach handlers or
+ * `.strict()` validation. In zod 4's JSON Schema output (`io: 'input'`) a
+ * preprocess renders as the wrapped schema, so the advertised schema still
+ * shows only the canonical, required param.
+ *
+ * Wired up declaratively via `param_overrides: { id: { aliases: [...] } }` in
+ * product `tools.yaml` files — see services/mcp/scripts/generate-tools.ts.
+ */
+export const normalizeParamAliases =
+ (aliasMap: Record<string, readonly string[]>) =>
+ (input: unknown): unknown => {
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
+ return input
+ }
+ const record = input as Record<string, unknown>
+ const hasAlias = Object.values(aliasMap).some((aliases) => aliases.some((alias) => alias in record))
+ if (!hasAlias) {
+ return input
+ }
+ const result = { ...record }
+ for (const [canonical, aliases] of Object.entries(aliasMap)) {
+ for (const alias of aliases) {
+ if (alias in result) {
+ if (result[canonical] === undefined) {
+ result[canonical] = result[alias]
+ }
+ delete result[alias]
+ }
+ }
+ }
+ return result
+ }
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 9b8e1f695cc2..1778203715a9 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -237,9 +237,15 @@ export function describeValidationError(
return { fields, inputKeys }
}
-/** Whether the tool's input schema declares an `output_format` field. */
+/** Whether the tool's input schema declares an `output_format` field. Unwraps
+ * `z.preprocess(...)` pipes (e.g. the id-alias normalization on insight-query)
+ * to reach the underlying object schema. */
function schemaHasOutputFormat(schema: ZodObjectAny): boolean {
- return schema instanceof z.ZodObject && 'output_format' in schema.shape
+ let current: z.ZodType = schema
+ while (current instanceof z.ZodPipe) {
+ current = current.out as z.ZodType
+ }
+ return current instanceof z.ZodObject && 'output_format' in current.shape
}
/**
diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.ts
index df29e1b74c86..d53d97b07cb7 100644
--- a/services/mcp/src/tools/generated/product_analytics.ts
+++ b/services/mcp/src/tools/generated/product_analytics.ts
@@ -16,7 +16,7 @@ import {
InsightsRetrieveQueryParams,
InsightsTrendingRetrieveQueryParams,
} from '@/generated/product_analytics/api'
-import { castStringToInt } from '@/tools/cast-helpers'
+import { castStringToInt, normalizeParamAliases } from '@/tools/cast-helpers'
import { withPostHogUrl, omitResponseFields, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -245,7 +245,10 @@ const insightCreate = (): ToolBase<typeof InsightCreateSchema, WithPostHogUrl<Sc
},
})
-const InsightDeleteSchema = InsightsDestroyParams.omit({ project_id: true })
+const InsightDeleteSchema = z.preprocess(
+ normalizeParamAliases({ id: ['insightId', 'insight_id', 'short_id', 'shortId'] }),
+ InsightsDestroyParams.omit({ project_id: true })
+)
const insightDelete = (): ToolBase<typeof InsightDeleteSchema, Schemas.Insight> => ({
name: 'insight-delete',
@@ -261,22 +264,25 @@ const insightDelete = (): ToolBase<typeof InsightDeleteSchema, Schemas.Insight>
},
})
-const InsightGetSchema = InsightsRetrieveParams.omit({ project_id: true })
- .extend(InsightsRetrieveQueryParams.omit({ format: true, from_dashboard: true, refresh: true }).shape)
- .extend({
- filters_override: z
- .union([z.string(), z.record(z.string(), z.unknown())])
- .optional()
- .describe(
- "Object (or pre-encoded JSON string) to override the insight's filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token."
- ),
- variables_override: z
- .union([z.string(), z.record(z.string(), z.unknown())])
- .optional()
- .describe(
- 'Object (or pre-encoded JSON string) to override the insight\'s HogQL variables for this request only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `insight-get` first, copy the matching entry from the response, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.'
- ),
- })
+const InsightGetSchema = z.preprocess(
+ normalizeParamAliases({ id: ['insightId', 'insight_id', 'short_id', 'shortId'] }),
+ InsightsRetrieveParams.omit({ project_id: true })
+ .extend(InsightsRetrieveQueryParams.omit({ format: true, from_dashboard: true, refresh: true }).shape)
+ .extend({
+ filters_override: z
+ .union([z.string(), z.record(z.string(), z.unknown())])
+ .optional()
+ .describe(
+ "Object (or pre-encoded JSON string) to override the insight's filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token."
+ ),
+ variables_override: z
+ .union([z.string(), z.record(z.string(), z.unknown())])
+ .optional()
+ .describe(
+ 'Object (or pre-encoded JSON string) to override the insight\'s HogQL variables for this request only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `insight-get` first, copy the matching entry from the response, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.'
+ ),
+ })
+)
const insightGet = (): ToolBase<typeof InsightGetSchema, WithPostHogUrl<Schemas.Insight>> => ({
name: 'insight-get',
@@ -305,17 +311,20 @@ const insightGet = (): ToolBase<typeof InsightGetSchema, WithPostHogUrl<Schemas.
},
})
-const InsightUpdateSchema = InsightsPartialUpdateParams.omit({ project_id: true })
- .extend(
- InsightsPartialUpdateBody.omit({ derived_name: true, order: true, deleted: true, _create_in_folder: true })
- .shape
- )
- .extend({
- query: InsightQuery.optional(),
- dashboards: InsightsPartialUpdateBody.shape['dashboards'].describe(
- 'Dashboard IDs this insight should belong to. This is a full replacement — always include all existing dashboard IDs when adding a new one.'
- ),
- })
+const InsightUpdateSchema = z.preprocess(
+ normalizeParamAliases({ id: ['insightId', 'insight_id', 'short_id', 'shortId'] }),
+ InsightsPartialUpdateParams.omit({ project_id: true })
+ .extend(
+ InsightsPartialUpdateBody.omit({ derived_name: true, order: true, deleted: true, _create_in_folder: true })
+ .shape
+ )
+ .extend({
+ query: InsightQuery.optional(),
+ dashboards: InsightsPartialUpdateBody.shape['dashboards'].describe(
+ 'Dashboard IDs this insight should belong to. This is a full replacement — always include all existing dashboard IDs when adding a new one.'
+ ),
+ })
+)
const insightUpdate = (): ToolBase<typeof InsightUpdateSchema, WithPostHogUrl<Schemas.Insight>> => ({
name: 'insight-update',
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-query.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-query.json
index 2c03bfc86630..fa2c1abc5a43 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-query.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-query.json
@@ -17,8 +17,15 @@
"description": "Object (or pre-encoded JSON string) to override the insight's filters for this run only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token."
},
"insightId": {
- "description": "The insight ID or short_id to run.",
- "type": "string"
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "number"
+ }
+ ],
+ "description": "The insight to run: its numeric `id` or 8-character `short_id`."
},
"output_format": {
"default": "optimized",
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index d9b6e0c85d0d..966f1e7fc345 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -651,12 +651,16 @@ describe('exec tool', () => {
describe('output_format suppression', () => {
// Mirrors the generated query wrappers / insight-query: `output_format`
// toggles whether the handler surfaces the server-side formatted table.
- function makeFormatterTool(received: Record<string, unknown>[]): Tool<ZodObjectAny> {
+ function makeFormatterTool(
+ received: Record<string, unknown>[],
+ { wrapInPreprocess = false }: { wrapInPreprocess?: boolean } = {}
+ ): Tool<ZodObjectAny> {
+ const objectSchema = z.object({
+ series: z.string().optional().describe('Query series'),
+ output_format: z.enum(['optimized', 'json']).default('optimized').optional(),
+ })
return makeMockTool({
- schema: z.object({
- series: z.string().optional().describe('Query series'),
- output_format: z.enum(['optimized', 'json']).default('optimized').optional(),
- }),
+ schema: wrapInPreprocess ? z.preprocess((value) => value, objectSchema) : objectSchema,
handler: async (_ctx, params) => {
received.push(params as Record<string, unknown>)
const optimized = (params as { output_format?: string }).output_format !== 'json'
@@ -696,6 +700,14 @@ describe('exec tool', () => {
expect(JSON.parse(result).results).toEqual([{ count: 6 }])
})
+ it('folds --json through a z.preprocess-wrapped schema (id-alias normalization, e.g. insight-query)', async () => {
+ const received: Record<string, unknown>[] = []
+ const exec = createExec([makeFormatterTool(received, { wrapInPreprocess: true })])
+ const result = (await exec.handler(mockContext, { command: 'call --json mock-tool' })) as string
+ expect(received[0]!.output_format).toBe('json')
+ expect(JSON.parse(result).results).toEqual([{ count: 6 }])
+ })
+
it('still dispatches the schema default "optimized" so the formatted table wins by default', async () => {
const received: Record<string, unknown>[] = []
const exec = createExec([makeFormatterTool(received)])
diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.ts
index 6ec58dc0b885..d868a4f13aeb 100644
--- a/services/mcp/tests/unit/generate-tools.test.ts
+++ b/services/mcp/tests/unit/generate-tools.test.ts
@@ -990,6 +990,44 @@ describe('rename_params', () => {
})
})
+describe('param_overrides aliases', () => {
+ it('wraps the composed schema with normalizeParamAliases and imports the helper', () => {
+ const config: ToolConfig = {
+ operation: 'things_retrieve',
+ enabled: true,
+ param_overrides: {
+ id: { aliases: ['thingId', 'thing_id'] },
+ },
+ }
+ const resolved = makeResolved({
+ method: 'GET',
+ path: '/api/projects/{project_id}/things/{id}/',
+ operation: {
+ operationId: 'things_retrieve',
+ parameters: [
+ { name: 'project_id', in: 'path', required: true, schema: { type: 'string' } },
+ { name: 'id', in: 'path', required: true, schema: { type: 'integer' } },
+ ],
+ },
+ })
+
+ const result = generateToolCode(
+ 'things-get',
+ config,
+ resolved,
+ defaultCategory,
+ makeSpec(),
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+
+ expect(result.castHelperImports.has('normalizeParamAliases')).toBe(true)
+ expect(result.code).toContain(
+ "const ThingsGetSchema = z.preprocess(normalizeParamAliases({ id: ['thingId', 'thing_id'] }), ThingsRetrieveParams.omit({ project_id: true }))"
+ )
+ })
+})
+
describe('x-accepts-stringified-json query params', () => {
function resolvedWith(parameters: NonNullable<ResolvedOperation['operation']['parameters']>): ResolvedOperation {
return makeResolved({
diff --git a/services/mcp/tests/unit/insight-id-aliases.test.ts b/services/mcp/tests/unit/insight-id-aliases.test.ts
new file mode 100644
index 000000000000..dc15124608f4
--- /dev/null
+++ b/services/mcp/tests/unit/insight-id-aliases.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest'
+
+import { InsightQueryInputSchema } from '@/schema/tool-inputs'
+import { GENERATED_TOOLS } from '@/tools/generated/product_analytics'
+
+// Agents interchange `id` / `insightId` / `insight_id` / `short_id` / `shortId`
+// across the insight tools — production traces show the mismatched key as the
+// dominant validation failure for all four. Every alias must normalize to each
+// tool's canonical param (canonical key wins on conflict, then the first-listed
+// alias) or those failures come back.
+describe('insight id aliases', () => {
+ const ALIAS_KEYS = ['insightId', 'insight_id', 'short_id', 'shortId'] as const
+
+ describe.each([['insight-get'], ['insight-update'], ['insight-delete']])(
+ '%s normalizes aliases to `id`',
+ (toolName) => {
+ const schema = GENERATED_TOOLS[toolName]!().schema
+
+ it.each([
+ ['id (numeric)', { id: 123 }, 123],
+ ['id (short_id value)', { id: 'AaVQ8Ijw' }, 'AaVQ8Ijw'],
+ ['insightId', { insightId: 123 }, 123],
+ ['insight_id', { insight_id: 123 }, 123],
+ ['short_id', { short_id: 'AaVQ8Ijw' }, 'AaVQ8Ijw'],
+ ['shortId', { shortId: 'AaVQ8Ijw' }, 'AaVQ8Ijw'],
+ ['id over aliases on conflict', { id: 1, insightId: 2, short_id: 'AaVQ8Ijw' }, 1],
+ ['first-listed alias on alias conflict', { insight_id: 3, shortId: 'AaVQ8Ijw' }, 3],
+ ])('accepts %s', (_label, input, expected) => {
+ const result = schema.safeParse(input)
+ expect(result.success).toBe(true)
+ const data = result.data as Record<string, unknown>
+ expect(data.id).toEqual(expected)
+ for (const alias of ALIAS_KEYS) {
+ expect(data).not.toHaveProperty(alias)
+ }
+ })
+
+ it('still rejects a call with no identifier', () => {
+ expect(schema.safeParse({}).success).toBe(false)
+ })
+ }
+ )
+
+ describe('insight-query normalizes aliases to `insightId` and coerces numbers to string', () => {
+ it.each([
+ ['insightId (string)', { insightId: 'AaVQ8Ijw' }, 'AaVQ8Ijw'],
+ ['insightId (numeric)', { insightId: 36 }, '36'],
+ ['id (numeric)', { id: 36 }, '36'],
+ ['id (string)', { id: '36' }, '36'],
+ ['insight_id', { insight_id: 36 }, '36'],
+ ['short_id', { short_id: 'AaVQ8Ijw' }, 'AaVQ8Ijw'],
+ ['shortId', { shortId: 'AaVQ8Ijw' }, 'AaVQ8Ijw'],
+ ['insightId over aliases on conflict', { insightId: 1, id: 2 }, '1'],
+ ['first-listed alias on alias conflict', { id: 2, short_id: 'AaVQ8Ijw' }, '2'],
+ ])('accepts %s', (_label, input, expected) => {
+ const result = InsightQueryInputSchema.safeParse(input)
+ expect(result.success).toBe(true)
+ expect(result.data?.insightId).toBe(expected)
+ })
+
+ it('still rejects a call with no identifier', () => {
+ expect(InsightQueryInputSchema.safeParse({}).success).toBe(false)
+ })
+ })
+})