refactor(mcp): make analysis states unrepresentable (#468)
* refactor(config): parse capability settings into exact states * refactor(runtime): encode replay and process outcomes exactly * refactor: make analysis states unrepresentable * refactor(mcp): register canonical schemas with SDK * fix: preserve capability and catalog invariants * fix(build): remove stale compiled modules * fix(replay): update real verifier policy dependency * fix(package): verify the complete MCP catalog * fix(test): supply complete replay reload policy * refactor(contracts): centralize output schema lookup * refactor(mcp): delegate protocol boundaries to SDK * fix(browser): approve real source capture * fix(mcp): preserve catalog guidance
This commit is contained in:
@@ -38,7 +38,7 @@ it(
|
||||
const connected = await connectBrowser(browser);
|
||||
|
||||
const tools = await connected.client.listTools();
|
||||
expect(tools.tools.length).toBeLessThan(TOOL_CONTRACTS.length);
|
||||
expect(tools.tools).toHaveLength(TOOL_CONTRACTS.length);
|
||||
expect(tools.tools.map(({ name }) => name)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"list_browser_targets",
|
||||
@@ -80,6 +80,17 @@ it(
|
||||
targets: { items: [{ target_id: "allowed-page" }] },
|
||||
},
|
||||
});
|
||||
const unapprovedSourceCapture = await connected.client.callTool({
|
||||
name: "inspect_web_page",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
include_script_sources: true,
|
||||
},
|
||||
});
|
||||
expect(unapprovedSourceCapture.isError).toBe(true);
|
||||
const inspected = await connected.client.callTool({
|
||||
name: "inspect_web_page",
|
||||
arguments: {
|
||||
@@ -95,6 +106,7 @@ it(
|
||||
include_websocket_shapes: true,
|
||||
websocket_shape_approved: true,
|
||||
include_script_sources: true,
|
||||
source_capture_approved: true,
|
||||
},
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
@@ -205,6 +217,11 @@ const verifySessionAndComparisonTools = async (
|
||||
expect(compared.structuredContent).toMatchObject({
|
||||
result: { overall_status: "unknown" },
|
||||
});
|
||||
const incompleteComparison = await connected.client.callTool({
|
||||
name: "compare_web_captures",
|
||||
arguments: { before: { inspection: capture } },
|
||||
});
|
||||
expect(incompleteComparison.isError).toBe(true);
|
||||
const screenshot = await connected.client.callTool({
|
||||
name: "capture_web_screenshot",
|
||||
arguments: {
|
||||
|
||||
@@ -439,7 +439,7 @@ it("reports an unconfigured investigation ceiling before static analysis", async
|
||||
(await client.listTools()).tools.some(
|
||||
({ name }) => name === "analyze_javascript_application",
|
||||
),
|
||||
).toBe(false);
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
const evidenceFor = (session: BinarySession, value: unknown) => {
|
||||
|
||||
@@ -219,7 +219,7 @@ describe("enhanced MCP tools", () => {
|
||||
expect(JSON.stringify(result)).toContain("operation budget");
|
||||
});
|
||||
|
||||
it("returns correction-only structured validation issues", async () => {
|
||||
it("lets the SDK reject misspelled and out-of-range inputs", async () => {
|
||||
const client = await connect();
|
||||
const valid = await client.callTool({
|
||||
name: "trace_feature",
|
||||
@@ -230,18 +230,8 @@ describe("enhanced MCP tools", () => {
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operatons: 1 },
|
||||
});
|
||||
expect(misspelled).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
retryable: true,
|
||||
details: {
|
||||
issues: [{ path: ["max_operatons"], reason: "unknown_argument" }],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(misspelled.isError).toBe(true);
|
||||
expect(misspelled.structuredContent).toBeUndefined();
|
||||
const nestedMisspelled = await client.callTool({
|
||||
name: "analyze_function",
|
||||
arguments: {
|
||||
@@ -249,42 +239,14 @@ describe("enhanced MCP tools", () => {
|
||||
collection_offset: { commentz: 1 },
|
||||
},
|
||||
});
|
||||
expect(nestedMisspelled).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: {
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["collection_offset", "commentz"],
|
||||
reason: "unknown_argument",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(nestedMisspelled.isError).toBe(true);
|
||||
expect(nestedMisspelled.structuredContent).toBeUndefined();
|
||||
const bounded = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operations: 101 },
|
||||
});
|
||||
expect(bounded.structuredContent).toMatchObject({
|
||||
error: {
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["max_operations"],
|
||||
reason: "out_of_range",
|
||||
maximum: 100,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(bounded.content[0]).toEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(bounded.structuredContent),
|
||||
});
|
||||
expect(bounded.isError).toBe(true);
|
||||
expect(bounded.structuredContent).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns a typed tool error for malformed Hopper boundary values", async () => {
|
||||
|
||||
@@ -22,7 +22,7 @@ describe("Ghidra MCP capability routing", () => {
|
||||
const availableNames = (await mcp.listTools()).tools.map(
|
||||
({ name }) => name,
|
||||
);
|
||||
expect(availableNames).not.toContain("set_comment");
|
||||
expect(availableNames).toContain("set_comment");
|
||||
expect(calls).not.toContain("set_comment");
|
||||
|
||||
const status = await mcp.callTool({
|
||||
|
||||
@@ -14,12 +14,14 @@ const dependencies = ({
|
||||
shutdown,
|
||||
exitCodes,
|
||||
shutdownUnregistrations = [],
|
||||
loadOptionalProviders,
|
||||
}: {
|
||||
readonly serve: RuntimeDependencies["serve"];
|
||||
readonly output: string[];
|
||||
readonly shutdown: Array<() => void>;
|
||||
readonly exitCodes: number[];
|
||||
readonly shutdownUnregistrations?: string[];
|
||||
readonly loadOptionalProviders?: RuntimeDependencies["loadOptionalProviders"];
|
||||
}): RuntimeDependencies => ({
|
||||
env: {},
|
||||
serve,
|
||||
@@ -29,6 +31,7 @@ const dependencies = ({
|
||||
shutdown.push(handler);
|
||||
return () => shutdownUnregistrations.push("shutdown");
|
||||
},
|
||||
...(loadOptionalProviders === undefined ? {} : { loadOptionalProviders }),
|
||||
});
|
||||
|
||||
describe("MCP runtime errors", () => {
|
||||
@@ -121,6 +124,28 @@ describe("MCP runtime errors", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("starts the core transport when optional providers fail to load", async () => {
|
||||
const output: string[] = [];
|
||||
let serveCalls = 0;
|
||||
expect(
|
||||
await run(
|
||||
dependencies({
|
||||
serve: () => {
|
||||
serveCalls += 1;
|
||||
return { close: () => Promise.resolve() };
|
||||
},
|
||||
output,
|
||||
shutdown: [],
|
||||
exitCodes: [],
|
||||
loadOptionalProviders: () =>
|
||||
Promise.reject(new Error("synthetic optional import failure")),
|
||||
}),
|
||||
),
|
||||
).toBe(0);
|
||||
expect(serveCalls).toBe(1);
|
||||
expect(output).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports shutdown failure and sets a failing exit code", async () => {
|
||||
const output: string[] = [];
|
||||
const shutdown: Array<() => void> = [];
|
||||
|
||||
@@ -53,23 +53,29 @@ describe("runtime permission reload", () => {
|
||||
runtime.reload();
|
||||
await validReadStarted.promise;
|
||||
|
||||
expect(runtime.notifications()).toBe(0);
|
||||
expect(runtime.options.processPolicy?.enabled).toBe(false);
|
||||
expect(runtime.options.processPolicy?.().status).toBe("disabled");
|
||||
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
|
||||
fixture.oldRoot,
|
||||
]);
|
||||
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(false);
|
||||
expectOptionalPolicies(runtime.options, { status: "disabled" });
|
||||
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(true);
|
||||
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(false);
|
||||
|
||||
releaseValidRead.resolve();
|
||||
await runtime.notificationCount(1);
|
||||
await expect
|
||||
.poll(() => canRead(runtime.authority, fixture.newRoot))
|
||||
.toBe(true);
|
||||
|
||||
expect(runtime.options.processPolicy?.enabled).toBe(true);
|
||||
expect(runtime.options.processPolicy?.().status).toBe("enabled");
|
||||
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
|
||||
fixture.newRoot,
|
||||
]);
|
||||
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(true);
|
||||
expectOptionalPolicies(runtime.options, {
|
||||
status: "enabled",
|
||||
root: fixture.newRoot,
|
||||
});
|
||||
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(false);
|
||||
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(true);
|
||||
});
|
||||
@@ -102,13 +108,16 @@ describe("runtime permission reload", () => {
|
||||
expect(secondStarted).toBe(false);
|
||||
releaseFirstRead.resolve();
|
||||
await secondReadStarted.promise;
|
||||
await runtime.notificationCount(2);
|
||||
await expect
|
||||
.poll(() => canRead(runtime.authority, fixture.latestRoot))
|
||||
.toBe(true);
|
||||
|
||||
expect(runtime.options.processPolicy?.enabled).toBe(false);
|
||||
expect(runtime.options.processPolicy?.().status).toBe("disabled");
|
||||
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
|
||||
fixture.latestRoot,
|
||||
]);
|
||||
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(false);
|
||||
expectOptionalPolicies(runtime.options, { status: "disabled" });
|
||||
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(false);
|
||||
expect(await canRead(runtime.authority, fixture.latestRoot)).toBe(true);
|
||||
});
|
||||
@@ -125,19 +134,57 @@ describe("runtime permission reload", () => {
|
||||
configure(fixture.env, fixture.newRoot, true);
|
||||
runtime.reload();
|
||||
runtime.reload();
|
||||
await runtime.notificationCount(1);
|
||||
await expect.poll(() => reads).toBe(2);
|
||||
await expect
|
||||
.poll(() => canRead(runtime.authority, fixture.newRoot))
|
||||
.toBe(true);
|
||||
|
||||
expect(reads).toBe(2);
|
||||
expect(runtime.options.processPolicy?.enabled).toBe(true);
|
||||
expect(runtime.options.processPolicy?.().status).toBe("enabled");
|
||||
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
|
||||
fixture.newRoot,
|
||||
]);
|
||||
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(true);
|
||||
expectOptionalPolicies(runtime.options, {
|
||||
status: "enabled",
|
||||
root: fixture.newRoot,
|
||||
});
|
||||
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(false);
|
||||
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
type ExpectedOptionalPolicies =
|
||||
| { readonly status: "disabled" }
|
||||
| { readonly status: "enabled"; readonly root: string };
|
||||
|
||||
const expectOptionalPolicies = (
|
||||
options: CreateServerOptions,
|
||||
expected: ExpectedOptionalPolicies,
|
||||
): void => {
|
||||
const enabled = expected.status === "enabled";
|
||||
expect(options.managedRuntimePolicy?.()).toEqual(
|
||||
enabled
|
||||
? {
|
||||
status: "enabled",
|
||||
roots: [expected.root],
|
||||
executablePath: process.execPath,
|
||||
}
|
||||
: { status: "disabled" },
|
||||
);
|
||||
expect(options.javascriptReplayPolicy?.()).toMatchObject(
|
||||
enabled
|
||||
? { status: "enabled", roots: [expected.root] }
|
||||
: { status: "disabled" },
|
||||
);
|
||||
expect(options.availabilityPolicy?.()).toMatchObject({
|
||||
browserObservationEnabled: enabled,
|
||||
electronObservationEnabled: enabled,
|
||||
v8InspectorObservationEnabled: enabled,
|
||||
javascriptReplayEnabled: enabled,
|
||||
});
|
||||
};
|
||||
|
||||
const reloadFixture = async () => {
|
||||
const directory = await createTestTempDirectory("rea-main-reload-");
|
||||
directories.push(directory);
|
||||
@@ -169,6 +216,33 @@ const configure = (
|
||||
env.REA_PROCESS_EXECUTABLE_ROOTS_JSON = JSON.stringify([root]);
|
||||
env.REA_PROCESS_WORKING_ROOTS_JSON = JSON.stringify([root]);
|
||||
env.REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED = String(enabled);
|
||||
env.REA_MANAGED_RUNTIME_ENABLED = String(enabled);
|
||||
env.REA_MANAGED_RUNTIME_ROOTS_JSON = JSON.stringify([root]);
|
||||
env.REA_MANAGED_RUNTIME_EXECUTABLE_PATH = process.execPath;
|
||||
env.REA_JAVASCRIPT_REPLAY_ENABLED = String(enabled);
|
||||
env.REA_JAVASCRIPT_REPLAY_ROOTS_JSON = JSON.stringify([root]);
|
||||
env.REA_JAVASCRIPT_REPLAY_NODE_PATH = process.execPath;
|
||||
env.REA_JAVASCRIPT_REPLAY_BWRAP_PATH = process.execPath;
|
||||
env.REA_JAVASCRIPT_REPLAY_SYSTEMD_RUN_PATH = process.execPath;
|
||||
env.REA_JAVASCRIPT_REPLAY_SYSTEMCTL_PATH = process.execPath;
|
||||
env.REA_JAVASCRIPT_REPLAY_SHELL_PATH = process.execPath;
|
||||
env.REA_BROWSER_OBSERVE_ENABLED = String(enabled);
|
||||
env.REA_BROWSER_CDP_ENDPOINTS_JSON = JSON.stringify([
|
||||
"http://127.0.0.1:9222",
|
||||
]);
|
||||
env.REA_BROWSER_ALLOWED_ORIGINS_JSON = JSON.stringify([
|
||||
"https://example.test",
|
||||
]);
|
||||
env.REA_ELECTRON_OBSERVE_ENABLED = String(enabled);
|
||||
env.REA_ELECTRON_CDP_ENDPOINTS_JSON = JSON.stringify([
|
||||
"http://127.0.0.1:9223",
|
||||
]);
|
||||
env.REA_ELECTRON_FILE_ROOTS_JSON = JSON.stringify([root]);
|
||||
env.REA_V8_INSPECTOR_OBSERVE_ENABLED = String(enabled);
|
||||
env.REA_V8_INSPECTOR_ENDPOINTS_JSON = JSON.stringify([
|
||||
"http://127.0.0.1:9224",
|
||||
]);
|
||||
env.REA_V8_INSPECTOR_FILE_ROOTS_JSON = JSON.stringify([root]);
|
||||
};
|
||||
|
||||
const startRuntime = async (
|
||||
@@ -177,9 +251,6 @@ const startRuntime = async (
|
||||
) => {
|
||||
let reload: (() => void) | undefined;
|
||||
let options: CreateServerOptions | undefined;
|
||||
let notificationCount = 0;
|
||||
let notification = deferred<void>();
|
||||
const waiters = new Map<number, ReturnType<typeof deferred<void>>>();
|
||||
const result = await run({
|
||||
env,
|
||||
serve: (factory) => {
|
||||
@@ -196,14 +267,7 @@ const startRuntime = async (
|
||||
readProjectPermissionStore: readStore,
|
||||
createServer: (analysis, session, received) => {
|
||||
options = received;
|
||||
const server = createServer(analysis, session, received);
|
||||
server.sendToolListChanged = () => {
|
||||
notificationCount += 1;
|
||||
notification.resolve(undefined);
|
||||
notification = deferred<void>();
|
||||
waiters.get(notificationCount)?.resolve(undefined);
|
||||
};
|
||||
return server;
|
||||
return createServer(analysis, session, received);
|
||||
},
|
||||
});
|
||||
expect(result).toBe(0);
|
||||
@@ -215,13 +279,6 @@ const startRuntime = async (
|
||||
reload,
|
||||
options: capturedOptions,
|
||||
authority,
|
||||
notifications: () => notificationCount,
|
||||
notificationCount: (count: number) => {
|
||||
if (notificationCount >= count) return Promise.resolve();
|
||||
const waiter = deferred<void>();
|
||||
waiters.set(count, waiter);
|
||||
return waiter.promise;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -55,11 +55,11 @@ it("opens a managed PE and executes the managed static provider through MCP", as
|
||||
if (!authority.ok) throw authority.error;
|
||||
const server = createServer(session, session, {
|
||||
permissionAuthority: authority.value,
|
||||
managedRuntimePolicy: {
|
||||
enabled: true,
|
||||
managedRuntimePolicy: () => ({
|
||||
status: "enabled",
|
||||
roots: [directory],
|
||||
executablePath: runtimePath,
|
||||
},
|
||||
}),
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
|
||||
@@ -46,7 +46,7 @@ describe("production MCP doctor", () => {
|
||||
expect(result.inventory?.tools.expected).toBe(
|
||||
result.inventory?.tools.observed,
|
||||
);
|
||||
expect(result.inventory?.tools.expected).toBeLessThan(
|
||||
expect(result.inventory?.tools.expected).toBe(
|
||||
CATALOG_IDENTITY.counts.mcp_tools,
|
||||
);
|
||||
}, 30_000);
|
||||
|
||||
@@ -34,13 +34,13 @@ describe("process-capture MCP elicitation handshake", () => {
|
||||
createServer(session, session, {
|
||||
logger: silentLogger,
|
||||
permissionAuthority: authority,
|
||||
processPolicy: {
|
||||
enabled: true,
|
||||
processPolicy: () => ({
|
||||
status: "enabled",
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
networkAccess: "external",
|
||||
}),
|
||||
});
|
||||
const client = new Client(
|
||||
{ name: "process-elicit", version: "1" },
|
||||
@@ -70,6 +70,29 @@ describe("process-capture MCP elicitation handshake", () => {
|
||||
});
|
||||
try {
|
||||
await client.connect(clientTransport);
|
||||
const identity = await client.readResource({
|
||||
uri: "rea://server/identity",
|
||||
});
|
||||
const identityContent = identity.contents[0];
|
||||
if (identityContent === undefined || !("text" in identityContent))
|
||||
throw new Error("missing modern server identity resource");
|
||||
expect(JSON.parse(identityContent.text)).toMatchObject({
|
||||
client: { name: "process-elicit", version: "1" },
|
||||
});
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
client_features: {
|
||||
elicitation_form: true,
|
||||
elicitation_url: false,
|
||||
roots: false,
|
||||
sampling: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
const captured = await client.callTool({
|
||||
name: "capture_process_scenario",
|
||||
arguments: {
|
||||
|
||||
@@ -56,13 +56,13 @@ describe("process-capture MCP elicitation handshake", () => {
|
||||
createServer(session, session, {
|
||||
logger: silentLogger,
|
||||
permissionAuthority: authority,
|
||||
processPolicy: {
|
||||
enabled: true,
|
||||
processPolicy: () => ({
|
||||
status: "enabled",
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
networkAccess: "external",
|
||||
}),
|
||||
}),
|
||||
{ transport: serverTransport, legacy: "reject" },
|
||||
);
|
||||
|
||||
@@ -59,10 +59,8 @@ describe("direct replay machine MCP parity", () => {
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(invalid).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: { error: { code: "invalid_request" } },
|
||||
});
|
||||
expect(invalid.isError).toBe(true);
|
||||
expect(invalid.structuredContent).toBeUndefined();
|
||||
expect(JSON.stringify(invalid)).not.toContain("private-request-body");
|
||||
} finally {
|
||||
await client.close();
|
||||
|
||||
@@ -59,6 +59,41 @@ const availabilityProvider = (): AnalysisProvider => {
|
||||
};
|
||||
};
|
||||
|
||||
const statusCapability = (
|
||||
operation: string,
|
||||
availability:
|
||||
| { readonly available: true }
|
||||
| {
|
||||
readonly available: false;
|
||||
readonly availability_code: "unsupported_host";
|
||||
readonly reason: string;
|
||||
} = { available: true },
|
||||
) => ({
|
||||
operation,
|
||||
input_contract_version: 1,
|
||||
output_contract_version: 1,
|
||||
pagination: "none" as const,
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutates_artifact: false,
|
||||
launches_process: false,
|
||||
may_show_ui: false,
|
||||
may_access_network: false,
|
||||
may_write_filesystem: false,
|
||||
changes_permissions: false,
|
||||
requires_root: false,
|
||||
},
|
||||
limits: {
|
||||
max_results: null,
|
||||
max_payload_bytes: null,
|
||||
timeout_ms: null,
|
||||
},
|
||||
limitations: [],
|
||||
...(availability.available
|
||||
? { available: true as const, reason: null, availability_code: null }
|
||||
: availability),
|
||||
});
|
||||
|
||||
describe("server and catalog identity", () => {
|
||||
it("derives package and SDK versions from canonical package metadata", async () => {
|
||||
const packageJson = JSON.parse(await readFile("package.json", "utf8"));
|
||||
@@ -132,7 +167,7 @@ describe("server and catalog identity", () => {
|
||||
"list_documents",
|
||||
"list_procedures",
|
||||
"list_strings",
|
||||
].map((operation) => ({ operation, available: true, reason: null })),
|
||||
].map((operation) => statusCapability(operation)),
|
||||
},
|
||||
policy,
|
||||
);
|
||||
@@ -144,9 +179,7 @@ describe("server and catalog identity", () => {
|
||||
open: true,
|
||||
kind: "artifact",
|
||||
format: "javascript",
|
||||
capabilities: [
|
||||
{ operation: "current_address", available: true, reason: null },
|
||||
],
|
||||
capabilities: [statusCapability("current_address")],
|
||||
},
|
||||
policy,
|
||||
);
|
||||
@@ -163,12 +196,11 @@ describe("server and catalog identity", () => {
|
||||
kind: "executable",
|
||||
format: "elf",
|
||||
capabilities: [
|
||||
{
|
||||
operation: "inspect_macho",
|
||||
statusCapability("inspect_macho", {
|
||||
available: false,
|
||||
availability_code: "unsupported_host",
|
||||
reason: "Native macOS utilities require macOS.",
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
policy,
|
||||
@@ -184,7 +216,7 @@ describe("server and catalog identity", () => {
|
||||
});
|
||||
|
||||
describe("live server identity over MCP", () => {
|
||||
it("exposes live identity, labeled inventories, availability, and list changes", async () => {
|
||||
it("exposes live identity, a stable catalog, and changing availability", async () => {
|
||||
const session = composeBinarySessionFromProvider(availabilityProvider());
|
||||
const server = createServer(session, session);
|
||||
const client = new Client(
|
||||
@@ -209,12 +241,12 @@ describe("live server identity over MCP", () => {
|
||||
await assertCapabilityViews(client);
|
||||
expect(
|
||||
(await client.listTools()).tools.map(({ name }) => name),
|
||||
).not.toContain("current_address");
|
||||
).toContain("current_address");
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: process.execPath },
|
||||
});
|
||||
await expect.poll(() => toolListChanges).toBeGreaterThan(0);
|
||||
expect(toolListChanges).toBe(0);
|
||||
expect(
|
||||
(await client.listTools()).tools.map(({ name }) => name),
|
||||
).toContain("current_address");
|
||||
@@ -251,7 +283,7 @@ const assertLiveIdentity = async (client: Client): Promise<void> => {
|
||||
server: SDK_IDENTITY.server,
|
||||
client_test: PACKAGE_METADATA.clientSdkVersion,
|
||||
},
|
||||
client: { name: "identity-test", version: "9" },
|
||||
client: null,
|
||||
alignment: { state: "unknown" },
|
||||
});
|
||||
};
|
||||
@@ -286,7 +318,7 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
|
||||
required: [],
|
||||
optional: ["elicitation_form"],
|
||||
missing_required: [],
|
||||
missing_optional: [],
|
||||
missing_optional: ["elicitation_form"],
|
||||
},
|
||||
}),
|
||||
expect.objectContaining({
|
||||
@@ -304,7 +336,7 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
|
||||
}),
|
||||
]),
|
||||
client_features: {
|
||||
elicitation_form: true,
|
||||
elicitation_form: false,
|
||||
elicitation_url: false,
|
||||
roots: false,
|
||||
sampling: false,
|
||||
@@ -354,7 +386,7 @@ const assertCapabilityViews = async (client: Client): Promise<void> => {
|
||||
has_more: true,
|
||||
},
|
||||
client_features: {
|
||||
elicitation_form: true,
|
||||
elicitation_form: false,
|
||||
elicitation_url: false,
|
||||
roots: false,
|
||||
sampling: false,
|
||||
|
||||
@@ -85,6 +85,31 @@ it("projects remote failures without provider or bridge details", async () => {
|
||||
expect(text(result)).toBe(JSON.stringify(result.structuredContent));
|
||||
});
|
||||
|
||||
it("lets the SDK validate a tool call before invoking its handler", async () => {
|
||||
let invocations = 0;
|
||||
const client = await connect({
|
||||
execute: () => {
|
||||
invocations += 1;
|
||||
return Promise.resolve(ok([]));
|
||||
},
|
||||
});
|
||||
|
||||
const malformed = await client.callTool({
|
||||
name: "procedure_info",
|
||||
arguments: {},
|
||||
});
|
||||
|
||||
expect(malformed.isError).toBe(true);
|
||||
expect(invocations).toBe(0);
|
||||
|
||||
const valid = await client.callTool({
|
||||
name: "list_documents",
|
||||
arguments: {},
|
||||
});
|
||||
expect(valid.isError).not.toBe(true);
|
||||
expect(invocations).toBe(1);
|
||||
});
|
||||
|
||||
it("handles concurrent tool calls without corruption", async () => {
|
||||
const invocations: string[] = [];
|
||||
const client = await connect({
|
||||
|
||||
@@ -43,86 +43,6 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
return Object.fromEntries(Object.entries(result.structuredContent));
|
||||
};
|
||||
|
||||
const objectEntries = (value: unknown): readonly [string, unknown][] =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
? Object.entries(value)
|
||||
: [];
|
||||
|
||||
const referencedSchema = (schema: unknown, root: unknown): unknown => {
|
||||
const object = Object.fromEntries(objectEntries(schema));
|
||||
const reference = object.$ref;
|
||||
if (typeof reference !== "string" || !reference.startsWith("#/$defs/"))
|
||||
return schema;
|
||||
return Object.fromEntries(objectEntries(root)).$defs instanceof Object
|
||||
? Object.fromEntries(
|
||||
objectEntries(Object.fromEntries(objectEntries(root)).$defs),
|
||||
)[reference.slice(8)]
|
||||
: schema;
|
||||
};
|
||||
|
||||
const assertDescribedStrictObjects = (
|
||||
schema: unknown,
|
||||
root = schema,
|
||||
path = "$",
|
||||
strictObject = true,
|
||||
): void => {
|
||||
for (const [key, value] of objectEntries(schema)) {
|
||||
if (key === "examples") continue;
|
||||
if (key === "properties") {
|
||||
const properties = objectEntries(value);
|
||||
for (const [property, propertySchema] of properties) {
|
||||
const resolved = referencedSchema(propertySchema, root);
|
||||
const propertyObject = Object.fromEntries(
|
||||
objectEntries(propertySchema),
|
||||
);
|
||||
expect(
|
||||
propertyObject.description ??
|
||||
Object.fromEntries(objectEntries(resolved)).description,
|
||||
`${path}.properties.${property}`,
|
||||
).toEqual(expect.any(String));
|
||||
assertDescribedStrictObjects(
|
||||
propertySchema,
|
||||
root,
|
||||
`${path}.properties.${property}`,
|
||||
);
|
||||
}
|
||||
if (strictObject)
|
||||
expect(
|
||||
Object.fromEntries(objectEntries(schema)).additionalProperties,
|
||||
).toBe(false);
|
||||
continue;
|
||||
}
|
||||
assertDescribedStrictObjects(
|
||||
value,
|
||||
root,
|
||||
`${path}.${key}`,
|
||||
strictObject &&
|
||||
key !== "allOf" &&
|
||||
key !== "contains" &&
|
||||
key !== "if" &&
|
||||
key !== "then",
|
||||
);
|
||||
}
|
||||
if (Array.isArray(schema))
|
||||
for (const [index, value] of schema.entries())
|
||||
assertDescribedStrictObjects(
|
||||
value,
|
||||
root,
|
||||
`${path}[${String(index)}]`,
|
||||
strictObject,
|
||||
);
|
||||
};
|
||||
|
||||
const assertDescribedRootObject = (schema: unknown, path: string): void => {
|
||||
const object = Object.fromEntries(objectEntries(schema));
|
||||
expect(object.additionalProperties, path).toBe(false);
|
||||
for (const [property, propertySchema] of objectEntries(object.properties))
|
||||
expect(
|
||||
Object.fromEntries(objectEntries(propertySchema)).description,
|
||||
`${path}.properties.${property}`,
|
||||
).toEqual(expect.any(String));
|
||||
};
|
||||
|
||||
it("executes a realistic workflow: list methods, decompile selected, get xrefs", async () => {
|
||||
const client = await connect({
|
||||
execute: (name, args) => {
|
||||
@@ -213,8 +133,8 @@ it("advertises the complete currently available inventory with a session", async
|
||||
expect(names).toContain("open_binary");
|
||||
expect(names).toContain("close_binary");
|
||||
expect(names).toContain("binary_session");
|
||||
expect(names).not.toContain("binary_overview");
|
||||
expect(names).not.toContain("batch_decompile");
|
||||
expect(names).toContain("binary_overview");
|
||||
expect(names).toContain("batch_decompile");
|
||||
const status = structured(
|
||||
await client.callTool({
|
||||
name: "binary_session",
|
||||
@@ -234,7 +154,11 @@ it("advertises the complete currently available inventory with a session", async
|
||||
.result.tool_availability.filter((item) => item.available)
|
||||
.map(({ name }) => name),
|
||||
);
|
||||
expect(new Set(names)).toEqual(available);
|
||||
expect(new Set(names)).toEqual(
|
||||
new Set(TOOL_CONTRACTS.map(({ name }) => name)),
|
||||
);
|
||||
expect(available).not.toContain("binary_overview");
|
||||
expect(available).not.toContain("batch_decompile");
|
||||
|
||||
const contracts = new Map<string, (typeof TOOL_CONTRACTS)[number]>(
|
||||
TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
|
||||
@@ -245,8 +169,7 @@ it("advertises the complete currently available inventory with a session", async
|
||||
expect(tool.title, tool.name).toBe(contract?.title);
|
||||
expect(tool.description, tool.name).toBe(contract?.description);
|
||||
expect(tool.annotations, tool.name).toEqual(contract?.annotations);
|
||||
expect(tool.inputSchema, tool.name).toBeDefined();
|
||||
expect(tool.outputSchema, tool.name).toBeDefined();
|
||||
assertDescribedStrictObjects(tool.inputSchema, tool.inputSchema, tool.name);
|
||||
assertDescribedRootObject(tool.outputSchema, `${tool.name}.output`);
|
||||
}
|
||||
}, 10_000);
|
||||
|
||||
@@ -130,8 +130,8 @@ describe("target-free MCP workflow", () => {
|
||||
);
|
||||
expect(beforeNames).toContain("open_binary");
|
||||
expect(beforeNames).toContain("binary_session");
|
||||
expect(beforeNames).not.toContain("current_document");
|
||||
expect(beforeNames).not.toContain("capture_process_scenario");
|
||||
expect(beforeNames).toContain("current_document");
|
||||
expect(beforeNames).toContain("capture_process_scenario");
|
||||
expect(
|
||||
(await mcp.callTool({ name: "open_binary", arguments: { path: first } }))
|
||||
.isError,
|
||||
@@ -235,13 +235,13 @@ describe("process residuals over MCP", () => {
|
||||
);
|
||||
const server = createServer(session, session, {
|
||||
logger: silentLogger,
|
||||
processPolicy: {
|
||||
enabled: true,
|
||||
processPolicy: () => ({
|
||||
status: "enabled",
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [dirname(processFixture)],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
networkAccess: "external",
|
||||
}),
|
||||
});
|
||||
const mcp = new Client({ name: "process-unknown", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
|
||||
@@ -1,68 +1,164 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
describe("tool registration options", () => {
|
||||
it("reuses finalized advertised schemas", () => {
|
||||
const contract = TOOL_CONTRACTS[0];
|
||||
expect(contract).toBeDefined();
|
||||
if (contract === undefined) return;
|
||||
|
||||
const first = toolRegistrationOptions(contract);
|
||||
const second = toolRegistrationOptions(contract);
|
||||
expect(first.inputSchema["~standard"].jsonSchema.input()).toBe(
|
||||
second.inputSchema["~standard"].jsonSchema.output(),
|
||||
);
|
||||
expect(first.outputSchema["~standard"].jsonSchema.input()).toBe(
|
||||
second.outputSchema["~standard"].jsonSchema.output(),
|
||||
);
|
||||
it("preserves canonical Zod parsers in the SDK schemas", () => {
|
||||
for (const contract of TOOL_CONTRACTS) {
|
||||
const options = toolRegistrationOptions(contract);
|
||||
expect(options.inputSchema).not.toBe(contract.inputSchema);
|
||||
expect(
|
||||
options.inputSchema.safeParse(contract.examples[0]?.input ?? {}),
|
||||
).toEqual(
|
||||
contract.inputSchema.safeParse(contract.examples[0]?.input ?? {}),
|
||||
);
|
||||
expect(options.outputSchema).toBe(contract.outputSchema);
|
||||
}
|
||||
});
|
||||
|
||||
it("gives fallback parameter guidance operational meaning", () => {
|
||||
it("retains the canonical parser as the SDK validation boundary", async () => {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "analyze_function",
|
||||
);
|
||||
expect(contract).toBeDefined();
|
||||
if (contract === undefined) return;
|
||||
|
||||
const advertisedSchema =
|
||||
toolRegistrationOptions(contract).inputSchema[
|
||||
"~standard"
|
||||
].jsonSchema.input();
|
||||
const properties = Object.fromEntries(
|
||||
Object.entries(advertisedSchema.properties ?? {}),
|
||||
);
|
||||
expect(properties.include_assembly).toMatchObject({
|
||||
description: "Whether to include assembly in the result.",
|
||||
});
|
||||
expect(properties.max_instructions).toMatchObject({
|
||||
description: "Maximum permitted instructions for this operation.",
|
||||
});
|
||||
expect(properties.pseudocode_offset).toMatchObject({
|
||||
description: "Zero-based index of the first pseudocode to return.",
|
||||
});
|
||||
const result = await contract.inputSchema["~standard"].validate({});
|
||||
expect("issues" in result).toBe(true);
|
||||
});
|
||||
|
||||
it("advertises validated contract examples on the MCP input schema", () => {
|
||||
for (const name of [
|
||||
"record_unknown",
|
||||
"run_replay_machine",
|
||||
"build_reconstruction_obligation_ledger",
|
||||
]) {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
(candidate) => candidate.name === name,
|
||||
it("generates the checked-in catalog from the SDK wire projection", async () => {
|
||||
const server = new McpServer({ name: "catalog-test", version: "0" });
|
||||
for (const contract of TOOL_CONTRACTS)
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async () => ({
|
||||
content: [{ type: "text" as const, text: "catalog-only" }],
|
||||
isError: true as const,
|
||||
}),
|
||||
);
|
||||
expect(contract).toBeDefined();
|
||||
if (contract === undefined) continue;
|
||||
const client = new Client({ name: "catalog-test", version: "0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = (await client.listTools()).tools.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
}));
|
||||
for (const contract of TOOL_CONTRACTS) {
|
||||
const tool = advertised.find(({ name }) => name === contract.name);
|
||||
expect(tool?.inputSchema.examples, contract.name).toEqual(
|
||||
contract.examples.map(({ input }) => input),
|
||||
);
|
||||
expect(
|
||||
missingPropertyDescriptions(tool?.inputSchema),
|
||||
contract.name,
|
||||
).toEqual([]);
|
||||
}
|
||||
const analyzeFunction = advertised.find(
|
||||
({ name }) => name === "analyze_function",
|
||||
);
|
||||
expect(analyzeFunction?.inputSchema.properties).toMatchObject({
|
||||
include_assembly: {
|
||||
description: "Whether to include assembly in the result.",
|
||||
},
|
||||
max_instructions: {
|
||||
description: "Maximum permitted instructions for this operation.",
|
||||
},
|
||||
pseudocode_offset: {
|
||||
description: "Zero-based index of the first pseudocode to return.",
|
||||
},
|
||||
});
|
||||
expect(advertised).toEqual(
|
||||
GENERATED_MCP_TOOL_CATALOG.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
})),
|
||||
);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
const schema =
|
||||
toolRegistrationOptions(contract).inputSchema[
|
||||
"~standard"
|
||||
].jsonSchema.input();
|
||||
expect(schema.examples).toEqual(
|
||||
contract.examples.map(({ input }) => input),
|
||||
it("delegates output validation to the SDK boundary", async () => {
|
||||
const server = new McpServer({ name: "output-test", version: "0" });
|
||||
server.registerTool(
|
||||
"invalid_output",
|
||||
{
|
||||
inputSchema: z.object({}),
|
||||
outputSchema: z.object({ value: z.string() }),
|
||||
},
|
||||
async () => ({
|
||||
content: [{ type: "text", text: "invalid" }],
|
||||
structuredContent: { value: 42 },
|
||||
}),
|
||||
);
|
||||
const client = new Client({ name: "output-test", version: "0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({ name: "invalid_output" });
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "text",
|
||||
text: expect.stringContaining("Output validation error"),
|
||||
}),
|
||||
);
|
||||
expect(result.structuredContent).toBeUndefined();
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const missingPropertyDescriptions = (
|
||||
value: unknown,
|
||||
path = "inputSchema",
|
||||
): string[] => {
|
||||
if (Array.isArray(value))
|
||||
return value.flatMap((child, index) =>
|
||||
missingPropertyDescriptions(child, `${path}[${index}]`),
|
||||
);
|
||||
if (!isObject(value)) return [];
|
||||
|
||||
const missing: string[] = [];
|
||||
if (isObject(value.properties))
|
||||
for (const [property, schema] of Object.entries(value.properties)) {
|
||||
const propertyPath = `${path}.properties.${property}`;
|
||||
if (!isObject(schema) || typeof schema.description !== "string")
|
||||
missing.push(propertyPath);
|
||||
missing.push(...missingPropertyDescriptions(schema, propertyPath));
|
||||
}
|
||||
for (const [key, child] of Object.entries(value))
|
||||
if (
|
||||
key !== "properties" &&
|
||||
key !== "examples" &&
|
||||
key !== "default" &&
|
||||
key !== "const" &&
|
||||
key !== "enum"
|
||||
)
|
||||
missing.push(...missingPropertyDescriptions(child, `${path}.${key}`));
|
||||
return missing;
|
||||
};
|
||||
|
||||
const isObject = (value: unknown): value is Readonly<Record<string, unknown>> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
@@ -87,31 +87,6 @@ describe("tool result projection", () => {
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("cookie");
|
||||
});
|
||||
it("classifies output contract failures without naming a provider", () => {
|
||||
const result = toCallToolResult(ok({ value: 42 }), contract);
|
||||
expect(result).toMatchObject({
|
||||
structuredContent: {
|
||||
error: {
|
||||
code: "unreadable_output",
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
retryable: false,
|
||||
remediation: {
|
||||
action:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
restart_required: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
isError: true,
|
||||
});
|
||||
expect(result.content[0]).toEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(result.structuredContent),
|
||||
});
|
||||
});
|
||||
|
||||
it("links successful evidence only when its session resource exists", () => {
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
|
||||
Reference in New Issue
Block a user