Skip to content

Commit 1534a33

Browse files
committed
fix: getParseErrorMessage now surfaces custom Zod v4 error messages
In Zod v4, `error.message` is a JSON serialization of the issues array rather than a user-facing string. The previous implementation prioritized `error.message`, which caused custom error messages defined via `.min(1, 'My custom error')` or custom error maps to be swallowed — callers saw a raw JSON blob instead of the human-readable message. Fix by extracting messages from `error.issues` first, falling back to `error.message` only when no issue messages are available. Also update call sites in `client.ts` and `mcp.ts` that were hand-rolling `issues.map(i => i.message).join(', ')` to use `getParseErrorMessage` consistently. Closes modelcontextprotocol#1415
1 parent 108f2f3 commit 1534a33

4 files changed

Lines changed: 133 additions & 4 deletions

File tree

‎packages/client/src/client/client.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import {
4747
ElicitResultSchema,
4848
EmptyResultSchema,
4949
GetPromptResultSchema,
50+
getParseErrorMessage,
5051
InitializeResultSchema,
5152
LATEST_PROTOCOL_VERSION,
5253
ListChangedOptionsBaseSchema,
@@ -1004,7 +1005,7 @@ export class Client extends Protocol<ClientContext> {
10041005
// Validate options using Zod schema (validates autoRefresh and debounceMs)
10051006
const parseResult = parseSchema(ListChangedOptionsBaseSchema, options);
10061007
if (!parseResult.success) {
1007-
throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
1008+
throw new Error(`Invalid ${listType} listChanged options: ${getParseErrorMessage(parseResult.error)}`);
10081009
}
10091010

10101011
// Validate callback

‎packages/core/src/util/schema.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,20 @@ export function unwrapOptionalSchema(schema: AnySchema): AnySchema {
9292
const candidate = schema as { def?: { innerType?: AnySchema } };
9393
return candidate.def?.innerType ?? schema;
9494
}
95+
96+
/**
97+
* Extracts error message from a Zod parse error result.
98+
* In Zod v4, error.message is a JSON serialization of issues rather than a
99+
* user-facing message, so prefer individual issue messages when available.
100+
*/
101+
export function getParseErrorMessage(error: z.core.$ZodError): string {
102+
const issueMessages = error.issues
103+
.map((issue: { message?: string }) => issue.message?.trim())
104+
.filter((message): message is string => Boolean(message));
105+
106+
if (issueMessages.length > 0) {
107+
return issueMessages.join(', ');
108+
}
109+
110+
return error.message;
111+
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/**
2+
* Tests for schema utility functions
3+
*/
4+
5+
import { describe, expect, test } from 'vitest';
6+
import * as z from 'zod/v4';
7+
import { getParseErrorMessage, parseSchema } from '../../src/util/schema.js';
8+
9+
describe('getParseErrorMessage', () => {
10+
test('should preserve custom error messages from Zod v4', () => {
11+
const schema = z.object({
12+
name: z.string().min(1, 'Name is required'),
13+
email: z.string().email('Please provide a valid email address'),
14+
age: z.number().min(18, 'Must be at least 18 years old')
15+
});
16+
17+
// Test with invalid data that should trigger custom errors
18+
const parseResult = parseSchema(schema, {
19+
name: '',
20+
email: 'invalid-email',
21+
age: 16
22+
});
23+
24+
expect(parseResult.success).toBe(false);
25+
if (!parseResult.success) {
26+
const errorMessage = getParseErrorMessage(parseResult.error);
27+
28+
// The error message should contain our custom messages
29+
expect(errorMessage).toContain('Name is required');
30+
expect(errorMessage).toContain('Please provide a valid email address');
31+
expect(errorMessage).toContain('Must be at least 18 years old');
32+
}
33+
});
34+
35+
test('should handle single custom error message', () => {
36+
const schema = z.string().min(1, 'My custom error');
37+
38+
const parseResult = parseSchema(schema, '');
39+
40+
expect(parseResult.success).toBe(false);
41+
if (!parseResult.success) {
42+
const errorMessage = getParseErrorMessage(parseResult.error);
43+
expect(errorMessage).toBe('My custom error');
44+
}
45+
});
46+
47+
test('should fall back to default error messages when no custom message is provided', () => {
48+
const schema = z.string().min(5); // No custom message
49+
50+
const parseResult = parseSchema(schema, 'abc');
51+
52+
expect(parseResult.success).toBe(false);
53+
if (!parseResult.success) {
54+
const errorMessage = getParseErrorMessage(parseResult.error);
55+
// Should contain some error message (exact wording may vary)
56+
expect(errorMessage).toBeTruthy();
57+
expect(errorMessage.length).toBeGreaterThan(0);
58+
}
59+
});
60+
61+
test('should handle nested object validation errors', () => {
62+
const schema = z.object({
63+
user: z.object({
64+
profile: z.object({
65+
displayName: z.string().min(1, 'Display name cannot be empty')
66+
})
67+
})
68+
});
69+
70+
const parseResult = parseSchema(schema, {
71+
user: {
72+
profile: {
73+
displayName: ''
74+
}
75+
}
76+
});
77+
78+
expect(parseResult.success).toBe(false);
79+
if (!parseResult.success) {
80+
const errorMessage = getParseErrorMessage(parseResult.error);
81+
expect(errorMessage).toContain('Display name cannot be empty');
82+
}
83+
});
84+
85+
test('should prefer issue messages over Zod v4 JSON error.message output', () => {
86+
const schema = z.string().min(1, 'Custom error message');
87+
88+
const parseResult = parseSchema(schema, '');
89+
90+
expect(parseResult.success).toBe(false);
91+
if (!parseResult.success) {
92+
const ourMessage = getParseErrorMessage(parseResult.error);
93+
const zodMessage = parseResult.error.message;
94+
95+
expect(zodMessage).toContain('"message": "Custom error message"');
96+
expect(ourMessage).toBe('Custom error message');
97+
expect(ourMessage).not.toBe(zodMessage);
98+
}
99+
});
100+
101+
test('should fall back to error.message when issues do not contain usable messages', () => {
102+
const fallbackMessage = 'Serialized Zod failure';
103+
const error = {
104+
issues: [{ message: ' ' }, {}],
105+
message: fallbackMessage
106+
} as unknown as z.core.$ZodError;
107+
108+
expect(getParseErrorMessage(error)).toBe(fallbackMessage);
109+
});
110+
});

‎packages/server/src/server/mcp.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import type {
3232
import {
3333
assertCompleteRequestPrompt,
3434
assertCompleteRequestResourceTemplate,
35+
getParseErrorMessage,
3536
getSchemaDescription,
3637
getSchemaShape,
3738
isOptionalSchema,
@@ -258,7 +259,7 @@ export class McpServer {
258259

259260
const parseResult = await parseSchemaAsync(tool.inputSchema, args ?? {});
260261
if (!parseResult.success) {
261-
const errorMessage = parseResult.error.issues.map((i: { message: string }) => i.message).join(', ');
262+
const errorMessage = getParseErrorMessage(parseResult.error);
262263
throw new ProtocolError(
263264
ProtocolErrorCode.InvalidParams,
264265
`Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`
@@ -295,7 +296,7 @@ export class McpServer {
295296
// if the tool has an output schema, validate structured content
296297
const parseResult = await parseSchemaAsync(tool.outputSchema, result.structuredContent);
297298
if (!parseResult.success) {
298-
const errorMessage = parseResult.error.issues.map((i: { message: string }) => i.message).join(', ');
299+
const errorMessage = getParseErrorMessage(parseResult.error);
299300
throw new ProtocolError(
300301
ProtocolErrorCode.InvalidParams,
301302
`Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`
@@ -1262,7 +1263,7 @@ function createPromptHandler(
12621263
return async (args, ctx) => {
12631264
const parseResult = await parseSchemaAsync(argsSchema, args);
12641265
if (!parseResult.success) {
1265-
const errorMessage = parseResult.error.issues.map((i: { message: string }) => i.message).join(', ');
1266+
const errorMessage = getParseErrorMessage(parseResult.error);
12661267
throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${errorMessage}`);
12671268
}
12681269
return typedCallback(parseResult.data as SchemaOutput<AnySchema>, ctx);

0 commit comments

Comments
 (0)