diff --git a/.changeset/37411-mcp-schema-refusal-coded.md b/.changeset/37411-mcp-schema-refusal-coded.md new file mode 100644 index 00000000000..f946878b593 --- /dev/null +++ b/.changeset/37411-mcp-schema-refusal-coded.md @@ -0,0 +1,12 @@ +--- +'@objectstack/mcp': patch +--- + +fix(mcp): a tool argument that fails the published JSON Schema is refused with the platform's coded refusal + +Clause-②: no +Metadata-protocol: none + +On both MCP doors (Streamable HTTP and stdio), a `tools/call` whose arguments fail the tool's published JSON Schema used to come back as the SDK's own text, `MCP error -32602: Input validation error: …`, with no `code` and no `status`, and with every unknown key echoed exactly as sent (a raw newline or NUL included, however many there were). + +It now answers the same coded tool error every other refusal on these doors answers: `isError: true`, one text content holding `{ "error": { "code": "VALIDATION_ERROR", "status": 400, "message": "Invalid arguments for tool NAME: …" } }`. The message still names each problem at its path, and an unknown key's rename advice (`sort` → `orderBy`) is kept. The keys are echoed bounded and sanitised: at most five unknown keys per object are named and the rest are counted, each key is cut at 64 characters, and every control character is written as its escape. A client that matched the `-32602` text should branch on `error.code` instead. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 3cbdf5258a6..1490c423cfa 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -211,7 +211,7 @@ The tool is stricter than the service in a few places, so that a mistake is repo - An empty `scope`, an entry with no ids, and an empty `sourceIds` are refused, not answered with no hits. - An object name, record id or field name over 255 characters, or one holding a NUL character, is refused. -- Each malformed argument is refused `VALIDATION_ERROR` (400), naming the argument. Over MCP, a shape the tool's schema states (an empty or over-long `scope`, a string over 255 characters, an unknown `granularity` or key) is refused first by the MCP input-validation check, as error `-32602` naming the argument, without that code. The coded refusal answers what the schema cannot state, such as a NUL character or `groupBy` with `"chunk"`, and every malformed argument the in-product agent sends. +- Each malformed argument is refused `VALIDATION_ERROR` (400), naming the argument. Over MCP, a shape the tool's schema states (an empty or over-long `scope`, a string over 255 characters, an unknown `granularity` or key) is refused first by the MCP door's schema check, before the tool runs, with the same coded `VALIDATION_ERROR` (400) naming the argument. What the schema cannot state, such as a NUL character or `groupBy` with `"chunk"`, is refused by the tool itself, as is every malformed argument the in-product agent sends. The answer never says how many hits the permission re-check or the scope removed. A `scope` entry or `groupBy` field that only a withheld source would answer gets the same empty answer as one that no source answers, so the answer never shows that a withheld source exists. diff --git a/packages/mcp/src/argument-echo.ts b/packages/mcp/src/argument-echo.ts new file mode 100644 index 00000000000..a8e9867b26e --- /dev/null +++ b/packages/mcp/src/argument-echo.ts @@ -0,0 +1,71 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * How a tool-argument refusal names what the CALLER sent: a key it wrote, or + * a path through its arguments. Both MCP doors (HTTP and stdio) refuse a + * `tools/call` whose arguments fail the tool's published JSON Schema, and the + * refusal names the offending keys so the caller can fix the call. The names + * are the caller's own text, so they are echoed BOUNDED and SANITISED: + * + * - at most {@link MAX_ECHOED_KEYS} unknown keys are named per object, and + * the rest are counted, not listed; + * - each name is cut at {@link MAX_ECHOED_KEY_LENGTH} characters, marked + * with a trailing ellipsis; + * - every control character (C0, DEL, C1, and the two Unicode line + * separators) is written as its `\u` escape, never as the raw character: + * a raw newline or NUL in a key would otherwise reach the client's log + * and screen as it was sent. + * + * The caller sees only its own input, so this is not a disclosure guard; it + * is the platform's refusal convention (a coded, bounded answer) holding on + * the one path where the SDK used to answer by itself. The two halves that + * apply it are `strictToolInput` in `mcp-http-tools.ts` (the platform's own + * tools, whose unknown-key sentence keeps its rename advice) and the schema + * refusal in `request-params.ts` (every tool, whoever registered it). + */ + +/** Unknown keys named per rejected object; the rest are counted. */ +export const MAX_ECHOED_KEYS = 5; + +/** Characters of one echoed key (after escaping) before it is cut. */ +export const MAX_ECHOED_KEY_LENGTH = 64; + +/** C0, DEL, C1, LINE SEPARATOR and PARAGRAPH SEPARATOR. */ +const CONTROL_CHARACTER = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/; + +function escapedCharacter(character: string): string { + return CONTROL_CHARACTER.test(character) + ? `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}` + : character; +} + +/** + * One caller-written name as a refusal may echo it: control characters + * escaped, cut at {@link MAX_ECHOED_KEY_LENGTH} characters with a trailing + * `…`. The cut falls between whole characters, never inside an escape or a + * surrogate pair. A name with nothing to escape or cut comes back unchanged, + * so a plain misspelling (`sort`) is echoed exactly as written. + */ +export function echoedKey(key: string): string { + let out = ''; + for (const character of key) { + const next = escapedCharacter(character); + if (out.length + next.length > MAX_ECHOED_KEY_LENGTH) return `${out}…`; + out += next; + } + return out; +} + +/** + * Server-authored refusal prose with any control character it carries + * escaped, except the newline and tab the prose itself is laid out with. + * A backstop for messages this package did not render: a caller's raw + * control character that reached one is written as its escape. + */ +export function withControlCharactersEscaped(text: string): string { + let out = ''; + for (const character of text) { + out += character === '\n' || character === '\t' ? character : escapedCharacter(character); + } + return out; +} diff --git a/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts index 429c16e6213..7c620b07945 100644 --- a/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts +++ b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts @@ -193,9 +193,10 @@ describe('[#34209] run_action and resume_run refuse the retired confirm member o expect(unknown.result.isError, tool).toBe(true); expect(statementOf(memberText), tool).toBe(statementOf(unknownText)); expect(statementOf(memberText).length, `${tool}: the statement read empty`).toBeGreaterThan(10); - // Not an ADR-0112 envelope: no second code is minted for the member. - expect(memberText, tool).not.toContain('ACTION_CONFIRMATION_REQUIRED","status"'); - expect(() => JSON.parse(memberText), tool).toThrow(); + // No second code is minted for the member: it is the schema refusal's VALIDATION_ERROR (#37411), the + // code the undeclared key gets, never the confirmation gate's. + expect(JSON.parse(memberText).error.code, tool).toBe('VALIDATION_ERROR'); + expect(JSON.parse(unknownText).error.code, tool).toBe('VALIDATION_ERROR'); } }); diff --git a/packages/mcp/src/mcp-dataset-tools.test.ts b/packages/mcp/src/mcp-dataset-tools.test.ts index 552ef03ae4d..c93fe8a2a92 100644 --- a/packages/mcp/src/mcp-dataset-tools.test.ts +++ b/packages/mcp/src/mcp-dataset-tools.test.ts @@ -368,9 +368,10 @@ describe('[ADR-0149 D2] dataset tools on MCP — the spec refusal is kept whole' const json = await callTool(runtime, bridge, LIST_DATASETS_TOOL_NAME, { terms: ['营收'], zzUndeclaredProbeKey: 'x' }); const text = json.error?.message ?? json.result?.content[0]?.text ?? ''; expect(Boolean(json.error) || json.result?.isError === true).toBe(true); - expect(text).toContain('-32602'); - expect(text).toContain('`zzUndeclaredProbeKey`'); - expect(text).toContain(RETIRED_KEY_UPGRADE_GUIDE_SENTENCE); + const { error } = JSON.parse(text); + expect(error.code).toBe('VALIDATION_ERROR'); + expect(error.message).toContain('`zzUndeclaredProbeKey`'); + expect(error.message).toContain(RETIRED_KEY_UPGRADE_GUIDE_SENTENCE); expect(bridge.calls.filter((c) => c[0] === 'listDatasets')).toEqual([]); }); }); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index bf81a274c12..11f20e499ed 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -120,6 +120,7 @@ import type { AuthoredExpressionSite } from '@objectstack/lint'; // the `packages/spec` campaign standardised on — already carried in // `api-surface/shared.json`, so reusing it adds nothing to any public surface. import { strictUnknownKeyError } from '@objectstack/spec/shared'; +import { MAX_ECHOED_KEYS, echoedKey } from './argument-echo.js'; // [#27411] The input schemas the save/build gate parses an expression slot // with. `validate_expression` parses with the SAME schema before it runs the // formula checks, so a blank source gets the gate's verdict and its published @@ -3166,6 +3167,27 @@ function withoutHistorySentence(map: z.core.$ZodErrorMap): z.core.$ZodErrorMap { }; } +/** + * [#37411] Name a rejected object's unknown keys bounded and sanitised + * (`argument-echo.ts`): the factory is handed at most `MAX_ECHOED_KEYS` of + * them, each through {@link echoedKey}, and the rest are counted in one + * closing sentence. The keys the factory sees are the ones it renders AND the + * ones it looks up in the alias table, so a plain misspelling (`sort`) still + * gets its rename advice: {@link echoedKey} hands such a key back unchanged. + * Only the rendering is bounded; the issue's own `keys` are not edited. + */ +function withBoundedKeyEcho(map: z.core.$ZodErrorMap): z.core.$ZodErrorMap { + return (issue) => { + if (issue.code !== 'unrecognized_keys') return map(issue); + const keys: readonly string[] = issue.keys ?? []; + const shown = keys.slice(0, MAX_ECHOED_KEYS).map(echoedKey); + const answer = map({ ...issue, keys: shown }); + const notShown = keys.length - shown.length; + if (typeof answer !== 'string' || notShown <= 0) return answer; + return `${answer} ${notShown} more unrecognized key(s) not shown.`; + }; +} + /** * Close an MCP tool's argument shape against keys it does not declare. * @@ -3249,7 +3271,7 @@ function strictToolInput( ) { return z .object(shape, { - error: withoutHistorySentence(strictUnknownKeyError({ + error: withBoundedKeyEcho(withoutHistorySentence(strictUnknownKeyError({ surface: options.surface, knownKeys: Object.keys(shape), aliases: options.aliases, @@ -3262,7 +3284,7 @@ function strictToolInput( // HERE opt out; the dataset pair takes spec `strictObject` schemas and // keeps the spec refusal. retiredKeyUpgradeGuide: false, - })), + }))), }) .strict(); } diff --git a/packages/mcp/src/mcp-http-tools.unknown-argument-keys.test.ts b/packages/mcp/src/mcp-http-tools.unknown-argument-keys.test.ts index 813720e4b83..3435f3083d3 100644 --- a/packages/mcp/src/mcp-http-tools.unknown-argument-keys.test.ts +++ b/packages/mcp/src/mcp-http-tools.unknown-argument-keys.test.ts @@ -357,7 +357,7 @@ describe('MCP tool arguments — no upgrade-guide pointer, and the recordId hand }); expect(refused).toBe(true); expect(json.result?.isError).toBe(true); - expect(text).toContain('-32602'); + expect(JSON.parse(text).error.code).toBe('VALIDATION_ERROR'); expect(text).toContain('`id` → `recordId`'); expect(text).not.toContain(PROTOCOL_UPGRADE_GUIDE_URL); expect(bridge.calls.find((c: any[]) => c[0] === 'update')).toBeUndefined(); @@ -369,7 +369,7 @@ describe('MCP tool arguments — no upgrade-guide pointer, and the recordId hand filter: { stage: 'open' }, }); expect(refused).toBe(true); - expect(text).toContain('-32602'); + expect(JSON.parse(text).error.code).toBe('VALIDATION_ERROR'); expect(text).toContain('`filter` → `where`'); expect(text).not.toContain(PROTOCOL_UPGRADE_GUIDE_URL); }); diff --git a/packages/mcp/src/mcp-knowledge-tools.test.ts b/packages/mcp/src/mcp-knowledge-tools.test.ts index 544868c418a..dcf7229a999 100644 --- a/packages/mcp/src/mcp-knowledge-tools.test.ts +++ b/packages/mcp/src/mcp-knowledge-tools.test.ts @@ -398,11 +398,12 @@ describe('[ADR-0161 K9] search_knowledge over the real definition — every tran jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args }, })).result as { content: Array<{ text: string }>; isError?: boolean }; expect(search).not.toHaveBeenCalled(); - // The SDK's input-validation refusal (-32602), naming the argument: a schema-stated shape never reaches the - // executor over MCP, so it carries no ADR-0112 code. The coded VALIDATION_ERROR is the executor's own. + // The door's schema refusal, naming the argument: a schema-stated shape never reaches the executor over + // MCP. It carries the platform's coded refusal (#37411), VALIDATION_ERROR as the executor's own does. expect(http.isError).toBe(true); - expect(http.content[0].text).toContain('-32602'); - expect(http.content[0].text).toContain('scope'); + const { error } = JSON.parse(http.content[0].text); + expect(error.code).toBe('VALIDATION_ERROR'); + expect(error.message).toMatch(/ at scope$/); expect(stdio.isError).toBe(true); expect(stdio.content[0].text).toBe(http.content[0].text); }); diff --git a/packages/mcp/src/mcp-record-id-key-mistake-refusal.test.ts b/packages/mcp/src/mcp-record-id-key-mistake-refusal.test.ts index 0c22bd569b8..763956ee54a 100644 --- a/packages/mcp/src/mcp-record-id-key-mistake-refusal.test.ts +++ b/packages/mcp/src/mcp-record-id-key-mistake-refusal.test.ts @@ -55,14 +55,14 @@ * for the new sentence would pass just as well against an implementation that * had added the alias. * - * MINIMUM ASSERTIONS ON A REFUSAL. There is no ADR-0112 envelope on this wire — - * MCP answers a rejected `tools/call` as a TOOL ERROR, so the `code` + `status` - * pair is asserted in this surface's own vocabulary: the protocol code - * `-32602` (invalid params) carried in the message, and `result.isError: true` - * with `error` ABSENT, which is this transport's promise that a refusal is - * returned rather than thrown across the wire. The HTTP status stays `200` - * because JSON-RPC carries its own outcome; that is pinned too, so a later - * change cannot turn a tool error into a transport error unnoticed. + * MINIMUM ASSERTIONS ON A REFUSAL. MCP answers a rejected `tools/call` as a + * TOOL ERROR whose text is the platform's coded refusal (#37411): the + * ADR-0112 `code` + `status` pair is read off that text (`VALIDATION_ERROR`, + * 400), beside `result.isError: true` with `error` ABSENT, which is this + * transport's promise that a refusal is returned rather than thrown across the + * wire. The HTTP status stays `200` because JSON-RPC carries its own outcome; + * that is pinned too, so a later change cannot turn a tool error into a + * transport error unnoticed. * * ⚠️ WHY EVERY KEY ASSERTION USES THE BACKTICK FORM. A bare * `expect(text).toContain('id')` is satisfied by the word **Invalid** in @@ -83,8 +83,12 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' import { MCPServerRuntime } from './mcp-server-runtime.js'; import type { McpActionBridge, McpDataBridge } from './mcp-http-tools.js'; -/** The protocol code for invalid params — the `code` half of the refusal pin. */ -const INVALID_PARAMS = '-32602'; +/** The `code` + `status` half of the refusal pin, read off the tool error's coded text. */ +function expectSchemaRefusal(text: string): void { + const { error } = JSON.parse(text); + expect(error.code).toBe('VALIDATION_ERROR'); + expect(error.status).toBe(400); +} /** The record id from the card's recording, kept so the repro reads as itself. */ const RECORD_ID = '_IFp-Bf8yQcrfV8o'; @@ -168,7 +172,7 @@ describe('#17568 a missing required key names the unexpected key that was sent', // The refusal pin's `code` + `status` half, in this surface's vocabulary. expect(refused).toBe(true); - expect(text).toContain(INVALID_PARAMS); + expectSchemaRefusal(text); expect(protocolError).toBeUndefined(); expect(status).toBe(200); @@ -222,7 +226,7 @@ describe('#17568 a missing required key names the unexpected key that was sent', data: { status: 'qualified' }, }); expect(refused).toBe(true); - expect(text).toContain(INVALID_PARAMS); + expectSchemaRefusal(text); expect(text).toContain('recordId'); // There is no offending key, so nothing is quoted as one. Asserted as the // ABSENCE OF ANY quoted key rather than of one particular sentence: an @@ -259,7 +263,7 @@ describe('#17568 a missing required key names the unexpected key that was sent', id: RECORD_ID, }); expect(refused).toBe(true); - expect(text).toContain(INVALID_PARAMS); + expectSchemaRefusal(text); expect(text).toContain('recordId'); expect(text).toContain('`id`'); expect(text).toContain('`recordId`'); @@ -379,7 +383,7 @@ describe('#17568 the same refusal arrives over the stdio transport', () => { const text = String(frame.result?.content?.map((c: { text?: string }) => c.text).join('\n') ?? ''); expect(frame.result?.isError).toBe(true); expect(frame.error).toBeUndefined(); - expect(text).toContain(INVALID_PARAMS); + expectSchemaRefusal(text); expect(text).toContain('recordId'); expect(text).toContain('`id`'); expect(text).toContain('`recordId`'); diff --git a/packages/mcp/src/request-params.test.ts b/packages/mcp/src/request-params.test.ts index c8f9da183b9..303c2b5d757 100644 --- a/packages/mcp/src/request-params.test.ts +++ b/packages/mcp/src/request-params.test.ts @@ -81,15 +81,15 @@ describe('malformed request params answer -32602 Invalid params (HTTP transport) expectInvalidParams(frame, 'params.protocolVersion is required'); }); - it("control: a tool's own argument check keeps its answer", async () => { + it("control: a tool's own argument check stays a tool error, not a JSON-RPC error", 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: /, + expect(JSON.parse(frame.result.content[0].text).error.message).toMatch( + /^Invalid arguments for tool validate_expression: /, ); }); }); @@ -148,3 +148,86 @@ describe('only the request-schema parse is mapped', () => { } }); }); + +/** + * [#37411] A `tools/call` whose ARGUMENTS fail the tool's published JSON + * Schema is refused with the platform's coded refusal on both doors, not the + * SDK's bare `MCP error -32602: Input validation error` text, and the unknown + * keys it names are the caller's own text echoed bounded and sanitised: a + * capped count, each key cut, every control character written as its escape. + */ +describe('a tool argument that fails the published schema answers the coded refusal', () => { + const closers: Array<() => Promise> = []; + afterEach(async () => { + for (const close of closers.splice(0)) await close(); + }); + + /** A wrong type, plus nine unknown keys that each carry a newline, a NUL and a long tail. */ + function failingArguments(): Record { + const args: Record = { objectName: 42, expression: 'record.amount > 1' }; + for (let i = 0; i < 9; i++) args[`junk_${i}\n\u0000${'x'.repeat(60)}`] = i; + return args; + } + + function expectCodedArgumentRefusal(result: any): void { + expect(result.isError, JSON.stringify(result)).toBe(true); + expect(result.content).toHaveLength(1); + const text: string = result.content[0].text; + expect(text).not.toContain('MCP error -32602'); + const { error } = JSON.parse(text); + expect(error.code).toBe('VALIDATION_ERROR'); + expect(error.status).toBe(400); + const message: string = error.message; + expect(message).toMatch(/^Invalid arguments for tool validate_expression: /); + // The wrong type is named at its path. + expect(message).toMatch(/expected string, received number at objectName/); + // A capped count: five keys named, the other four counted. + expect(message.match(/junk_\d/g)).toEqual(['junk_0', 'junk_1', 'junk_2', 'junk_3', 'junk_4']); + expect(message).toContain('4 more unrecognized key(s) not shown.'); + // Sanitised and cut: the newline and the NUL are escapes, and the key stops at 64 characters. + expect(message).toContain(`\`junk_0\\u000a\\u0000${'x'.repeat(46)}…\``); + expect(message).not.toMatch(/[\u0000-\u0009\u000b-\u001f\u007f]/); + } + + it('over HTTP', async () => { + const frame = await overHttp('tools/call', { name: 'validate_expression', arguments: failingArguments() }); + expect(frame.error).toBeUndefined(); + expectCodedArgumentRefusal(frame.result); + }); + + it('over stdio, 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((resolve) => { + let buffered = ''; + stdout.on('data', (chunk) => { + buffered += String(chunk); + const lines = buffered.split('\n'); + buffered = lines.pop() ?? ''; + for (const line of lines) if (line.trim()) resolve(JSON.parse(line)); + }); + const call = { name: 'validate_expression', arguments: failingArguments() }; + stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 8, method: 'tools/call', params: call })}\n`); + }); + expect(frame.id).toBe(8); + expect(frame.error).toBeUndefined(); + expectCodedArgumentRefusal(frame.result); + }); + + it('a plain misspelling is still echoed as written, with its rename advice', async () => { + const frame = await overHttp('tools/call', { + name: 'query_records', + arguments: { objectName: 'crm_opportunity', sort: [{ field: 'amount', order: 'desc' }] }, + }); + const { error } = JSON.parse(frame.result.content[0].text); + expect(error.code).toBe('VALIDATION_ERROR'); + expect(error.message).toContain('`sort` → `orderBy`'); + expect(error.message).not.toContain('not shown'); + }); +}); diff --git a/packages/mcp/src/request-params.ts b/packages/mcp/src/request-params.ts index d548fe070be..b7488a32f32 100644 --- a/packages/mcp/src/request-params.ts +++ b/packages/mcp/src/request-params.ts @@ -1,10 +1,15 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { normalizeObjectSchema, safeParseAsync } from '@modelcontextprotocol/sdk/server/zod-compat.js'; import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'; +import { StandardErrorCode } from '@objectstack/spec/api'; import { formatZodIssue } from '@objectstack/spec/shared'; import { z } from 'zod'; +import { echoedKey, withControlCharactersEscaped } from './argument-echo.js'; +import { codedErrorResult } from './mcp-http-tools.js'; + /** * 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 @@ -23,15 +28,131 @@ import { z } from 'zod'; * 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. + * + * [#37411] And a `tools/call` whose ARGUMENTS fail the tool's published JSON + * Schema is answered with the platform's coded refusal + * ({@link answerToolArgumentRefusalsWithCode}), not the SDK's bare + * `MCP error -32602: Input validation error` text. */ export function createPlatformMcpServer( ...args: ConstructorParameters ): McpServer { const server = new McpServer(...args); answerMalformedParamsAsInvalidParams(server); + answerToolArgumentRefusalsWithCode(server); return server; } +type RegisteredToolLike = { inputSchema?: unknown }; +type ToolInputValidator = (tool: RegisteredToolLike, args: unknown, toolName: string) => Promise; + +/** Problems named per refusal; the rest are counted. */ +const MAX_REFUSAL_ISSUES = 10; + +/** Characters of one refusal's message before it is cut. */ +const MAX_REFUSAL_MESSAGE_LENGTH = 2000; + +/** + * [#37411] A `tools/call` whose arguments fail the tool's published JSON + * Schema is the caller's mistake, refused before the tool runs. The SDK + * refuses it by itself (`McpServer.validateToolInput`, measured on + * `@modelcontextprotocol/sdk` 1.32.1): it throws `McpError(InvalidParams)` + * and its `tools/call` handler turns the message into a tool error, so the + * client read `MCP error -32602: Input validation error: …` with no `code` + * and no `status`, and every unknown key echoed as it was sent (a raw newline + * or NUL included, however many there were). Every other refusal a tool + * answers carries the platform's coded shape ({@link codedErrorResult}), so + * an AI client could branch on all of them but this one. + * + * Now the same failure answers the coded shape on both doors, because both + * build their server here: `VALIDATION_ERROR`, status 400 (the status a REST + * door answers a body that fails its schema with), and a message that names + * each problem bounded and sanitised (`argument-echo.ts`): at most + * {@link MAX_REFUSAL_ISSUES} problems, caller-written keys and paths escaped + * and cut, and the whole message cut at {@link MAX_REFUSAL_MESSAGE_LENGTH}. + * It is still a tool error (`isError: true`, one text content), never a + * JSON-RPC error, as every refusal on this surface is. + * + * How: the SDK's own validator runs first and decides. Only when it refuses + * with `InvalidParams` are the arguments parsed again, the way it parses them, + * to read the issues its message flattened; a refusal the schema parse does + * not reproduce (the SDK's argument-size cap) keeps the SDK's answer. A + * successful call is parsed once, as before. The refusal leaves as a plain + * `Error` whose message IS the coded result's text: the SDK hands a thrown + * message to its tool-error builder verbatim, which yields exactly the result + * {@link codedErrorResult} builds. + * + * `validateToolInput` is private to the SDK and read once here; its absence + * is loud, as the request-handler seam's is: a later SDK that renames it + * fails server construction naming this function, never silently goes back + * to the uncoded answer. + */ +function answerToolArgumentRefusalsWithCode(server: McpServer): void { + const target = server as unknown as { validateToolInput?: ToolInputValidator }; + const validate = target.validateToolInput; + if (typeof validate !== 'function') { + throw new Error( + 'answerToolArgumentRefusalsWithCode: the MCP SDK no longer validates tool arguments where this server ' + + 'reads it, so a tool argument that fails its schema would be refused without the platform\'s code. ' + + 'Re-read the SDK tools/call path and move this seam.', + ); + } + target.validateToolInput = async (tool, args, toolName) => { + try { + return await validate.call(server, tool, args, toolName); + } catch (error) { + if (!(error instanceof McpError) || error.code !== ErrorCode.InvalidParams) throw error; + const issues = await schemaIssuesOf(tool, args); + if (issues === undefined) throw error; + throw new Error(toolArgumentRefusalText(toolName, issues)); + } + }; +} + +/** The issues the tool's input schema finds in `args`, parsed as the SDK parses them; `undefined` when it finds none. */ +async function schemaIssuesOf(tool: RegisteredToolLike, args: unknown): Promise { + if (tool?.inputSchema === undefined) return undefined; + const schema = (normalizeObjectSchema(tool.inputSchema as never) ?? tool.inputSchema) as Parameters[0]; + const parsed = await safeParseAsync(schema, args ?? {}); + if (parsed.success) return undefined; + const issues = (parsed.error as { issues?: unknown } | undefined)?.issues; + return Array.isArray(issues) && issues.length > 0 ? (issues as ZodIssueLike[]) : undefined; +} + +/** The text of the coded refusal for `issues` on `toolName`. */ +export function toolArgumentRefusalText(toolName: string, issues: readonly ZodIssueLike[]): string { + const shown = issues.slice(0, MAX_REFUSAL_ISSUES).map(issueSentence); + const notShown = issues.length - shown.length; + let message = `Invalid arguments for tool ${toolName}: ${shown.join('\n')}`; + if (notShown > 0) message += `\n${notShown} more problem(s) not shown.`; + // Cut between whole characters, never inside a surrogate pair. + const characters = Array.from(message); + if (characters.length > MAX_REFUSAL_MESSAGE_LENGTH) message = `${characters.slice(0, MAX_REFUSAL_MESSAGE_LENGTH).join('')}…`; + const result = codedErrorResult({ code: StandardErrorCode.enum.VALIDATION_ERROR, status: 400, message }); + return result.content[0].text; +} + +/** + * One problem as the refusal names it, in the SDK's own layout (`message at + * path`). An unknown key the message quotes raw (a schema this package did + * not close, answered with zod's or the spec's own sentence) is replaced by + * its {@link echoedKey} form; the platform's own tools already render theirs + * that way. Path segments are the caller's keys too, so they are echoed the + * same way, and any control character left in the message is escaped. + */ +function issueSentence(issue: ZodIssueLike): string { + let text = issue.message; + if (issue.code === 'unrecognized_keys' && Array.isArray(issue.keys)) { + for (const key of issue.keys) { + const echoed = echoedKey(key); + if (key !== '' && echoed !== key) text = text.split(key).join(echoed); + } + } + text = withControlCharactersEscaped(text); + const path = issue.path.map((segment) => echoedKey(String(segment))).join('.'); + return path ? `${text} at ${path}` : text; +} + type RequestDispatcher = (request: unknown, extra: unknown) => Promise; /** diff --git a/packages/qa/dogfood/test/approval-decide-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-decide-over-mcp.dogfood.test.ts index bd3c7340fe4..d6ca33be063 100644 --- a/packages/qa/dogfood/test/approval-decide-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-decide-over-mcp.dogfood.test.ts @@ -259,7 +259,9 @@ describe('an approver\'s agent decides a pending approval request over MCP (#324 expect(answer.isError, answer.text).toBe(true); if (confirm) { expect(answer.text).toContain(`\`${AI_ACTION_CONFIRMATION_MEMBER}\``); - expect(answer.payload?.error?.code, answer.text).toBeUndefined(); + // [#37411] The closed input's schema refusal is coded VALIDATION_ERROR, the code any undeclared key + // gets; the member mints none of its own, and never the confirmation gate's. + expect(answer.payload?.error?.code, answer.text).toBe('VALIDATION_ERROR'); return; } expect(answer.payload?.error?.code, answer.text).toBe('ACTION_CONFIRMATION_REQUIRED'); diff --git a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts index 96c8a630e58..5d34be614ce 100644 --- a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts @@ -479,7 +479,9 @@ describe('an approver\'s agent lists the approvals waiting on them over MCP (#32 }); expect(withMember.isError, withMember.text).toBe(true); expect(withMember.text).toContain(`\`${AI_ACTION_CONFIRMATION_MEMBER}\``); - expect(withMember.payload?.error?.code, withMember.text).toBeUndefined(); + // [#37411] The closed input's schema refusal is coded VALIDATION_ERROR, the code any undeclared key + // gets; the member mints none of its own, and never the confirmation gate's. + expect(withMember.payload?.error?.code, withMember.text).toBe('VALIDATION_ERROR'); expect((await requestRow(first.requestId)).status).toBe('pending'); expect((await pendingIds({ bearer: approver })).sort()).toEqual([first.requestId, second.requestId].sort()); diff --git a/packages/qa/dogfood/test/mcp-system-object-action-exposure.dogfood.test.ts b/packages/qa/dogfood/test/mcp-system-object-action-exposure.dogfood.test.ts index 7ef4c80b1c1..bac93e3ae53 100644 --- a/packages/qa/dogfood/test/mcp-system-object-action-exposure.dogfood.test.ts +++ b/packages/qa/dogfood/test/mcp-system-object-action-exposure.dogfood.test.ts @@ -302,7 +302,9 @@ describe('[#27681, #27900] sys_user identity actions over MCP: what each bucket\ }); expect(withMember.isError, withMember.text).toBe(true); expect(withMember.text).toContain('`confirm`'); - expect(withMember.payload?.error?.code, withMember.text).toBeUndefined(); + // [#37411] The closed input's schema refusal is coded VALIDATION_ERROR, the code any undeclared key + // gets; the member mints none of its own, and never the confirmation gate's. + expect(withMember.payload?.error?.code, withMember.text).toBe('VALIDATION_ERROR'); expect(await isBanned(targetUserId)).toBe(false); }, 120_000); @@ -386,7 +388,9 @@ describe('[#27681, #27900] sys_user identity actions over MCP: what each bucket\ }); expect(withMember.isError, withMember.text).toBe(true); expect(withMember.text).toContain('`confirm`'); - expect(withMember.payload?.error?.code, withMember.text).toBeUndefined(); + // [#37411] The closed input's schema refusal is coded VALIDATION_ERROR, the code any undeclared key + // gets; the member mints none of its own, and never the confirmation gate's. + expect(withMember.payload?.error?.code, withMember.text).toBe('VALIDATION_ERROR'); expect(await isBanned(agentTargetUserId)).toBe(false); }, 120_000);