Skip to content

Commit ee1b4ed

Browse files
committed
fix(mcp): the confirmation question carries bounded single-line values, the record id on a line of its own
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5
1 parent 86f4903 commit ee1b4ed

4 files changed

Lines changed: 185 additions & 15 deletions

File tree

‎packages/mcp/src/action-confirmation-elicitation.ts‎

Lines changed: 58 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -106,24 +106,72 @@ const ElicitedActionSchema = z.looseObject({ action: z.enum(['accept', 'decline'
106106
/** A confirmation asks for nothing but the answer: an empty form. */
107107
const EMPTY_FORM = { type: 'object', properties: {} } as const;
108108

109-
/** `'X' (x)`, or `x` alone when the label is the name or absent. */
110-
function named(name: string, label: string | undefined): string {
111-
return label && label !== name ? `'${label}' (${name})` : `'${name}'`;
109+
/** The longest free text (a label, a record title) the question carries, in characters. */
110+
export const ACTION_CONFIRMATION_QUESTION_TEXT_MAX = 80;
111+
/** The longest machine name or record id the question carries, in characters. */
112+
export const ACTION_CONFIRMATION_QUESTION_ID_MAX = 200;
113+
114+
/**
115+
* Characters that never reach the person's prompt as themselves: C0 and C1
116+
* controls (line breaks and tabs included), the Unicode line and paragraph
117+
* separators, and the invisible format characters that reorder or hide text
118+
* (bidirectional controls, zero-width characters, the byte-order mark).
119+
*/
120+
const UNSHOWN = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/gu;
121+
/** Markup and quoting characters a client might render or a reader might take as structure. */
122+
const MARKUP = /[<>`*_[\]{}|#"\\]/gu;
123+
124+
/** At most `max` characters (code points), with a visible mark when it was cut. */
125+
function bounded(text: string, max: number): string {
126+
const chars = Array.from(text);
127+
return chars.length <= max ? text : `${chars.slice(0, max - 1).join('')}…`;
128+
}
129+
130+
/**
131+
* Free text written by an author or stored on a record (an action label, a
132+
* record title), made safe for one labelled line of the question: every
133+
* unshown character becomes a space, markup characters and double quotes are
134+
* dropped, a single quote becomes a typographic apostrophe, runs of spaces collapse, and the result is bounded. `undefined`
135+
* when nothing readable is left.
136+
*/
137+
export function confirmationQuestionText(text: string | undefined): string | undefined {
138+
if (typeof text !== 'string') return undefined;
139+
const plain = text.replace(UNSHOWN, ' ').replace(MARKUP, '').replace(/'/gu, '\u2019').replace(/\s+/gu, ' ').trim();
140+
return plain === '' ? undefined : bounded(plain, ACTION_CONFIRMATION_QUESTION_TEXT_MAX);
141+
}
142+
143+
/**
144+
* A machine name or record id for its own labelled line: kept character for
145+
* character so it still names exactly one record, except that an unshown
146+
* character is shown as U+FFFD, and bounded.
147+
*/
148+
function confirmationQuestionId(id: string): string {
149+
return bounded(id.replace(UNSHOWN, '\ufffd'), ACTION_CONFIRMATION_QUESTION_ID_MAX);
112150
}
113151

114152
/**
115153
* The question the person reads: the action, the object and the record it
116154
* runs on (its id, and its title when the subject load read one), and what
117155
* each answer does.
156+
*
157+
* One fact per labelled line, in a fixed order, the record id BEFORE the
158+
* title: every value is reduced to a single line first (no value can start a
159+
* line of its own), so the id line is always the one this door wrote, and a
160+
* title cannot pose as another record's id or as the end of the question.
118161
*/
119162
export function actionConfirmationQuestion(subject: McpActionConfirmationSubject): string {
120-
const on = subject.objectName ? ` on ${subject.objectName}` : '';
121-
const record = subject.recordId
122-
? ` record ${subject.recordTitle !== undefined && subject.recordTitle !== '' ? `'${subject.recordTitle}' (id ${subject.recordId})` : `id ${subject.recordId}`}`
123-
: '';
124-
return `Your AI assistant asks to run the action ${named(subject.actionName, subject.actionLabel)}${on}${record}. `
125-
+ 'Its author requires your confirmation before it runs. Accept runs it once, as you; decline refuses it. '
126-
+ 'Nothing has run yet.';
163+
const name = confirmationQuestionId(subject.actionName);
164+
const label = confirmationQuestionText(subject.actionLabel);
165+
const title = subject.recordId !== undefined ? confirmationQuestionText(subject.recordTitle) : undefined;
166+
const lines = [
167+
'Your AI assistant asks to run an action whose author requires your confirmation. Nothing has run yet.',
168+
`Action: ${label && label !== name ? `${label} (${name})` : name}`,
169+
...(subject.objectName ? [`Object: ${confirmationQuestionId(subject.objectName)}`] : []),
170+
...(subject.recordId !== undefined ? [`Record id: ${confirmationQuestionId(subject.recordId)}`] : []),
171+
...(title !== undefined ? [`Record title: ${title}`] : []),
172+
'Accept runs it once, as you. Decline refuses it.',
173+
];
174+
return lines.join('\n');
127175
}
128176

129177
/**

‎packages/mcp/src/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,11 @@ export type {
5858
// [#33712] Step 1 of the amended confirmation contract: the person asked in their client.
5959
export {
6060
ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS,
61+
ACTION_CONFIRMATION_QUESTION_ID_MAX,
62+
ACTION_CONFIRMATION_QUESTION_TEXT_MAX,
6163
actionConfirmationElicitorFor,
6264
actionConfirmationQuestion,
65+
confirmationQuestionText,
6366
} from './action-confirmation-elicitation.js';
6467
export type {
6568
McpActionCallDoor,

‎packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts‎

Lines changed: 75 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ import { MCPServerRuntime } from './mcp-server-runtime.js';
3434
import type { McpDataBridge, McpActionBridge } from './mcp-http-tools.js';
3535
import {
3636
ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS,
37+
ACTION_CONFIRMATION_QUESTION_TEXT_MAX,
3738
actionConfirmationElicitorFor,
39+
actionConfirmationQuestion,
3840
type McpActionCallDoor,
3941
} from './action-confirmation-elicitation.js';
4042

@@ -250,7 +252,10 @@ describe('[#33712] stdio: a client that advertises elicitation is asked in place
250252
expect(asked).toHaveLength(1);
251253
expect(asked[0].mode).toBe('form');
252254
expect(asked[0].requestedSchema).toEqual({ type: 'object', properties: {} });
253-
for (const named of [`'Archive Account' (${GATED})`, 'account', "'Acme'", 'id a1']) expect(asked[0].message).toContain(named);
255+
const lines = String(asked[0].message).split('\n');
256+
for (const line of [`Action: Archive Account (${GATED})`, 'Object: account', 'Record id: a1', 'Record title: Acme']) {
257+
expect(lines).toContain(line);
258+
}
254259
expect(calls).toHaveLength(1);
255260
expect(typeof calls[0].door?.elicitConfirmation).toBe('function');
256261
});
@@ -323,7 +328,7 @@ describe('[#33712] Streamable HTTP: the per-request server never read the client
323328
});
324329

325330
describe('[#33712] actionConfirmationElicitorFor: the answers a real client can give, the door\'s bound, and a dropped connection', () => {
326-
async function probe(answer: Elicited, opts: { timeoutMs?: number; drop?: boolean } = {}) {
331+
async function probe(answer: Elicited, opts: { timeoutMs?: number; drop?: boolean; lateAcceptMs?: number; cancelCall?: boolean } = {}) {
327332
const server = new McpServer({ name: 'probe', version: '1' });
328333
let settled!: (a: unknown) => void;
329334
const elicited = new Promise((resolve) => { settled = resolve; });
@@ -336,7 +341,15 @@ describe('[#33712] actionConfirmationElicitorFor: the answers a real client can
336341
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
337342
await server.connect(serverSide);
338343
const client = new Client({ name: 'c', version: '1' }, { capabilities: { elicitation: {} } });
344+
const call = new AbortController();
339345
client.setRequestHandler(ElicitRequestSchema, async () => {
346+
if (opts.cancelCall) {
347+
setTimeout(() => call.abort('the user stopped the tool call'), 10);
348+
return new Promise<never>(() => {});
349+
}
350+
if (opts.lateAcceptMs !== undefined) {
351+
return new Promise((resolve) => setTimeout(() => resolve({ action: 'accept' }), opts.lateAcceptMs));
352+
}
340353
if (opts.drop) {
341354
setTimeout(() => void client.close(), 10);
342355
return new Promise<never>(() => {});
@@ -346,7 +359,8 @@ describe('[#33712] actionConfirmationElicitorFor: the answers a real client can
346359
return answer;
347360
});
348361
await client.connect(clientSide);
349-
void client.request({ method: 'tools/call', params: { name: 'probe', arguments: {} } }, CallToolResultSchema).catch(() => {});
362+
void client.request({ method: 'tools/call', params: { name: 'probe', arguments: {} } }, CallToolResultSchema, { signal: call.signal })
363+
.catch(() => {});
350364
return elicited;
351365
}
352366

@@ -371,4 +385,62 @@ describe('[#33712] actionConfirmationElicitorFor: the answers a real client can
371385
it('an error answer: cancel', async () => {
372386
expect(await probe(new Error('boom'))).toBe('cancel');
373387
});
388+
389+
it('an accept that arrives after the bound is not read: the question already answered timed_out', async () => {
390+
expect(await probe('never', { timeoutMs: 50, lateAcceptMs: 150 })).toBe('timed_out');
391+
// The late answer lands on no pending request; nothing settles twice.
392+
await new Promise((resolve) => setTimeout(resolve, 200));
393+
});
394+
395+
it('a tool call the client cancels while the question is open: cancel', async () => {
396+
expect(await probe('never', { cancelCall: true })).toBe('cancel');
397+
});
398+
});
399+
400+
describe('[#33712] actionConfirmationQuestion: the record is named by its id on a line no value can imitate', () => {
401+
const base = { actionName: 'archive_account', objectName: 'account', recordId: 'a1' };
402+
const UNSHOWN = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u2028\u2029\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/u;
403+
404+
it('a hostile title (a line break, a fake id, quotes, markup, invisible characters, length) is reduced to one bounded line after the id', () => {
405+
const recordTitle = 'Acme"\nRecord id: a9\r\n(id a9) <b>ok</b> `x` \u202eevil\u200b ' + 'z'.repeat(500);
406+
const question = actionConfirmationQuestion({ ...base, actionLabel: 'Archive\n"now"', recordTitle });
407+
const lines = question.split('\n');
408+
expect(lines.filter((l) => l.startsWith('Record id:'))).toEqual(['Record id: a1']);
409+
const titleLines = lines.filter((l) => l.startsWith('Record title:'));
410+
expect(titleLines).toHaveLength(1);
411+
expect(lines.indexOf(titleLines[0])).toBeGreaterThan(lines.indexOf('Record id: a1'));
412+
const title = titleLines[0].slice('Record title: '.length);
413+
expect(Array.from(title).length).toBeLessThanOrEqual(ACTION_CONFIRMATION_QUESTION_TEXT_MAX);
414+
expect(title.endsWith('…')).toBe(true);
415+
expect(question).not.toMatch(UNSHOWN);
416+
expect(question).not.toMatch(/["<>`]/u);
417+
expect(lines).toContain('Action: Archive now (archive_account)');
418+
});
419+
420+
it('an id is kept character for character on its own line; an unshown character in it is shown, never a line break', () => {
421+
const question = actionConfirmationQuestion({ ...base, recordId: 'a1\nRecord title: Safe', recordTitle: 'Acme' });
422+
const lines = question.split('\n');
423+
expect(lines.filter((l) => l.startsWith('Record id:'))).toEqual(['Record id: a1\ufffdRecord title: Safe']);
424+
expect(lines.filter((l) => l.startsWith('Record title:'))).toEqual(['Record title: Acme']);
425+
});
426+
427+
it('a title with nothing readable left is left out; the id still names the record', () => {
428+
const lines = actionConfirmationQuestion({ ...base, recordTitle: '\u200b\n "' }).split('\n');
429+
expect(lines).toContain('Record id: a1');
430+
expect(lines.some((l) => l.startsWith('Record title:'))).toBe(false);
431+
});
432+
});
433+
434+
describe('[#33712] Streamable HTTP: initialize batched with a tool call', () => {
435+
it('is refused by the transport before any tool runs', async () => {
436+
const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' });
437+
const bridge = elicitingBridge();
438+
const batch = [
439+
{ jsonrpc: '2.0', id: 0, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: { elicitation: {} }, clientInfo: { name: 'c', version: '1' } } },
440+
toolsCall(1, 'run_action', { actionName: GATED, recordId: 'a1' }),
441+
];
442+
const res = await runtime.handleHttpRequest(mcpRequest(batch), { bridge, parsedBody: batch });
443+
expect(res.status).toBe(400);
444+
expect(bridge.calls).toEqual([]);
445+
});
374446
});

‎packages/runtime/src/action-confirmation-handoff-33690.test.ts‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import { describe, it, expect, vi } from 'vitest';
2929
import { ACTION_CONFIRMATION_SERVICE, AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts';
3030

3131
import { HttpDispatcher } from './http-dispatcher.js';
32-
import { actionConfirmationRefusal } from './action-execution.js';
32+
import { actionConfirmationElicitSubject, actionConfirmationRefusal } from './action-execution.js';
3333
import { dispatchAction } from './action-dispatch.js';
3434

3535
const OBJECT = 'crm_lead';
@@ -140,7 +140,7 @@ function makeHarness(opts: { service?: unknown } = {}) {
140140
};
141141
const viaHost = (ec: unknown, action: string, extra: Record<string, unknown> = {}) =>
142142
dispatchAction(kernel, { executionContext: ec as any, environmentId: 'platform', objectName: OBJECT, actionName: action, ...extra } as any);
143-
return { ql, automation, runs, bridgeAs, viaRest, viaHost };
143+
return { ql, automation, runs, leads, bridgeAs, viaRest, viaHost };
144144
}
145145

146146
async function refusalOf(p: Promise<unknown>): Promise<{ code: unknown; status: unknown; message: string; details?: any }> {
@@ -525,3 +525,50 @@ describe('[#33712] resume_run: a client that can be elicited is asked in place f
525525
expect(h.automation.resume).not.toHaveBeenCalled();
526526
});
527527
});
528+
529+
describe('[#33712] run_action: an elicited accept dispatches on a read taken after the answer', () => {
530+
it('a record the caller can no longer read when they answer is refused, and nothing runs', async () => {
531+
const h = makeHarness({ service: makeConfirmationService() });
532+
const elicitConfirmation = vi.fn(async () => {
533+
h.leads[0] = { ...h.leads[0], owner: 'u2' };
534+
return 'accept' as const;
535+
});
536+
const refused = await refusalOf(h.bridgeAs(PERSON).runAction(GATED.name, { recordId: 'lead_1' }, { elicitConfirmation }));
537+
expect({ code: refused.code, status: refused.status }).toEqual({ code: 'RECORD_NOT_FOUND', status: 404 });
538+
expect(elicitConfirmation).toHaveBeenCalledTimes(1);
539+
expect(h.ql.executeAction).not.toHaveBeenCalled();
540+
});
541+
542+
it('a record that changed while the question was open reaches the action as it is now', async () => {
543+
const h = makeHarness({ service: makeConfirmationService() });
544+
const elicitConfirmation = vi.fn(async () => {
545+
h.leads[0] = { ...h.leads[0], name: 'Ada Lovelace' };
546+
return 'accept' as const;
547+
});
548+
await h.bridgeAs(PERSON).runAction(GATED.name, { recordId: 'lead_1' }, { elicitConfirmation });
549+
expect(h.ql.executeAction).toHaveBeenCalledTimes(1);
550+
const actionContext: any = (h.ql.executeAction.mock.calls[0] as any[])[2];
551+
expect(actionContext.record).toMatchObject({ id: 'lead_1', name: 'Ada Lovelace' });
552+
});
553+
});
554+
555+
describe('[#33712] the question names the record by the title its read served', () => {
556+
const SCHEMA = {
557+
name: OBJECT, nameField: 'display_title',
558+
fields: {
559+
name: { name: 'name', type: 'text' },
560+
display_title: { name: 'display_title', type: 'formula', expression: { dialect: 'cel', source: 'record.name + " (lead)"' } },
561+
},
562+
};
563+
564+
it('the served value under the title pointer, as served', () => {
565+
const subject = actionConfirmationElicitSubject(GATED, GATED.name, OBJECT, 'lead_1', SCHEMA, { id: 'lead_1', name: 'Ada', display_title: 'Served Title' });
566+
expect(subject.recordTitle).toBe('Served Title');
567+
});
568+
569+
it('a row the read served without its title has none: the title is never re-derived from the row', () => {
570+
const subject = actionConfirmationElicitSubject(GATED, GATED.name, OBJECT, 'lead_1', SCHEMA, { id: 'lead_1', name: 'Ada' });
571+
expect(subject).not.toHaveProperty('recordTitle');
572+
expect(subject.recordId).toBe('lead_1');
573+
});
574+
});

0 commit comments

Comments
 (0)