import { InMemoryTransport } from "@modelcontextprotocol/client"; import { isJSONRPCErrorResponse, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResultResponse, type JSONRPCErrorResponse, type JSONRPCResultResponse, } from "@modelcontextprotocol/server"; import { setImmediate } from "node:timers/promises"; import { vi } from "vitest"; import { ErrorEvidenceTransport } from "../../src/server/ErrorEvidenceTransport.js"; import { McpToolRequest } from "../../src/server/McpToolRequest.js"; import { phaseArrival, phaseGate } from "./lifecycleHarness.js"; /** The server message a call is held at, until the test releases it. */ export type HeldToolCallMessage = | { /** Only record the call; nothing is held. */ readonly kind: "none"; } | { /** Hold after the matching `notifications/progress` reached the client. */ readonly kind: "progress"; readonly matches: (message: string) => boolean; } | { /** Hold the first reply frame before it is physically sent. */ readonly kind: "reply"; }; /** One JSON-RPC response written for the observed call. */ export type ObservedReplyFrame = JSONRPCResultResponse | JSONRPCErrorResponse; export interface ObservedToolCall { /** Resolves with the held progress text, or "reply", once the hold is entered. */ reached(operation: Promise, boundary: string): Promise; /** * Resolves once the client's `notifications/cancelled` for this call was * handed to the server. Follow it with `client.ping()`: in-memory messages * are ordered, so the ping reply shows the server processed the abort. */ cancelled(operation: Promise, boundary: string): Promise; /** Resolves once the server physically sent a result or error frame for this call. */ replySent(operation: Promise, boundary: string): Promise; /** * Resolves once the server is done with this call: its tool handler * returned, the SDK decided whether to reply, and any reply it handed to * REA's transport finished writing. Assert on `replies` after this. */ settled(operation: Promise, boundary: string): Promise; /** Progress texts delivered to the client for this call, held one included. */ readonly progress: readonly string[]; /** Result or error frames the server physically sent for this call. */ readonly replies: readonly ObservedReplyFrame[]; /** Let the held message continue. */ release(): void; /** Release, then restore the transport spy; call from `finally`. */ restore(): void; } /** * Observe one `tools/call` below the SDK's transport wrapper, optionally * holding the server at a chosen message. The call is identified by its tool * name, so concurrent calls and other tools are left alone. Release in a * `finally` before the spy is restored: `restore` does both. */ export const observeToolCall = ( tool: string, held: HeldToolCallMessage, ): ObservedToolCall => { const gate = phaseGate(); const cancellation = phaseArrival(); const reply = phaseArrival(); const handled = phaseArrival(); const writes: Promise[] = []; const progress: string[] = []; const replies: ObservedReplyFrame[] = []; const originalSend = InMemoryTransport.prototype.send; let requestId: string | number | undefined; let progressToken: string | number | undefined; let holding = false; const finishHandler = McpToolRequest.prototype.finishHandler; const handler = vi .spyOn(McpToolRequest.prototype, "finishHandler") .mockImplementation(function (this: McpToolRequest) { finishHandler.call(this); if (requestId !== undefined && this.id === requestId) handled.arrive(); }); const offer = ErrorEvidenceTransport.prototype.send; const offered = vi .spyOn(ErrorEvidenceTransport.prototype, "send") .mockImplementation(function ( this: ErrorEvidenceTransport, message, options, ) { const writing = offer.call(this, message, options); if ( requestId !== undefined && (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) && message.id === requestId ) writes.push(writing.catch(() => undefined)); return writing; }); const spy = vi .spyOn(InMemoryTransport.prototype, "send") .mockImplementation(async function ( this: InMemoryTransport, message, options, ) { if ( requestId === undefined && isJSONRPCRequest(message) && message.method === "tools/call" && message.params?.["name"] === tool ) { requestId = message.id; const meta = message.params["_meta"]; if ( typeof meta === "object" && meta !== null && "progressToken" in meta ) progressToken = meta.progressToken as string | number; await originalSend.call(this, message, options); return; } if ( requestId !== undefined && (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) && message.id === requestId ) { if (held.kind === "reply" && !holding) { holding = true; await gate.hold("reply"); } await originalSend.call(this, message, options); replies.push(message); reply.arrive(); return; } await originalSend.call(this, message, options); if (requestId === undefined || !isJSONRPCNotification(message)) return; if ( message.method === "notifications/cancelled" && message.params?.["requestId"] === requestId ) cancellation.arrive(); if ( message.method === "notifications/progress" && progressToken !== undefined && message.params?.["progressToken"] === progressToken ) { const text = message.params["message"]; if (typeof text !== "string") return; progress.push(text); if (held.kind === "progress" && !holding && held.matches(text)) { holding = true; await gate.hold(text); } } }); return { reached: gate.reached, cancelled: (operation, boundary) => cancellation.reached(operation, boundary), replySent: (operation, boundary) => reply.reached(operation, boundary), settled: async (operation, boundary) => { await handled.reached(operation, boundary); // The SDK's reply decision follows the handler without I/O. await setImmediate(); await Promise.all(writes); }, progress, replies, release: () => gate.release(), restore: () => { gate.release(); spy.mockRestore(); handler.mockRestore(); offered.mockRestore(); }, }; };