Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tool-argument-protocol-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@modelcontextprotocol/server": patch
---

Return protocol errors for invalid tool arguments.
7 changes: 5 additions & 2 deletions packages/server/src/server/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,11 @@ export class McpServer {
await this.validateToolOutput(tool, result, request.params.name);
return result;
} catch (error) {
if (error instanceof ProtocolError && error.code === ProtocolErrorCode.UrlElicitationRequired) {
throw error; // Return the error to the caller without wrapping in CallToolResult
if (
error instanceof ProtocolError &&
(error.code === ProtocolErrorCode.UrlElicitationRequired || error.message.startsWith('Input validation error:'))
) {
throw error;
}
return this.createToolError(error instanceof Error ? error.message : String(error));
}
Expand Down
44 changes: 43 additions & 1 deletion packages/server/test/server/mcp.compat.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { JSONRPCMessage } from '@modelcontextprotocol/core';
import { InMemoryTransport, isStandardSchema, LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/core';
import { InMemoryTransport, isStandardSchema, LATEST_PROTOCOL_VERSION, ProtocolErrorCode } from '@modelcontextprotocol/core';
import { describe, expect, expectTypeOf, it, vi } from 'vitest';
import * as z from 'zod/v4';
import { McpServer } from '../../src/index.js';
Expand Down Expand Up @@ -119,6 +119,48 @@ describe('registerTool/registerPrompt accept raw Zod shape (auto-wrapped)', () =

await server.close();
});

it('returns a protocol error for invalid tool arguments', async () => {
const server = new McpServer({ name: 't', version: '1.0.0' });

server.registerTool('echo', { inputSchema: { x: z.number() } }, async ({ x }) => ({
content: [{ type: 'text' as const, text: String(x) }]
}));

const [client, srv] = InMemoryTransport.createLinkedPair();
await server.connect(srv);
await client.start();

const responses: JSONRPCMessage[] = [];
client.onmessage = m => responses.push(m);

await client.send({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: LATEST_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'c', version: '1.0.0' }
}
} as JSONRPCMessage);
await client.send({ jsonrpc: '2.0', method: 'notifications/initialized' } as JSONRPCMessage);
await client.send({
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: { name: 'echo', arguments: { x: 'nope' } }
} as JSONRPCMessage);

await vi.waitFor(() => expect(responses.some(r => 'id' in r && r.id === 2)).toBe(true));

const response = responses.find(r => 'id' in r && r.id === 2) as { error?: { code: number; message: string }; result?: unknown };
expect(response.result).toBeUndefined();
expect(response.error?.code).toBe(ProtocolErrorCode.InvalidParams);
expect(response.error?.message).toContain('Invalid arguments for tool echo');

await server.close();
});
});

describe('InferRawShape', () => {
Expand Down
19 changes: 4 additions & 15 deletions test/e2e/requirements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -452,8 +452,7 @@ export const REQUIREMENTS: Record<string, Requirement> = {
},
'mcpserver:tool:input-validation': {
source: 'sdk',
behavior:
"Arguments that fail the tool's input validation produce a tool execution error (isError true with the validation failure described in content) without invoking the function."
behavior: "Arguments that fail the tool's input validation are rejected with JSON-RPC -32602 without invoking the function."
},
'mcpserver:tool:naming-validation': {
source: 'sdk',
Expand All @@ -467,7 +466,7 @@ export const REQUIREMENTS: Record<string, Requirement> = {
'typescript:mcpserver:tool:schema-variants': {
source: 'sdk',
behavior:
'inputSchema accepts Zod union, intersection, nested-object, preprocess, transform, and pipe schemas; validation/coercion runs before the handler.'
'inputSchema accepts Zod union, intersection, nested-object, preprocess, transform, and pipe schemas; validation/coercion runs before the handler, and invalid arguments reject with JSON-RPC -32602.'
},
'client:call-tool:compat-result-schema': {
source: 'sdk',
Expand Down Expand Up @@ -2109,12 +2108,7 @@ export const REQUIREMENTS: Record<string, Requirement> = {
'standardschema:tool:invalid-args-rejected': {
source: 'sdk',
behavior:
'tools/call arguments that fail the registered Standard Schema validation are rejected with JSON-RPC -32602 (Input validation error) and the tool handler is not invoked.',
knownFailures: [
{
note: "McpServer's tools/call handler catches the input-validation ProtocolError (-32602) and returns it as an isError result, so callTool() resolves instead of rejecting; the handler is still not invoked."
}
]
'tools/call arguments that fail the registered Standard Schema validation are rejected with JSON-RPC -32602 (Input validation error) and the tool handler is not invoked.'
},
'validators:from-json-schema:tool-roundtrip': {
source: 'sdk',
Expand All @@ -2124,12 +2118,7 @@ export const REQUIREMENTS: Record<string, Requirement> = {
'validators:from-json-schema:invalid-args-rejected': {
source: 'sdk',
behavior:
'tools/call arguments violating the JSON Schema wrapped by fromJsonSchema() are rejected with JSON-RPC -32602 and the handler is not invoked.',
knownFailures: [
{
note: "McpServer's tools/call handler catches the input-validation ProtocolError (-32602) and returns it as an isError result, so callTool() resolves instead of rejecting; the handler is still not invoked."
}
]
'tools/call arguments violating the JSON Schema wrapped by fromJsonSchema() are rejected with JSON-RPC -32602 and the handler is not invoked.'
},
'validators:custom-validator:override': {
source: 'sdk',
Expand Down
36 changes: 21 additions & 15 deletions test/e2e/scenarios/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1064,14 +1064,16 @@ verifies('mcpserver:tool:input-validation', async ({ transport }: TestArgs) => {
expect(ok.isError).toBeFalsy();
expect(handlerCalls.n).toBe(1);

const wrongType = await client.callTool({ name: 'typed', arguments: { prompt: 123 } });
expect(wrongType.isError).toBe(true);
expect(wrongType.content).toEqual([{ type: 'text', text: expect.stringMatching(/invalid|validation/i) }]);
await expect(client.callTool({ name: 'typed', arguments: { prompt: 123 } })).rejects.toMatchObject({
code: ProtocolErrorCode.InvalidParams,
message: expect.stringMatching(/input validation error/i)
});
expect(handlerCalls.n).toBe(1);

const missing = await client.callTool({ name: 'typed', arguments: {} });
expect(missing.isError).toBe(true);
expect(missing.content).toEqual([{ type: 'text', text: expect.stringMatching(/invalid|validation|required/i) }]);
await expect(client.callTool({ name: 'typed', arguments: {} })).rejects.toMatchObject({
code: ProtocolErrorCode.InvalidParams,
message: expect.stringMatching(/input validation error/i)
});
expect(handlerCalls.n).toBe(1);
});

Expand Down Expand Up @@ -1199,15 +1201,19 @@ verifies('typescript:mcpserver:tool:schema-variants', async ({ transport }: Test
const coerced = await client.callTool({ name: 'zod-coerce', arguments: { n: ' 7 ' } });
expect(coerced.content).toEqual([{ type: 'text', text: 'coerced:7' }]);

// Rejections — proves parse() actually runs for each shape.
const unionRejected = await client.callTool({ name: 'zod-union', arguments: { kind: 'a', a: 123 } });
expect(unionRejected.isError).toBe(true);
const intersectionRejected = await client.callTool({ name: 'zod-intersection', arguments: { left: 'L' } });
expect(intersectionRejected.isError).toBe(true);
const nestedRejected = await client.callTool({ name: 'zod-nested', arguments: { outer: { inner: { value: 'x' } } } });
expect(nestedRejected.isError).toBe(true);
const coerceRejected = await client.callTool({ name: 'zod-coerce', arguments: { n: '-3' } });
expect(coerceRejected.isError).toBe(true);
// Rejections prove parse() actually runs for each shape.
await expect(client.callTool({ name: 'zod-union', arguments: { kind: 'a', a: 123 } })).rejects.toMatchObject({
code: ProtocolErrorCode.InvalidParams
});
await expect(client.callTool({ name: 'zod-intersection', arguments: { left: 'L' } })).rejects.toMatchObject({
code: ProtocolErrorCode.InvalidParams
});
await expect(client.callTool({ name: 'zod-nested', arguments: { outer: { inner: { value: 'x' } } } })).rejects.toMatchObject({
code: ProtocolErrorCode.InvalidParams
});
await expect(client.callTool({ name: 'zod-coerce', arguments: { n: '-3' } })).rejects.toMatchObject({
code: ProtocolErrorCode.InvalidParams
});
});

verifies('typescript:mcpserver:tool:extra', async ({ transport }: TestArgs) => {
Expand Down
131 changes: 65 additions & 66 deletions test/integration/test/server/mcp.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,37 @@
import { Client } from '@modelcontextprotocol/client';
import type { Notification, TextContent } from '@modelcontextprotocol/core';
import { getDisplayName, InMemoryTransport, ProtocolErrorCode, UriTemplate, UrlElicitationRequiredError } from '@modelcontextprotocol/core';
import {
getDisplayName,
InMemoryTransport,
ProtocolError,
ProtocolErrorCode,
UriTemplate,
UrlElicitationRequiredError
} from '@modelcontextprotocol/core';
import { completable, McpServer, ResourceTemplate } from '@modelcontextprotocol/server';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as z from 'zod/v4';

async function expectInvalidToolArguments(request: Promise<unknown>, expectedMessages: Array<string | RegExp>) {
let error: unknown;
try {
await request;
} catch (error_) {
error = error_;
}

expect(error).toBeInstanceOf(ProtocolError);
const protocolError = error as ProtocolError;
expect(protocolError.code).toBe(ProtocolErrorCode.InvalidParams);
for (const expected of expectedMessages) {
if (typeof expected === 'string') {
expect(protocolError.message).toContain(expected);
} else {
expect(protocolError.message).toMatch(expected);
}
}
}

describe('Zod v4', () => {
describe('McpServer', () => {
/***
Expand Down Expand Up @@ -1189,25 +1216,18 @@ describe('Zod v4', () => {

await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]);

const result = await client.request({
method: 'tools/call',
params: {
name: 'test',
arguments: {
await expectInvalidToolArguments(
client.request({
method: 'tools/call',
params: {
name: 'test',
value: 'not a number'
}
}
});

expect(result.isError).toBe(true);
expect(result.content).toEqual(
expect.arrayContaining([
{
type: 'text',
text: expect.stringContaining('Input validation error: Invalid arguments for tool test')
arguments: {
name: 'test',
value: 'not a number'
}
}
])
}),
['Input validation error: Invalid arguments for tool test']
);
});

Expand Down Expand Up @@ -4986,22 +5006,15 @@ describe('Zod v4', () => {
await server.connect(serverTransport);
await client.connect(clientTransport);

const invalidTypeResult = await client.callTool({
name: 'union-test',
arguments: {
type: 'a',
value: 123
}
});

expect(invalidTypeResult.isError).toBe(true);
expect(invalidTypeResult.content).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: 'text',
text: expect.stringContaining('Input validation error')
})
])
await expectInvalidToolArguments(
client.callTool({
name: 'union-test',
arguments: {
type: 'a',
value: 123
}
}),
['Input validation error']
);
});
});
Expand Down Expand Up @@ -6244,40 +6257,26 @@ describe('Zod v4', () => {
await server.connect(serverTransport);
await client.connect(clientTransport);

const invalidTypeResult = await client.callTool({
name: 'union-test',
arguments: {
type: 'a',
value: 123
}
});

expect(invalidTypeResult.isError).toBe(true);
expect(invalidTypeResult.content).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: 'text',
text: expect.stringContaining('Input validation error')
})
])
await expectInvalidToolArguments(
client.callTool({
name: 'union-test',
arguments: {
type: 'a',
value: 123
}
}),
['Input validation error']
);

const invalidDiscriminatorResult = await client.callTool({
name: 'union-test',
arguments: {
type: 'c',
value: 'test'
}
});

expect(invalidDiscriminatorResult.isError).toBe(true);
expect(invalidDiscriminatorResult.content).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: 'text',
text: expect.stringContaining('Input validation error')
})
])
await expectInvalidToolArguments(
client.callTool({
name: 'union-test',
arguments: {
type: 'c',
value: 'test'
}
}),
['Input validation error']
);
});
});
Expand Down
Loading
Loading