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): flatten union tool input schemas for client compatibility (#71765)

Rafael Audiberte40f6da8e149
diff --git a/services/mcp/src/hono/tool-catalog.ts b/services/mcp/src/hono/tool-catalog.ts
index 88cb380ac4d9..eb8a48ae04c0 100644
--- a/services/mcp/src/hono/tool-catalog.ts
+++ b/services/mcp/src/hono/tool-catalog.ts
@@ -25,6 +25,43 @@ export type { PreBuiltTool }
const EMPTY_OBJECT_JSON_SCHEMA = { type: 'object' as const, properties: {} }
+type JsonSchema = Record<string, unknown>
+
+/**
+ * Merge a top-level anyOf/oneOf of object variants into a single object schema,
+ * or return null if any variant is not a plain object schema.
+ *
+ * A root union keyword breaks clients that translate tool schemas into a
+ * restricted JSON Schema subset: GitHub Copilot Chat rejects the whole tool at
+ * registration with "object has unsupported top-level schema keyword 'anyOf'".
+ * The merge is advertisement-only and lossy (a variant's extra requirements are
+ * not enforced by the merged schema); call-time validation in the executor still
+ * runs against the original zod union, so invalid variant mixes are rejected.
+ */
+function flattenTopLevelUnion(variants: JsonSchema[]): JsonSchema | null {
+ if (variants.length === 0 || !variants.every((v) => v['type'] === 'object' && v['properties'])) {
+ return null
+ }
+ const properties: Record<string, JsonSchema> = {}
+ for (const variant of variants) {
+ for (const [name, prop] of Object.entries(variant['properties'] as Record<string, JsonSchema>)) {
+ const existing = properties[name]
+ if (!existing) {
+ properties[name] = prop
+ } else if (Array.isArray(existing['enum']) && Array.isArray(prop['enum'])) {
+ // Discriminator fields carry one enum value per variant; merge them
+ // so every variant stays expressible.
+ properties[name] = { ...existing, enum: [...new Set([...existing['enum'], ...prop['enum']])] }
+ }
+ }
+ }
+ // Only fields required by every variant stay required.
+ const required = variants
+ .map((v) => (Array.isArray(v['required']) ? (v['required'] as string[]) : []))
+ .reduce((acc, r) => acc.filter((field) => r.includes(field)))
+ return { type: 'object', properties, ...(required.length > 0 ? { required } : {}) }
+}
+
/**
* Convert a tool's zod schema to the MCP `inputSchema` wire shape. Single source
* for every advertised schema (catalog entries and the `render-ui` umbrella entry)
@@ -36,10 +73,11 @@ export function toMcpInputSchema(schema: ZodObjectAny): McpTool['inputSchema'] {
delete jsonSchema['additionalProperties']
// MCP requires inputSchema.type === 'object'. Top-level discriminated unions
// (e.g. `oneOf` on a polymorphic request body) come back without a root `type`.
- // Add it so the schema satisfies the MCP tool contract; the union constraint
- // still applies via the nested anyOf/oneOf.
+ // Flatten object-variant unions (see flattenTopLevelUnion); for anything else,
+ // add the root `type` so the schema satisfies the MCP tool contract.
if (!jsonSchema['type'] && (Array.isArray(jsonSchema['anyOf']) || Array.isArray(jsonSchema['oneOf']))) {
- jsonSchema = { type: 'object', ...jsonSchema }
+ const variants = (jsonSchema['anyOf'] ?? jsonSchema['oneOf']) as JsonSchema[]
+ jsonSchema = flattenTopLevelUnion(variants) ?? { type: 'object', ...jsonSchema }
}
return jsonSchema as McpTool['inputSchema']
}
diff --git a/services/mcp/tests/unit/tool-catalog.test.ts b/services/mcp/tests/unit/tool-catalog.test.ts
index dad10e8dee52..c7c38b1bc7ad 100644
--- a/services/mcp/tests/unit/tool-catalog.test.ts
+++ b/services/mcp/tests/unit/tool-catalog.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
-import { ToolCatalog } from '@/hono/tool-catalog'
+import { ToolCatalog, toMcpInputSchema } from '@/hono/tool-catalog'
import type { ToolBase, ZodObjectAny } from '@/tools/types'
type FakeDefinition = {
@@ -102,6 +102,44 @@ describe('ToolCatalog', () => {
catalog = new ToolCatalog()
})
+ describe('toMcpInputSchema', () => {
+ // GitHub Copilot Chat rejects tools whose inputSchema has a root union
+ // keyword ("object has unsupported top-level schema keyword 'anyOf'"),
+ // so polymorphic request bodies must advertise as one flat object.
+ it('flattens a top-level union of object variants into a single object schema', () => {
+ const union = z.union([
+ z.object({
+ model: z.enum(['events']),
+ file: z.object({ format: z.string() }),
+ include: z.array(z.string()).optional(),
+ }),
+ z.object({
+ model: z.enum(['persons']),
+ file: z.object({ format: z.string() }),
+ }),
+ ]) as unknown as ZodObjectAny
+
+ const result = toMcpInputSchema(union) as Record<string, unknown>
+
+ expect(result.anyOf).toBeUndefined()
+ expect(result.oneOf).toBeUndefined()
+ expect(result.type).toBe('object')
+ const properties = result.properties as Record<string, Record<string, unknown>>
+ expect(properties.model!.enum).toEqual(['events', 'persons'])
+ expect(Object.keys(properties)).toEqual(['model', 'file', 'include'])
+ // `include` only exists on one variant, so it must not be required.
+ expect(result.required).toEqual(['model', 'file'])
+ })
+
+ it('keeps a root type of object when union variants are not all objects', () => {
+ const union = z.union([z.object({ a: z.string() }), z.string()]) as unknown as ZodObjectAny
+
+ const result = toMcpInputSchema(union) as Record<string, unknown>
+
+ expect(result.type).toBe('object')
+ })
+ })
+
describe('warmup', () => {
it('should import tool modules and build the pre-computed map', async () => {
expect(catalog.warmedUp).toBe(false)