: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): expose array/union variants in exec schema drill-down (#61485)
Georgiy Tarasov045243c93276
diff --git a/services/mcp/src/tools/schema-utils.ts b/services/mcp/src/tools/schema-utils.tsindex 58586172e763..9853eb4f6106 100644--- a/services/mcp/src/tools/schema-utils.ts+++ b/services/mcp/src/tools/schema-utils.ts@@ -17,26 +17,64 @@ interface SummarizedProperty {hint?: string}-interface SchemaSummary {+/**+ * A summarized schema node. `properties` is always present (empty for non-object+ * nodes) so callers can read it unconditionally; `items` (arrays) and `variants`+ * (unions) carry the recursive shape that the old object-only summarizer dropped.+ */+interface NodeSummary {type: string+ title?: stringrequired?: string[]properties: Record<string, SummarizedProperty>- note?: string+ items?: NodeSummary+ variants?: NodeSummary[]+ description?: string+ enum?: unknown[]+ const?: unknown+ default?: unknown}/**- * Describe the type of a union (anyOf/oneOf) concisely.- * Extracts variant names from `title`, `description`, or `const` fields.+ * Properties that conventionally discriminate a union variant. Zod discriminated+ * unions (e.g. the trends `series` EventsNode/ActionsNode/GroupNode split) carry the+ * variant identity in one of these as a `const`/single-value `enum`, not in `title`.*/-function describeUnion(variants: JSONSchema[]): string {- const names: string[] = []- for (const v of variants) {- if (typeof v.title === 'string') {- names.push(v.title)- } else if (typeof v.const === 'string') {- names.push(v.const)+const DISCRIMINATOR_KEYS = ['kind', 'type', 'nodeKind'] as const++/** Best-effort human label for a union variant: `title`, a root `const`, or a discriminator property's `const`/single-value `enum`. */+function variantName(variant: JSONSchema): string | undefined {+ if (typeof variant.title === 'string') {+ return variant.title+ }+ if (typeof variant.const === 'string') {+ return variant.const+ }+ const props = variant.properties as Record<string, JSONSchema> | undefined+ if (!props) {+ return undefined+ }+ for (const key of DISCRIMINATOR_KEYS) {+ const disc = props[key]+ if (!disc) {+ continue+ }+ if (typeof disc.const === 'string') {+ return disc.const+ }+ if (Array.isArray(disc.enum) && disc.enum.length === 1 && typeof disc.enum[0] === 'string') {+ return disc.enum[0]}}+ return undefined+}++/**+ * Describe the type of a union (anyOf/oneOf) concisely.+ * Names variants via `variantName` (title, root const, or discriminator const).+ */+function describeUnion(variants: JSONSchema[]): string {+ const names = variants.map(variantName).filter((n): n is string => typeof n === 'string')if (names.length > 0 && names.length <= 6) {return `union of ${variants.length} types (${names.join(', ')})`}@@ -108,11 +146,17 @@ function describeItems(items: JSONSchema): string {return getTypeString(items)}+// Defensive recursion bound for `summarizeNode`. Zod's `toJSONSchema` inlines, so+// schemas are finite trees, but array/union unwrapping recurses — cap it anyway.+const MAX_SUMMARY_DEPTH = 6+/**- * Summarize a JSON Schema's top-level properties.- * Produces field names, types, descriptions, and drill-down hints for complex fields.+ * Summarize an object's top-level properties: field names, types, descriptions,+ * and drill-down hints for complex fields. Intentionally does NOT recurse into a+ * nested object/array/union field — each complex field instead carries a `hint`+ * pointing at the next `schema <tool> <path>` call.*/-export function summarizeSchema(schema: JSONSchema, toolName: string, fieldPath?: string): SchemaSummary {+function summarizeObject(schema: JSONSchema, toolName: string, fieldPath?: string): NodeSummary {const properties = (schema.properties || {}) as Record<string, JSONSchema>const requiredFields = (schema.required || []) as string[]const result: Record<string, SummarizedProperty> = {}@@ -120,8 +164,7 @@ export function summarizeSchema(schema: JSONSchema, toolName: string, fieldPath?for (const [name, prop] of Object.entries(properties)) {const entry: SummarizedProperty = {}- const typeStr = getTypeString(prop)- entry.type = typeStr+ entry.type = getTypeString(prop)if (typeof prop.description === 'string') {entry.description = prop.description@@ -159,11 +202,109 @@ export function summarizeSchema(schema: JSONSchema, toolName: string, fieldPath?result[name] = entry}- return {+ const summary: NodeSummary = {type: (schema.type as string) || 'object',...(requiredFields.length > 0 ? { required: requiredFields } : {}),properties: result,}+ if (typeof schema.title === 'string') {+ summary.title = schema.title+ }+ return summary+}++/** Summarize a scalar/leaf node — its descriptive metadata only, no children. */+function summarizeLeaf(schema: JSONSchema): NodeSummary {+ const summary: NodeSummary = { type: getTypeString(schema), properties: {} }+ if (typeof schema.title === 'string') {+ summary.title = schema.title+ }+ if (typeof schema.description === 'string') {+ summary.description = schema.description+ }+ if (schema.enum) {+ summary.enum = schema.enum as unknown[]+ }+ if (schema.const !== undefined) {+ summary.const = schema.const+ }+ if (schema.default !== undefined) {+ summary.default = schema.default+ }+ return summary+}++/**+ * Summarize any schema node, dispatching on its kind.+ *+ * Array and union WRAPPERS recurse, unlike the per-field summary inside an object+ * (which stops at one level and emits a `hint`). The reason: `items` and union+ * variants don't consume a path segment — `resolveSchemaPath` walks through them+ * transparently (`series.event` reaches into `series`'s array-of-union items) — so+ * a faithful summary has to unwrap them until it reaches the object/scalar beneath.+ * Without this, summarizing an array- or union-typed field that overflows the inline+ * budget (e.g. `query-trends series`) collapsed to an empty `{ type, properties: {} }`+ * and the variant shapes were invisible.+ */+function summarizeNode(+ schema: JSONSchema,+ toolName: string,+ fieldPath: string | undefined,+ depth: number+): NodeSummary {+ // Union: summarize each non-null variant. A lone non-null variant (a nullable+ // wrapper) collapses to that variant so we don't emit a pointless 1-way union.+ const unionVariants = (schema.anyOf || schema.oneOf) as JSONSchema[] | undefined+ if (unionVariants) {+ const nonNull = unionVariants.filter((v) => v.type !== 'null')+ if (nonNull.length === 0) {+ return { type: 'null', properties: {} }+ }+ if (depth >= MAX_SUMMARY_DEPTH) {+ return { type: getTypeString(schema), properties: {} }+ }+ if (nonNull.length === 1) {+ // Unwrap a nullable wrapper. Count it against `depth` so a pathological+ // chain of nested nullable unions still terminates at MAX_SUMMARY_DEPTH.+ return summarizeNode(nonNull[0]!, toolName, fieldPath, depth + 1)+ }+ return {+ type: getTypeString(schema),+ properties: {},+ variants: nonNull.map((v) => summarizeNode(v, toolName, fieldPath, depth + 1)),+ }+ }++ // Array: summarize the item schema (which itself may be an object or a union).+ if (schema.type === 'array' && schema.items && !Array.isArray(schema.items)) {+ const items = schema.items as JSONSchema+ if (depth >= MAX_SUMMARY_DEPTH) {+ return { type: 'array', properties: {}, items: { type: describeItems(items), properties: {} } }+ }+ return { type: 'array', properties: {}, items: summarizeNode(items, toolName, fieldPath, depth + 1) }+ }++ // Object with properties: list field names + drill-down hints (one level deep).+ if (schema.properties) {+ return summarizeObject(schema, toolName, fieldPath)+ }++ // A property-less object keeps the historical empty shape; anything else is a leaf.+ if (schema.type === 'object') {+ return { type: 'object', properties: {} }+ }+ return summarizeLeaf(schema)+}++/**+ * Summarize a JSON Schema for the `info` / `schema` exec commands.+ *+ * Objects list their top-level properties with drill-down hints; arrays and unions+ * recurse through the wrapper into the underlying item/variant shapes, so the result+ * is never an empty `{ type, properties: {} }`.+ */+export function summarizeSchema(schema: JSONSchema, toolName: string, fieldPath?: string): NodeSummary {+ return summarizeNode(schema, toolName, fieldPath, 0)}/**diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex a1cc3768789d..6c2c530e511d 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -512,6 +512,59 @@ describe('exec tool', () => {expect(drilled.note).toBeUndefined()expect(drilled.schema).not.toBeUndefined()})++ // Regression for the reported bug: `schema query-trends series` resolves to an+ // array-of-union node that overflows the inline budget. The summarizer used to+ // walk only `properties`, so it returned `{ type: 'array', properties: {} }` —+ // an empty schema that hid the EventsNode/ActionsNode/GroupNode variants and+ // forced callers onto the prose examples instead. The series item shapes must+ // now be visible in the summary.+ it('eval: query-trends series drill-down exposes the item variant shapes (not an empty array)', async () => {+ const context: Context = {+ api: {} as any,+ cache: {} as any,+ env: {+ MCP_APPS_BASE_URL: undefined,+ POSTHOG_ANALYTICS_API_KEY: undefined,+ POSTHOG_ANALYTICS_HOST: undefined,+ POSTHOG_API_BASE_URL: undefined,+ POSTHOG_PUBLIC_URL: undefined,+ POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: undefined,+ POSTHOG_UI_APPS_TOKEN: undefined,+ },+ stateManager: {+ getApiKey: async () => ({ scopes: ['*'] }),+ getAiConsentGiven: async () => true,+ } as any,+ sessionManager: new SessionManager({} as any),+ getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},+ }+ const v2Tools = await getToolsFromContext(context)+ const exec = createExecTool(v2Tools, context, 'test', 'test', undefined)++ const drilled = JSON.parse(+ (await exec.handler(context, { command: 'schema query-trends series' })) as string+ ) as {+ field?: string+ schema?: {+ type?: string+ items?: { variants?: Array<{ properties?: Record<string, unknown> }> }+ }+ }++ expect(drilled.field).toBe('series')+ expect(drilled.schema?.type).toBe('array')+ // The historical bug returned `{ type: "array", properties: {} }` with no+ // `items` at all. The item schema — here a summarized union of variants —+ // must now be present, and the variants must carry real field names. The old+ // empty output exposes none of these keys, so this fails on a regression.+ const variants = drilled.schema?.items?.variants+ expect(variants?.length).toBeGreaterThan(0)+ const variantFields = variants!.flatMap((v) => Object.keys(v.properties ?? {}))+ expect(variantFields).toContain('kind')+ expect(variantFields).toContain('event')+ })})describe('search command', () => {diff --git a/services/mcp/tests/unit/schema-utils.test.ts b/services/mcp/tests/unit/schema-utils.test.tsindex ec8bceba2252..e51eb0b0b2fe 100644--- a/services/mcp/tests/unit/schema-utils.test.ts+++ b/services/mcp/tests/unit/schema-utils.test.ts@@ -145,6 +145,118 @@ describe('schema-utils', () => {'DO NOT GUESS — you MUST run `schema my-tool parent.nested` before populating this field')})++ // Regression: `schema query-trends series` resolves to an array-of-union node+ // that overflows the inline budget, so it gets summarized. The old summarizer+ // only walked `properties`, collapsing it to `{ type: 'array', properties: {} }`+ // and hiding every variant shape — forcing callers back to the prose examples.+ it('summarizes an array-of-union root by recursing into the item variants', () => {+ const schema = {+ type: 'array',+ items: {+ anyOf: [+ {+ type: 'object',+ title: 'EventsNode',+ properties: { event: { type: 'string' }, math: { type: 'string' } },+ },+ {+ type: 'object',+ title: 'ActionsNode',+ properties: { id: { type: 'number' } },+ },+ ],+ },+ }++ const result = summarizeSchema(schema, 'query-trends', 'series')++ expect(result.type).toBe('array')+ // Not an empty object summary anymore — the items shape is present.+ expect(result.items).not.toBeUndefined()+ expect(result.items!.type).toBe('union of 2 types (EventsNode, ActionsNode)')+ expect(result.items!.variants).toHaveLength(2)+ expect(result.items!.variants![0]!.properties.event).toEqual(expect.objectContaining({ type: 'string' }))+ expect(result.items!.variants![1]!.properties.id).toEqual(expect.objectContaining({ type: 'number' }))+ })++ // The `series.0` numeric-step workaround resolves to the bare union node; it+ // suffered the same empty-summary collapse.+ it('summarizes a union root into its variants', () => {+ const schema = {+ anyOf: [+ { type: 'object', title: 'TypeA', properties: { a: { type: 'string' } } },+ { type: 'object', title: 'TypeB', properties: { b: { type: 'number' } } },+ ],+ }++ const result = summarizeSchema(schema, 'my-tool', 'field.0')++ expect(result.type).toBe('union of 2 types (TypeA, TypeB)')+ expect(result.variants).toHaveLength(2)+ expect(result.variants![0]!.properties.a).toEqual(expect.objectContaining({ type: 'string' }))+ })++ // Array `items` and union variants don't consume a path segment, so a hint on a+ // field reached through them must still point at `<field>.<name>` for the+ // follow-up `schema` call to resolve.+ it('threads the original field path into hints through array/union unwrapping', () => {+ const schema = {+ type: 'array',+ items: {+ anyOf: [+ {+ type: 'object',+ properties: { props: { type: 'object', properties: { x: { type: 'string' } } } },+ },+ ],+ },+ }++ const result = summarizeSchema(schema, 'query-trends', 'series')++ expect(result.items!.properties.props!.hint).toBe(+ 'DO NOT GUESS — you MUST run `schema query-trends series.props` before populating this field'+ )+ })++ // Zod discriminated unions (e.g. trends series) put variant identity in a `kind`+ // const, not a `title` — name them off that so the union header is legible.+ it('names union variants by a discriminator const when no title is present', () => {+ const schema = {+ anyOf: [+ { type: 'object', properties: { kind: { type: 'string', const: 'EventsNode' } } },+ { type: 'object', properties: { kind: { type: 'string', enum: ['ActionsNode'] } } },+ ],+ }++ const result = summarizeSchema(schema, 'query-trends', 'series.0')++ expect(result.type).toBe('union of 2 types (EventsNode, ActionsNode)')+ })++ it('collapses a nullable object union to the underlying object summary', () => {+ const schema = {+ anyOf: [{ type: 'object', properties: { a: { type: 'string' } } }, { type: 'null' }],+ }++ const result = summarizeSchema(schema, 'my-tool', 'maybeObj')++ expect(result.type).toBe('object')+ expect(result.variants).toBeUndefined()+ expect(result.properties.a).toEqual(expect.objectContaining({ type: 'string' }))+ })++ // Nullable-wrapper unwrapping recurses; a pathological chain must terminate via+ // the depth guard rather than blowing the stack on malformed input.+ it('terminates on a deeply nested chain of nullable wrappers', () => {+ let schema: Record<string, unknown> = { type: 'object', properties: { a: { type: 'string' } } }+ for (let i = 0; i < 100; i++) {+ schema = { anyOf: [schema, { type: 'null' }] }+ }++ expect(() => summarizeSchema(schema, 'my-tool', 'deep')).not.toThrow()+ })})describe('resolveSchemaPath', () => {