diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index b65155dc8..c58db195f 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -150,13 +150,15 @@ structured data and matching text projection. Oversized errors are retained as Evidence before delivery of a bounded diagnostic with an export reference; if retention is unavailable or fails, the diagnostic reports that reason. -REA accepts ordinary `tools/call` progress tokens. Updates are monotonic, -rate-bounded to at most one intermediate update per 100 ms, and always allow a -terminal update. Unknown totals are omitted; REA does not fabricate percentages. +REA accepts ordinary `tools/call` progress tokens. The numeric `progress` counts +emitted status observations and strictly increases, including when a waiting +phase has completed no additional work. Updates are rate-bounded to at most one +intermediate update per 100 ms and always allow a terminal update. `total` is +omitted because the number of future status observations is unknown. Read +`message` for the phase and observed work; REA does not fabricate percentages. `capture_process_scenario` uses that boundary only when the client supplies a -progress token. Notifications set `progress` to the count of collected terminal -frames, process samples, and interaction events, omit `total`, and put the -lifecycle phase, elapsed time, and final cleanup status in `message`. A client +progress token. Notifications put the lifecycle phase, elapsed time, and final +cleanup status in `message`. A client that does not send a progress token receives no progress notifications. The tool result is unchanged either way. Provider calls receive the request cancellation signal. Artifact traversal, @@ -230,6 +232,18 @@ engine readiness or a percentage of Ghidra auto-analysis. A longer server startup allowance does not extend the client's deadline; progress also does not extend it unless the client explicitly implements that policy. +While Ghidra startup is pending, REA sends a waiting notification every ten +seconds when the request has a progress token. Its message gives elapsed waiting +time; import, auto-analysis and bridge readiness may all still be pending. +Waiting notifications stop when startup settles or the caller cancels. They do +not measure engine work completed. + +The pinned SDK can reset the request's inactivity timeout on progress with +`resetTimeoutOnProgress: true`. Also set `maxTotalTimeout` to bound the complete +request; the provider's startup deadline still applies. These options belong in +the same second argument of `callTool`. Without that explicit client policy, the +default 60-second request deadline still expires despite waiting notifications. + The 240-second setting is a measured example, not a universal timeout: a controlled Linux x64/WSL2 fixture took about 64 seconds for its first overview with Ghidra 12.1.4 on a mounted NTFS installation, native JDK 21, two CPUs, and a @@ -265,9 +279,10 @@ observed process-family member remained after final close. This was a small 1,024-byte fixture, so the longer request setting remains an example, not a guarantee for larger targets. No macOS cold-start recovery was exercised. -With a supplied progress token, the Windows run received an operation-start +With a supplied progress token, that earlier Windows run received an operation-start notification before timeout and start/completion notifications for the -successful retry. It received no intermediate import or auto-analysis progress. +successful retry, before startup waiting notifications were added. It received +no intermediate import or auto-analysis progress. These operation markers do not measure analysis work completed or extend the client's deadline. Each new provider session still imports the target into a fresh temporary project. diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts index ad35b3569..8b2b49c44 100644 --- a/src/ghidra/GhidraClient.ts +++ b/src/ghidra/GhidraClient.ts @@ -1,5 +1,6 @@ import { randomBytes, randomUUID } from "node:crypto"; import type { Socket } from "node:net"; +import type { ProgressReporter } from "../application/ProgressReporter.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import type { JsonValue } from "../domain/jsonValue.js"; @@ -162,7 +163,12 @@ export class GhidraClient { } /** Launch Ghidra once and require its exact post-analysis handshake. */ - start(signal?: AbortSignal): Promise { + start( + signal?: AbortSignal, + progress?: ProgressReporter, + ): Promise { + if (progress !== undefined) + return this.#reportStartupWait(this.start(signal), signal, progress); if (this.#closePromise !== undefined) return this.#closePromise.then( () => this.start(signal), @@ -216,6 +222,41 @@ export class GhidraClient { return started; } + async #reportStartupWait( + started: Promise, + signal: AbortSignal | undefined, + progress: ProgressReporter, + ): Promise { + const startedAt = performance.now(); + let active = true; + let reporting = false; + const timer = setInterval(() => { + if (!active || reporting || signal?.aborted) return; + reporting = true; + void Promise.resolve() + .then(() => { + if (!active || signal?.aborted) return; + return progress.report({ + phase: "ghidra_startup", + completed: 0, + total: null, + message: `Waiting for Ghidra startup (${String(Math.floor((performance.now() - startedAt) / 1000))}s elapsed); import, auto-analysis and bridge readiness may still be pending`, + }); + }) + // Notification failure does not release the owned startup process. + .catch(() => {}) + .finally(() => { + reporting = false; + }); + }, 10_000); + try { + return await started; + } finally { + active = false; + clearInterval(timer); + } + } + /** Revalidate live bridge, provider, run, and profile metadata. */ async ping( options: GhidraRequestOptions = {}, @@ -231,9 +272,12 @@ export class GhidraClient { async callTool( operation: GhidraOperation, parameters: Readonly>, - options: { readonly signal?: AbortSignal } = {}, + options: { + readonly signal?: AbortSignal; + readonly progress?: ProgressReporter; + } = {}, ): Promise> { - const started = await this.start(options.signal); + const started = await this.start(options.signal, options.progress); if (!started.ok) return started; return this.#requestQueue.run( operation, diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts index dd172cd77..91d793c12 100644 --- a/src/ghidra/GhidraProviderClient.ts +++ b/src/ghidra/GhidraProviderClient.ts @@ -573,7 +573,7 @@ export const createGhidraProviderClient = (input: { ), ); if (operation === "health") { - const started = await client.start(options?.signal); + const started = await client.start(options?.signal, options?.progress); if (!started.ok) return err( projectSessionError( @@ -596,7 +596,7 @@ export const createGhidraProviderClient = (input: { : parseGhidraInventoryInput(operation, parameters); if (!input.ok) return input; if (extensions.length > 0 || seeds !== undefined) { - const started = await client.start(options?.signal); + const started = await client.start(options?.signal, options?.progress); if (!started.ok) return err( projectSessionError( @@ -608,11 +608,12 @@ export const createGhidraProviderClient = (input: { const failed = await checkExtensions(operation, started.value); if (failed !== undefined) return err(failed); } - const called = await client.callTool( - operation, - input.value, - options?.signal === undefined ? {} : { signal: options.signal }, - ); + const called = await client.callTool(operation, input.value, { + ...(options?.signal === undefined ? {} : { signal: options.signal }), + ...(options?.progress === undefined + ? {} + : { progress: options.progress }), + }); if (!called.ok) return err( projectSessionError( @@ -637,7 +638,10 @@ export const createGhidraProviderClient = (input: { const address = input.value.address; if (typeof address === "string") { if (target.format === "pe" && nativeAotOwner !== undefined) { - const started = await client.start(options?.signal); + const started = await client.start( + options?.signal, + options?.progress, + ); if (!started.ok) return err( projectSessionError( diff --git a/src/server/mcpProgress.ts b/src/server/mcpProgress.ts index 0cbe0a194..a3fd4fde0 100644 --- a/src/server/mcpProgress.ts +++ b/src/server/mcpProgress.ts @@ -22,8 +22,10 @@ export const mcpProgressReporter = ( method: "notifications/progress", params: { progressToken: token, - progress: update.completed, - ...(update.total === null ? {} : { total: update.total }), + // Status phases can repeat their work count while waiting. The + // protocol requires every notification to advance; count emitted + // observations without inventing a total amount of analysis work. + progress: update.sequence, message: `${update.phase}: ${update.message}`, }, }); diff --git a/src/server/runDerivedOperation.test.ts b/src/server/runDerivedOperation.test.ts index f2404279a..5fc511f47 100644 --- a/src/server/runDerivedOperation.test.ts +++ b/src/server/runDerivedOperation.test.ts @@ -67,8 +67,10 @@ describe("derived MCP operation boundary", () => { ); expect(result).toEqual({ ok: true, value: "complete" }); - expect(notifications.map(({ params }) => params?.progress)).toEqual([0, 2]); - expect(notifications.every(({ params }) => params?.total === 2)).toBe(true); + expect(notifications.map(({ params }) => params?.progress)).toEqual([1, 2]); + expect( + notifications.every(({ params }) => params?.total === undefined), + ).toBe(true); }); it("projects synchronous computation failures into a typed result", async () => { diff --git a/tests/boundary/mcp/electronMcp.test.ts b/tests/boundary/mcp/electronMcp.test.ts index 39bdc3ef7..3fe41b1ca 100644 --- a/tests/boundary/mcp/electronMcp.test.ts +++ b/tests/boundary/mcp/electronMcp.test.ts @@ -415,8 +415,11 @@ it("exposes the target-free static JavaScript application workflow", async () => ); expect(analyzed.isError).not.toBe(true); - expect(progress[0]).toBe(0); - expect(progress.at(-1)).toBe(1); + expect(progress[0]).toBe(1); + expect(progress.at(-1)).toBeGreaterThan(1); + progress.forEach((value, index) => { + expect(value).toBeGreaterThan(progress[index - 1] ?? 0); + }); const projected = z .object({ evidence_id: z.string(), diff --git a/tests/boundary/mcp/progressMcp.test.ts b/tests/boundary/mcp/progressMcp.test.ts index 31c537a92..6c95b291a 100644 --- a/tests/boundary/mcp/progressMcp.test.ts +++ b/tests/boundary/mcp/progressMcp.test.ts @@ -1,4 +1,5 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { setTimeout as delay } from "node:timers/promises"; import { describe, expect, it } from "vitest"; import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js"; @@ -8,29 +9,52 @@ import { createServer } from "../../../src/server/createServer.js"; import { observed } from "../../fixtures/analysisExecution.js"; describe("ordinary MCP progress and cancellation", () => { - it("emits bounded progress for a normal tool request", async () => { + it("advances MCP progress when provider waiting does not advance completed work", async () => { const analysis: AnalysisOperationPort = { - execute: () => Promise.resolve(observed("0x1000")), + execute: async (_operation, _parameters, options) => { + for (const message of ["import pending", "analysis pending"]) { + await delay(120); + await options?.progress?.report({ + phase: "ghidra_startup", + completed: 0, + total: null, + message, + }); + } + return observed("0x1000"); + }, }; const server = createServer({ kind: "fixed", analysis }); const client = new Client({ name: "progress-test", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const progress: number[] = []; + const progress: { + progress: number; + total?: number | undefined; + message?: string | undefined; + }[] = []; try { await server.connect(serverTransport); await client.connect(clientTransport); const result = await client.callTool( { name: "current_address", arguments: {} }, - { onprogress: (update) => progress.push(update.progress) }, + { onprogress: (update) => progress.push(update) }, ); expect(result.isError).not.toBe(true); - expect(progress[0]).toBe(0); - expect(progress.at(-1)).toBe(1); - progress.forEach((value, index) => { - expect(value).toBeGreaterThanOrEqual(progress[index - 1] ?? 0); - expect(value).toBeLessThanOrEqual(1); + expect(progress[0]?.progress).toBe(1); + expect(progress.map((update) => update.message)).toEqual( + expect.arrayContaining([ + "ghidra_startup: import pending", + "ghidra_startup: analysis pending", + ]), + ); + expect(progress.at(-1)?.message).toContain("completed"); + progress.forEach((update, index) => { + expect(update.progress).toBeGreaterThan( + progress[index - 1]?.progress ?? 0, + ); + expect(update.total).toBeUndefined(); }); } finally { await Promise.allSettled([client.close(), server.close()]); diff --git a/tests/boundary/providers/ghidra/ghidraClient.test.ts b/tests/boundary/providers/ghidra/ghidraClient.test.ts index 0e84f1769..b93884792 100644 --- a/tests/boundary/providers/ghidra/ghidraClient.test.ts +++ b/tests/boundary/providers/ghidra/ghidraClient.test.ts @@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url"; import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; import pino from "pino"; import type { Logger } from "pino"; +import type { ProgressUpdate } from "../../../../src/application/ProgressReporter.js"; import { ok } from "../../../../src/domain/result.js"; import { GhidraClient } from "../../../../src/ghidra/GhidraClient.js"; @@ -146,6 +147,81 @@ afterEach(async () => { await Promise.all(clients.splice(0).map((client) => client.close())); }); +it("reports unknown startup work and stops notifications when cancellation releases the process", async () => { + vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); + const launcher = new FixtureLauncher("silent"); + const client = clientFor(launcher, { startupTimeoutMs: 30_000 }); + const controller = new AbortController(); + const updates: ProgressUpdate[] = []; + const started = client.start(controller.signal, { + report: async (update) => { + updates.push(update); + controller.abort(); + }, + }); + const child = await launcher.started; + await vi.advanceTimersByTimeAsync(10_000); + expect(await started).toMatchObject({ + ok: false, + error: { kind: "cancelled" }, + }); + expect(updates).toEqual([ + expect.objectContaining({ + phase: "ghidra_startup", + completed: 0, + total: null, + message: expect.stringContaining("Waiting for Ghidra startup"), + }), + ]); + await client.close(); + await expect(waitForChildExit(child, 5_000)).resolves.toBe(true); + await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({ + code: "ENOENT", + }); + await vi.advanceTimersByTimeAsync(30_000); + expect(updates).toHaveLength(1); +}); + +it("keeps one shared startup despite a failed progress sink and stops reports after readiness", async () => { + vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); + const launcher = new FixtureLauncher(); + let releaseLaunch: (() => void) | undefined; + let markLaunchPending: (() => void) | undefined; + const launchPending = new Promise((resolve) => { + markLaunchPending = resolve; + }); + const launchGate = new Promise((resolve) => { + releaseLaunch = resolve; + }); + const client = clientFor( + { + async launch(session) { + markLaunchPending?.(); + await launchGate; + return launcher.launch(session); + }, + }, + { startupTimeoutMs: 30_000 }, + ); + let reports = 0; + const started = client.start(undefined, { + report: async () => { + reports += 1; + throw new Error("notification unavailable"); + }, + }); + const concurrent = client.start(); + await launchPending; + await vi.advanceTimersByTimeAsync(10_000); + expect(reports).toBe(1); + releaseLaunch?.(); + await expect(started).resolves.toMatchObject({ ok: true }); + await expect(concurrent).resolves.toMatchObject({ ok: true }); + expect(launcher.processes).toHaveLength(1); + await vi.advanceTimersByTimeAsync(30_000); + expect(reports).toBe(1); +}); + describe("GhidraClient captured source snapshot", () => { it("exposes the immutable import snapshot only during the live session", async () => { const client = clientFor(new FixtureLauncher());