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): emit body for tools with anyOf/oneOf request schemas (#60474)

Tomás Farías Santana72f421d7a328
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 093ab2c73ae4..83228c3735a9 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -72,6 +72,8 @@ interface OpenApiSchema {
required?: string[]
$ref?: string
allOf?: Array<OpenApiSchema | { $ref: string }>
+ anyOf?: Array<OpenApiSchema | { $ref: string }>
+ oneOf?: Array<OpenApiSchema | { $ref: string }>
enum?: string[]
maxLength?: number
default?: unknown
@@ -228,6 +230,88 @@ function resolveSchema(spec: OpenApiSpec, schemaOrRef: OpenApiSchema | { $ref: s
return schemaOrRef as OpenApiSchema
}
+/**
+ * Flatten body schema properties across the three composition keywords that
+ * can hide fields from a naive ``schema.properties`` read:
+ *
+ * - ``properties``: own fields on the schema
+ * - ``allOf``: composition / inheritance — every member must hold, so fields
+ * are merged and required sets are unioned
+ * - ``anyOf`` / ``oneOf``: discriminated unions (e.g. polymorphic Python
+ * serializers) — at least one variant must hold, so fields are merged
+ * while required is the intersection across variants
+ *
+ * Returns:
+ * - ``properties``: the union of properties across all branches
+ * - ``required``: fields that are required on every reachable branch
+ * - ``variantSpecific``: fields only some union variants declare — the handler
+ * must guard access with ``'X' in params`` to satisfy TypeScript narrowing
+ * on the resulting Zod union type
+ *
+ * Without this flattening, the generated handler can silently omit fields and
+ * POST an empty (or partial) body — the same class of bug that exists when
+ * ``anyOf`` / ``oneOf`` is unhandled.
+ */
+function flattenBodySchemaProperties(
+ spec: OpenApiSpec,
+ schema: OpenApiSchema | undefined
+): { properties: Map<string, OpenApiSchema>; required: Set<string>; variantSpecific: Set<string> } {
+ if (!schema) {
+ return { properties: new Map(), required: new Set(), variantSpecific: new Set() }
+ }
+
+ // Start with own properties, then fold every allOf member in. Fields are
+ // merged (first writer wins on collision); required sets are unioned.
+ const baseProperties = new Map<string, OpenApiSchema>(Object.entries(schema.properties ?? {}))
+ const baseRequired = new Set<string>(schema.required ?? [])
+ for (const member of schema.allOf ?? []) {
+ const sub = flattenBodySchemaProperties(spec, resolveSchema(spec, member))
+ for (const [name, prop] of sub.properties) {
+ if (!baseProperties.has(name)) {
+ baseProperties.set(name, prop)
+ }
+ }
+ for (const r of sub.required) {
+ baseRequired.add(r)
+ }
+ }
+
+ const variantRefs = [...(schema.anyOf ?? []), ...(schema.oneOf ?? [])]
+ if (variantRefs.length === 0) {
+ return { properties: baseProperties, required: baseRequired, variantSpecific: new Set() }
+ }
+
+ const variants = variantRefs
+ .map((v) => resolveSchema(spec, v))
+ .filter((v): v is OpenApiSchema => !!v)
+ .map((v) => flattenBodySchemaProperties(spec, v))
+ const merged = new Map(baseProperties)
+ for (const v of variants) {
+ for (const [name, prop] of v.properties) {
+ if (!merged.has(name)) {
+ merged.set(name, prop)
+ }
+ }
+ }
+ const required = new Set(baseRequired)
+ const variantSpecific = new Set<string>()
+ for (const name of merged.keys()) {
+ // Locally-declared / allOf-composed fields are always present, so they
+ // are never variant-specific regardless of what each variant says.
+ if (baseProperties.has(name)) {
+ continue
+ }
+ if (variants.every((v) => v.properties.has(name))) {
+ if (variants.every((v) => v.required.has(name))) {
+ required.add(name)
+ }
+ } else {
+ variantSpecific.add(name)
+ }
+ }
+ return { properties: merged, required, variantSpecific }
+}
+
/**
* Resolve the response type name from an operation's success response.
* Returns the Schemas.* type name if the $ref maps to a type that exists
@@ -325,6 +409,13 @@ interface SchemaComposition {
pathParamNames: string[]
queryParamNames: string[]
bodyFieldNames: string[]
+ /**
+ * Body fields that only appear in some variants of a union (anyOf/oneOf) body schema.
+ * The handler emits `'X' in params && params.X !== undefined` for these to satisfy
+ * TypeScript's union narrowing — referencing `params.X` directly fails type-checking
+ * because variant types that lack the field have no such property.
+ */
+ variantSpecificBodyFieldNames: Set<string>
/** Maps alias → original field name for renamed params */
renamedFields: Record<string, string>
/** Maps param name → fallback key for optional params with state fallbacks */
@@ -343,6 +434,7 @@ function composeToolSchema(
const pathParamNames: string[] = []
const queryParamNames: string[] = []
const bodyFieldNames: string[] = []
+ const variantSpecificBodyFieldNames = new Set<string>()
/**
* Params whose underlying Orval shape is `.optional()` (or `.nullish()`).
* Used by the cast branch in `param_overrides`: `z.preprocess(fn, source)`
@@ -432,44 +524,49 @@ function composeToolSchema(
const bodySchema = resolveSchema(spec, bodySchemaRef)
// PATCH bodies are partial — Orval emits every field as `.optional()`.
// For POST/PUT, optionality follows the body schema's `required` list.
- const bodyRequiredSet = new Set(bodySchema?.required ?? [])
+ const {
+ properties: bodyProperties,
+ required: bodyRequiredSet,
+ variantSpecific: bodyVariantSpecific,
+ } = flattenBodySchemaProperties(spec, bodySchema)
const bodyAllOptional = resolved.method === 'PATCH'
- if (bodySchema?.properties) {
- for (const [name, prop] of Object.entries(bodySchema.properties)) {
- // Orval excludes readOnly fields from Body schemas — skip them
- // so we don't try to .omit() keys that don't exist
- if (prop.readOnly) {
- continue
- }
+ for (const [name, prop] of bodyProperties) {
+ // Orval excludes readOnly fields from Body schemas — skip them
+ // so we don't try to .omit() keys that don't exist
+ if (prop.readOnly) {
+ continue
+ }
- // exclude_params are removed at the Orval schema level by
- // applyNestedExclusions in generate-orval-schemas.mjs, so
- // they won't exist in the Zod schema. Skip them here to
- // avoid generating .omit() calls for nonexistent fields.
- if (excludeSet.has(name)) {
- continue
- }
+ // exclude_params are removed at the Orval schema level by
+ // applyNestedExclusions in generate-orval-schemas.mjs, so
+ // they won't exist in the Zod schema. Skip them here to
+ // avoid generating .omit() calls for nonexistent fields.
+ if (excludeSet.has(name)) {
+ continue
+ }
- // Auto-exclude underscore-prefixed fields
- if (name.startsWith('_')) {
- bodyOmitFields.add(name)
- continue
- }
- if (includeSet && !includeSet.has(name)) {
- bodyOmitFields.add(name)
- continue
- }
+ // Auto-exclude underscore-prefixed fields
+ if (name.startsWith('_')) {
+ bodyOmitFields.add(name)
+ continue
+ }
+ if (includeSet && !includeSet.has(name)) {
+ bodyOmitFields.add(name)
+ continue
+ }
- // If this field is renamed, store the alias instead so the
- // handler references params.<alias>. The original→alias
- // mapping is tracked in renamedFields for body-building.
- const alias = renameMap.get(name)
- const fieldKey = alias ?? name
- bodyFieldNames.push(fieldKey)
- if (bodyAllOptional || !bodyRequiredSet.has(name)) {
- optionalParamNames.add(fieldKey)
- }
+ // If this field is renamed, store the alias instead so the
+ // handler references params.<alias>. The original→alias
+ // mapping is tracked in renamedFields for body-building.
+ const alias = renameMap.get(name)
+ const fieldKey = alias ?? name
+ bodyFieldNames.push(fieldKey)
+ if (bodyVariantSpecific.has(name)) {
+ variantSpecificBodyFieldNames.add(fieldKey)
+ }
+ if (bodyAllOptional || !bodyRequiredSet.has(name)) {
+ optionalParamNames.add(fieldKey)
}
}
@@ -635,6 +732,7 @@ function composeToolSchema(
pathParamNames,
queryParamNames,
bodyFieldNames,
+ variantSpecificBodyFieldNames,
renamedFields,
paramFallbacks,
}
@@ -847,7 +945,12 @@ function generateToolCode(
// If the field was renamed, bf is the alias (used for params access)
// and bodyKey is the original name (used as the HTTP body key).
const bodyKey = composition.renamedFields[bf] ?? bf
- handlerBody += ` if (params.${bf} !== undefined) body[${JSON.stringify(bodyKey)}] = params.${bf}\n`
+ // Variant-specific fields (only in some union variants) need an `in`
+ // narrowing guard — TypeScript rejects bare `params.X` access otherwise.
+ const guard = composition.variantSpecificBodyFieldNames.has(bf)
+ ? `'${bf}' in params && params.${bf} !== undefined`
+ : `params.${bf} !== undefined`
+ handlerBody += ` if (${guard}) body[${JSON.stringify(bodyKey)}] = params.${bf}\n`
}
// inject_body: hardcoded values that always override caller-supplied params.
// Emitted last so they overwrite anything set above.
diff --git a/services/mcp/src/tools/generated/batch_exports.ts b/services/mcp/src/tools/generated/batch_exports.ts
index 4a2bceee86ff..c441fa8a02a7 100644
--- a/services/mcp/src/tools/generated/batch_exports.ts
+++ b/services/mcp/src/tools/generated/batch_exports.ts
@@ -215,12 +215,31 @@ const FileDownloadBatchExportsCreateSchema = FileDownloadBatchExportsCreateBody
const fileDownloadBatchExportsCreate = (): ToolBase<typeof FileDownloadBatchExportsCreateSchema, unknown> => ({
name: 'file-download-batch-exports-create',
schema: FileDownloadBatchExportsCreateSchema,
- // eslint-disable-next-line no-unused-vars
handler: async (context: Context, params: z.infer<typeof FileDownloadBatchExportsCreateSchema>) => {
const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.file !== undefined) {
+ body['file'] = params.file
+ }
+ if (params.model !== undefined) {
+ body['model'] = params.model
+ }
+ if ('include' in params && params.include !== undefined) {
+ body['include'] = params.include
+ }
+ if ('exclude' in params && params.exclude !== undefined) {
+ body['exclude'] = params.exclude
+ }
+ if (params.data_interval_start !== undefined) {
+ body['data_interval_start'] = params.data_interval_start
+ }
+ if (params.data_interval_end !== undefined) {
+ body['data_interval_end'] = params.data_interval_end
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/file_download_batch_exports/`,
+ body,
})
return result
},
diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.ts
index 9aa5ad821ba6..d29246ef16bb 100644
--- a/services/mcp/tests/unit/generate-tools.test.ts
+++ b/services/mcp/tests/unit/generate-tools.test.ts
@@ -546,6 +546,219 @@ describe('inject_body', () => {
})
})
+describe('anyOf / oneOf body schemas (discriminated unions)', () => {
+ // Polymorphic Python serializers (e.g. file-download-batch-exports) emit
+ // request bodies as `anyOf` of per-variant object schemas. Without union
+ // handling, `bodyFieldNames` stays empty and the generated handler POSTs
+ // with no body — the server rejects the request as "field required".
+ const unionResolved = (): ResolvedOperation =>
+ makeResolved({
+ method: 'POST',
+ operation: {
+ operationId: 'things_create',
+ parameters: [],
+ requestBody: {
+ content: {
+ 'application/json': {
+ schema: {
+ anyOf: [
+ {
+ type: 'object',
+ properties: {
+ kind: { type: 'string', enum: ['a'] },
+ shared_field: { type: 'string' },
+ only_in_a: { type: 'string' },
+ },
+ required: ['kind', 'shared_field'],
+ },
+ {
+ type: 'object',
+ properties: {
+ kind: { type: 'string', enum: ['b'] },
+ shared_field: { type: 'string' },
+ only_in_b: { type: 'number' },
+ },
+ required: ['kind', 'shared_field', 'only_in_b'],
+ },
+ ],
+ },
+ },
+ },
+ },
+ },
+ })
+
+ it('emits body assembly for every field, guarding variant-specific access with `in`', () => {
+ const config: ToolConfig = {
+ operation: 'things_create',
+ enabled: true,
+ }
+
+ const result = generateToolCode(
+ 'things-create',
+ config,
+ unionResolved(),
+ defaultCategory,
+ makeSpec(),
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+
+ // Body is initialized and forwarded.
+ expect(result.code).toContain('const body: Record<string, unknown> = {}')
+ expect(result.code).toContain('body,')
+
+ // Every field across all variants is assembled into the body.
+ expect(result.code).toContain(`body["kind"] = params.kind`)
+ expect(result.code).toContain(`body["shared_field"] = params.shared_field`)
+ expect(result.code).toContain(`body["only_in_a"] = params.only_in_a`)
+ expect(result.code).toContain(`body["only_in_b"] = params.only_in_b`)
+
+ // Fields present in every variant don't need the `in` guard.
+ expect(result.code).toContain('if (params.kind !== undefined)')
+ expect(result.code).toContain('if (params.shared_field !== undefined)')
+ // Fields only in some variants must be guarded with `'X' in params` so
+ // accessing them on the inferred union type still type-checks.
+ expect(result.code).toContain(`if ('only_in_a' in params && params.only_in_a !== undefined)`)
+ expect(result.code).toContain(`if ('only_in_b' in params && params.only_in_b !== undefined)`)
+ })
+
+ it('flattens allOf composition inside a union variant', () => {
+ // Mirrors the common OpenAPI pattern of a variant that extends a base
+ // schema via allOf (e.g. `$ref` + extra properties). Without allOf
+ // handling the base-schema fields would be dropped from the body.
+ const spec = makeSpec({
+ components: {
+ schemas: {
+ BaseFields: {
+ type: 'object',
+ properties: {
+ base_field: { type: 'string' },
+ },
+ required: ['base_field'],
+ },
+ },
+ },
+ })
+ const resolved = makeResolved({
+ method: 'POST',
+ operation: {
+ operationId: 'things_create',
+ parameters: [],
+ requestBody: {
+ content: {
+ 'application/json': {
+ schema: {
+ anyOf: [
+ {
+ allOf: [
+ { $ref: '#/components/schemas/BaseFields' },
+ {
+ type: 'object',
+ properties: {
+ kind: { type: 'string', enum: ['a'] },
+ only_in_a: { type: 'string' },
+ },
+ required: ['kind'],
+ },
+ ],
+ },
+ {
+ type: 'object',
+ properties: {
+ base_field: { type: 'string' },
+ kind: { type: 'string', enum: ['b'] },
+ },
+ required: ['base_field', 'kind'],
+ },
+ ],
+ },
+ },
+ },
+ },
+ },
+ })
+
+ const config: ToolConfig = {
+ operation: 'things_create',
+ enabled: true,
+ }
+ const result = generateToolCode(
+ 'things-create',
+ config,
+ resolved,
+ defaultCategory,
+ spec,
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+
+ // allOf-composed fields reach the body builder, treated as shared
+ // (present in every variant) rather than variant-specific.
+ expect(result.code).toContain(`body["base_field"] = params.base_field`)
+ expect(result.code).toContain('if (params.base_field !== undefined)')
+ expect(result.code).toContain('if (params.kind !== undefined)')
+ // The variant-only field still gets `in`-guarded.
+ expect(result.code).toContain(`if ('only_in_a' in params && params.only_in_a !== undefined)`)
+ })
+
+ it('resolves $ref-based union variants from components.schemas', () => {
+ const spec = makeSpec({
+ components: {
+ schemas: {
+ VariantA: {
+ type: 'object',
+ properties: { kind: { type: 'string' }, payload_a: { type: 'string' } },
+ required: ['kind'],
+ },
+ VariantB: {
+ type: 'object',
+ properties: { kind: { type: 'string' }, payload_b: { type: 'string' } },
+ required: ['kind'],
+ },
+ },
+ },
+ })
+ const resolved = makeResolved({
+ method: 'POST',
+ operation: {
+ operationId: 'things_create',
+ parameters: [],
+ requestBody: {
+ content: {
+ 'application/json': {
+ schema: {
+ oneOf: [
+ { $ref: '#/components/schemas/VariantA' },
+ { $ref: '#/components/schemas/VariantB' },
+ ],
+ },
+ },
+ },
+ },
+ },
+ })
+
+ const config: ToolConfig = {
+ operation: 'things_create',
+ enabled: true,
+ }
+
+ const result = generateToolCode(
+ 'things-create',
+ config,
+ resolved,
+ defaultCategory,
+ spec,
+ new Set<string>(),
+ stubGetQuerySchema
+ )
+
+ expect(result.code).toContain(`body["payload_a"] = params.payload_a`)
+ expect(result.code).toContain(`body["payload_b"] = params.payload_b`)
+ })
+})
+
describe('rename_params', () => {
it('swaps field names in schema expression and tracks renames', () => {
const config: ToolConfig = {