Files
reverse-engineering-anything/tests/fixtures/localToolsMcp.ts
T
morluto 116f159a8a fix: isolate concurrent doctor cleanup scopes, trace JS fixture helpers, and share MCP/home lifecycles
Address all four PR review findings structurally:
- Isolate concurrent Doctor probes and host subsystems in child
  ArtifactResourceScope instances tracked via resources.track() so a failed
  cleanup on one probe cannot deadlock or abort sibling reads before close().
- Include tests/ JS/TS helper modules and fixture path literals in
  throughHelpers() and named() so changes to JS fixtures such as
  fakeHopperReplies.mjs reach transitive helper and socket tests.
- Extract generic createSharedMcpSession() and reuse it in lazyLocalToolsMcp()
  to preserve retryable cleanup draining and startup-failure attribution.
- Replace test-scoped createTestTempDirectory() with a file-scoped workspace
  in jsonInputStatus.test.ts so the shared isolated home persists across tests.
2026-11-17 19:58:40 +08:00

154 lines
5.2 KiB
TypeScript

import {
canonicalOutputSchema,
withCanonicalOutputSchema,
} from "./canonicalOutputSchema.js";
import {
Client,
type CallToolRequestOptions,
type ClientOptions,
} from "@modelcontextprotocol/client";
import {
StdioClientTransport,
type StdioServerParameters,
} from "@modelcontextprotocol/client/stdio";
import { closeVerifierResources } from "../../scripts/lib/verifier-cleanup.mjs";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, expect, onTestFinished } from "vitest";
import { createMcpSchemaValidation } from "./mcpSchemaValidation.js";
import { createSharedMcpSession } from "../support/mcp/sharedMcpSession.js";
/** Default to native tools while preserving explicit caller configuration. */
export const localToolsMcpEnvironment = (
environment: Readonly<Record<string, string>> = {},
): Record<string, string> => ({
PATH: process.env.PATH ?? "/usr/bin:/bin",
REA_LOG_LEVEL: "silent",
HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper",
GHIDRA_INSTALL_DIR: process.execPath,
...environment,
});
/** Start the built production server without configuring deep binary providers. */
export async function connectLocalToolsMcp(
environment: Readonly<Record<string, string>> = {},
registerCleanup: (cleanup: () => Promise<void>) => void = onTestFinished,
transportOptions: Readonly<Pick<StdioServerParameters, "maxBufferSize">> = {},
jsonSchemaValidator?: NonNullable<ClientOptions["jsonSchemaValidator"]>,
) {
const transport = new StdioClientTransport({
...transportOptions,
command: process.execPath,
args: [
fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url)),
"mcp",
],
env: localToolsMcpEnvironment(environment),
stderr: "pipe",
});
const validation = createMcpSchemaValidation();
const client = new Client(
{ name: "local-tools-e2e", version: "1" },
{ jsonSchemaValidator: jsonSchemaValidator ?? validation },
);
registerCleanup(async () => {
await closeVerifierResources([
() => client.close(),
() => transport.close(),
() => validation.clear(),
]);
});
await client.connect(transport);
const tools = (await client.listTools()).tools;
// Catalog dialect/reference validity belongs to toolSchemaValidity and the
// compact-profile catalog tests.
// tools/list omits output schemas by default; bind each definition to its
// canonical output contract so the SDK client validates successful replies.
const definitions = new Map(
tools.map((tool) => [tool.name, withCanonicalOutputSchema(tool)]),
);
const call = async (
name: string,
arguments_: Record<string, unknown>,
options?: Pick<CallToolRequestOptions, "signal" | "onprogress">,
) => {
const definition = definitions.get(name);
const response = await client.callTool(
{ name, arguments: arguments_ },
{
...options,
...(definition === undefined ? {} : { toolDefinition: definition }),
},
);
// The SDK skips error payloads. A caller-supplied validator also retains
// the fixture's independent canonical-schema assertion.
if (
(response.isError === true || jsonSchemaValidator !== undefined) &&
response.structuredContent !== undefined &&
definition !== undefined
) {
expect(
validation.assertions.validate(
definition.outputSchema,
response.structuredContent,
),
JSON.stringify(validation.assertions.errors),
).toBe(true);
}
return response;
};
return { client, call };
}
/**
* Lazy file-scoped production stdio MCP client. Connects on first use so
* skipped files pay zero startup cost, sharing `createSharedMcpSession`'s
* retryable cleanup queue and handshake-failure attribution.
*/
export const lazyLocalToolsMcp = (
environment: Readonly<Record<string, string>> = {},
): (() => Promise<Awaited<ReturnType<typeof connectLocalToolsMcp>>>) => {
const { session, close } = createSharedMcpSession(
async (registerCleanup, isClosed) => {
if (isClosed()) throw new Error("Shared MCP session is closed");
return connectLocalToolsMcp(environment, registerCleanup);
},
);
afterAll(() => close());
return () => session.call();
};
/**
* One production stdio MCP client for the calling test file. It connects
* before the file's tests. Teardown removes each cleanup only after it
* succeeds, so a failed cleanup stays owned.
*/
export const fileLocalToolsMcp = (
environment: Readonly<Record<string, string>> = {},
) => {
let connected: Awaited<ReturnType<typeof connectLocalToolsMcp>> | undefined;
const cleanups: Array<() => Promise<void>> = [];
beforeAll(async () => {
connected = await connectLocalToolsMcp(environment, (cleanup) => {
cleanups.push(cleanup);
});
});
afterAll(async () => {
for (let cleanup = cleanups.at(-1); cleanup; cleanup = cleanups.at(-1)) {
await cleanup();
cleanups.pop();
}
});
return {
get client() {
if (connected === undefined)
throw new Error("The file's MCP client is not connected");
return connected.client;
},
get call() {
if (connected === undefined)
throw new Error("The file's MCP client is not connected");
return connected.call;
},
};
};