Files
reverse-engineering-anything/tests/support/mcpToolCallObserver.ts
T
Cassie_FoxandClaude Opus 5.5 5919dc983a test(mcp): cancel analyze_javascript_application through an MCP client (#16476)
* test(mcp): cancel analyze_javascript_application through an MCP client

Refs #1065. The existing JavaScript cancellation tests either call the
analysis function directly or cancel through a mocked progress reporter
in the process-global project. These six mcp-boundary tests cancel
through the production server, the real 100 ms progress throttle and a
real worker, and pin the delivered cancelled result, the absent reply
frame, the removed worker folders and the next call. The last test pins
the late race: a cancel that arrives while the success reply is being
written still lets that reply out, keeps the Evidence and logs ok.

The terminal-progress cancel is left to the process-global test, which
already covers it. The observer helper lives in tests/support so the
reply and progress holds are not copied between files.

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>

* test(mcp): assert no reply only after the cancelled call settles

The three no-reply checks followed a client ping, which only raced the
server's handler tail on microtask order. With REA's transport changed to
keep notifications/cancelled from the SDK, so the SDK really writes the
cancelled result, the old tests still passed 6 of 6.

observeToolCall now offers settled(): it waits until REA's handler for the
call returned, lets the SDK make its reply decision, and joins any reply the
SDK handed to REA's transport. The same late-reply change now fails all five
cancellation tests at their no-reply check, also with a 50 ms delay in the
handler or in REA's publish path.

Raised by Greptile on #16476.

🤖 Generated with Claude Code (Opus 5.5) 🦊

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 17:49:02 -05:00

189 lines
6.6 KiB
TypeScript

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<unknown>, boundary: string): Promise<string>;
/**
* 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<unknown>, boundary: string): Promise<void>;
/** Resolves once the server physically sent a result or error frame for this call. */
replySent(operation: Promise<unknown>, boundary: string): Promise<void>;
/**
* 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<unknown>, boundary: string): Promise<void>;
/** 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<string>();
const cancellation = phaseArrival();
const reply = phaseArrival();
const handled = phaseArrival();
const writes: Promise<unknown>[] = [];
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();
},
};
};