Skip to content
Merged
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
10 changes: 10 additions & 0 deletions .changeset/29135-mcp-malformed-params-invalid-params.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/mcp': patch
---

fix(mcp): a request with malformed params answers JSON-RPC -32602 Invalid params naming the param, not -32603 Internal error with a raw Zod issue list

Clause-②: no
Metadata-protocol: none

An MCP request whose `params` fail the method's request schema (`prompts/get` with no `name`, `tools/call` with `{}`, `prompts/get` with `"name": 42`) used to answer `-32603 Internal error` whose message was the serialised Zod issue array: the client was told the server failed, and an agent that retries on Internal error kept retrying a request that could never succeed. It now answers `-32602 Invalid params` with one sentence per problem, such as `params.name is required` or `params.name must be a string`. The same requests stay refused; only the error class and the message change. Both transports (Streamable HTTP and stdio) build their server through one seam, so the answer is the same on either and for every method, including the ones the SDK installs itself (`initialize`). A tool's own argument check (for example `validate_expression` with an unknown `site`) keeps its answer, and an error raised inside a handler keeps its own code.
8 changes: 6 additions & 2 deletions packages/mcp/src/mcp-server-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
metadataPartialListingSentence,
} from './metadata-completeness.js';
import { DEFAULT_SERVER_VERSION } from './package-version.js';
import { createPlatformMcpServer } from './request-params.js';
import { protocolStdout } from './protocol-stdout.js';
import { renderSkillMarkdown, type RenderSkillOptions } from './skill-md.js';
import {
Expand Down Expand Up @@ -1223,7 +1224,9 @@ export class MCPServerRuntime {
...config,
};

this.mcpServer = new McpServer(
// [#29135] Built through the one seam both transports share, so malformed
// params answer -32602 Invalid params rather than -32603 (see request-params.ts).
this.mcpServer = createPlatformMcpServer(
{
name: this.config.name,
version: this.config.version,
Expand Down Expand Up @@ -1830,7 +1833,8 @@ export class MCPServerRuntime {
: undefined;

// Fresh, isolated server per request (stateless).
const server = new McpServer(
// [#29135] The same seam as the long-lived server: malformed params answer -32602.
const server = createPlatformMcpServer(
{ name: this.config.name, version: this.config.version },
{
// [#8034] `tools` is DERIVED, exactly as on the long-lived server:
Expand Down
150 changes: 150 additions & 0 deletions packages/mcp/src/request-params.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, it, expect, afterEach } from 'vitest';
import { PassThrough } from 'node:stream';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
import { GetPromptRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';

import { MCPServerRuntime } from './mcp-server-runtime.js';
import { createPlatformMcpServer } from './request-params.js';
import type { McpDataBridge } from './mcp-http-tools.js';
import type { McpSkillBridge } from './skill-prompts.js';

/**
* A request whose params fail the method's request schema is the CALLER's
* mistake: JSON-RPC -32602 Invalid params with a sentence naming the param,
* never -32603 Internal error carrying the serialised Zod issue list. Driven
* over both real transports, because both build their server through the one
* seam in `request-params.ts`.
*/

const INVALID_PARAMS = -32602;
const INTERNAL_ERROR = -32603;

function makeBridge(): McpDataBridge & McpSkillBridge {
return {
async listObjects() {
return [{ name: 'crm_opportunity', label: 'Opportunity', fieldCount: 1 }];
},
async describeObject(name: string) {
return name === 'crm_opportunity'
? { name, label: 'Opportunity', fields: [{ name: 'amount', type: 'currency', label: 'Amount', required: false }] }
: null;
},
async query() { return { records: [] }; },
async get() { return null; },
async create() { return {}; },
async update() { return {}; },
async remove() { return {}; },
async listSkills() { return []; },
};
}

async function overHttp(method: string, params: unknown): Promise<any> {
const runtime = new MCPServerRuntime({ name: 'request-params', version: '0.0.0' });
const body = { jsonrpc: '2.0', id: 1, method, params };
const res = await runtime.handleHttpRequest(
new Request('http://localhost/api/v1/mcp', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
body: JSON.stringify(body),
}),
{ bridge: makeBridge(), parsedBody: body } as never,
);
return res.json();
}

/** The refusal shape every malformed request must get: the code, the named param, no JSON dump. */
function expectInvalidParams(frame: any, sentence: string): void {
expect(frame.error, JSON.stringify(frame)).toBeDefined();
expect(frame.error.code).toBe(INVALID_PARAMS);
expect(frame.error.message).toBe(`MCP error -32602: ${sentence}`);
}

describe('malformed request params answer -32602 Invalid params (HTTP transport)', () => {
it('prompts/get with no name', async () => {
expectInvalidParams(await overHttp('prompts/get', {}), 'params.name is required');
});

it('tools/call with {}', async () => {
expectInvalidParams(await overHttp('tools/call', {}), 'params.name is required');
});

it('prompts/get with a non-string name', async () => {
expectInvalidParams(await overHttp('prompts/get', { name: 42 }), 'params.name must be a string');
});

it('initialize, a handler the SDK installs in its own constructor, takes the same answer', async () => {
const frame = await overHttp('initialize', { capabilities: {}, clientInfo: { name: 't', version: '1' } });
expectInvalidParams(frame, 'params.protocolVersion is required');
});

it("control: a tool's own argument check keeps its answer", async () => {
const frame = await overHttp('tools/call', {
name: 'validate_expression',
arguments: { objectName: 'crm_opportunity', expression: 'record.amount > 1', site: 'nope' },
});
expect(frame.error).toBeUndefined();
expect(frame.result.isError).toBe(true);
expect(frame.result.content[0].text).toMatch(
/^MCP error -32602: Input validation error: Invalid arguments for tool validate_expression: /,
);
});
});

describe('malformed request params answer -32602 Invalid params (stdio transport)', () => {
const closers: Array<() => Promise<void>> = [];
afterEach(async () => {
for (const close of closers.splice(0)) await close();
});

it('tools/call with {} on the long-lived server', async () => {
const runtime = new MCPServerRuntime({ name: 'request-params', version: '0.0.0' });
runtime.bridgeDataTools(makeBridge());
const stdin = new PassThrough();
const stdout = new PassThrough();
const transport = new StdioServerTransport(stdin, stdout);
await runtime.server.connect(transport);
closers.push(() => transport.close().catch(() => {}));

const frame = await new Promise<any>((resolve) => {
stdout.on('data', (chunk) => {
for (const line of String(chunk).split('\n')) {
if (line.trim()) resolve(JSON.parse(line));
}
});
stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: {} })}\n`);
});
expect(frame.id).toBe(7);
expectInvalidParams(frame, 'params.name is required');
});
});

describe('only the request-schema parse is mapped', () => {
it('a ZodError thrown inside a handler keeps the -32603 answer', async () => {
const server = createPlatformMcpServer({ name: 'request-params', version: '0.0.0' }, { capabilities: { prompts: {} } });
server.server.setRequestHandler(GetPromptRequestSchema, async () => {
z.object({ inner: z.string() }).parse({});
return { messages: [] };
});
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
await server.connect(transport);
const body = { jsonrpc: '2.0', id: 1, method: 'prompts/get', params: { name: 'any' } };
try {
const res = await transport.handleRequest(
new Request('http://localhost/mcp', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
body: JSON.stringify(body),
}),
{ parsedBody: body },
);
const frame = (await res.json()) as { error: { code: number } };
expect(frame.error.code).toBe(INTERNAL_ERROR);
} finally {
await server.close();
}
});
});
134 changes: 134 additions & 0 deletions packages/mcp/src/request-params.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
import { formatZodIssue } from '@objectstack/spec/shared';
import { z } from 'zod';

/**
* The one place the platform builds an MCP {@link McpServer}: both transports
* (the long-lived stdio server and the per-request Streamable HTTP server) go
* through here, so a malformed request gets the same answer on either.
*
* What it adds over `new McpServer(...)`: a request whose `params` fail the
* method's request schema is answered as JSON-RPC `-32602 Invalid params` with
* a sentence naming the param (`params.name is required`), instead of
* `-32603 Internal error` carrying the serialised Zod issue list.
*
* Why the SDK answers -32603 (measured on `@modelcontextprotocol/sdk` 1.32.1,
* and unchanged in 1.32.2): `Protocol.setRequestHandler` installs a closure
* that parses the request with the method's schema and rethrows the ZodError
* as-is. A ZodError has no numeric `code`, so the protocol's error branch
* falls back to `InternalError` with the error's message — the JSON dump. The
* client is told the server failed when its own input was wrong, and an agent
* that treats Internal error as retryable retries a request that can never
* succeed.
*/
export function createPlatformMcpServer(
...args: ConstructorParameters<typeof McpServer>
): McpServer {
const server = new McpServer(...args);
answerMalformedParamsAsInvalidParams(server);
return server;
}

type RequestDispatcher = (request: unknown, extra: unknown) => Promise<unknown>;

/**
* Wraps every request dispatcher the low-level `Server` holds — those the SDK
* installed in its constructor (`initialize`, `ping`, …) and every one
* registered later (`tools/call`, `prompts/get`, `resources/read`, …).
*
* The SDK keeps them in the protocol's `_requestHandlers` map, which it does
* not expose; there is no public hook between the request-schema parse and
* the error answer. The map is read once here, and its absence is loud: a
* later SDK that renames it fails server construction with this function's
* name, never silently goes back to -32603.
*
* Only a parse failure is mapped. The installed dispatcher parses
* SYNCHRONOUSLY and only then calls the async handler, so a ZodError thrown
* synchronously is the request-schema parse and nothing else; a ZodError from
* inside a handler arrives as a rejected promise and keeps its own answer.
*/
function answerMalformedParamsAsInvalidParams(server: McpServer): void {
const handlers = (server.server as unknown as { _requestHandlers?: unknown })._requestHandlers;
if (!(handlers instanceof Map)) {
throw new Error(
'answerMalformedParamsAsInvalidParams: the MCP SDK no longer keeps its request handlers where this '
+ 'server reads them, so malformed params would answer -32603 Internal error instead of -32602 '
+ 'Invalid params. Re-read the SDK Protocol request path and move this seam.',
);
}
const map = handlers as Map<string, RequestDispatcher>;

const guard = (dispatch: RequestDispatcher): RequestDispatcher => (request, extra) => {
try {
return dispatch(request, extra);
} catch (error) {
if (isZodError(error)) {
throw new McpError(ErrorCode.InvalidParams, invalidParamsSentence(error.issues, request));
}
throw error;
}
};

for (const [method, dispatch] of map) map.set(method, guard(dispatch));
const set = map.set.bind(map);
map.set = (method, dispatch) => set(method, guard(dispatch));
}

interface ZodIssueLike {
code: string;
path: PropertyKey[];
message: string;
expected?: unknown;
values?: unknown[];
keys?: string[];
}

/**
* The SDK parses with zod's core (`$ZodError`, not classic `ZodError`), so the
* check is zod's own structural `instanceof` on the core class, which holds
* across both builds.
*/
function isZodError(error: unknown): error is { issues: ZodIssueLike[] } {
return error instanceof z.core.$ZodError;
}

/**
* One plain-English sentence per issue, joined with `; ` (`McpError` itself
* prefixes `MCP error -32602:`): `params.name is
* required`, `params.name must be a string`. The path is the request's own
* (`params.…`), so it names exactly what the caller sent. An issue outside the
* two shapes above falls back to the platform's shared Zod issue formatter.
*/
export function invalidParamsSentence(issues: readonly ZodIssueLike[], request: unknown): string {
const sentences = issues.map((issue) => {
const path = issue.path.length > 0 ? issue.path.map(String).join('.') : 'params';
if (issue.code === 'invalid_type') {
if (valueAt(request, issue.path) === undefined) return `${path} is required`;
if (typeof issue.expected === 'string') return `${path} must be ${article(issue.expected)}`;
}
if (issue.code === 'invalid_value' && Array.isArray(issue.values) && issue.values.length > 0) {
return `${path} must be one of ${issue.values.map((v) => JSON.stringify(v)).join(', ')}`;
}
if (issue.code === 'unrecognized_keys' && Array.isArray(issue.keys)) {
return `${path} has unrecognized key(s): ${issue.keys.join(', ')}`;
}
return formatZodIssue(issue as Parameters<typeof formatZodIssue>[0]);
});
return sentences.join('; ');
}

function valueAt(root: unknown, path: readonly PropertyKey[]): unknown {
let node: unknown = root;
for (const key of path) {
if (typeof node !== 'object' || node === null) return undefined;
node = (node as Record<PropertyKey, unknown>)[key];
}
return node;
}

function article(type: string): string {
return /^[aeiou]/.test(type) ? `an ${type}` : `a ${type}`;
}
Loading