Skip to content

Commit 4682eb8

Browse files
committed
fix(mcp): the refusal-reasons relay withholds only the security gate's own refusal
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L6bhgVUz5oS8fMgmncxU96
1 parent 54ea3c8 commit 4682eb8

3 files changed

Lines changed: 251 additions & 16 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/mcp': patch
3+
---
4+
5+
Clause-②: no
6+
Metadata-protocol: none
7+
8+
MCP tools: a refusal an app declares at 403 now names its reasons to the agent.
9+
10+
A refusal with several declared reasons, thrown under the app's own code at `status: 403`, is served as
11+
`PERMISSION_DENIED` with the app's code in `declaredCode`, as every door demotes an unregistered code. The
12+
second text block that names every reason, whole and in order, was withheld for it, because the tools withheld
13+
the block on any `PERMISSION_DENIED`. They now withhold it only on the security gate's own refusal (a
14+
`PERMISSION_DENIED` with no `declaredCode`). Both REST doors already serve the same caller those lines as
15+
`details.refusals`. The gate's refusal is unchanged: no block, and none of its `details`.
16+
17+
The block's lead now reads "Tell the user every line below, whole and in this order, in place of userMessage:".
18+
It used to say the door "may have cut" the `userMessage`, which `run_action` and `resume_run` never cut.
19+
`delete_records` is unchanged: each refused group's `reason` already names every listed line whole, the
20+
closing line last.

‎packages/mcp/src/mcp-http-tools.ts‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1374,7 +1374,11 @@ function errorResultFromThrown(err: unknown, request: string, objectName?: strin
13741374
...(answer.declaredCode !== undefined ? { declaredCode: answer.declaredCode } : {}),
13751375
...(answer.userMessage !== undefined ? { userMessage: answer.userMessage } : {}),
13761376
};
1377-
if (answer.code === StandardErrorCode.enum.PERMISSION_DENIED) return codedErrorResult(envelope);
1377+
// [#37512] Its `details` stay withheld; a listed refusal an app declared at
1378+
// 403 still names its lines ({@link withRefusalReasonsRelay} says which).
1379+
if (answer.code === StandardErrorCode.enum.PERMISSION_DENIED) {
1380+
return withRefusalReasonsRelay(codedErrorResult(envelope), err, envelope);
1381+
}
13781382
// A fault (5xx) carries nothing but the door's sanitised answer: a thrown
13791383
// `details` rides only on a refusal, as `/actions` serves no producer
13801384
// context on a fault.
@@ -1397,7 +1401,7 @@ function errorResultFromThrown(err: unknown, request: string, objectName?: strin
13971401
* for the pin; not on the package entry.
13981402
*/
13991403
export const REFUSAL_REASONS_RELAY_LEAD =
1400-
'Tell the user every line below, whole and in this order, rather than a userMessage the door may have cut:\n';
1404+
'Tell the user every line below, whole and in this order, in place of userMessage:\n';
14011405

14021406
/**
14031407
* [#37416] A refusal thrown as a declared `reasons` list (#36877, ruling
@@ -1432,18 +1436,31 @@ export const REFUSAL_REASONS_RELAY_LEAD =
14321436
*
14331437
* ## When it is withheld
14341438
*
1435-
* - A `PERMISSION_DENIED` answer gets no block, as it gets no `details` (the
1436-
* ruling on #7450, {@link errorResultFromThrown}).
1437-
* - An answer that serves no `userMessage`, or a fault (5xx), gets none: the
1438-
* door decided that the marked sentence does not reach this caller, and the
1439-
* lines are that sentence.
1439+
* - [#37512] The security gate's own refusal gets no block: a served
1440+
* `PERMISSION_DENIED` with no `declaredCode` (the ruling on #7450,
1441+
* {@link errorResultFromThrown}). A refusal an app's catalogue declared at
1442+
* `403` under its own code is served as `PERMISSION_DENIED` too, the doors'
1443+
* demotion of an unregistered code, with that code in `declaredCode`; it
1444+
* gets the block. It is not the gate's refusal, and both REST doors serve
1445+
* its lines whole to the same caller as `details.refusals` (`mapDataError`,
1446+
* `thrownAnswerOf`). The relay never reads `details`, so the gate's
1447+
* `positions` and `permissionSets` reach it on no path, and the `details`
1448+
* withholding in {@link errorResultFromThrown} is unchanged.
1449+
* - An answer that serves no `userMessage` gets none: there is no sentence for
1450+
* the lines to stand in for.
1451+
* - A fault (5xx) gets none. The block's lines are a refusal's reasons, and a
1452+
* refusal catalogue declares only a 4xx (`declaredRefusalEntrySchema`,
1453+
* `@objectstack/spec`), so a listed throw at a 5xx is no catalogue refusal.
1454+
* The doors still serve its `userMessage` (and `/data` its
1455+
* `details.refusals`); this tool serves the `userMessage` in the envelope,
1456+
* and serves a fault no `details`.
14401457
*/
14411458
function withRefusalReasonsRelay<R extends { content: Array<{ type: 'text'; text: string }> }>(
14421459
result: R,
14431460
err: unknown,
1444-
served: { code?: string; status?: number; userMessage?: string },
1461+
served: { code?: string; status?: number; declaredCode?: string; userMessage?: string },
14451462
): R {
1446-
if (served.code === StandardErrorCode.enum.PERMISSION_DENIED) return result;
1463+
if (served.code === StandardErrorCode.enum.PERMISSION_DENIED && served.declaredCode === undefined) return result;
14471464
if (served.userMessage === undefined) return result;
14481465
if (served.status !== undefined && isServerFault(served.status)) return result;
14491466
const text = refusalReasonsRelayText(err);
@@ -2392,6 +2409,13 @@ interface DeleteEachOutcome {
23922409
*
23932410
* Measured on a booted stack: REST `DELETE` answers the sandboxed refusal
23942411
* `400 HOOK_ABORTED` and the code hook's bare throw `500 INTERNAL_ERROR`.
2412+
*
2413+
* [#37512] A refusal thrown as a declared `reasons` list needs no relay block
2414+
* here ({@link withRefusalReasonsRelay}). It is coded, so its `reason` is the
2415+
* thrown value's own sentence, never the door's 500-character cut: the
2416+
* runtime's refusal catalogue sets that sentence to the same text as
2417+
* `userMessage`, every listed line whole and in order, its closing line last.
2418+
* So the group already names each line as ruling 7178348458 term 3 asks.
23952419
*/
23962420
function rowRefusalOf(err: unknown, objectName: string): Omit<DeleteRefusalGroup, 'count' | 'recordIds'> | undefined {
23972421
const door = dataDoorAnswerOf(err, objectName);

‎packages/mcp/src/mcp-refusal-reasons.test.ts‎

Lines changed: 198 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,37 @@
3232
* #7450); a list the shared recogniser does not read gets none; a
3333
* `userMessage` that does not begin with the lines gets no invented closing
3434
* line.
35+
*
36+
* [#37512] The follow-ups:
37+
*
38+
* - The withholding's reach: the security gate's own refusal (a served
39+
* `PERMISSION_DENIED` with no `declaredCode`) gets no relay and serves none
40+
* of its `details`; a listed refusal an app declared at 403, which the doors
41+
* demote to `PERMISSION_DENIED` beside `declaredCode`, gets it. The parity
42+
* case reads both REST doors' own answer to that throw (`mapDataError`,
43+
* `actionsDoorAnswerOf`): each serves the same lines as `details.refusals`.
44+
* - A listed throw at a 5xx gets no relay (`run_action`, `resume_run`, the
45+
* only tools whose renderer reaches the relay on a fault).
46+
* - The record read tools and `delete_records`' outer catch, the not-recorded
47+
* members beside a relay, and a `FLOW_FAILED` throw that is also listed.
48+
* - `delete_records`' per-row groups name a listed refusal whole in `reason`
49+
* (the catalogue's caller sentence IS its `userMessage`, `asCatalogue`), so
50+
* they carry no relay block.
3551
*/
3652

3753
import { describe, it, expect } from 'vitest';
3854

55+
import { GET_RECORD_CONTEXT_TOOL_NAME } from '@objectstack/spec/ai';
56+
import { createRecordContextTools } from '@objectstack/service-record-context';
57+
import { actionsDoorAnswerOf, mapDataError } from '@objectstack/types';
58+
3959
import { MCPServerRuntime } from './mcp-server-runtime.js';
40-
import { REFUSAL_REASONS_RELAY_LEAD, type McpActionBridge, type McpDataBridge } from './mcp-http-tools.js';
60+
import {
61+
FLOW_FAILURE_RELAY_LEAD,
62+
REFUSAL_REASONS_RELAY_LEAD,
63+
type McpActionBridge,
64+
type McpDataBridge,
65+
} from './mcp-http-tools.js';
4166

4267
type Bridge = McpDataBridge & McpActionBridge;
4368

@@ -72,18 +97,30 @@ const TWO: Listed = {
7297
*/
7398
function listedRefusal(
7499
listed: Listed,
75-
opts: { withList?: boolean; code?: string; status?: number; userMessage?: string; refusals?: unknown } = {},
100+
opts: {
101+
withList?: boolean;
102+
code?: string;
103+
status?: number;
104+
userMessage?: string;
105+
refusals?: unknown;
106+
/** The caller sentence; the catalogue sets it to `userMessage` (`asCatalogue`). */
107+
innerMessage?: string;
108+
asCatalogue?: boolean;
109+
name?: string;
110+
details?: unknown;
111+
} = {},
76112
): () => Error {
77113
return () => {
78114
const userMessage = opts.userMessage ?? [...listed.lines.map((line) => line.message), listed.closing].join('\n');
79115
const err = Object.assign(new Error(`hook 'expense_submit_guard' threw: Error: ${CODE}`), {
80-
innerMessage: CODE,
116+
innerMessage: opts.innerMessage ?? (opts.asCatalogue ? userMessage : CODE),
81117
code: opts.code ?? CODE,
82118
status: opts.status ?? 400,
83119
userMessage,
120+
...(opts.details !== undefined ? { details: opts.details } : {}),
84121
...(opts.withList === false ? {} : { refusals: opts.refusals ?? listed.lines.map((line) => ({ ...line })) }),
85122
});
86-
err.name = 'SandboxError';
123+
err.name = opts.name ?? 'SandboxError';
87124
return err;
88125
};
89126
}
@@ -109,7 +146,7 @@ function refusingBridge(thrown: () => Error): Bridge {
109146
let nextId = 1;
110147

111148
/** One `tools/call` over the real HTTP transport; answers the parsed tool result. */
112-
async function callOverHttp(bridge: Bridge, name: string, args: Record<string, unknown>) {
149+
async function callOverHttp(bridge: Bridge, name: string, args: Record<string, unknown>, isError = true) {
113150
const body = { jsonrpc: '2.0', id: nextId++, method: 'tools/call', params: { name, arguments: args } };
114151
const runtime = new MCPServerRuntime({ name: 'pin', version: '0.0.0' });
115152
const res = await runtime.handleHttpRequest(
@@ -123,8 +160,8 @@ async function callOverHttp(bridge: Bridge, name: string, args: Record<string, u
123160
expect(res.status, `${name}: the HTTP transport itself answered ${res.status}`).toBe(200);
124161
const json = JSON.parse(await res.text()) as { result?: any; error?: unknown };
125162
expect(json.error, `${name}: JSON-RPC error ${JSON.stringify(json.error)}`).toBeUndefined();
126-
expect(json.result.isError, `${name}: not a tool error`).toBe(true);
127-
return json.result as { isError: true; content: Array<{ type: string; text: string }> };
163+
expect(json.result.isError === true, `${name}: isError`).toBe(isError);
164+
return json.result as { isError?: true; content: Array<{ type: string; text: string }> };
128165
}
129166

130167
/** The tools whose catch renders the door's `userMessage`, and which door that is. */
@@ -214,3 +251,157 @@ describe('MCP tools: a refusal with several declared reasons names every line, w
214251
expect(content[1].text).toBe(`${REFUSAL_REASONS_RELAY_LEAD}${LINE_ON_REPORT}\n${LINE_APPROVED}`);
215252
});
216253
});
254+
255+
/** The record read tools and `delete_records`' selection read: the refusal is thrown by the read. */
256+
function readRefusingBridge(thrown: () => Error): Bridge {
257+
return {
258+
...refusingBridge(thrown),
259+
async query() { throw thrown(); },
260+
async get() { throw thrown(); },
261+
async aggregate() { throw thrown(); },
262+
async getRecordContext() { throw thrown(); },
263+
recordContextToolDefinitions: () => createRecordContextTools().definitions,
264+
};
265+
}
266+
267+
/** The tools whose refusal the read throws, each rendered through the `/data` door's answer. */
268+
const READ_DOORS = [
269+
{ tool: 'query_records', args: { objectName: OBJECT } },
270+
{ tool: 'aggregate_records', args: { objectName: OBJECT, aggregations: [{ function: 'count', alias: 'n' }] } },
271+
{ tool: 'get_record', args: { objectName: OBJECT, recordId: RECORD_ID } },
272+
{ tool: GET_RECORD_CONTEXT_TOOL_NAME, args: { objectName: OBJECT, recordId: RECORD_ID } },
273+
// The selection read is the outer catch's coded throw.
274+
{ tool: 'delete_records', args: { objectName: OBJECT, recordIds: [RECORD_ID], confirm: true } },
275+
] as const;
276+
277+
describe('[#37512] the relay\'s reach: the security gate\'s own refusal is withheld, an app\'s 403 is not', () => {
278+
const appAt403 = listedRefusal(TWO, { status: 403, asCatalogue: true });
279+
280+
for (const door of DOORS) {
281+
it(`${door.tool} (${door.door}): a listed refusal an app declared at 403 names its lines; no details are served`, async () => {
282+
const { content } = await callOverHttp(refusingBridge(appAt403), door.tool, door.args);
283+
expect(content).toHaveLength(2);
284+
const envelope = JSON.parse(content[0].text);
285+
expect(envelope.error).toMatchObject({ code: 'PERMISSION_DENIED', declaredCode: CODE, status: 403 });
286+
expect(envelope.error.details).toBeUndefined();
287+
expect(content[1]).toEqual({ type: 'text', text: relayOf(TWO) });
288+
});
289+
}
290+
291+
it('parity: both REST doors serve the same caller every relayed line for that throw', () => {
292+
const data = mapDataError(appAt403(), OBJECT);
293+
expect(data.status).toBe(403);
294+
expect(data.body).toMatchObject({ code: 'PERMISSION_DENIED', declaredCode: CODE });
295+
expect((data.body.details as { refusals?: unknown }).refusals).toEqual(TWO.lines);
296+
297+
const actions = actionsDoorAnswerOf(appAt403(), OBJECT);
298+
expect(actions).toMatchObject({ status: 403, code: 'PERMISSION_DENIED', declaredCode: CODE });
299+
expect(actions.details?.refusals).toEqual(TWO.lines);
300+
// `/actions` serves userMessage uncut, so the closing line is served there too.
301+
const served = actions.userMessage!.split('\n');
302+
expect(served[served.length - 1]).toBe(CLOSING);
303+
304+
// Every line the relay names is one of those: nothing beyond what REST serves.
305+
const relayed = relayOf(TWO).slice(REFUSAL_REASONS_RELAY_LEAD.length).split('\n');
306+
expect(relayed).toEqual([...TWO.lines.map((line) => line.message), CLOSING]);
307+
});
308+
309+
it('control: the gate\'s own PERMISSION_DENIED (no declaredCode) gets no relay and serves none of its details', async () => {
310+
const gate = listedRefusal(TWO, {
311+
code: 'PERMISSION_DENIED',
312+
status: 403,
313+
name: 'PermissionDeniedError',
314+
details: { positions: ['pin37512_position'], permissionSets: ['pin37512_set'] },
315+
});
316+
for (const door of DOORS) {
317+
const { content } = await callOverHttp(refusingBridge(gate), door.tool, door.args);
318+
expect(content, door.tool).toHaveLength(1);
319+
const error = JSON.parse(content[0].text).error;
320+
expect(error.code, door.tool).toBe('PERMISSION_DENIED');
321+
expect(error.declaredCode, door.tool).toBeUndefined();
322+
expect(content[0].text, door.tool).not.toContain('pin37512_');
323+
}
324+
});
325+
});
326+
327+
describe('[#37512] a listed throw at a 5xx is a fault: no relay block', () => {
328+
for (const door of DOORS.filter((d) => d.door === '/actions')) {
329+
it(`${door.tool}: a listed throw at 503 answers the envelope alone`, async () => {
330+
const { content } = await callOverHttp(
331+
refusingBridge(listedRefusal(TWO, { status: 503, asCatalogue: true })), door.tool, door.args,
332+
);
333+
expect(content).toHaveLength(1);
334+
const error = JSON.parse(content[0].text).error;
335+
expect(error.status).toBe(503);
336+
expect(error.details).toBeUndefined();
337+
});
338+
}
339+
});
340+
341+
describe('[#37512] the record read tools and delete_records\' outer catch relay a listed refusal', () => {
342+
for (const door of READ_DOORS) {
343+
it(`${door.tool}: every line rides as a second text block; the envelope is unchanged`, async () => {
344+
const listed = await callOverHttp(readRefusingBridge(listedRefusal(TWO)), door.tool, door.args);
345+
const unlisted = await callOverHttp(readRefusingBridge(listedRefusal(TWO, { withList: false })), door.tool, door.args);
346+
expect(unlisted.content).toHaveLength(1);
347+
expect(listed.content).toHaveLength(2);
348+
expect(listed.content[0]).toEqual(unlisted.content[0]);
349+
expect(JSON.parse(listed.content[0].text).error).toMatchObject({ status: 400, declaredCode: CODE });
350+
expect(listed.content[1]).toEqual({ type: 'text', text: relayOf(TWO) });
351+
});
352+
}
353+
354+
it('query_records: the not-recorded members stay beside the envelope, and the relay still follows it', async () => {
355+
const { content } = await callOverHttp(
356+
readRefusingBridge(listedRefusal(TWO)), 'query_records', { objectName: OBJECT, fields: ['pin37512_missing'] },
357+
);
358+
expect(content).toHaveLength(2);
359+
const envelope = JSON.parse(content[0].text);
360+
expect(envelope.notRecorded).toEqual({ object: OBJECT, fields: ['pin37512_missing'] });
361+
expect(typeof envelope.ifNotRecorded).toBe('string');
362+
expect(content[1]).toEqual({ type: 'text', text: relayOf(TWO) });
363+
});
364+
});
365+
366+
describe('[#37512] a FLOW_FAILED throw that is also listed answers three blocks', () => {
367+
it('run_action: the envelope, then the flow sentence, then every listed line', async () => {
368+
const thrown = listedRefusal(TWO, {
369+
code: 'FLOW_FAILED',
370+
status: 400,
371+
asCatalogue: true,
372+
details: { errorMessage: 'pin37512 The approval flow refused the report.' },
373+
});
374+
const { content } = await callOverHttp(refusingBridge(thrown), 'run_action', DOORS[0].args);
375+
expect(content).toHaveLength(3);
376+
expect(JSON.parse(content[0].text).error.code).toBe('FLOW_FAILED');
377+
expect(content[1]).toEqual({ type: 'text', text: `${FLOW_FAILURE_RELAY_LEAD}pin37512 The approval flow refused the report.` });
378+
expect(content[2]).toEqual({ type: 'text', text: relayOf(TWO) });
379+
});
380+
});
381+
382+
describe('[#37512] delete_records: a row\'s listed refusal is named whole in its group, with no relay block', () => {
383+
it('a list longer than the door\'s 500-character cut: the group reason is every line whole, the closing line last', async () => {
384+
const lines = Array.from({ length: 6 }, (_, i) => ({
385+
reason: 'on_report',
386+
message: `pin37512 Expense line ${i + 1} (${'x'.repeat(90)}) is already on another report.`,
387+
}));
388+
const whole = [...lines.map((line) => line.message), CLOSING].join('\n');
389+
expect(whole.length).toBeGreaterThan(500);
390+
const bridge: Bridge = {
391+
...refusingBridge(listedRefusal({ lines, closing: CLOSING }, { asCatalogue: true })),
392+
async query() { return { object: OBJECT, records: [{ id: 'er_1' }, { id: 'er_2' }], total: 2 }; },
393+
};
394+
395+
const { content } = await callOverHttp(
396+
bridge, 'delete_records', { objectName: OBJECT, recordIds: ['er_1', 'er_2'], confirm: true }, false,
397+
);
398+
399+
expect(content).toHaveLength(1);
400+
const outcome = JSON.parse(content[0].text);
401+
expect(outcome).toMatchObject({ deleted: 0, refused: 2 });
402+
expect(outcome.refusals).toHaveLength(1);
403+
expect(outcome.refusals[0]).toMatchObject({ code: CODE, status: 400, count: 2, recordIds: ['er_1', 'er_2'] });
404+
expect(outcome.refusals[0].reason).toBe(whole);
405+
expect(outcome.refusals[0].reason.split('\n')).toEqual([...lines.map((line) => line.message), CLOSING]);
406+
});
407+
});

0 commit comments

Comments
 (0)