Skip to content

Commit 7b808a9

Browse files
ankitvirdi4ankitvuk9
authored andcommitted
fix(server): preserve inputSchema for z.discriminatedUnion / z.union (modelcontextprotocol#1643)
normalizeObjectSchema returned undefined for any schema whose root was not z.object(...), so registerTool silently advertised an empty schema in tools/list when given z.discriminatedUnion(...). Tool calls still validated correctly via the fallback in validateToolInput, which masked the bug from end-to-end tests. Pass discriminated unions and unions through unchanged in normalizeObjectSchema; let toJsonSchemaCompat handle the actual conversion (zod-to-json-schema for v3, Mini's z.toJSONSchema for v4). Both emit oneOf/anyOf branches. Default a top-level type: "object" on the emitted JSON Schema in mcp.ts so the wire payload is spec compliant when the converter does not include one (the discriminated-union and union case). Adds three regression tests under "Tools with union and intersection schemas" exercising tools/list, callTool, and outputSchema for v3 and v4.
1 parent a8cf503 commit 7b808a9

4 files changed

Lines changed: 179 additions & 14 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@modelcontextprotocol/sdk': patch
3+
---
4+
5+
Fix `registerTool` / `registerPrompt` silently dropping `inputSchema` and `outputSchema` when given a `z.discriminatedUnion(...)` or `z.union(...)` of objects.
6+
7+
`normalizeObjectSchema` previously returned `undefined` for any schema whose root was not `z.object(...)`, so the schema never reached `toJsonSchemaCompat` and `tools/list` advertised an empty schema. Tool calls still validated correctly via the fallback in `validateToolInput`,
8+
which masked the bug.
9+
10+
`normalizeObjectSchema` now passes discriminated unions and unions through unchanged. The `tools/list` payload is also given a top-level `type: "object"` when missing so the emitted JSON Schema satisfies the MCP spec for tool input/output schemas (Zod emits `oneOf` / `anyOf`
11+
without a root type for these cases).
12+
13+
Closes #1643.

‎src/server/mcp.ts‎

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -194,12 +194,17 @@ export class McpServer {
194194
description: tool.description,
195195
inputSchema: (() => {
196196
const obj = normalizeObjectSchema(tool.inputSchema);
197-
return obj
198-
? (toJsonSchemaCompat(obj, {
199-
strictUnions: true,
200-
pipeStrategy: 'input'
201-
}) as Tool['inputSchema'])
202-
: EMPTY_OBJECT_JSON_SCHEMA;
197+
if (!obj) return EMPTY_OBJECT_JSON_SCHEMA;
198+
const json = toJsonSchemaCompat(obj, {
199+
strictUnions: true,
200+
pipeStrategy: 'input'
201+
});
202+
// MCP requires `type: "object"` at the root of
203+
// tool inputSchema. Discriminated unions and
204+
// unions of objects produce `oneOf` / `anyOf`
205+
// without a top-level `type`; default it so the
206+
// emitted schema is spec compliant.
207+
return ensureObjectRoot(json) as Tool['inputSchema'];
203208
})(),
204209
annotations: tool.annotations,
205210
execution: tool.execution,
@@ -209,10 +214,11 @@ export class McpServer {
209214
if (tool.outputSchema) {
210215
const obj = normalizeObjectSchema(tool.outputSchema);
211216
if (obj) {
212-
toolDefinition.outputSchema = toJsonSchemaCompat(obj, {
217+
const json = toJsonSchemaCompat(obj, {
213218
strictUnions: true,
214219
pipeStrategy: 'output'
215-
}) as Tool['outputSchema'];
220+
});
221+
toolDefinition.outputSchema = ensureObjectRoot(json) as Tool['outputSchema'];
216222
}
217223
}
218224

@@ -1388,6 +1394,22 @@ const EMPTY_OBJECT_JSON_SCHEMA = {
13881394
properties: {}
13891395
};
13901396

1397+
/**
1398+
* Ensures a JSON Schema produced from a Zod schema has a top-level
1399+
* `type: "object"` per the MCP spec for tool input/output schemas.
1400+
*
1401+
* Plain `z.object(...)` already emits `type: "object"`, so this is a
1402+
* no-op for the common case. Discriminated unions and unions of objects
1403+
* emit `oneOf` / `anyOf` without a root `type`; we default it here so
1404+
* the wire payload is spec compliant. Schemas with an explicit non-object
1405+
* root `type` are left alone (they will fail downstream validation, which
1406+
* is the right signal for the user).
1407+
*/
1408+
function ensureObjectRoot(json: Record<string, unknown>): Record<string, unknown> {
1409+
if (json.type !== undefined) return json;
1410+
return { type: 'object', ...json };
1411+
}
1412+
13911413
/**
13921414
* Checks if a value looks like a Zod schema by checking for parse/safeParse methods.
13931415
*/

‎src/server/zod-compat.ts‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -133,9 +133,18 @@ export function getObjectShape(schema: AnyObjectSchema | undefined): Record<stri
133133

134134
// --- Schema normalization ---
135135
/**
136-
* Normalizes a schema to an object schema. Handles both:
136+
* Normalizes a schema for use as an object-shaped tool/prompt input or output.
137+
* Handles:
137138
* - Already-constructed object schemas (v3 or v4)
139+
* - Discriminated unions and unions whose branches are object schemas
140+
* (e.g. `z.discriminatedUnion('action', [...])`); these convert to a
141+
* valid JSON Schema (`oneOf` / `anyOf`) via `toJsonSchemaCompat` and
142+
* parse correctly via `safeParse`, so they pass through unchanged.
138143
* - Raw shapes that need to be wrapped into object schemas
144+
*
145+
* Returns `undefined` for schemas whose root is not object-shaped (e.g.
146+
* `z.string()`, `z.array(...)`), since those cannot satisfy the MCP spec's
147+
* requirement that tool input/output schemas describe objects.
139148
*/
140149
export function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | undefined): AnyObjectSchema | undefined {
141150
if (!schema) return undefined;
@@ -169,20 +178,35 @@ export function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | un
169178
}
170179

171180
// If we get here, it should be an AnySchema (not a raw shape)
172-
// Check if it's already an object schema
181+
// Check if it's already an object schema, a discriminated union, or a
182+
// union — all three convert cleanly to a JSON Schema with type:object
183+
// (via `toJsonSchemaCompat`) and validate via `safeParse`.
173184
if (isZ4Schema(schema as AnySchema)) {
174-
// Check if it's a v4 object
175185
const v4Schema = schema as unknown as ZodV4Internal;
176186
const def = v4Schema._zod?.def;
177-
if (def && (def.type === 'object' || def.shape !== undefined)) {
178-
return schema as AnyObjectSchema;
187+
if (def) {
188+
if (def.type === 'object' || def.shape !== undefined) {
189+
return schema as AnyObjectSchema;
190+
}
191+
// v4 reports both `z.union(...)` and `z.discriminatedUnion(...)`
192+
// as `def.type === 'union'`. Pass them through; downstream
193+
// `toJsonSchemaCompat` (Mini's `z.toJSONSchema`) emits a valid
194+
// `oneOf` / `anyOf` JSON Schema and `safeParse` handles them.
195+
if (def.type === 'union') {
196+
return schema as AnyObjectSchema;
197+
}
179198
}
180199
} else {
181-
// Check if it's a v3 object
182200
const v3Schema = schema as unknown as ZodV3Internal;
183201
if (v3Schema.shape !== undefined) {
184202
return schema as AnyObjectSchema;
185203
}
204+
// v3 distinguishes the two; both serialise to a JSON Schema with
205+
// `oneOf` / `anyOf` via the vendored `zodToJsonSchema` converter.
206+
const typeName = v3Schema._def?.typeName;
207+
if (typeName === 'ZodDiscriminatedUnion' || typeName === 'ZodUnion') {
208+
return schema as AnyObjectSchema;
209+
}
186210
}
187211

188212
return undefined;

‎test/server/mcp.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5182,6 +5182,112 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => {
51825182
])
51835183
);
51845184
});
5185+
5186+
// Regression for https://github.com/modelcontextprotocol/typescript-sdk/issues/1643
5187+
// Before the fix, normalizeObjectSchema returned undefined for
5188+
// discriminated unions and unions, so registerTool silently dropped
5189+
// the schema in tools/list and emitted EMPTY_OBJECT_JSON_SCHEMA. Tool
5190+
// calls still validated correctly via the fallback in validateToolInput.
5191+
test('should expose a discriminated union inputSchema in tools/list', async () => {
5192+
const server = new McpServer({ name: 'test', version: '1.0.0' });
5193+
const client = new Client({ name: 'test-client', version: '1.0.0' });
5194+
5195+
const inputSchema = z.discriminatedUnion('action', [
5196+
z.object({ action: z.literal('create'), name: z.string() }),
5197+
z.object({ action: z.literal('delete'), id: z.string() })
5198+
]);
5199+
5200+
server.registerTool('mutate', { inputSchema }, async args => ({
5201+
content: [{ type: 'text' as const, text: JSON.stringify(args) }]
5202+
}));
5203+
5204+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
5205+
await server.connect(serverTransport);
5206+
await client.connect(clientTransport);
5207+
5208+
const list = await client.listTools();
5209+
expect(list.tools).toHaveLength(1);
5210+
const advertised = list.tools[0].inputSchema as Record<string, unknown>;
5211+
expect(advertised.type).toBe('object');
5212+
// Both v3 (zod-to-json-schema) and v4 (Mini) emit oneOf or anyOf.
5213+
const branches = (advertised.oneOf ?? advertised.anyOf) as Array<Record<string, unknown>> | undefined;
5214+
expect(branches).toBeDefined();
5215+
expect(branches).toHaveLength(2);
5216+
5217+
// Tool calls keep working.
5218+
const ok = await client.callTool({
5219+
name: 'mutate',
5220+
arguments: { action: 'create', name: 'foo' }
5221+
});
5222+
expect(ok.isError).toBeFalsy();
5223+
5224+
const bad = await client.callTool({
5225+
name: 'mutate',
5226+
arguments: { action: 'create' }
5227+
});
5228+
expect(bad.isError).toBe(true);
5229+
});
5230+
5231+
test('should expose a union of objects inputSchema in tools/list', async () => {
5232+
const server = new McpServer({ name: 'test', version: '1.0.0' });
5233+
const client = new Client({ name: 'test-client', version: '1.0.0' });
5234+
5235+
const inputSchema = z.union([
5236+
z.object({ kind: z.literal('a'), x: z.string() }),
5237+
z.object({ kind: z.literal('b'), y: z.number() })
5238+
]);
5239+
5240+
server.registerTool('pick', { inputSchema }, async () => ({
5241+
content: [{ type: 'text' as const, text: 'ok' }]
5242+
}));
5243+
5244+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
5245+
await server.connect(serverTransport);
5246+
await client.connect(clientTransport);
5247+
5248+
const list = await client.listTools();
5249+
const advertised = list.tools[0].inputSchema as Record<string, unknown>;
5250+
expect(advertised.type).toBe('object');
5251+
expect(advertised.oneOf ?? advertised.anyOf).toBeDefined();
5252+
});
5253+
5254+
test('should expose a discriminated union outputSchema in tools/list', async () => {
5255+
const server = new McpServer({ name: 'test', version: '1.0.0' });
5256+
const client = new Client({ name: 'test-client', version: '1.0.0' });
5257+
5258+
const outputSchema = z.discriminatedUnion('kind', [
5259+
z.object({ kind: z.literal('ok'), data: z.string() }),
5260+
z.object({ kind: z.literal('err'), message: z.string() })
5261+
]);
5262+
5263+
server.registerTool(
5264+
'maybe',
5265+
{
5266+
inputSchema: z.object({ should_fail: z.boolean() }),
5267+
outputSchema
5268+
},
5269+
async ({ should_fail }) => {
5270+
const structured = should_fail ? { kind: 'err' as const, message: 'oops' } : { kind: 'ok' as const, data: 'fine' };
5271+
return {
5272+
content: [{ type: 'text' as const, text: JSON.stringify(structured) }],
5273+
structuredContent: structured
5274+
};
5275+
}
5276+
);
5277+
5278+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
5279+
await server.connect(serverTransport);
5280+
await client.connect(clientTransport);
5281+
5282+
const list = await client.listTools();
5283+
const advertised = list.tools[0].outputSchema as Record<string, unknown> | undefined;
5284+
expect(advertised).toBeDefined();
5285+
expect(advertised!.type).toBe('object');
5286+
expect(advertised!.oneOf ?? advertised!.anyOf).toBeDefined();
5287+
5288+
const ok = await client.callTool({ name: 'maybe', arguments: { should_fail: false } });
5289+
expect(ok.isError).toBeFalsy();
5290+
});
51855291
});
51865292

51875293
describe('Tools with transformation schemas', () => {

0 commit comments

Comments
 (0)