diff --git a/tests/boundary/mcp/javascriptApplicationCancellationMcp.test.ts b/tests/boundary/mcp/javascriptApplicationCancellationMcp.test.ts new file mode 100644 index 00000000000..38718c55f45 --- /dev/null +++ b/tests/boundary/mcp/javascriptApplicationCancellationMcp.test.ts @@ -0,0 +1,467 @@ +import type { Client } from "@modelcontextprotocol/client"; +import { + isCallToolResult, + isJSONRPCResultResponse, + type CallToolResult, +} from "@modelcontextprotocol/server"; +import { access, mkdir, writeFile } from "node:fs/promises"; +import { basename, join } from "node:path"; +import pino from "pino"; +import { expect, it, onTestFinished, vi } from "vitest"; +import { z } from "zod"; + +import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js"; +import { parseEvidence } from "../../../src/domain/evidence.js"; +import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; +import { ToolResultDelivery } from "../../../src/server/ToolResultDelivery.js"; +import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; +import { createDeferred } from "../../fixtures/binarySession.js"; +import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { phaseGate } from "../../support/lifecycleHarness.js"; +import { + observeToolCall, + type HeldToolCallMessage, +} from "../../support/mcpToolCallObserver.js"; + +const TOOL = "analyze_javascript_application"; +const TERMINAL_PROGRESS = `${TOOL}: Application graph and Electron boundaries reconstructed`; + +/** + * The client rejects as soon as it aborts, so waits after an abort cannot race + * the call; the test's wait deadline bounds them. + */ +const SERVER_SIDE: Promise = new Promise(() => undefined); + +const analysisCall = (root: string) => ({ + name: TOOL, + arguments: { input_path: root, format: "directory" }, +}); + +const writeFunctions = (path: string, count: number, prefix: string) => + writeFile( + path, + Array.from( + { length: count }, + (_, index) => + `function ${prefix}_${String(index)}(value) { const next = JSON.stringify(value); return next + 'item-${String(index)}'; }`, + ).join("\n"), + ); + +const oneFileApplication = async () => { + const root = await createTestTempDirectory("rea-js-mcp-cancel-"); + await writeFile(join(root, "main.js"), "export const observed = 1;\n"); + return root; +}; + +const completionSchema = z.object({ + tool: z.string(), + status: z.string(), + msg: z.string(), +}); + +/** + * Production server, SDK client and a real JavaScript worker, plus three + * observation points: the worker roots REA allocates, the cancelled results the + * server delivers (the SDK drops the reply of a cancelled request), and the + * server's completion log. + */ +const fixture = async () => { + // The project shares one thread between files, so every spy dies with the test. + onTestFinished(() => { + vi.restoreAllMocks(); + }); + const roots: string[] = []; + const create = PrivateRuntimeRoot.create.bind(PrivateRuntimeRoot); + vi.spyOn(PrivateRuntimeRoot, "create").mockImplementation(async (...args) => { + const root = await create(...args); + if (basename(root.path).startsWith("rea-javascript-analysis-")) + roots.push(root.path); + return root; + }); + const deliveries: CallToolResult[] = []; + const delivery = createDeferred(); + const deliver = ToolResultDelivery.prototype.toPartialErrorToolResult; + vi.spyOn( + ToolResultDelivery.prototype, + "toPartialErrorToolResult", + ).mockImplementation(function (this: ToolResultDelivery, ...args) { + const result = deliver.apply(this, args); + deliveries.push(result); + delivery.resolve(result); + return result; + }); + const statuses: string[] = []; + const completed = createDeferred(); + const logger = pino( + { level: "info" }, + { + write(line) { + const entry = completionSchema.safeParse(JSON.parse(line)); + if ( + entry.success && + entry.data.tool === TOOL && + entry.data.msg === "MCP tool execution completed" + ) { + statuses.push(entry.data.status); + completed.resolve(entry.data.status); + } + }, + }, + ); + const harness = await createApplicationMcpHarness({ + serverOptions: { logger }, + }); + return { + ...harness, + roots, + deliveries, + statuses, + /** The first cancelled result the server built for the call. */ + delivered: () => + awaitAcknowledgement( + delivery.promise, + SERVER_SIDE, + "cancelled delivery", + ).then(() => delivery.promise), + /** The status of the server's first completion log for the call. */ + completion: () => + awaitAcknowledgement( + completed.promise, + SERVER_SIDE, + "completion log", + ).then(() => completed.promise), + }; +}; +type Fixture = Awaited>; + +const removed = async (paths: readonly string[]) => { + expect(paths.length).toBeGreaterThan(0); + for (const path of paths) + await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" }); +}; + +const partialStatisticsSchema = z.object({ + statistics: z.object({ + relevant_files: z.number(), + parsed_javascript_files: z.number(), + parse_failures: z.number(), + }), +}); + +/** Read the retained partial Evidence a cancelled result references. */ +const partialStatistics = (test: Fixture, result: CallToolResult) => { + const { error } = parseMcpToolError(result); + const reference = z + .object({ + partial_observation: z.object({ + kind: z.literal("retained-evidence"), + evidence_id: z.string(), + }), + }) + .parse(error.details).partial_observation; + const evidence = test.session.evidenceById(reference.evidence_id); + expect(evidence?.operation).toBe(TOOL); + return { + error, + evidenceId: reference.evidence_id, + statistics: partialStatisticsSchema.parse(evidence?.normalized_result) + .statistics, + }; +}; + +/** A client call whose rejection is data, so a gate failure cannot orphan it. */ +const startCall = ( + client: Client, + root: string, + signal: AbortSignal, +): Promise => + client + .callTool(analysisCall(root), { signal, onprogress: () => undefined }) + .then( + (reply) => reply, + (cause: unknown) => cause, + ); + +const retainedEvidenceIds = z + .object({ + result: z.object({ + kind: z.literal("evidence-bundle-summary"), + records: z.array(z.object({ evidence_id: z.string() })), + }), + }) + .transform(({ result }) => + result.records.map((record) => record.evidence_id), + ); + +const expectRetainedAndServing = async (test: Fixture, evidenceId: string) => { + await expect(test.client.ping()).resolves.toEqual({}); + // Summary detail: a complete bundle of the cancelled multi-file graph can + // exceed the response budget, and identity is what this check needs. + const bundle = await test.client.callTool({ + name: "get_evidence_bundle", + arguments: { detail: "summary" }, + }); + expect(bundle.isError, JSON.stringify(bundle.content)).not.toBe(true); + expect(retainedEvidenceIds.parse(bundle.structuredContent)).toEqual([ + evidenceId, + ]); + const next = await oneFileApplication(); + const reply = await test.client.callTool(analysisCall(next)); + expect(reply.isError, JSON.stringify(reply.content)).not.toBe(true); + expect(parseEvidence(reply.structuredContent).operation).toBe(TOOL); +}; + +/** + * Failure-path teardown: stop and join the call before its spy goes, even when + * a wait failed. Aborting an already settled call changes nothing. + */ +const teardown = async ( + controller: AbortController, + observed: ReturnType, + call: Promise, +) => { + controller.abort(); + observed.release(); + await call; + observed.restore(); +}; + +/** Cancel at the held boundary, wait until the server handled it, then release. */ +const cancelHeld = async (held: { + readonly test: Fixture; + readonly controller: AbortController; + readonly observed: ReturnType; + readonly call: Promise; + readonly reason: Error; + readonly boundary: string; +}) => { + const { test, controller, observed, call, reason, boundary } = held; + await observed.reached(call, boundary); + controller.abort(reason); + await observed.cancelled(SERVER_SIDE, `${boundary} cancellation delivery`); + // In-memory messages are ordered: the ping reply follows the server's + // handling of the cancellation, so its signal is aborted before the release. + await test.client.ping(); + expect(await call).toMatchObject({ + code: "REQUEST_TIMEOUT", + message: expect.stringContaining(reason.message), + }); + observed.release(); +}; + +/** + * Cancel a one-file analysis held at `held` and check what every such + * cancellation shares: a typed cancelled result with retained partial + * Evidence, an error completion log, and no reply frame. + */ +const cancelOneFileAt = async ( + held: HeldToolCallMessage, + reason: Error, + boundary: string, +) => { + const test = await fixture(); + const observed = observeToolCall(TOOL, held); + const controller = new AbortController(); + const call = startCall( + test.client, + await oneFileApplication(), + controller.signal, + ); + try { + await cancelHeld({ test, controller, observed, call, reason, boundary }); + expect(await test.completion()).toBe("error"); + const partial = partialStatistics(test, await test.delivered()); + expect(partial.error.code).toBe("cancelled"); + await observed.settled(SERVER_SIDE, "cancelled call settlement"); + expect(observed.replies).toEqual([]); + return { test, progress: [...observed.progress], ...partial }; + } finally { + await teardown(controller, observed, call); + } +}; + +it("cancels one large source at its first worker boundary through the SDK and serves the next call", async () => { + const test = await fixture(); + const root = await createTestTempDirectory("rea-js-mcp-cancel-large-"); + await writeFunctions(join(root, "main.js"), 1200, "selected"); + const observed = observeToolCall(TOOL, { + kind: "progress", + matches: (message) => message.startsWith("javascript_worker_"), + }); + const controller = new AbortController(); + const call = startCall(test.client, root, controller.signal); + try { + await cancelHeld({ + test, + controller, + observed, + call, + reason: new Error("cancel at the first worker boundary"), + boundary: "first worker boundary", + }); + expect(await test.completion()).toBe("error"); + const result = await test.delivered(); + const { error, evidenceId, statistics } = partialStatistics(test, result); + expect(error).toMatchObject({ + code: "cancelled", + category: "cancelled", + retryable: true, + details: { operation: TOOL, cleanup: "complete" }, + }); + expect(statistics).toEqual({ + relevant_files: 1, + parsed_javascript_files: 0, + parse_failures: 0, + }); + // The SDK drops a cancelled request's reply once its handler returns. + await observed.settled(SERVER_SIDE, "cancelled call settlement"); + expect(observed.replies).toEqual([]); + expect(observed.progress.at(-1)).toBe( + "javascript_worker_parse: JavaScript worker parse: main.js", + ); + expect(test.roots).toHaveLength(1); + await removed(test.roots); + await expectRetainedAndServing(test, evidenceId); + } finally { + await teardown(controller, observed, call); + } +}); + +it("cancels between files of a multi-file application, keeping the parsed files", async () => { + const test = await fixture(); + const root = await createTestTempDirectory("rea-js-mcp-cancel-files-"); + const files = 40; + const cancelledFile = 12; + await mkdir(join(root, "src")); + await Promise.all( + Array.from({ length: files }, (_, index) => + writeFunctions( + join(root, "src", `module_${String(index).padStart(2, "0")}.js`), + 30, + `fn${String(index)}`, + ), + ), + ); + // The reporter drops all but the first parse update per 100 ms, so cancel + // where each file reaches its worker instead of at a progress message. + const reached = phaseGate(); + let started = 0; + const analyze = JavaScriptAnalysisWorker.prototype.analyze; + vi.spyOn(JavaScriptAnalysisWorker.prototype, "analyze").mockImplementation( + async function (this: JavaScriptAnalysisWorker, ...args) { + // Only sources analyzed for the result count, not preload discovery. + const counted = args[5] === undefined || args[5] === "analysis"; + if (counted && ++started === cancelledFile) await reached.hold(); + return analyze.apply(this, args); + }, + ); + const observed = observeToolCall(TOOL, { kind: "none" }); + const controller = new AbortController(); + const call = startCall(test.client, root, controller.signal); + const reason = new Error("cancel between files"); + try { + await reached.reached(call, "file worker call"); + controller.abort(reason); + await observed.cancelled(SERVER_SIDE, "between-file cancellation delivery"); + await test.client.ping(); + expect(await call).toMatchObject({ + code: "REQUEST_TIMEOUT", + message: expect.stringContaining(reason.message), + }); + reached.release(); + expect(await test.completion()).toBe("error"); + const result = await test.delivered(); + const { error, evidenceId, statistics } = partialStatistics(test, result); + expect(error.code).toBe("cancelled"); + expect(statistics.relevant_files).toBe(files); + // Sources run in order: the held call never ran, the rest never started. + expect(started).toBe(cancelledFile); + expect(statistics.parsed_javascript_files).toBe(cancelledFile - 1); + await observed.settled(SERVER_SIDE, "cancelled call settlement"); + expect(observed.replies).toEqual([]); + await removed(test.roots); + await expectRetainedAndServing(test, evidenceId); + } finally { + reached.release(); + await teardown(controller, observed, call); + } +}); + +it.each([ + "build_javascript_application_graph", + "validate_javascript_application_result", + "hash_javascript_application_evidence", +])( + "cancels at %s after every source parsed, keeping them and delivering no completion", + async (phase) => { + const { test, progress, evidenceId, statistics } = await cancelOneFileAt( + { + kind: "progress", + matches: (message) => message.startsWith(`${phase}:`), + }, + new Error(`cancel at ${phase}`), + phase, + ); + expect(statistics).toEqual({ + relevant_files: 1, + parsed_javascript_files: 1, + parse_failures: 0, + }); + expect(progress.at(-1)).toMatch(new RegExp(`^${phase}:`)); + expect(progress).not.toContain(TERMINAL_PROGRESS); + await expectRetainedAndServing(test, evidenceId); + // A healthy worker stays parked on the session until it closes. + await test.close(); + await removed(test.roots); + }, +); + +it("publishes a completed success whose reply was already being written when cancellation arrived", async () => { + const test = await fixture(); + const root = await oneFileApplication(); + const observed = observeToolCall(TOOL, { kind: "reply" }); + const controller = new AbortController(); + const reason = new Error("cancel while the success reply is held"); + const call = startCall(test.client, root, controller.signal); + try { + await observed.reached(call, "success reply"); + // The handler is done: it logged success and its Evidence is retained. + expect(test.statuses).toEqual(["ok"]); + const retained = test.session.exportEvidenceBundle().records; + expect(retained.map((record) => record.operation)).toEqual([TOOL]); + controller.abort(reason); + await observed.cancelled(SERVER_SIDE, "late cancellation delivery"); + await test.client.ping(); + expect(await call).toMatchObject({ + code: "REQUEST_TIMEOUT", + message: expect.stringContaining(reason.message), + }); + expect(observed.replies).toEqual([]); + observed.release(); + await observed.replySent(SERVER_SIDE, "success reply write"); + const [frame] = observed.replies; + if (frame === undefined || !isJSONRPCResultResponse(frame)) + throw new Error("Expected the success reply frame"); + expect(isCallToolResult(frame.result)).toBe(true); + expect(frame.result["isError"]).not.toBe(true); + const evidence = parseEvidence(frame.result["structuredContent"]); + expect(evidence.operation).toBe(TOOL); + expect(retained.map((record) => record.evidence_id)).toEqual([ + evidence.evidence_id, + ]); + expect(test.deliveries).toEqual([]); + expect(test.statuses).toEqual(["ok"]); + await expect(test.client.ping()).resolves.toEqual({}); + const bundle = await test.client.callTool({ + name: "get_evidence_bundle", + arguments: { detail: "summary" }, + }); + expect(retainedEvidenceIds.parse(bundle.structuredContent)).toEqual([ + evidence.evidence_id, + ]); + } finally { + await teardown(controller, observed, call); + } +}); diff --git a/tests/support/mcpToolCallObserver.ts b/tests/support/mcpToolCallObserver.ts new file mode 100644 index 00000000000..13f571899ba --- /dev/null +++ b/tests/support/mcpToolCallObserver.ts @@ -0,0 +1,188 @@ +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(); + }, + }; +};