: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 the read-data-schema shapes callers still send (#94077)
posthog[bot]c47d113bc2ca
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 0a31ca8a74eb..5cc8079e9152 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -997,7 +997,8 @@"maximum": 9007199254740991}},- "required": ["kind"]+ "required": ["kind"],+ "additionalProperties": false},{"type": "object",@@ -1011,7 +1012,8 @@"description": "The name of the event that you want to retrieve properties for."}},- "required": ["kind", "event_name"]+ "required": ["kind", "event_name"],+ "additionalProperties": false},{"type": "object",@@ -1025,7 +1027,8 @@"description": "The type of the entity that you want to retrieve properties for."}},- "required": ["kind", "entity"]+ "required": ["kind", "entity"],+ "additionalProperties": false},{"type": "object",@@ -1041,7 +1044,8 @@"description": "The ID of the action that you want to retrieve properties for."}},- "required": ["kind", "action_id"]+ "required": ["kind", "action_id"],+ "additionalProperties": false},{"type": "object",@@ -1059,7 +1063,8 @@"description": "Verified property name of an entity."}},- "required": ["kind", "entity", "property_name"]+ "required": ["kind", "entity", "property_name"],+ "additionalProperties": false},{"type": "object",@@ -1077,7 +1082,8 @@"description": "Verified property name of an event."}},- "required": ["kind", "event_name", "property_name"]+ "required": ["kind", "event_name", "property_name"],+ "additionalProperties": false},{"type": "object",@@ -1097,7 +1103,8 @@"description": "Verified property name of an action."}},- "required": ["kind", "action_id", "property_name"]+ "required": ["kind", "action_id", "property_name"],+ "additionalProperties": false}],"description": "The data schema query to execute."diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 7c1d8bd433ff..6db666f69c71 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -2,7 +2,7 @@ import { z } from 'zod'// 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 { normalizeParamAliases } from '../tools/cast-helpers'+import { castStringToInt, normalizeParamAliases } from '../tools/cast-helpers'export const ChannelInstructionsBaseVersionSchema = z.number()@@ -676,76 +676,180 @@ export const ExecuteSQLSchema = z.object({),})-const ReadEventsQuerySchema = z.object({- kind: z.literal('events'),- limit: z.number().int().min(1).max(500).default(500).optional().describe('Number of events to return per page.'),- offset: z.number().int().min(0).default(0).optional().describe('Number of events to skip for pagination.'),-})+const MAX_EVENTS_PAGE_SIZE = 500-const ReadEventPropertiesQuerySchema = z.object({- kind: z.literal('event_properties'),- event_name: z.string().describe('The name of the event that you want to retrieve properties for.'),-})+// Every read below is strict so a field it does not have is named back to the caller. Left+// open, an ignored `search` or `property_name` returns a confident answer to a different+// question than the one asked.+const ReadEventsQuerySchema = z+ .object({+ kind: z.literal('events'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(MAX_EVENTS_PAGE_SIZE)+ .default(MAX_EVENTS_PAGE_SIZE)+ .optional()+ .describe('Number of events to return per page.'),+ offset: z.number().int().min(0).default(0).optional().describe('Number of events to skip for pagination.'),+ })+ .strict()-const ReadEntityPropertiesQuerySchema = z.object({- kind: z.literal('entity_properties'),- entity: z.string().describe('The type of the entity that you want to retrieve properties for.'),-})+const ReadEventPropertiesQuerySchema = z+ .object({+ kind: z.literal('event_properties'),+ event_name: z.string().describe('The name of the event that you want to retrieve properties for.'),+ })+ .strict()-const ReadActionPropertiesQuerySchema = z.object({- kind: z.literal('action_properties'),- action_id: z.number().int().describe('The ID of the action that you want to retrieve properties for.'),-})+const ReadEntityPropertiesQuerySchema = z+ .object({+ kind: z.literal('entity_properties'),+ entity: z.string().describe('The type of the entity that you want to retrieve properties for.'),+ })+ .strict()-const ReadEntitySamplePropertyValuesQuerySchema = z.object({- kind: z.literal('entity_property_values'),- entity: z.string().describe('The type of the entity that you want to retrieve properties for.'),- property_name: z.string().describe('Verified property name of an entity.'),-})+const ReadActionPropertiesQuerySchema = z+ .object({+ kind: z.literal('action_properties'),+ action_id: z.number().int().describe('The ID of the action that you want to retrieve properties for.'),+ })+ .strict()-const ReadEventSamplePropertyValuesQuerySchema = z.object({- kind: z.literal('event_property_values'),- event_name: z.string().describe('Verified event name'),- property_name: z.string().describe('Verified property name of an event.'),-})+const ReadEntitySamplePropertyValuesQuerySchema = z+ .object({+ kind: z.literal('entity_property_values'),+ entity: z.string().describe('The type of the entity that you want to retrieve properties for.'),+ property_name: z.string().describe('Verified property name of an entity.'),+ })+ .strict()-const ReadActionSamplePropertyValuesQuerySchema = z.object({- kind: z.literal('action_property_values'),- action_id: z.number().int().describe('Verified action ID'),- property_name: z.string().describe('Verified property name of an action.'),-})+const ReadEventSamplePropertyValuesQuerySchema = z+ .object({+ kind: z.literal('event_property_values'),+ event_name: z.string().describe('Verified event name'),+ property_name: z.string().describe('Verified property name of an event.'),+ })+ .strict()++const ReadActionSamplePropertyValuesQuerySchema = z+ .object({+ kind: z.literal('action_property_values'),+ action_id: z.number().int().describe('Verified action ID'),+ property_name: z.string().describe('Verified property name of an action.'),+ })+ .strict()++const READ_DATA_SCHEMA_QUERIES = [+ ReadEventsQuerySchema,+ ReadEventPropertiesQuerySchema,+ ReadEntityPropertiesQuerySchema,+ ReadActionPropertiesQuerySchema,+ ReadEntitySamplePropertyValuesQuerySchema,+ ReadEventSamplePropertyValuesQuerySchema,+ ReadActionSamplePropertyValuesQuerySchema,+] as constconst ReadDataSchemaBodySchema = z.object({- query: z- .discriminatedUnion('kind', [- ReadEventsQuerySchema,- ReadEventPropertiesQuerySchema,- ReadEntityPropertiesQuerySchema,- ReadActionPropertiesQuerySchema,- ReadEntitySamplePropertyValuesQuerySchema,- ReadEventSamplePropertyValuesQuerySchema,- ReadActionSamplePropertyValuesQuerySchema,- ])- .describe('The data schema query to execute.'),+ query: z.discriminatedUnion('kind', READ_DATA_SCHEMA_QUERIES).describe('The data schema query to execute.'),})-// Person and session properties are read through `entity_properties`, but the two names below-// read so naturally next to `event_properties` that callers keep sending them. Accept them:-// the call says exactly what it wants, and a rejection costs the caller a whole round trip.-const READ_DATA_SCHEMA_KIND_ALIASES: Record<string, { kind: string; entity: string }> = {+const READ_DATA_SCHEMA_KINDS = new Set<string>(READ_DATA_SCHEMA_QUERIES.map((query) => query.shape.kind.value))++const READ_DATA_SCHEMA_QUERY_FIELDS = new Set<string>(+ READ_DATA_SCHEMA_QUERIES.flatMap((query) => Object.keys(query.shape))+)++/**+ * Names callers reach for instead of the seven declared kinds. Each one says exactly which+ * read it wants, so a rejection only costs a round trip. `person_properties` and+ * `session_properties` read so naturally next to `event_properties` that callers keep sending+ * them; the rest are the plural/singular and list/definition variants of the same words.+ */+const READ_DATA_SCHEMA_KIND_ALIASES: Record<string, { kind: string; entity?: string }> = {+ event: { kind: 'events' },+ events_list: { kind: 'events' },+ event_list: { kind: 'events' },+ list_events: { kind: 'events' },+ all_events: { kind: 'events' },+ event_names: { kind: 'events' },+ event_definitions: { kind: 'events' },+ taxonomy: { kind: 'events' },+ event_property: { kind: 'event_properties' },+ entity_property: { kind: 'entity_properties' },+ action_property: { kind: 'action_properties' },person_properties: { kind: 'entity_properties', entity: 'person' },session_properties: { kind: 'entity_properties', entity: 'session' },+ group_properties: { kind: 'entity_properties' },+ person_property_values: { kind: 'entity_property_values', entity: 'person' },+ session_property_values: { kind: 'entity_property_values', entity: 'session' },+ group_property_values: { kind: 'entity_property_values' },+ event_property_value: { kind: 'event_property_values' },+ entity_property_value: { kind: 'entity_property_values' },+ action_property_value: { kind: 'action_property_values' },}+/** Names callers use for the seven reads' own fields. */+const normalizeReadDataSchemaFields = normalizeParamAliases({+ event_name: ['event', 'eventName', 'event_names'],+ property_name: ['property', 'propertyName', 'property_key'],+ entity: ['entity_type', 'entityType', 'group_type', 'groupType'],+ action_id: ['action', 'actionId'],+})+function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value)}+/** Applies the field aliases, unwraps a single-element list, and reads numbers out of strings. */+function normalizeQueryFields(source: Record<string, unknown>): Record<string, unknown> {+ const fields = { ...(normalizeReadDataSchemaFields(source) as Record<string, unknown>) }+ // A one-event list means that event. A longer list needs one call per event, so leave it for+ // the schema to reject rather than answer about an event the caller did not pick.+ if (Array.isArray(fields['event_name']) && fields['event_name'].length === 1) {+ fields['event_name'] = fields['event_name'][0]+ }+ for (const name of ['action_id', 'limit', 'offset']) {+ if (fields[name] !== undefined) {+ fields[name] = castStringToInt(fields[name])+ }+ }+ // Clamped rather than refused: the backend returns at most one page of this size anyway, so+ // a bigger ask is answered instead of costing the caller a round trip.+ if (typeof fields['limit'] === 'number') {+ fields['limit'] = Math.min(fields['limit'], MAX_EVENTS_PAGE_SIZE)+ }+ return fields+}++/** Picks the branch a call with no usable kind is describing from its own fields. */+function inferKind(fields: Record<string, unknown>): string | undefined {+ const hasValue = fields['property_name'] !== undefined+ if (fields['event_name'] !== undefined) {+ return hasValue ? 'event_property_values' : 'event_properties'+ }+ if (fields['action_id'] !== undefined) {+ return hasValue ? 'action_property_values' : 'action_properties'+ }+ if (fields['entity'] !== undefined) {+ return hasValue ? 'entity_property_values' : 'entity_properties'+ }+ return undefined+}+/**- * Accept a call that puts the query fields at the top level (`{kind, event_name}`) instead of- * under `query`, and an aliased `kind`. Both say exactly what they want, so a rejection only- * costs the caller a round trip. `query` still wins whenever it is an object, so a well-formed- * call is never reinterpreted.+ * Accept the shapes callers keep sending for a read that is never ambiguous: the query fields+ * at the top level instead of under `query`, an aliased kind or field name, a count written as+ * a string, a kind left out entirely. Each one says what it wants, so a rejection only costs a+ * round trip. `query` still wins whenever it is an object, so a well-formed call is never+ * reinterpreted.+ *+ * Two things are deliberately left to fail. A field the tool does not have (a `search` term on+ * an events read) reaches the schema, because the events read returns the full list and+ * dropping the term would answer a different question than the one asked. And a caller that+ * named nothing this tool understands gets the events list only when it sent no other field —+ * otherwise it is asking about something else and deserves to hear so.** Same `z.preprocess` seam as `normalizeParamAliases`, and transparent to JSON Schema output* for the same reason: the advertised shape stays the wrapped one.@@ -755,12 +859,50 @@ function normalizeReadDataSchemaInput(input: unknown): unknown {return input}const { query, ...topLevel } = input- const source = isRecord(query) ? query : typeof topLevel['kind'] === 'string' ? topLevel : query- if (!isRecord(source)) {- return input+ let source: Record<string, unknown>+ if (isRecord(query)) {+ source = query+ } else if (+ typeof query === 'string' &&+ (READ_DATA_SCHEMA_KINDS.has(query) || READ_DATA_SCHEMA_KIND_ALIASES[query])+ ) {+ source = { ...topLevel, kind: query }+ } else {+ // A free-text `query` is a schema question with no kind in it, so it is dropped and the+ // remaining fields decide the read.+ source = topLevel+ }++ const rawKind = typeof source['kind'] === 'string' ? source['kind'] : undefined+ const alias = rawKind ? READ_DATA_SCHEMA_KIND_ALIASES[rawKind] : undefined+ const fields = normalizeQueryFields(source)+ if (alias?.entity !== undefined && fields['entity'] === undefined) {+ fields['entity'] = alias.entity+ }++ // A kind this tool does not have (`properties`, `property_values`) still leaves the fields,+ // and they name one read on their own.+ const named = alias?.kind ?? (rawKind !== undefined && READ_DATA_SCHEMA_KINDS.has(rawKind) ? rawKind : undefined)+ let kind = named ?? inferKind(fields)+ // Only a call that named no kind at all falls back to the event list, and only when every+ // field it did send is one this tool has. Anything else is asking about something else.+ if (kind === undefined && rawKind === undefined) {+ const sent = Object.keys(fields).filter((key) => key !== 'kind')+ if (sent.every((key) => READ_DATA_SCHEMA_QUERY_FIELDS.has(key))) {+ kind = 'events'+ }+ }+ if (kind === undefined) {+ return { query: source }+ }++ // Paging belongs to the events read alone. Every other kind returns one entity's schema, so+ // a stray page size is noise rather than a different question.+ if (kind !== 'events') {+ delete fields['limit']+ delete fields['offset']}- const alias = typeof source['kind'] === 'string' ? READ_DATA_SCHEMA_KIND_ALIASES[source['kind']] : undefined- return { query: alias ? { ...source, ...alias } : source }+ return { query: { ...fields, kind } }}export const ReadDataSchemaSchema = z.preprocess(normalizeReadDataSchemaInput, ReadDataSchemaBodySchema)diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-schema.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-schema.jsonindex 895a8d226661..aef27843b268 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-schema.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-schema.json@@ -5,6 +5,7 @@"description": "The data schema query to execute.","oneOf": [{+ "additionalProperties": false,"properties": {"kind": {"const": "events",@@ -29,6 +30,7 @@"type": "object"},{+ "additionalProperties": false,"properties": {"event_name": {"description": "The name of the event that you want to retrieve properties for.",@@ -43,6 +45,7 @@"type": "object"},{+ "additionalProperties": false,"properties": {"entity": {"description": "The type of the entity that you want to retrieve properties for.",@@ -57,6 +60,7 @@"type": "object"},{+ "additionalProperties": false,"properties": {"action_id": {"description": "The ID of the action that you want to retrieve properties for.",@@ -73,6 +77,7 @@"type": "object"},{+ "additionalProperties": false,"properties": {"entity": {"description": "The type of the entity that you want to retrieve properties for.",@@ -91,6 +96,7 @@"type": "object"},{+ "additionalProperties": false,"properties": {"event_name": {"description": "Verified event name",@@ -109,6 +115,7 @@"type": "object"},{+ "additionalProperties": false,"properties": {"action_id": {"description": "Verified action ID",diff --git a/services/mcp/tests/unit/read-data-schema-input.test.ts b/services/mcp/tests/unit/read-data-schema-input.test.tsindex 9818dbc181e8..ff27d894a2e0 100644--- a/services/mcp/tests/unit/read-data-schema-input.test.ts+++ b/services/mcp/tests/unit/read-data-schema-input.test.ts@@ -30,6 +30,69 @@ describe('read-data-schema input', () => {{ query: { kind: 'session_properties' } },{ query: { kind: 'entity_properties', entity: 'session' } },],+ ['no input at all', {}, { query: { kind: 'events', limit: 500, offset: 0 } }],+ ['an empty query object', { query: {} }, { query: { kind: 'events', limit: 500, offset: 0 } }],+ [+ 'a free-text query with nothing else to go on',+ { query: 'what data do we collect?' },+ { query: { kind: 'events', limit: 500, offset: 0 } },+ ],+ ['a kind named as a bare string', { query: 'events' }, { query: { kind: 'events', limit: 500, offset: 0 } }],+ [+ 'a kind alias named as a bare string',+ { query: 'person_properties' },+ { query: { kind: 'entity_properties', entity: 'person' } },+ ],+ [+ 'the event_names kind alias',+ { query: { kind: 'event_names' } },+ { query: { kind: 'events', limit: 500, offset: 0 } },+ ],+ [+ 'the person_property_values alias',+ { query: { kind: 'person_property_values', property_name: 'email' } },+ { query: { kind: 'entity_property_values', entity: 'person', property_name: 'email' } },+ ],+ [+ 'the event field alias',+ { kind: 'event_properties', event: 'purchase' },+ { query: { kind: 'event_properties', event_name: 'purchase' } },+ ],+ [+ 'a one-event list',+ { query: { kind: 'event_properties', event_names: ['purchase'] } },+ { query: { kind: 'event_properties', event_name: 'purchase' } },+ ],+ [+ 'the group_type field alias',+ { query: { kind: 'entity_properties', group_type: 'organization' } },+ { query: { kind: 'entity_properties', entity: 'organization' } },+ ],+ [+ 'an action id written as a string',+ { query: { kind: 'action_properties', action_id: '42' } },+ { query: { kind: 'action_properties', action_id: 42 } },+ ],+ [+ 'an over-sized page size written as a string',+ { query: { kind: 'events', limit: '1000' } },+ { query: { kind: 'events', limit: 500, offset: 0 } },+ ],+ [+ 'a missing kind inferred from the fields',+ { event_name: 'purchase', property_name: 'plan' },+ { query: { kind: 'event_property_values', event_name: 'purchase', property_name: 'plan' } },+ ],+ [+ 'a kind this tool does not have, resolved by the fields',+ { query: { kind: 'properties', entity: 'person' } },+ { query: { kind: 'entity_properties', entity: 'person' } },+ ],+ [+ 'paging sent alongside a single-entity read',+ { query: { kind: 'event_properties', event_name: 'purchase', limit: 50 } },+ { query: { kind: 'event_properties', event_name: 'purchase' } },+ ],])('accepts %s', (_name, input, expected) => {expect(ReadDataSchemaSchema.parse(input)).toEqual(expected)})@@ -43,8 +106,13 @@ describe('read-data-schema input', () => {expect(parsed).toEqual({ query: { kind: 'event_properties', event_name: 'purchase' } })})- it('still rejects a call that names no kind', () => {- expect(ReadDataSchemaSchema.safeParse({ event_name: 'purchase' }).success).toBe(false)+ it.each([+ ['a search term the events read cannot honor', { kind: 'events', search: 'purchase' }],+ ['a kind this tool does not have and no field to fall back on', { kind: 'actions' }],+ ['a subject this tool does not read', { table: 'stripe_invoices' }],+ ['a multi-event list no single read can answer', { kind: 'event_properties', event_names: ['a', 'b'] }],+ ])('still rejects %s', (_name, input) => {+ expect(ReadDataSchemaSchema.safeParse(input).success).toBe(false)})it('advertises the wrapped query as the only input shape', () => {