test(mcp): check recovery promises on an agent's first wrong calls

Calls every served tool with generated wrong arguments on a session with
nothing open: an unknown path key, an omitted required field, valid
arguments for an active-target tool, a missing file and an unknown id.
Every refusal must name only advertised tools, name open_binary for an
active-target tool, give no schema remediation to arguments the served
schema accepts, and claim retryable only when an identical replay can
succeed. A seeded property varies the guessed key and missing path.

Known failures are listed by root cause (#15309, #15312, #15323 and the
active-target declarations #15350 removes); a new failure or a stale
entry fails the sweep.
This commit is contained in:
morluto
2026-11-30 19:27:29 -05:00
parent e9639f999b
commit b5b8f8f3aa
@@ -0,0 +1,616 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { fc } from "@fast-check/vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
import { afterAll, beforeAll, expect, it } from "vitest";
import type { ToolContract } from "../../../src/contracts/toolContractTypes.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import {
servedToolCatalog,
type ServedTool,
} from "../../fixtures/servedToolCatalog.js";
// What an agent's first, mistaken calls receive. Each served tool is called
// with generated wrong arguments on a session with nothing open, and every
// refusal must keep three promises:
// I1 every tool the refusal names as a next step is advertised, and a tool
// that needs an open target names open_binary, whatever the argument
// error;
// I2 arguments the served schema accepts never get schema remediation;
// I3 retryable:true means an identical replay may succeed, so a refusal
// that a deterministic replay repeats unchanged must not claim it.
type JsonRecord = Record<string, unknown>;
const isRecord = (value: unknown): value is JsonRecord =>
typeof value === "object" && value !== null && !Array.isArray(value);
type MistakeKind =
| "unknown_path_key"
| "omitted_required"
| "nothing_open"
| "missing_file"
| "unknown_id"
| "stale_revision";
interface WrongCall {
readonly tool: string;
readonly kind: MistakeKind;
readonly args: JsonRecord;
}
interface Finding {
readonly invariant: "I1" | "I2" | "I3";
readonly tool: string;
readonly kind: MistakeKind;
readonly detail: string;
}
const findingKey = ({ invariant, tool, kind }: Finding): string =>
`${invariant} ${tool} ${kind}`;
const contracts: ReadonlyMap<string, ToolContract> = new Map(
TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
);
const requiresTarget = (tool: string): boolean =>
contracts.get(tool)?.requiresActiveTarget === true;
/** Effects that could reach past REA's own state when a call is admitted. */
const reachesOutside = (tool: string): boolean => {
const effects = contracts.get(tool)?.effects;
if (effects === undefined) return true;
return (
effects.launchesProcess ||
effects.accessesNetwork ||
effects.writesFilesystem ||
effects.executesForeignCode ||
effects.mutatesDevice ||
effects.mutatesTarget ||
effects.changesUiState ||
effects.mayDiscardData
);
};
const servedProperties = (tool: ServedTool): JsonRecord =>
isRecord(tool.inputSchema.properties) ? tool.inputSchema.properties : {};
const servedRequired = (tool: ServedTool): readonly string[] =>
Array.isArray(tool.inputSchema.required)
? tool.inputSchema.required.filter(
(name): name is string => typeof name === "string",
)
: [];
const isPathField = (field: string, value: unknown): value is string =>
typeof value === "string" &&
value.startsWith("/") &&
/(?:^|_)path$/u.test(field);
interface Values {
readonly missingFile: string;
readonly unknownKey: string;
}
/** Keys an agent guesses for its target file. */
const GUESSED_KEYS = ["path", "file", "binary_path", "target"] as const;
const DEFAULT_VALUES: Values = {
missingFile: "/rea-first-contact/missing/target.bin",
unknownKey: "path",
};
/**
* The wrong calls an agent makes first, from each tool's first example.
* Calls that schema validation or the open-target check refuses are made
* for every tool. Calls that the served schema admits run only for tools
* whose declared effects stay inside REA, so the sweep never launches,
* writes, changes a device or reaches the network.
*/
const wrongCallsFor = (tool: ServedTool, values: Values): WrongCall[] => {
const contract = contracts.get(tool.name);
const example = contract?.examples[0]?.input;
if (contract === undefined || example === undefined) return [];
const base: JsonRecord = { ...example };
const properties = servedProperties(tool);
const required = servedRequired(tool);
const calls: WrongCall[] = [];
const add = (kind: MistakeKind, args: JsonRecord) =>
calls.push({ tool: tool.name, kind, args });
// The guessed key, or the next guess when the tool serves that name.
const unknownKey = [values.unknownKey, ...GUESSED_KEYS].find(
(key) => !(key in properties),
);
if (unknownKey !== undefined)
add("unknown_path_key", { ...base, [unknownKey]: values.missingFile });
for (const field of required) {
const { [field]: _omitted, ...rest } = base;
add("omitted_required", rest);
}
// inspect_packet_fields and inspect_signal_decoders declare an open target
// but run a host tool without one (#15350), so with nothing open they
// would launch TShark or sigrok wherever it is installed.
if (requiresTarget(tool.name) && typeof contract.availability !== "object") {
// An optional path names its own target; without it the open one is used.
const pathless = Object.fromEntries(
Object.entries(base).filter(
([field, value]) =>
!isPathField(field, value) || required.includes(field),
),
);
if (!Object.entries(pathless).some(([f, v]) => isPathField(f, v)))
add("nothing_open", pathless);
}
if (reachesOutside(tool.name)) return calls;
for (const [field, value] of Object.entries(base)) {
if (isPathField(field, value))
add("missing_file", { ...base, [field]: values.missingFile });
if (typeof value === "string" && field.endsWith("_id"))
add("unknown_id", base);
}
return calls;
};
type Refusal = ReturnType<typeof parseMcpToolError>["error"];
const SCHEMA_REMEDIATION =
/advertised input schema|Read the declared input schema/iu;
/** Tool names a refusal offers as next steps, in prose or structure. */
const namedTools = (refusal: Refusal): readonly string[] => {
const named = new Set<string>();
for (const [token] of refusal.remediation.action.matchAll(
/\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\b/gu,
))
if (contracts.has(token)) named.add(token);
if (refusal.recovery !== undefined) named.add(refusal.recovery.operation);
return [...named];
};
let names: ReadonlySet<string>;
let served: readonly ServedTool[];
let validators: ReadonlyMap<string, (input: unknown) => boolean>;
let client: Client;
let release: () => Promise<void>;
beforeAll(async () => {
served = await servedToolCatalog();
names = new Set(served.map((tool) => tool.name));
const ajv = new Ajv2020({
strict: false,
validateFormats: false,
inlineRefs: false,
code: { optimize: false },
});
validators = new Map(
served.map((tool) => {
const compiled = ajv.compile(tool.inputSchema);
return [tool.name, (input: unknown) => compiled(input)] as const;
}),
);
const session = createTestBinarySession(() => {
throw new Error("A wrong first call must not start a binary provider");
});
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
client = new Client(
{ name: "agent-first-contact", version: "1" },
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
release = async () => {
await Promise.allSettled([client.close(), server.close()]);
await session.close();
};
});
afterAll(async () => {
await release();
});
const call = async (tool: string, args: JsonRecord): Promise<CallToolResult> =>
(await client.callTool({ name: tool, arguments: args })) as CallToolResult;
/**
* Check one call's refusal and, for I3, its identical replay. Returns
* undefined when the call succeeded, so a sweep can count what it checked.
*/
const judge = async (
wrong: WrongCall,
): Promise<
{ readonly error: Refusal; readonly findings: readonly Finding[] } | undefined
> => {
const result = await call(wrong.tool, wrong.args);
if (result.isError !== true) return undefined;
const { error } = parseMcpToolError(result);
const findings: Finding[] = [];
const found = (invariant: Finding["invariant"], detail: string) =>
findings.push({ invariant, tool: wrong.tool, kind: wrong.kind, detail });
const next = namedTools(error);
for (const tool of next)
if (!names.has(tool)) found("I1", `names unadvertised ${tool}`);
if (
requiresTarget(wrong.tool) &&
wrong.kind !== "missing_file" &&
!next.includes("open_binary")
)
found("I1", `${error.code} with nothing open omits open_binary`);
if (
validators.get(wrong.tool)?.(wrong.args) === true &&
(error.recovery?.kind === "inspect_input_contract" ||
SCHEMA_REMEDIATION.test(error.message) ||
SCHEMA_REMEDIATION.test(error.remediation.action))
)
found("I2", `schema-valid ${error.code} gets schema remediation`);
if (error.retryable) {
const replay = await call(wrong.tool, wrong.args);
if (
replay.isError === true &&
parseMcpToolError(replay).error.code === error.code
)
found("I3", `retryable ${error.code} repeats on an identical replay`);
}
return { error, findings };
};
/**
* Refusals known to break a promise, grouped by root cause and keyed
* `invariant tool kind`. Fixing a cause removes its entries: an entry that no
* longer matches a finding fails the sweep, and a new finding fails it too.
*/
interface KnownFailure {
readonly reason: string;
readonly findings: readonly string[];
}
/** `invariant tool kind` entries for each tool listed. */
const entries = (
invariant: Finding["invariant"],
kind: MistakeKind,
tools: readonly string[],
): readonly string[] => tools.map((tool) => `${invariant} ${tool} ${kind}`);
const KNOWN_FAILURES: Readonly<Record<string, KnownFailure>> = {
argumentErrorBeforeTarget: {
reason:
"#15309 (open: #15356, #15333): input validation runs before the open-target check, so an argument error with nothing open never names open_binary.",
findings: [
...entries("I1", "unknown_path_key", [
"address_name",
"address_to_file_offset",
"analyze_function",
"analyze_swift_types",
"annotate_native_function",
"batch_decompile",
"binary_overview",
"capture_native_ui_scenario",
"comment",
"current_address",
"current_document",
"current_procedure",
"decode_interface_builder",
"decompile_all",
"define_native_data_types",
"demangle_swift",
"extract_artifact",
"find_xrefs_to_name",
"get_call_graph",
"get_navigation_context",
"get_objc_classes",
"get_objc_protocols",
"goto_address",
"inline_comment",
"inspect_address_context",
"inspect_asset_catalog",
"inspect_macho",
"inspect_native_api",
"inspect_native_data_type",
"inspect_native_dispatch_metadata",
"inspect_native_instruction",
"inspect_native_load_image",
"inspect_signature",
"list_architectures",
"list_bookmarks",
"list_documents",
"list_names",
"list_procedures",
"list_segments",
"list_strings",
"next_address",
"observe_native_calls",
"observe_native_ui",
"prev_address",
"procedure_address",
"procedure_assembly",
"procedure_callees",
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"read_bytes",
"read_function_instructions",
"resolve_containing_procedure",
"resolve_native_call_targets",
"search_bytes",
"search_procedures",
"search_strings",
"set_address_name",
"set_addresses_names",
"set_bookmark",
"set_comment",
"set_inline_comment",
"trace_call_path",
"trace_dylib_resolution",
"trace_feature",
"trace_native_ui_action",
"trace_native_values",
"unset_bookmark",
"xrefs",
]),
...entries("I1", "omitted_required", [
"address_to_file_offset",
"analyze_function",
"annotate_native_function",
"capture_native_ui_scenario",
"decompile_all",
"define_native_data_types",
"demangle_swift",
"find_xrefs_to_name",
"get_call_graph",
"goto_address",
"inspect_address_context",
"inspect_native_api",
"inspect_native_instruction",
"observe_native_calls",
"observe_native_ui",
"procedure_address",
"procedure_assembly",
"procedure_callees",
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"read_bytes",
"read_function_instructions",
"resolve_containing_procedure",
"resolve_native_call_targets",
"search_bytes",
"search_procedures",
"search_strings",
"set_address_name",
"set_addresses_names",
"set_bookmark",
"set_comment",
"set_inline_comment",
"trace_call_path",
"trace_feature",
"trace_native_ui_action",
"trace_native_values",
"unset_bookmark",
]),
],
},
declaredTargetWithOwnInput: {
reason:
"#15350 (open): these tools read their own path or run a host tool, yet declare requiresActiveTarget, so they are held to the open_binary promise without needing an open target.",
findings: [
...entries("I1", "unknown_path_key", [
"decode_signal_recording",
"inspect_apk_signature",
"inspect_deb_package",
"inspect_desktop_application",
"inspect_electron_fuses",
"inspect_erlang_beam",
"inspect_evm_interface",
"inspect_go_binary",
"inspect_gpu_code_objects",
"inspect_il2cpp_metadata",
"inspect_keyed_archive",
"inspect_labview_artifact",
"inspect_model_artifact",
"inspect_nuget_nupkg",
"inspect_oci_image_layout",
"inspect_packet_capture",
"inspect_packet_fields",
"inspect_plist",
"inspect_python_pyc",
"inspect_rust_binary",
"inspect_signal_decoders",
"inspect_sqlite_database",
"inspect_vsix_package",
"inspect_wasm_artifact",
]),
...entries("I1", "omitted_required", [
"decode_signal_recording",
"inspect_apk_signature",
"inspect_deb_package",
"inspect_desktop_application",
"inspect_electron_fuses",
"inspect_erlang_beam",
"inspect_evm_interface",
"inspect_go_binary",
"inspect_gpu_code_objects",
"inspect_il2cpp_metadata",
"inspect_labview_artifact",
"inspect_model_artifact",
"inspect_nuget_nupkg",
"inspect_oci_image_layout",
"inspect_packet_capture",
"inspect_python_pyc",
"inspect_rust_binary",
"inspect_sqlite_database",
"inspect_vsix_package",
"inspect_wasm_artifact",
]),
],
},
schemaRemediationOnConformingInput: {
reason:
"#15312 (open: #15331): a missing file or unknown session that the served schema accepts is presented as a schema mismatch with inspect_input_contract.",
findings: [
...entries("I2", "missing_file", [
"inspect_api_contract",
"inspect_apk_signature",
"inspect_apple_ips",
"inspect_binary_hardening",
"inspect_byte_entropy",
"inspect_deb_package",
"inspect_devicetree",
"inspect_dwarf_units",
"inspect_electron_fuses",
"inspect_elf_debug_link",
"inspect_elf_dependencies",
"inspect_elf_notes",
"inspect_elf_unwind_ranges",
"inspect_erlang_beam",
"inspect_esp_nvs",
"inspect_evtx_archive",
"inspect_firmware_vector_table",
"inspect_go_binary",
"inspect_il2cpp_metadata",
"inspect_kernel_build_config",
"inspect_kernel_module",
"inspect_labview_artifact",
"inspect_macho_function_starts",
"inspect_maven_gradle_metadata",
"inspect_native_exports",
"inspect_native_initializers",
"inspect_ntfs_journal",
"inspect_nuget_nupkg",
"inspect_oci_image_layout",
"inspect_pe_certificates",
"inspect_pe_imports",
"inspect_pe_load_config",
"inspect_pe_overlay",
"inspect_pe_resources",
"inspect_pe_unwind_ranges",
"inspect_playwright_trace",
"inspect_python_pyc",
"inspect_rust_binary",
"inspect_uefi_nvram",
"inspect_v8_code_cache",
"inspect_vsix_package",
"inspect_windows_shortcut",
]),
...entries("I2", "unknown_id", ["frida_session_status"]),
],
},
retryableByCodeTable: {
reason:
"#15323: revision_conflict is retryable by code, but an unchanged update with a stale expected_revision fails the same way every time.",
findings: ["I3 update_unknown stale_revision"],
},
};
const knownEntries = Object.values(KNOWN_FAILURES).flatMap(
({ findings }) => findings,
);
const isKnown = (finding: Finding): boolean =>
knownEntries.includes(findingKey(finding));
const SWEPT_KINDS = [
"unknown_path_key",
"omitted_required",
"nothing_open",
"missing_file",
"unknown_id",
] as const satisfies readonly MistakeKind[];
it("keeps recovery promises on every generated wrong first call", async () => {
const findings: Finding[] = [];
const checked = new Map<MistakeKind, number>();
for (const wrong of served.flatMap((tool) =>
wrongCallsFor(tool, DEFAULT_VALUES),
)) {
const judged = await judge(wrong);
if (judged === undefined) continue;
checked.set(wrong.kind, (checked.get(wrong.kind) ?? 0) + 1);
findings.push(...judged.findings);
}
// Each generated mistake reached refusals; an empty sweep proves nothing.
for (const kind of SWEPT_KINDS)
expect(checked.get(kind), kind).toBeGreaterThan(0);
const keys = [...new Set(findings.map(findingKey))].sort();
expect(
findings.filter((finding) => !isKnown(finding)),
"refusals that break a recovery promise",
).toEqual([]);
expect(
knownEntries.filter(
(entry) =>
SWEPT_KINDS.some((kind) => entry.endsWith(` ${kind}`)) &&
!keys.includes(entry),
),
"these known failures are fixed; remove them",
).toEqual([]);
});
it("keeps recovery promises for generated mistaken values", async () => {
const tools = new Map(
served
.filter((tool) => wrongCallsFor(tool, DEFAULT_VALUES).length > 0)
.map((tool) => [tool.name, tool]),
);
const segment = fc.stringMatching(/^[a-z][a-z0-9_.-]{0,11}$/u);
const values = fc.record({
missingFile: fc
.array(segment, { minLength: 1, maxLength: 4 })
.map((parts) => `/rea-first-contact-missing/${parts.join("/")}`),
unknownKey: fc.constantFrom(...GUESSED_KEYS),
});
await fc.assert(
fc.asyncProperty(
fc.constantFrom(...tools.keys()),
values,
fc.nat(),
async (name, generated, pick) => {
const tool = tools.get(name);
if (tool === undefined) throw new Error(`${name} is not served`);
const calls = wrongCallsFor(tool, generated);
const wrong = calls[pick % calls.length];
if (wrong === undefined) return true;
// A generated key or path is another spelling of the same mistake,
// so the sweep's known failures cover it.
return ((await judge(wrong))?.findings ?? []).every(isKnown);
},
),
{ seed: 15_309, numRuns: 150, interruptAfterTimeLimit: 20_000 },
);
});
it("marks a stale revision retryable only when a replay can succeed", async () => {
const recordExample = contracts.get("record_unknown")?.examples[0]?.input;
const updateExample = contracts.get("update_unknown")?.examples[0]?.input;
if (recordExample === undefined || updateExample === undefined)
throw new Error("Unknown tools have no examples");
const recorded = await call("record_unknown", { ...recordExample });
if (recorded.isError === true)
throw new Error(`record_unknown failed: ${JSON.stringify(recorded)}`);
const { unknown_id: unknownId } = (
recorded.structuredContent as { readonly result: { unknown_id: string } }
).result;
const judged = await judge({
tool: "update_unknown",
kind: "stale_revision",
args: { ...updateExample, unknown_id: unknownId, expected_revision: 99 },
});
expect(judged?.error.code, JSON.stringify(judged?.error)).toBe(
"revision_conflict",
);
expect(judged?.findings.filter((finding) => !isKnown(finding))).toEqual([]);
// The known failure still holds; remove its entry once it is fixed.
expect(judged?.findings.map(findingKey)).toEqual(
knownEntries.filter((entry) => entry.endsWith(" stale_revision")),
);
});