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): stop union coercion mangling property filter values (#78531)

Lucas Ricoy97a611ae000d
diff --git a/services/mcp/scripts/lib/json-schema-to-zod.ts b/services/mcp/scripts/lib/json-schema-to-zod.ts
index 695e44207b7f..45e195ea4c43 100644
--- a/services/mcp/scripts/lib/json-schema-to-zod.ts
+++ b/services/mcp/scripts/lib/json-schema-to-zod.ts
@@ -105,7 +105,7 @@ export function getEntryVarName(entryDefName: string): string {
// Core conversion
// ------------------------------------------------------------------
-function schemaToZod(schema: JsonSchema, ctx: ConvertContext): string {
+function schemaToZod(schema: JsonSchema, ctx: ConvertContext, opts?: { strictPrimitives?: boolean }): string {
// $ref
if (schema.$ref) {
const refName = schema.$ref.replace('#/definitions/', '')
@@ -141,7 +141,13 @@ function schemaToZod(schema: JsonSchema, ctx: ConvertContext): string {
if (variants.length === 1) {
return schemaToZod(variants[0]!, ctx)
}
- const members = variants.map((v) => schemaToZod(v, ctx)).join(', ')
+ // Union members must be strict: zod tries branches in order and a coercing
+ // branch is greedy — z.coerce.boolean() accepts every input (Boolean(x)
+ // never throws) and z.coerce.number() turns null into 0, so any array/null
+ // branch after them is unreachable and inputs get silently mangled
+ // (e.g. a `["host.com"]` filter value became `true`). Coercion is for
+ // lone primitive fields, where there is no other branch to fall through to.
+ const members = variants.map((v) => schemaToZod(v, ctx, { strictPrimitives: true })).join(', ')
return `z.union([${members}])`
}
@@ -159,10 +165,12 @@ function schemaToZod(schema: JsonSchema, ctx: ConvertContext): string {
if (Array.isArray(schema.type)) {
const types = schema.type.filter((t) => t !== 'null')
const hasNull = schema.type.includes('null')
+ // Multi-type arrays are unions too, so their primitives must be strict
+ // for the same branch-ordering reason as anyOf above.
const base =
types.length === 1
- ? primitiveToZod(types[0]!)
- : `z.union([${types.map((t) => primitiveToZod(t)).join(', ')}])`
+ ? primitiveToZod(types[0]!, opts?.strictPrimitives)
+ : `z.union([${types.map((t) => primitiveToZod(t, true)).join(', ')}])`
return hasNull ? `${base}.nullable()` : base
}
@@ -186,12 +194,12 @@ function schemaToZod(schema: JsonSchema, ctx: ConvertContext): string {
// integer special ref — use coerce for MCP client compatibility (some clients send numbers as strings)
if (schema.type === 'integer') {
- return applyNumericConstraints('z.coerce.number().int()', schema)
+ return applyNumericConstraints(primitiveToZod('integer', opts?.strictPrimitives), schema)
}
// primitives
if (schema.type) {
- const base = primitiveToZod(schema.type as string)
+ const base = primitiveToZod(schema.type as string, opts?.strictPrimitives)
if (schema.type === 'integer' || schema.type === 'number') {
return applyNumericConstraints(base, schema)
}
@@ -214,17 +222,21 @@ function applyNumericConstraints(expr: string, schema: JsonSchema): string {
return out
}
-/** Use z.coerce for numbers/booleans — some MCP clients send primitives as strings */
-function primitiveToZod(type: string): string {
+/**
+ * Use z.coerce for numbers/booleans — some MCP clients send primitives as strings.
+ * `strict` disables coercion for primitives that sit inside a union, where a
+ * coercing branch would greedily swallow inputs meant for later branches.
+ */
+function primitiveToZod(type: string, strict = false): string {
switch (type) {
case 'string':
return 'z.string()'
case 'number':
- return 'z.coerce.number()'
+ return strict ? 'z.number()' : 'z.coerce.number()'
case 'integer':
- return 'z.coerce.number().int()'
+ return strict ? 'z.number().int()' : 'z.coerce.number().int()'
case 'boolean':
- return 'z.coerce.boolean()'
+ return strict ? 'z.boolean()' : 'z.coerce.boolean()'
case 'null':
return 'z.null()'
default:
diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.ts
index 9aed0bbe938b..eb0b13f6f9dd 100644
--- a/services/mcp/src/tools/generated/ai_observability.ts
+++ b/services/mcp/src/tools/generated/ai_observability.ts
@@ -2475,7 +2475,7 @@ const AssistantFlagPropertyFilter = z.object({
)
.default('flag'),
value: z
- .union([z.coerce.boolean(), z.string()])
+ .union([z.boolean(), z.string()])
.describe('`true`/`false` for boolean flags, or a variant name string for multivariate flags.'),
})
diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.ts
index 079b7df8529e..93b2bd6a9e42 100644
--- a/services/mcp/src/tools/generated/mcp_analytics.ts
+++ b/services/mcp/src/tools/generated/mcp_analytics.ts
@@ -298,7 +298,7 @@ const PropertyOperator = z.enum([
'not_icontains_multi',
])
-const PropertyFilterBaseValue = z.union([z.string(), z.coerce.number(), z.coerce.boolean()])
+const PropertyFilterBaseValue = z.union([z.string(), z.number(), z.boolean()])
const PropertyFilterValue = z.union([PropertyFilterBaseValue, z.array(PropertyFilterBaseValue), z.null()])
@@ -390,7 +390,7 @@ const LogEntryPropertyFilter = z.object({
const GroupPropertyFilter = z.object({
group_key_names: z.record(z.string(), z.string()).optional(),
- group_type_index: z.union([z.coerce.number().int(), z.null()]).optional(),
+ group_type_index: z.union([z.number().int(), z.null()]).optional(),
key: z.string(),
label: z.string().optional(),
operator: PropertyOperator,
@@ -414,7 +414,7 @@ const FlagPropertyFilter = z.object({
.describe('Only flag_evaluates_to operator is allowed for flag dependencies')
.default('flag_evaluates_to'),
type: z.literal('flag').describe('Feature flag dependency').default('flag'),
- value: z.union([z.coerce.boolean(), z.string()]).describe('The value can be true, false, or a variant name'),
+ value: z.union([z.boolean(), z.string()]).describe('The value can be true, false, or a variant name'),
})
const HogQLPropertyFilter = z.object({
diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.ts
index f8e29dad1a8d..0fe19c9ba582 100644
--- a/services/mcp/src/tools/generated/query-wrappers.ts
+++ b/services/mcp/src/tools/generated/query-wrappers.ts
@@ -324,7 +324,7 @@ const AssistantFlagPropertyFilter = z.object({
)
.default('flag'),
value: z
- .union([z.coerce.boolean(), z.string()])
+ .union([z.boolean(), z.string()])
.describe('`true`/`false` for boolean flags, or a variant name string for multivariate flags.'),
})
diff --git a/services/mcp/src/tools/generated/replay.ts b/services/mcp/src/tools/generated/replay.ts
index 9ee3bf7be104..c58c4637752e 100644
--- a/services/mcp/src/tools/generated/replay.ts
+++ b/services/mcp/src/tools/generated/replay.ts
@@ -513,7 +513,7 @@ const AssistantFlagPropertyFilter = z.object({
)
.default('flag'),
value: z
- .union([z.coerce.boolean(), z.string()])
+ .union([z.boolean(), z.string()])
.describe('`true`/`false` for boolean flags, or a variant name string for multivariate flags.'),
})
diff --git a/services/mcp/src/tools/generated/web_analytics.ts b/services/mcp/src/tools/generated/web_analytics.ts
index 1d8b7cde632d..551b67fc66e6 100644
--- a/services/mcp/src/tools/generated/web_analytics.ts
+++ b/services/mcp/src/tools/generated/web_analytics.ts
@@ -356,7 +356,7 @@ const PropertyOperator = z.enum([
'not_icontains_multi',
])
-const PropertyFilterBaseValue = z.union([z.string(), z.coerce.number(), z.coerce.boolean()])
+const PropertyFilterBaseValue = z.union([z.string(), z.number(), z.boolean()])
const PropertyFilterValue = z.union([PropertyFilterBaseValue, z.array(PropertyFilterBaseValue), z.null()])
diff --git a/services/mcp/tests/unit/json-schema-to-zod.test.ts b/services/mcp/tests/unit/json-schema-to-zod.test.ts
index 5d5e19d54e2f..789cb74a428c 100644
--- a/services/mcp/tests/unit/json-schema-to-zod.test.ts
+++ b/services/mcp/tests/unit/json-schema-to-zod.test.ts
@@ -51,3 +51,58 @@ describe('generateZodFromSchemaRef — array constraints', () => {
expect(out).not.toMatch(/\.max\(/)
})
})
+
+describe('generateZodFromSchemaRef — union primitive strictness', () => {
+ // Coercing branches inside a union are greedy (z.coerce.boolean() accepts any
+ // input, z.coerce.number() turns null into 0), which made later array/null
+ // branches unreachable: a `["host.com"]` property-filter value parsed as `true`
+ // and a feature-flag variant string parsed as `true`. Union members must be strict.
+ it.each([
+ {
+ label: 'anyOf of primitives',
+ schema: {
+ anyOf: [{ type: 'string' }, { type: 'number' }, { type: 'boolean' }],
+ },
+ expected: 'z.union([z.string(), z.number(), z.boolean()])',
+ },
+ {
+ label: 'anyOf with array and null branches',
+ schema: {
+ anyOf: [
+ { anyOf: [{ type: 'string' }, { type: 'number' }] },
+ { type: 'array', items: { type: 'string' } },
+ { type: 'null' },
+ ],
+ },
+ expected: 'z.union([z.union([z.string(), z.number()]), z.array(z.string()), z.null()])',
+ },
+ {
+ label: 'multi-type array',
+ schema: { type: ['string', 'boolean'] },
+ expected: 'z.union([z.string(), z.boolean()])',
+ },
+ ])('emits strict primitives for $label', ({ schema, expected }) => {
+ const root = { definitions: { Subject: { type: 'object', properties: { value: schema } } } }
+
+ const out = generateZodFromSchemaRef(root, 'Subject')
+
+ expect(out).toContain(expected)
+ expect(out).not.toContain('z.coerce')
+ })
+
+ it('keeps coercion on lone primitive fields', () => {
+ const root = {
+ definitions: {
+ Subject: {
+ type: 'object',
+ properties: { count: { type: 'number' }, flag: { type: 'boolean' } },
+ },
+ },
+ }
+
+ const out = generateZodFromSchemaRef(root, 'Subject')
+
+ expect(out).toContain('z.coerce.number()')
+ expect(out).toContain('z.coerce.boolean()')
+ })
+})