Skip to content

Commit c9c5309

Browse files
committed
test: pin the elicit-first confirmation at the MCP action doors
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5
1 parent 9338516 commit c9c5309

2 files changed

Lines changed: 397 additions & 1 deletion

File tree

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

Lines changed: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,25 @@
1818
*/
1919

2020
import { describe, it, expect } from 'vitest';
21+
import { PassThrough } from 'node:stream';
22+
import { z } from 'zod';
23+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
24+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
25+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
26+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
27+
import { ReadBuffer, serializeMessage } from '@modelcontextprotocol/sdk/shared/stdio.js';
28+
import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
29+
import { CallToolResultSchema, ElicitRequestSchema, type JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
2130

2231
import { AI_ACTION_CONFIRMATION_MEMBER, type ActionConfirmationPending } from '@objectstack/spec/contracts';
2332

2433
import { MCPServerRuntime } from './mcp-server-runtime.js';
2534
import type { McpDataBridge, McpActionBridge } from './mcp-http-tools.js';
35+
import {
36+
ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS,
37+
actionConfirmationElicitorFor,
38+
type McpActionCallDoor,
39+
} from './action-confirmation-elicitation.js';
2640

2741
const GATED = 'archive_account';
2842

@@ -132,3 +146,231 @@ describe('[#33690] run_action and resume_run relay a hand-off as the call\'s suc
132146
}
133147
});
134148
});
149+
150+
// ---------------------------------------------------------------------------
151+
// [#33712] Step 1 of the amended contract: the person asked in their client.
152+
// ---------------------------------------------------------------------------
153+
154+
/** The client half of a stdio pipe: newline-delimited JSON-RPC over two streams, the framing the server reads. */
155+
class PipeClientTransport implements Transport {
156+
onclose?: () => void;
157+
onerror?: (error: Error) => void;
158+
onmessage?: (message: JSONRPCMessage) => void;
159+
private readonly buffer = new ReadBuffer();
160+
constructor(private readonly toServer: PassThrough, private readonly fromServer: PassThrough) {}
161+
async start(): Promise<void> {
162+
this.fromServer.on('data', (chunk: Buffer) => {
163+
this.buffer.append(chunk);
164+
for (let message = this.buffer.readMessage(); message; message = this.buffer.readMessage()) this.onmessage?.(message);
165+
});
166+
}
167+
async send(message: JSONRPCMessage): Promise<void> {
168+
this.toServer.write(serializeMessage(message));
169+
}
170+
async close(): Promise<void> {
171+
this.onclose?.();
172+
}
173+
}
174+
175+
type Elicited = { action: 'accept' | 'decline' | 'cancel'; content?: Record<string, unknown> } | 'never' | Error;
176+
177+
/**
178+
* A real SDK client on the long-lived server's stdio transport, advertising
179+
* `elicitation: {}` (form mode) or nothing, and answering each
180+
* `elicitation/create` with `answer`.
181+
*/
182+
async function openStdioClient(server: McpServer, opts: { elicitation: boolean; answer?: Elicited }) {
183+
const toServer = new PassThrough();
184+
const fromServer = new PassThrough();
185+
await server.connect(new StdioServerTransport(toServer, fromServer));
186+
const client = new Client(
187+
{ name: 'confirm-test-client', version: '1.0.0' },
188+
{ capabilities: opts.elicitation ? { elicitation: {} } : {} },
189+
);
190+
const asked: any[] = [];
191+
if (opts.elicitation) {
192+
client.setRequestHandler(ElicitRequestSchema, async (request) => {
193+
asked.push(request.params);
194+
const answer = opts.answer ?? { action: 'cancel' };
195+
if (answer === 'never') return new Promise<never>(() => {});
196+
if (answer instanceof Error) throw answer;
197+
return answer;
198+
});
199+
}
200+
await client.connect(new PipeClientTransport(toServer, fromServer));
201+
return { client, asked };
202+
}
203+
204+
/** A bridge double for the stdio door: runs the step-1 half the runtime owns, through whatever `door` the tool handed it. */
205+
function elicitingBridge() {
206+
const calls: Array<{ tool: string; door: McpActionCallDoor | undefined; argCount: number }> = [];
207+
const confirmWith = async (door: McpActionCallDoor | undefined, name: string) => {
208+
if (!door) return pendingOf(1);
209+
const answer = await door.elicitConfirmation({
210+
actionName: name, actionLabel: 'Archive Account', objectName: 'account', recordId: 'a1', recordTitle: 'Acme',
211+
});
212+
if (answer === 'accept') return { ok: true, action: name, objectName: 'account', recordId: 'a1', result: { ran: true } };
213+
const reason = { decline: 'declined', cancel: 'cancelled', timed_out: 'timed_out' }[answer];
214+
throw Object.assign(new Error(`refused: ${reason}`), {
215+
code: 'ACTION_CONFIRMATION_REQUIRED', status: 428,
216+
details: { actionName: name, objectName: 'account', confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, reason },
217+
});
218+
};
219+
const bridge = {
220+
...makeBridge('service'),
221+
calls,
222+
async runAction(name: string, _input: any, door?: McpActionCallDoor) {
223+
// eslint-disable-next-line prefer-rest-params
224+
calls.push({ tool: 'run_action', door, argCount: arguments.length });
225+
return confirmWith(door, name);
226+
},
227+
async resumeRun(_runId: string, _input: any, door?: McpActionCallDoor) {
228+
// eslint-disable-next-line prefer-rest-params
229+
calls.push({ tool: 'resume_run', door, argCount: arguments.length });
230+
return confirmWith(door, GATED);
231+
},
232+
};
233+
return bridge;
234+
}
235+
236+
async function stdioCall(opts: { elicitation: boolean; answer?: Elicited }, tool: 'run_action' | 'resume_run' = 'run_action') {
237+
const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' });
238+
const bridge = elicitingBridge();
239+
runtime.bridgeDataTools(bridge);
240+
const { client, asked } = await openStdioClient(runtime.server, opts);
241+
const args = tool === 'run_action' ? { actionName: GATED, recordId: 'a1' } : { runId: 'run_1', values: { reason: 'x' } };
242+
const result = await client.request({ method: 'tools/call', params: { name: tool, arguments: args } }, CallToolResultSchema);
243+
await client.close();
244+
return { result: result as any, asked, calls: bridge.calls };
245+
}
246+
247+
describe('[#33712] stdio: a client that advertises elicitation is asked in place by run_action and resume_run', () => {
248+
it('accept: one elicitation/create in form mode naming the action, the object and the record; the action runs', async () => {
249+
const { result, asked, calls } = await stdioCall({ elicitation: true, answer: { action: 'accept' } });
250+
expect(result.isError).toBeFalsy();
251+
expect(JSON.parse(result.content[0].text)).toMatchObject({ ok: true, action: GATED, result: { ran: true } });
252+
expect(asked).toHaveLength(1);
253+
expect(asked[0].mode).toBe('form');
254+
expect(asked[0].requestedSchema).toEqual({ type: 'object', properties: {} });
255+
for (const named of [`'Archive Account' (${GATED})`, 'account', "'Acme'", 'id a1']) expect(asked[0].message).toContain(named);
256+
expect(calls).toHaveLength(1);
257+
expect(typeof calls[0].door?.elicitConfirmation).toBe('function');
258+
});
259+
260+
it('accept with a form payload the door does not read still runs: only the result\'s action is read', async () => {
261+
const { result } = await stdioCall({ elicitation: true, answer: { action: 'accept', content: { note: 'yes' } } });
262+
expect(JSON.parse(result.content[0].text)).toMatchObject({ ok: true });
263+
});
264+
265+
for (const [answer, reason] of [
266+
[{ action: 'decline' } as const, 'declined'],
267+
[{ action: 'cancel' } as const, 'cancelled'],
268+
[new Error('the user closed the dialog'), 'cancelled'],
269+
] as const) {
270+
const label = answer instanceof Error ? 'an error answer' : answer.action;
271+
it(`${label}: refused 428 ACTION_CONFIRMATION_REQUIRED, reason ${reason}`, async () => {
272+
const { result, asked } = await stdioCall({ elicitation: true, answer });
273+
expect(asked).toHaveLength(1);
274+
expect(result.isError).toBe(true);
275+
const envelope = JSON.parse(result.content[0].text);
276+
expect({ code: envelope.error.code, status: envelope.error.status }).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 });
277+
expect(envelope.error.details.reason).toBe(reason);
278+
});
279+
}
280+
281+
it('resume_run: accept continues the run, decline refuses it', async () => {
282+
const accepted = await stdioCall({ elicitation: true, answer: { action: 'accept' } }, 'resume_run');
283+
expect(JSON.parse(accepted.result.content[0].text)).toMatchObject({ ok: true });
284+
expect(accepted.asked).toHaveLength(1);
285+
const declined = await stdioCall({ elicitation: true, answer: { action: 'decline' } }, 'resume_run');
286+
expect(JSON.parse(declined.result.content[0].text).error.details.reason).toBe('declined');
287+
});
288+
289+
it('a client WITHOUT the capability is never asked: the bridge is called exactly as before and hands off', async () => {
290+
const { result, calls } = await stdioCall({ elicitation: false });
291+
expect(result.isError).toBeFalsy();
292+
expect(JSON.parse(result.content[0].text)).toEqual(pendingOf(1));
293+
expect(calls).toEqual([{ tool: 'run_action', door: undefined, argCount: 2 }]);
294+
});
295+
});
296+
297+
describe('[#33712] Streamable HTTP: the per-request server never read the client\'s initialize, so its callers are handed off', () => {
298+
const INIT = {
299+
jsonrpc: '2.0', id: 0, method: 'initialize',
300+
params: { protocolVersion: '2025-11-25', capabilities: { elicitation: {} }, clientInfo: { name: 'c', version: '1' } },
301+
};
302+
303+
it('a client that advertised elicitation at initialize: the gated call is handed off, answered in one JSON body', async () => {
304+
const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' });
305+
const bridge = elicitingBridge();
306+
const init = await runtime.handleHttpRequest(mcpRequest(INIT), { bridge, parsedBody: INIT });
307+
expect(init.status).toBe(200);
308+
const body = toolsCall(1, 'run_action', { actionName: GATED, recordId: 'a1' });
309+
const req = mcpRequest(body);
310+
req.headers.set('mcp-protocol-version', '2025-11-25');
311+
const res = await runtime.handleHttpRequest(req, { bridge, parsedBody: body });
312+
expect(res.headers.get('content-type')).toContain('application/json');
313+
const json: any = await res.json();
314+
expect(JSON.parse(json.result.content[0].text)).toEqual(pendingOf(1));
315+
expect(bridge.calls).toEqual([{ tool: 'run_action', door: undefined, argCount: 2 }]);
316+
});
317+
318+
it('CONTROL: a non-gated tool call answers plain JSON, no event stream', async () => {
319+
const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' });
320+
const body = toolsCall(1, 'list_actions', {});
321+
const res = await runtime.handleHttpRequest(mcpRequest(body), { bridge: elicitingBridge(), parsedBody: body });
322+
expect(res.headers.get('content-type')).toContain('application/json');
323+
expect(((await res.json()) as any).result.isError).toBeFalsy();
324+
});
325+
});
326+
327+
describe('[#33712] actionConfirmationElicitorFor: the answers a real client can give, the door\'s bound, and a dropped connection', () => {
328+
async function probe(answer: Elicited, opts: { timeoutMs?: number; drop?: boolean } = {}) {
329+
const server = new McpServer({ name: 'probe', version: '1' });
330+
let settled!: (a: unknown) => void;
331+
const elicited = new Promise((resolve) => { settled = resolve; });
332+
server.registerTool('probe', { inputSchema: { x: z.string().optional() } }, async (_args, extra) => {
333+
const elicit = actionConfirmationElicitorFor(server, extra, opts.timeoutMs);
334+
const got = elicit ? await elicit({ actionName: 'a', objectName: 'o', recordId: 'r' }) : 'no-elicitor';
335+
settled(got);
336+
return { content: [{ type: 'text', text: String(got) }] };
337+
});
338+
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
339+
await server.connect(serverSide);
340+
const client = new Client({ name: 'c', version: '1' }, { capabilities: { elicitation: {} } });
341+
client.setRequestHandler(ElicitRequestSchema, async () => {
342+
if (opts.drop) {
343+
setTimeout(() => void client.close(), 10);
344+
return new Promise<never>(() => {});
345+
}
346+
if (answer === 'never') return new Promise<never>(() => {});
347+
if (answer instanceof Error) throw answer;
348+
return answer;
349+
});
350+
await client.connect(clientSide);
351+
void client.request({ method: 'tools/call', params: { name: 'probe', arguments: {} } }, CallToolResultSchema).catch(() => {});
352+
return elicited;
353+
}
354+
355+
it('the bound is the door\'s constant: five minutes', () => {
356+
expect(ACTION_CONFIRMATION_ELICITATION_TIMEOUT_MS).toBe(300_000);
357+
});
358+
359+
it('accept, decline and cancel are read off the result', async () => {
360+
expect(await probe({ action: 'accept' })).toBe('accept');
361+
expect(await probe({ action: 'decline' })).toBe('decline');
362+
expect(await probe({ action: 'cancel' })).toBe('cancel');
363+
});
364+
365+
it('no answer within the bound: timed_out', async () => {
366+
expect(await probe('never', { timeoutMs: 50 })).toBe('timed_out');
367+
});
368+
369+
it('a connection that drops before an answer: cancel', async () => {
370+
expect(await probe('never', { drop: true })).toBe('cancel');
371+
});
372+
373+
it('an error answer: cancel', async () => {
374+
expect(await probe(new Error('boom'))).toBe('cancel');
375+
});
376+
});

0 commit comments

Comments
 (0)