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
12 changes: 12 additions & 0 deletions .changeset/37411-mcp-schema-refusal-coded.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
71 changes: 71 additions & 0 deletions packages/mcp/src/argument-echo.ts
Original file line number Diff line number Diff line change
@@ -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;
}
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
});

Expand Down
7 changes: 4 additions & 3 deletions packages/mcp/src/mcp-dataset-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([]);
});
});
Expand Down
26 changes: 24 additions & 2 deletions packages/mcp/src/mcp-http-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -3249,7 +3271,7 @@ function strictToolInput<T extends z.ZodRawShape>(
) {
return z
.object(shape, {
error: withoutHistorySentence(strictUnknownKeyError({
error: withBoundedKeyEcho(withoutHistorySentence(strictUnknownKeyError({
surface: options.surface,
knownKeys: Object.keys(shape),
aliases: options.aliases,
Expand All @@ -3262,7 +3284,7 @@ function strictToolInput<T extends z.ZodRawShape>(
// HERE opt out; the dataset pair takes spec `strictObject` schemas and
// keeps the spec refusal.
retiredKeyUpgradeGuide: false,
})),
}))),
})
.strict();
}
Expand Down
4 changes: 2 additions & 2 deletions packages/mcp/src/mcp-http-tools.unknown-argument-keys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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);
});
Expand Down
9 changes: 5 additions & 4 deletions packages/mcp/src/mcp-knowledge-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down
32 changes: 18 additions & 14 deletions packages/mcp/src/mcp-record-id-key-mistake-refusal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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';
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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`');
Expand Down Expand Up @@ -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`');
Expand Down
Loading
Loading