Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(session): align call relationship discovery with traversal modes

morluto1d5bf5ff084b
diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md
index 7cb3a7cdc..c75a618f2 100644
--- a/docs/mcp-contracts.md
+++ b/docs/mcp-contracts.md
@@ -355,6 +355,17 @@ checking that a client received the full catalog. An operation absent from all
groups is missing from the complete inventory; it is not an implicit
unavailable entry.
+`get_call_graph` and `trace_call_path` report `forward` and `backward` modes.
+Each requires `procedure_address` plus `procedure_callees` or `procedure_callers`,
+respectively. The tool is available when either traversal mode is supported;
+`default_mode_available` describes the default forward direction. Read each mode's
+missing operations and remediation before selecting a direction. These facts
+describe traversal prerequisites, not relationship completeness or a guarantee
+for every selector. A trace whose start and goal resolve to the same address can
+finish without reading relationships, even when neither traversal mode is
+available. Discovery does not block that direct invocation or replace its typed
+partial/error outcomes.
+
The `effects` and `annotations` arrays list the true members of their fixed
vocabularies. A known member omitted from either array is false. This applies
only to these closed flag sets; it does not make an omitted tool, provider, mode,
diff --git a/src/application/CallPathTracing.ts b/src/application/CallPathTracing.ts
index 640f7c510..41d96a9b4 100644
--- a/src/application/CallPathTracing.ts
+++ b/src/application/CallPathTracing.ts
@@ -1,3 +1,5 @@
+import type { CallRelationshipDirection } from "../contracts/enhancedInputs.js";
+import { CALL_RELATIONSHIP_TRAVERSALS } from "./CallRelationshipTraversal.js";
import type {
AnalysisExecution,
AnalysisOperation,
@@ -30,7 +32,7 @@ type RelationshipCall = (
export interface CallPathTraceInput {
readonly start: string;
readonly goal?: string | undefined;
- readonly direction: "forward" | "backward";
+ readonly direction: CallRelationshipDirection;
}
interface TraceState {
@@ -137,9 +139,8 @@ const expandAddress = async (
expansion: AddressExpansion,
): Promise<Result<boolean, AnalysisError>> => {
const { input, state, address, current, signal } = expansion;
- const relation = input.direction === "forward" ? "callees" : "callers";
- const tool =
- input.direction === "forward" ? "procedure_callees" : "procedure_callers";
+ const { relation, operation: tool } =
+ CALL_RELATIONSHIP_TRAVERSALS[input.direction];
const result = await call(tool, { procedure: address }, signal, "provider");
if (!result.ok) {
if (
diff --git a/src/application/CallRelationshipTraversal.ts b/src/application/CallRelationshipTraversal.ts
new file mode 100644
index 000000000..7b6cfea6c
--- /dev/null
+++ b/src/application/CallRelationshipTraversal.ts
@@ -0,0 +1,16 @@
+import type { CallRelationshipDirection } from "../contracts/enhancedInputs.js";
+import type { AnalysisOperation } from "./AnalysisProvider.js";
+
+/** The provider read and response relation for each supported traversal direction. */
+export const CALL_RELATIONSHIP_TRAVERSALS = {
+ forward: { operation: "procedure_callees", relation: "callees" },
+ backward: { operation: "procedure_callers", relation: "callers" },
+} as const satisfies Readonly<
+ Record<
+ CallRelationshipDirection,
+ {
+ readonly operation: AnalysisOperation;
+ readonly relation: "callees" | "callers";
+ }
+ >
+>;
diff --git a/src/application/CapabilityInventory.ts b/src/application/CapabilityInventory.ts
index ca7088f74..9520cf255 100644
--- a/src/application/CapabilityInventory.ts
+++ b/src/application/CapabilityInventory.ts
@@ -1,3 +1,5 @@
+import { DEFAULT_CALL_RELATIONSHIP_DIRECTION } from "../contracts/enhancedInputs.js";
+import { CALL_RELATIONSHIP_TRAVERSALS } from "./CallRelationshipTraversal.js";
import { z } from "zod";
import { sqliteDatabaseCapability } from "./sqlite/SqliteDatabaseCapability.js";
import type {
@@ -21,7 +23,10 @@ import {
import type { ToolKind } from "../contracts/toolContractTypes.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { isMachOFormat } from "../domain/binaryTargetTypes.js";
-import type { ProviderAvailability } from "./AnalysisProvider.js";
+import type {
+ AnalysisOperation,
+ ProviderAvailability,
+} from "./AnalysisProvider.js";
import type { JebAnalysisAvailability } from "./jeb/JebAnalysisPort.js";
import { TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import { FRIDA_TOOL_CONTRACTS } from "../contracts/fridaToolContracts.js";
@@ -79,7 +84,7 @@ type Availability = AvailabilityFacts &
readonly remediation: string | null;
}
);
-type NavigationModeResult =
+type AvailabilityModeResult =
| (Extract<ToolAvailabilityMode, { available: true }> & {
readonly reason: "available";
})
@@ -101,37 +106,68 @@ type AvailabilityContext = {
readonly policy: AvailabilityPolicy;
};
-const ENHANCED_REQUIREMENTS: Readonly<
- Record<string, readonly (string | readonly string[])[]>
-> = {
- trace_native_values: ["analyze_function", "resolve_native_call_targets"],
- trace_native_ui_action: [
- "decode_interface_builder",
- "list_names",
- "procedure_callees",
- ],
- inspect_native_dispatch_metadata: ["list_names"],
- get_objc_classes: ["list_names"],
- get_objc_protocols: ["list_names"],
- batch_decompile: ["procedure_pseudo_code"],
- get_call_graph: ["procedure_callees", "procedure_callers"],
- analyze_swift_types: ["list_procedures"],
- find_xrefs_to_name: ["list_names", "xrefs"],
- binary_overview: [
- ["current_document", "list_documents"],
- "list_procedures",
- "list_strings",
- ],
- analyze_function: ["analyze_function"],
- inspect_native_api: ["analyze_function"],
- trace_feature: [
- "search_strings",
- "search_procedures",
- "xrefs",
- "resolve_containing_procedure",
- ],
+type EnhancedContractName = Extract<
+ (typeof TOOL_CONTRACTS)[number],
+ { readonly kind: "enhanced" }
+>["name"];
+type CompositionRequirements = readonly (
+ | AnalysisOperation
+ | readonly AnalysisOperation[]
+)[];
+type AvailabilityMode = {
+ readonly name: string;
+ readonly requirements: readonly AnalysisOperation[];
+};
+type ModeComposition = {
+ readonly defaultMode: string;
+ readonly modes: readonly AvailabilityMode[];
+};
+type ProviderComposition = CompositionRequirements | ModeComposition;
+
+const CALL_RELATIONSHIP_COMPOSITION: ModeComposition = {
+ defaultMode: DEFAULT_CALL_RELATIONSHIP_DIRECTION,
+ modes: Object.entries(CALL_RELATIONSHIP_TRAVERSALS).map(
+ ([name, traversal]) => ({
+ name,
+ requirements: ["procedure_address", traversal.operation],
+ }),
+ ),
};
+// Complete coverage is checked against canonical enhanced contracts, rather than
+// allowing a newly registered workflow to silently look like a missing provider.
+const ENHANCED_REQUIREMENTS: ReadonlyMap<string, ProviderComposition> = new Map(
+ Object.entries({
+ trace_native_values: ["analyze_function", "resolve_native_call_targets"],
+ trace_native_ui_action: [
+ "decode_interface_builder",
+ "list_names",
+ "procedure_callees",
+ ],
+ inspect_native_dispatch_metadata: ["list_names"],
+ get_objc_classes: ["list_names"],
+ get_objc_protocols: ["list_names"],
+ batch_decompile: ["procedure_pseudo_code"],
+ get_call_graph: CALL_RELATIONSHIP_COMPOSITION,
+ trace_call_path: CALL_RELATIONSHIP_COMPOSITION,
+ analyze_swift_types: ["list_procedures"],
+ find_xrefs_to_name: ["list_names", "xrefs"],
+ binary_overview: [
+ ["current_document", "list_documents"],
+ "list_procedures",
+ "list_strings",
+ ],
+ analyze_function: ["analyze_function"],
+ inspect_native_api: ["analyze_function"],
+ trace_feature: [
+ "search_strings",
+ "search_procedures",
+ "xrefs",
+ "resolve_containing_procedure",
+ ],
+ } satisfies Readonly<Record<EnhancedContractName, ProviderComposition>>),
+);
+
/** Contract kinds whose operations run on the active session target. */
const ACTIVE_TARGET_KINDS: ReadonlySet<ToolKind> = new Set([
"official-proxy",
@@ -296,7 +332,11 @@ const availabilityFor = (context: AvailabilityContext): Availability => {
)
return { reason: "available", remediation: null };
if (context.name === "get_navigation_context")
- return navigationContextAvailability(context.descriptors);
+ return availabilityForModes(
+ NAVIGATION_CONTEXT_MODES,
+ "current_selection",
+ context.descriptors,
+ );
const javascriptApplication = javascriptApplicationAvailability(context);
if (javascriptApplication !== null) return javascriptApplication;
const failure = optionalProviderFailureFor(context);
@@ -684,13 +724,19 @@ const composedAvailability = (
descriptors.get("read_binary_inventory_summary")?.available === true
)
return { reason: "available", remediation: null };
- const requirements = ENHANCED_REQUIREMENTS[name];
+ const requirements = ENHANCED_REQUIREMENTS.get(name);
if (requirements === undefined)
return {
reason: "provider_missing",
remediation: "No provider composition is declared for this operation.",
};
- return composedAvailabilityFor(requirements, descriptors);
+ return "modes" in requirements
+ ? availabilityForModes(
+ requirements.modes,
+ requirements.defaultMode,
+ descriptors,
+ )
+ : composedAvailabilityFor(requirements, descriptors);
};
const composedAvailabilityFor = (
@@ -753,35 +799,35 @@ const composedAvailabilityFor = (
return { reason: "available", remediation: null };
};
-const navigationContextAvailability = (
+const availabilityForModes = (
+ declarations: readonly AvailabilityMode[],
+ defaultMode: string,
descriptors: ReadonlyMap<string, ProviderDescriptor>,
): Availability => {
- const modeResults: NavigationModeResult[] = NAVIGATION_CONTEXT_MODES.map(
- (mode) => {
- const availability = composedAvailabilityFor(
- mode.requirements,
- descriptors,
- );
- if (availability.reason === "available")
- return {
- name: mode.name,
- available: true,
- reason: availability.reason,
- missing_operations: [],
- remediation: null,
- };
+ const modeResults: AvailabilityModeResult[] = declarations.map((mode) => {
+ const availability = composedAvailabilityFor(
+ mode.requirements,
+ descriptors,
+ );
+ if (availability.reason === "available")
return {
name: mode.name,
- available: false,
+ available: true,
reason: availability.reason,
- missing_operations: mode.requirements.filter((operation) => {
- const descriptor = descriptors.get(operation);
- return descriptor === undefined || descriptor.available === false;
- }),
- remediation: availability.remediation,
+ missing_operations: [],
+ remediation: null,
};
- },
- );
+ return {
+ name: mode.name,
+ available: false,
+ reason: availability.reason,
+ missing_operations: mode.requirements.filter((operation) => {
+ const descriptor = descriptors.get(operation);
+ return descriptor === undefined || descriptor.available === false;
+ }),
+ remediation: availability.remediation,
+ };
+ });
const modes: ToolAvailabilityMode[] = modeResults.map((mode) =>
mode.available
? {
@@ -803,13 +849,14 @@ const navigationContextAvailability = (
);
const failure = failures.sort(
(left, right) =>
- navigationFailurePriority(left.reason) -
- navigationFailurePriority(right.reason),
+ availabilityFailurePriority(left.reason) -
+ availabilityFailurePriority(right.reason),
)[0];
const specificFailureRemediation =
failure?.reason === "provider_missing" ? undefined : failure?.remediation;
const facts = {
- defaultModeAvailable: modes[0]?.available ?? false,
+ defaultModeAvailable:
+ modes.find((mode) => mode.name === defaultMode)?.available ?? false,
modes,
};
if (availableMode !== undefined)
@@ -826,7 +873,9 @@ const navigationContextAvailability = (
};
};
-const navigationFailurePriority = (reason: ToolAvailabilityReason): number => {
+const availabilityFailurePriority = (
+ reason: ToolAvailabilityReason,
+): number => {
switch (reason) {
case "unsupported_host":
return 0;
diff --git a/src/application/EnhancedTools.ts b/src/application/EnhancedTools.ts
index 8ff202f03..9badaabc2 100644
--- a/src/application/EnhancedTools.ts
+++ b/src/application/EnhancedTools.ts
@@ -1,3 +1,4 @@
+import { CALL_RELATIONSHIP_TRAVERSALS } from "./CallRelationshipTraversal.js";
import { z } from "zod";
import type {
@@ -6,8 +7,11 @@ import type {
AnalysisOperationPort,
ExecutionOptions,
} from "./AnalysisProvider.js";
-import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
-import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
+import {
+ enhancedInputSchemas,
+ type CallRelationshipDirection,
+ type EnhancedToolName,
+} from "../contracts/enhancedInputs.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
@@ -444,13 +448,12 @@ export class EnhancedTools {
async #callGraph(
input: {
readonly address: string;
- readonly direction: "forward" | "backward";
+ readonly direction: CallRelationshipDirection;
},
signal?: AbortSignal,
): EnhancedResult {
- const relation = input.direction === "forward" ? "callees" : "callers";
- const tool =
- input.direction === "forward" ? "procedure_callees" : "procedure_callers";
+ const { relation, operation: tool } =
+ CALL_RELATIONSHIP_TRAVERSALS[input.direction];
const limitations = new Set<string>();
const resolved = await this.#observe(
"procedure_address",
diff --git a/src/contracts/enhancedInputs.ts b/src/contracts/enhancedInputs.ts
index 5d81cc986..63d5a1682 100644
--- a/src/contracts/enhancedInputs.ts
+++ b/src/contracts/enhancedInputs.ts
@@ -5,6 +5,14 @@ const traceLiteralInputSchema = z.strictObject({
case_sensitive: z.boolean().default(false),
});
+export const DEFAULT_CALL_RELATIONSHIP_DIRECTION = "forward";
+const callRelationshipDirectionSchema = z
+ .enum(["forward", "backward"])
+ .default(DEFAULT_CALL_RELATIONSHIP_DIRECTION);
+export type CallRelationshipDirection = z.output<
+ typeof callRelationshipDirectionSchema
+>;
+
/** Input schemas shared by MCP registration and enhanced application dispatch. */
export const enhancedInputSchemas = {
trace_native_values: nativeValueTraceInputSchema,
@@ -24,7 +32,7 @@ export const enhancedInputSchemas = {
.describe(
"A procedure symbol or address to resolve to its canonical entry",
),
- direction: z.enum(["forward", "backward"]).default("forward"),
+ direction: callRelationshipDirectionSchema,
}),
analyze_swift_types: z.strictObject({
category: z
@@ -55,7 +63,7 @@ export const enhancedInputSchemas = {
.string()
.describe("An optional destination procedure symbol or address")
.optional(),
- direction: z.enum(["forward", "backward"]).default("forward"),
+ direction: callRelationshipDirectionSchema,
}),
trace_native_ui_action: z.strictObject({
action: z
diff --git a/tests/boundary/mcp/callRelationshipAvailability.test.ts b/tests/boundary/mcp/callRelationshipAvailability.test.ts
new file mode 100644
index 000000000..d3c3621a3
--- /dev/null
+++ b/tests/boundary/mcp/callRelationshipAvailability.test.ts
@@ -0,0 +1,423 @@
+import { rm } from "node:fs/promises";
+
+import type { Client } from "@modelcontextprotocol/client";
+import type { CallToolResult } from "@modelcontextprotocol/server";
+import { afterEach, describe, expect, it } from "vitest";
+
+import type {
+ AnalysisClient,
+ AnalysisProvider,
+ CapabilityDescriptor,
+} from "../../../src/application/AnalysisProvider.js";
+import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
+import { ok } from "../../../src/domain/result.js";
+import type { ProviderRejectionCode } from "../../../src/contracts/providerSelection.js";
+import { toolContract } from "../../../src/contracts/toolContracts.js";
+import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
+import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { createSessionMcpHarness } from "./sessionMcpHarness.js";
+
+const resources: Array<{ close(): Promise<unknown> }> = [];
+let directory: string | undefined;
+
+afterEach(async () => {
+ await Promise.all(resources.splice(0).map((resource) => resource.close()));
+ if (directory !== undefined)
+ await rm(directory, { recursive: true, force: true });
+ directory = undefined;
+});
+
+const providerIdentity = {
+ id: "fixture",
+ name: "Fixture analysis provider",
+ version: "1",
+};
+const effects = {
+ mutatesArtifact: false,
+ launchesProcess: false,
+ mayShowUi: false,
+ mayAccessNetwork: false,
+ mayWriteFilesystem: false,
+ changesPermissions: false,
+ requiresRoot: false,
+};
+const addressBySymbol = new Map([
+ ["start", "0x1000"],
+ ["goal", "0x2000"],
+]);
+type RelationshipOperation =
+ | "procedure_address"
+ | "procedure_callees"
+ | "procedure_callers";
+type Scenario = {
+ readonly name: string;
+ readonly operations: readonly RelationshipOperation[];
+ readonly unavailable?: RelationshipOperation;
+ readonly availabilityCode?: ProviderRejectionCode;
+ readonly unavailableReason?: string;
+};
+
+const FULL_SCENARIO: Scenario = {
+ name: "both directions",
+ operations: ["procedure_address", "procedure_callees", "procedure_callers"],
+};
+const scenarios: readonly Scenario[] = [
+ FULL_SCENARIO,
+ {
+ name: "forward only",
+ operations: ["procedure_address", "procedure_callees"],
+ },
+ {
+ name: "backward only",
+ operations: ["procedure_address", "procedure_callers"],
+ },
+ {
+ name: "address missing",
+ operations: ["procedure_callees", "procedure_callers"],
+ },
+ {
+ name: "address unavailable",
+ operations: ["procedure_address", "procedure_callees", "procedure_callers"],
+ unavailable: "procedure_address",
+ },
+ {
+ name: "forward relationship unavailable",
+ operations: ["procedure_address", "procedure_callees", "procedure_callers"],
+ unavailable: "procedure_callees",
+ },
+ {
+ name: "address unsupported on host",
+ operations: ["procedure_address", "procedure_callees", "procedure_callers"],
+ unavailable: "procedure_address",
+ availabilityCode: "unsupported_host",
+ unavailableReason: "Procedure address lookup is unsupported on this host.",
+ },
+ { name: "no relationships", operations: ["procedure_address"] },
+];
+
+describe("call relationship capability inventory at the public MCP boundary", () => {
+ it.each(scenarios)(
+ "keeps $name inventory aligned with callable modes",
+ async (scenario) => {
+ directory = await createTestTempDirectory("rea-call-availability-");
+ const calls: string[] = [];
+ const { mcp, first } = await createSessionMcpHarness(
+ directory,
+ () => relationshipProvider(scenario, calls),
+ resources,
+ );
+ const toolsBefore = await mcp.listTools();
+ const before = await sessionInventory(mcp);
+ const opened = await mcp.callTool({
+ name: "open_binary",
+ arguments: { path: first },
+ });
+ expect(opened.isError).not.toBe(true);
+
+ try {
+ const inventory = await sessionInventory(mcp);
+ await assertDirectExecution(mcp, scenario, calls);
+ assertInventory(inventory, scenario);
+ const after = await sessionInventory(mcp);
+ expect((await mcp.listTools()).tools.map(({ name }) => name)).toEqual(
+ toolsBefore.tools.map(({ name }) => name),
+ );
+ expect(after.result.server_identity.catalog).toEqual(
+ before.result.server_identity.catalog,
+ );
+ } finally {
+ const closed = await mcp.callTool({
+ name: "close_binary",
+ arguments: {},
+ });
+ expect(closed.isError).not.toBe(true);
+ }
+ },
+ );
+
+ it("keeps call relationship tools unavailable before a target is open", async () => {
+ directory = await createTestTempDirectory(
+ "rea-call-availability-no-target-",
+ );
+ const { mcp } = await createSessionMcpHarness(
+ directory,
+ () => relationshipProvider(FULL_SCENARIO, []),
+ resources,
+ );
+ const inventory = await sessionInventory(mcp);
+ expect(inventory.result.open).toBe(false);
+ expect(
+ Object.fromEntries(
+ callToolAvailability(inventory).map((entry) => [
+ entry.name,
+ entry.reason,
+ ]),
+ ),
+ ).toEqual({
+ trace_call_path: "target_required",
+ get_call_graph: "target_required",
+ });
+ });
+});
+
+const sessionInventory = async (mcp: Client) => {
+ const result = await mcp.callTool({ name: "binary_session", arguments: {} });
+ return toolContract("binary_session").outputSchema.parse(
+ result.structuredContent,
+ );
+};
+
+const callToolAvailability = (
+ inventory: Awaited<ReturnType<typeof sessionInventory>>,
+) =>
+ expandToolAvailability(inventory.result.tool_availability).filter((entry) =>
+ ["trace_call_path", "get_call_graph"].includes(entry.name),
+ );
+
+const assertDirectExecution = async (
+ mcp: Client,
+ scenario: Scenario,
+ calls: string[],
+): Promise<void> => {
+ for (const direction of ["forward", "backward"] as const) {
+ const relation =
+ direction === "forward" ? "procedure_callees" : "procedure_callers";
+ const start = direction === "forward" ? "start" : "goal";
+ const goal = direction === "forward" ? "goal" : "start";
+ const startAddress = direction === "forward" ? "0x1000" : "0x2000";
+ const nextAddress = direction === "forward" ? "0x2000" : "0x1000";
+ const graph = await mcp.callTool({
+ name: "get_call_graph",
+ arguments: { address: start, direction },
+ });
+ const trace = await mcp.callTool({
+ name: "trace_call_path",
+ arguments: { start, goal, direction },
+ });
+
+ if (!scenario.operations.includes("procedure_address")) {
+ expect(errorCode(graph)).toBe("capability_unavailable");
+ expect(errorCode(trace)).toBe("capability_unavailable");
+ } else if (scenario.unavailable === "procedure_address") {
+ expect(errorCode(graph)).toBe("capability_unavailable");
+ expect(errorCode(trace)).toBe("capability_unavailable");
+ expect(calls).toEqual([]);
+ } else if (
+ !scenario.operations.includes(relation) ||
+ scenario.unavailable === relation
+ ) {
+ expect(calls).not.toContain(relation);
+ expect(graph.structuredContent).toMatchObject({
+ normalized_result: {
+ graph: {
+ "0": [
+ {
+ address: startAddress,
+ status: "error",
+ error: { code: "capability_unavailable" },
+ },
+ ],
+ },
+ },
+ });
+ expect(trace.structuredContent).toMatchObject({
+ normalized_result: {
+ goal_status: "unknown",
+ truncated: true,
+ failures: expect.arrayContaining([
+ expect.objectContaining({
+ address: startAddress,
+ error: expect.objectContaining({
+ code: "capability_unavailable",
+ }),
+ }),
+ ]),
+ },
+ });
+ } else {
+ expect(graph.structuredContent).toMatchObject({
+ normalized_result: {
+ graph: {
+ "0": [
+ {
+ address: startAddress,
+ status: "ok",
+ calls: [nextAddress],
+ relationship_coverage: { status: "complete" },
+ },
+ ],
+ },
+ },
+ });
+ expect(trace.structuredContent).toMatchObject({
+ normalized_result: {
+ goal_status: "reached",
+ traversal_path: [startAddress, nextAddress],
+ relationship_coverage: { [startAddress]: { status: "complete" } },
+ },
+ });
+ }
+ }
+
+ if (
+ scenario.operations.includes("procedure_address") &&
+ !scenario.operations.includes("procedure_callees") &&
+ !scenario.operations.includes("procedure_callers")
+ ) {
+ const callsBefore = calls.length;
+ const sameEndpoint = await mcp.callTool({
+ name: "trace_call_path",
+ arguments: { start: "start", goal: "start" },
+ });
+ expect(sameEndpoint.structuredContent).toMatchObject({
+ normalized_result: {
+ goal_status: "reached",
+ traversal_path: ["0x1000"],
+ },
+ });
+ expect(
+ calls
+ .slice(callsBefore)
+ .every((operation) => operation === "procedure_address"),
+ ).toBe(true);
+ }
+};
+
+const assertInventory = (
+ inventory: Awaited<ReturnType<typeof sessionInventory>>,
+ scenario: Scenario,
+): void => {
+ const available = callToolAvailability(inventory);
+ const trace = available.find((entry) => entry.name === "trace_call_path");
+ const graph = available.find((entry) => entry.name === "get_call_graph");
+ expect(trace).toBeDefined();
+ expect(graph).toBeDefined();
+ if (trace === undefined || graph === undefined)
+ throw new Error("call relationship tools missing from inventory");
+
+ const forwardAvailable = modeAvailable(scenario, "procedure_callees");
+ const backwardAvailable = modeAvailable(scenario, "procedure_callers");
+ const expected = {
+ available: forwardAvailable || backwardAvailable,
+ reason: availabilityReason(scenario),
+ default_mode_available: forwardAvailable,
+ modes: [
+ mode("forward", scenario, "procedure_callees"),
+ mode("backward", scenario, "procedure_callers"),
+ ],
+ };
+ expect(trace).toMatchObject(expected);
+ expect(graph).toMatchObject(expected);
+ if (scenario.unavailableReason !== undefined) {
+ expect(trace.remediation).toContain(scenario.unavailableReason);
+ expect(graph.remediation).toContain(scenario.unavailableReason);
+ }
+};
+
+const modeAvailable = (
+ scenario: Scenario,
+ relation: "procedure_callees" | "procedure_callers",
+): boolean =>
+ scenario.operations.includes("procedure_address") &&
+ scenario.unavailable !== "procedure_address" &&
+ scenario.unavailable !== relation &&
+ scenario.operations.includes(relation);
+
+const mode = (
+ name: "forward" | "backward",
+ scenario: Scenario,
+ relation: "procedure_callees" | "procedure_callers",
+) => {
+ const available = modeAvailable(scenario, relation);
+ const required: readonly RelationshipOperation[] = [
+ "procedure_address",
+ relation,
+ ];
+ const missing = required.filter(
+ (operation) =>
+ !scenario.operations.includes(operation) ||
+ scenario.unavailable === operation,
+ );
+ return {
+ name,
+ available,
+ missing_operations: available ? [] : missing,
+ remediation: available ? null : expect.any(String),
+ };
+};
+
+const availabilityReason = (scenario: Scenario) => {
+ if (scenario.unavailable === "procedure_address")
+ return scenario.availabilityCode === "unsupported_host"
+ ? "unsupported_host"
+ : "provider_unavailable";
+ if (!scenario.operations.includes("procedure_address"))
+ return "provider_missing";
+ return scenario.operations.some((operation) =>
+ ["procedure_callees", "procedure_callers"].includes(operation),
+ )
+ ? "available"
+ : "provider_missing";
+};
+
+const errorCode = (result: CallToolResult): unknown =>
+ result.isError === true ? parseMcpToolError(result).error.code : undefined;
+
+const relationshipProvider = (
+ scenario: Scenario,
+ calls: string[],
+): AnalysisProvider => {
+ const capabilities: CapabilityDescriptor[] = scenario.operations.map(
+ (operation) => {
+ const shared = {
+ provider: providerIdentity,
+ operation,
+ effects,
+ limitations: [],
+ };
+ return scenario.unavailable === operation
+ ? {
+ ...shared,
+ available: false as const,
+ reason:
+ scenario.unavailableReason ?? "fixture operation unavailable",
+ ...(scenario.availabilityCode === undefined
+ ? {}
+ : { availabilityCode: scenario.availabilityCode }),
+ }
+ : { ...shared, available: true as const, reason: null };
+ },
+ );
+ return {
+ identity: () => providerIdentity,
+ capabilities: () => capabilities,
+ createClient: (): AnalysisClient => ({
+ execute: async (operation, arguments_) => {
+ if (operation === "health")
+ return ok(createAnalysisExecution(null, providerIdentity));
+ calls.push(operation);
+ if (operation === "procedure_address") {
+ const address = addressBySymbol.get(String(arguments_.procedure));
+ return ok(createAnalysisExecution(address ?? null, providerIdentity));
+ }
+ if (
+ operation === "procedure_callees" ||
+ operation === "procedure_callers"
+ ) {
+ const forward = operation === "procedure_callees";
+ const edge = forward ? "0x2000" : "0x1000";
+ const from = forward ? "0x1000" : "0x2000";
+ const related = String(arguments_.procedure) === from ? [edge] : [];
+ return ok(
+ createAnalysisExecution(related, providerIdentity, {
+ relationshipCoverage: { status: "complete" },
+ }),
+ );
+ }
+ throw new Error(`Unexpected operation ${operation}`);
+ },
+ close: async () => ok(null),
+ }),
+ };
+};