feat: evolve REA analysis platform

This commit is contained in:
morluto
2026-07-12 19:32:13 +08:00
parent 1f235cb52f
commit 4f18e26ee5
47 changed files with 1841 additions and 334 deletions
+37
View File
@@ -0,0 +1,37 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { AnalysisError } from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Result } from "../domain/result.js";
export interface ExecutionOptions {
readonly signal?: AbortSignal;
}
/** Provider-neutral application capability for one analysis operation. */
export interface AnalysisOperationPort {
execute(
operation: string,
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
): Promise<Result<JsonValue, AnalysisError>>;
}
/** Provider session bound to exactly one parsed artifact. */
export interface AnalysisClient extends AnalysisOperationPort {
close(): Promise<void>;
}
export type AnalysisClientFactory = (target: BinaryTarget) => AnalysisClient;
export interface ProviderIdentity {
readonly id: string;
readonly name: string;
readonly version: string | null;
}
/** Factory and capability declaration for an analysis implementation. */
export interface AnalysisProvider {
identity(): ProviderIdentity;
capabilities(): readonly string[];
createClient(target: BinaryTarget): AnalysisClient;
}
+47 -21
View File
@@ -3,18 +3,30 @@ import { parseBinaryTarget } from "../domain/binaryTarget.js";
import {
HopperCancelledError,
NoBinaryOpenError,
type HopperError,
type AnalysisError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../hopper/protocol.js";
import type { HopperToolPort } from "./HopperToolPort.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type {
AnalysisClient,
AnalysisClientFactory,
AnalysisOperationPort,
AnalysisProvider,
} from "./AnalysisProvider.js";
/** A closeable Hopper port created for exactly one parsed target. */
export interface BinaryClient extends HopperToolPort {
close(): Promise<void>;
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
export interface BinarySessionPort extends AnalysisOperationPort {
open(
path: string,
options?: {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
},
): Promise<Result<BinaryTarget, AnalysisError>>;
close(): Promise<Result<null, AnalysisError>>;
status(): JsonValue;
activeTarget(): BinaryTarget | undefined;
}
/** Production seam for creating one unstarted client for a parsed target. */
export type BinaryClientFactory = (target: BinaryTarget) => BinaryClient;
/**
* Owns the single active target shared by CLI and MCP adapters.
@@ -24,13 +36,20 @@ export type BinaryClientFactory = (target: BinaryTarget) => BinaryClient;
* down. A failed switch recreates the previous target instead of retaining a
* client whose bridge was already shut down.
*/
export class BinarySession implements HopperToolPort {
export class BinarySession implements BinarySessionPort {
#active:
| { readonly target: BinaryTarget; readonly client: BinaryClient }
| { readonly target: BinaryTarget; readonly client: AnalysisClient }
| undefined;
#transition: Promise<void> = Promise.resolve();
readonly #calls = new Set<Promise<unknown>>();
constructor(readonly createClient: BinaryClientFactory) {}
readonly #createClient: AnalysisClientFactory;
constructor(readonly provider: AnalysisProvider | AnalysisClientFactory) {
this.#createClient =
typeof provider === "function"
? provider
: (target) => provider.createClient(target);
}
/**
* Open or switch targets after draining calls against the current target.
@@ -42,7 +61,7 @@ export class BinarySession implements HopperToolPort {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
} = {},
): Promise<Result<BinaryTarget, HopperError>> {
): Promise<Result<BinaryTarget, AnalysisError>> {
return this.#serialize(async () => {
if (isAborted(options.signal)) return err(new HopperCancelledError());
const parsed = await parseBinaryTarget(
@@ -59,8 +78,8 @@ export class BinarySession implements HopperToolPort {
const previous = this.#active;
this.#active = undefined;
await previous?.client.close();
const client = this.createClient(parsed.value);
const started = await client.callTool("health", {}, options);
const client = this.#createClient(parsed.value);
const started = await client.execute("health", {}, options);
if (!started.ok) {
await client.close();
await this.#restore(previous);
@@ -77,7 +96,7 @@ export class BinarySession implements HopperToolPort {
}
/** Close the active target, if any. */
close(): Promise<Result<null, HopperError>> {
close(): Promise<Result<null, AnalysisError>> {
return this.#serialize(async () => {
const previous = this.#active;
this.#active = undefined;
@@ -95,26 +114,33 @@ export class BinarySession implements HopperToolPort {
: {
open: true,
path: target.path,
sha256: target.sha256,
format: target.format,
kind: target.kind,
architecture: target.architecture ?? null,
};
}
/** Return the immutable artifact identity captured before Hopper launched. */
activeTarget(): BinaryTarget | undefined {
return this.#active?.target;
}
/**
* Invoke a Hopper tool against the active target.
* Calls may overlap, but a pending target transition prevents new calls from
* entering until the transition has settled.
*/
async callTool(
async execute(
name: string,
arguments_: Readonly<Record<string, JsonValue>>,
options?: { readonly signal?: AbortSignal },
): Promise<Result<JsonValue, HopperError>> {
): Promise<Result<JsonValue, AnalysisError>> {
const transitioned = await this.#waitForTransition(options?.signal);
if (!transitioned.ok) return transitioned;
const active = this.#active;
if (active === undefined) return err(new NoBinaryOpenError());
const call = active.client.callTool(name, arguments_, options);
const call = active.client.execute(name, arguments_, options);
this.#calls.add(call);
try {
return await call;
@@ -138,12 +164,12 @@ export class BinarySession implements HopperToolPort {
async #restore(
previous:
| { readonly target: BinaryTarget; readonly client: BinaryClient }
| { readonly target: BinaryTarget; readonly client: AnalysisClient }
| undefined,
): Promise<void> {
if (previous === undefined) return;
const client = this.createClient(previous.target);
const started = await client.callTool("health", {});
const client = this.#createClient(previous.target);
const started = await client.execute("health", {});
if (started.ok) this.#active = { target: previous.target, client };
else await client.close();
}
+8 -3
View File
@@ -1,7 +1,8 @@
import { parseConfig } from "../config.js";
import type { JsonValue } from "../hopper/protocol.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { createBinarySession } from "./runtime.js";
import { silentLogger, type Logger } from "../logger.js";
import { createEvidence } from "../domain/evidence.js";
/**
* Open one binary, execute one tool, and always release the bridge session.
@@ -22,9 +23,13 @@ export const runDirectAnalysis = async (
const opened = await session.open(path);
if (!opened.ok)
return { error: opened.error._tag, message: opened.error.message };
const result = await session.callTool(tool, arguments_);
const result = await session.execute(tool, arguments_);
return result.ok
? result.value
? createEvidence(opened.value, {
operation: tool,
parameters: arguments_,
result: result.value,
})
: { error: result.error._tag, message: result.error.message };
} finally {
await session.close();
+176 -8
View File
@@ -1,7 +1,7 @@
import type { HopperToolPort } from "./HopperToolPort.js";
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import { HopperProtocolError, type HopperError } from "../domain/errors.js";
import { AnalysisProtocolError, type AnalysisError } from "../domain/errors.js";
import {
parseDocuments,
parseAddressedPage,
@@ -16,9 +16,15 @@ import {
discoverObjcProtocols,
discoverSwiftClasses,
} from "../domain/symbolAnalysis.js";
import type { JsonValue } from "../hopper/protocol.js";
import type { JsonValue } from "../domain/jsonValue.js";
type EnhancedResult = Promise<Result<JsonValue, HopperError>>;
type EnhancedResult = Promise<Result<JsonValue, AnalysisError>>;
type TraceMatch = { type: string; address: string; value: string };
type TraceReference = {
target_address: string;
source_address: string;
containing_procedure: JsonValue;
};
/**
* Composes official Hopper operations into bounded reverse-engineering tools.
@@ -26,7 +32,7 @@ type EnhancedResult = Promise<Result<JsonValue, HopperError>>;
* validates them, allowing direct callers to use the same service safely.
*/
export class EnhancedTools {
constructor(private readonly hopper: HopperToolPort) {}
constructor(private readonly analysis: AnalysisOperationPort) {}
/** Parse inputs again at the direct-call boundary, then dispatch exhaustively. */
execute(
@@ -81,6 +87,12 @@ export class EnhancedTools {
? this.#call("analyze_function", parsed.data, signal)
: invalidInput(name, parsed.error);
}
case "trace_feature": {
const parsed = enhancedInputSchemas.trace_feature.safeParse(input);
return parsed.success
? this.#traceFeature(parsed.data, signal)
: invalidInput(name, parsed.error);
}
}
}
@@ -253,6 +265,155 @@ export class EnhancedTools {
});
}
async #traceFeature(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): EnhancedResult {
const searched = await this.#literalMatches(input, signal);
if (!searched.ok) return searched;
const residual = new Set<string>();
const traced = await this.#traceReferences(
searched.value.matches,
input.limit,
input.max_operations - searched.value.operations,
signal,
);
if (!traced.ok) return traced;
for (const reason of traced.value.residual) residual.add(reason);
const operations = searched.value.operations + traced.value.operations;
if (operations >= input.max_operations)
residual.add("Investigation reached the operation budget.");
if (searched.value.matches.length >= input.limit)
residual.add("Literal matches reached the configured limit.");
return ok({
query: input.query,
search_mode: "literal",
operations_used: operations,
operation_budget: input.max_operations,
matches: searched.value.matches,
references: traced.value.references,
truncated: residual.size > 0,
residual_unknowns: [...residual],
});
}
async #literalMatches(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): Promise<
Result<{ matches: TraceMatch[]; operations: number }, AnalysisError>
> {
let operations = 0;
const matches: TraceMatch[] = [];
const needle = input.case_sensitive
? input.query
: input.query.toLowerCase();
for (const [tool, type] of [
["list_strings", "string"],
["list_procedures", "procedure"],
] as const) {
let offset = 0;
while (
operations < input.max_operations &&
matches.length < input.limit
) {
operations += 1;
const result = await this.#call(tool, { offset, limit: 500 }, signal);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
for (const item of page.value.items) {
const haystack = input.case_sensitive
? item.name
: item.name.toLowerCase();
if (haystack.includes(needle))
matches.push({ type, address: item.address, value: item.name });
if (matches.length >= input.limit) break;
}
if (!page.value.hasMore || page.value.nextOffset === null) break;
offset = page.value.nextOffset;
}
}
return ok({ matches, operations });
}
async #traceReferences(
matches: readonly TraceMatch[],
limit: number,
operationBudget: number,
signal?: AbortSignal,
): Promise<
Result<
{ references: TraceReference[]; operations: number; residual: string[] },
AnalysisError
>
> {
let operations = 0;
const references: TraceReference[] = [];
const residual = new Set<string>();
for (const match of matches) {
if (operations >= operationBudget) {
residual.add("Reference traversal stopped at the operation budget.");
break;
}
operations += 1;
const xrefs = await this.#call(
"xrefs",
{ address: match.address },
signal,
);
if (!xrefs.ok) return xrefs;
if (!Array.isArray(xrefs.value))
return err(
new AnalysisProtocolError("xrefs returned a non-array result"),
);
for (const source of xrefs.value) {
if (typeof source !== "string")
return err(
new AnalysisProtocolError("xrefs returned a non-address value"),
);
if (operations >= operationBudget) {
residual.add(
"Containing-procedure resolution stopped at the operation budget.",
);
break;
}
operations += 1;
const resolved = await this.#call(
"resolve_containing_procedure",
{ address: source },
signal,
);
if (!resolved.ok) return resolved;
references.push({
target_address: match.address,
source_address: source,
containing_procedure: resolved.value,
});
if (references.length >= limit) {
residual.add("Reference results reached the configured limit.");
break;
}
}
if (references.length >= limit) break;
}
return ok({
references,
operations,
residual: [...residual],
});
}
async #allProcedures(signal?: AbortSignal) {
return this.#allAddressed("list_procedures", signal);
}
@@ -272,6 +433,13 @@ export class EnhancedTools {
if (!page.value.hasMore || page.value.nextOffset === null) {
return ok(entries);
}
if (page.value.nextOffset <= offset) {
return err(
new AnalysisProtocolError(
`${tool} returned a non-advancing pagination offset`,
),
);
}
offset = page.value.nextOffset;
}
}
@@ -280,8 +448,8 @@ export class EnhancedTools {
name: string,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<JsonValue, HopperError>> {
return this.hopper.callTool(
): Promise<Result<JsonValue, AnalysisError>> {
return this.analysis.execute(
name,
arguments_,
signal === undefined ? {} : { signal },
@@ -292,7 +460,7 @@ export class EnhancedTools {
const invalidInput = (name: EnhancedToolName, cause: Error): EnhancedResult =>
Promise.resolve(
err(
new HopperProtocolError(`Invalid ${name} input after MCP validation`, {
new AnalysisProtocolError(`Invalid ${name} input after MCP validation`, {
cause,
}),
),
-17
View File
@@ -1,17 +0,0 @@
import type { HopperError } from "../domain/errors.js";
import type { Result } from "../domain/result.js";
import type { JsonValue } from "../hopper/protocol.js";
/** Application-owned capability for invoking one official Hopper tool. */
export interface HopperToolPort {
/**
* Invoke a declared bridge operation with JSON-safe arguments.
* Implementations return expected Hopper, timeout, and cancellation failures
* as values and must honor an already-aborted signal.
*/
callTool(
name: string,
arguments_: Readonly<Record<string, JsonValue>>,
options?: { readonly signal?: AbortSignal },
): Promise<Result<JsonValue, HopperError>>;
}
+2 -23
View File
@@ -1,9 +1,6 @@
import { fileURLToPath } from "node:url";
import type { AppConfig } from "../config.js";
import { BinarySession } from "./BinarySession.js";
import { HopperApplicationLauncher } from "../hopper/BridgeLauncher.js";
import { HopperClient } from "../hopper/HopperClient.js";
import { HopperProvider } from "../hopper/HopperProvider.js";
import { silentLogger, type Logger } from "../logger.js";
/**
@@ -15,23 +12,5 @@ export const createBinarySession = (
config: AppConfig,
logger: Logger = silentLogger,
): BinarySession => {
const bridgeScriptPath = fileURLToPath(
new URL("../../bridge/hopper_bridge.py", import.meta.url),
);
return new BinarySession(
(target) =>
new HopperClient({
launcher: new HopperApplicationLauncher({
launcherPath: config.hopperLauncherPath,
targetPath: target.path,
targetKind: target.kind,
loaderArgs:
config.hopperLoaderArgs.length > 0
? config.hopperLoaderArgs
: target.loaderArgs,
bridgeScriptPath,
}),
logger: logger.child({ layer: "bridge" }),
}),
);
return new BinarySession(new HopperProvider(config, logger));
};
+7
View File
@@ -29,6 +29,12 @@ export const enhancedInputSchemas = {
max_pseudocode_chars: z.number().int().min(1).max(100_000).default(20_000),
max_instructions: z.number().int().min(1).max(5_000).default(500),
}),
trace_feature: z.object({
query: z.string().min(1),
case_sensitive: z.boolean().default(false),
limit: z.number().int().min(1).max(100).default(20),
max_operations: z.number().int().min(1).max(100).default(20),
}),
} as const;
export type EnhancedToolName = keyof typeof enhancedInputSchemas;
@@ -44,4 +50,5 @@ export const enhancedToolNameSchema = z.enum([
"find_xrefs_to_name",
"binary_overview",
"analyze_function",
"trace_feature",
]);
+108 -65
View File
@@ -1,6 +1,11 @@
import { z } from "zod";
import { enhancedInputSchemas } from "./enhancedInputs.js";
import {
enhancedOutputSchemas,
officialOutputSchemas,
sessionOutputSchemas,
} from "./toolOutputSchemas.js";
const document = z.string().optional().describe("The document name");
const address = z.string().describe("A Hopper address");
@@ -15,22 +20,6 @@ const pagination = {
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(500).default(100),
};
const jsonScalar = z.union([z.string(), z.number(), z.boolean(), z.null()]);
const jsonOutput = z.object({
result: z.union([
jsonScalar,
z.array(z.unknown()),
z.record(z.string(), z.unknown()),
]),
});
const pageOutput = z.object({
items: z.array(z.object({ address: z.string(), value: z.string() })),
offset: z.number().int().min(0),
limit: z.number().int().min(1),
total: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
has_more: z.boolean(),
});
export interface ToolAnnotations {
readonly readOnlyHint: boolean;
@@ -78,9 +67,7 @@ const official = (
description,
kind: "official-proxy",
inputSchema,
outputSchema: ["list_procedures", "list_names", "list_strings"].includes(name)
? pageOutput
: jsonOutput,
outputSchema: requireOutputSchema(officialOutputSchemas, name),
annotations: annotations(name, "official-proxy"),
});
@@ -93,7 +80,7 @@ const enhanced = (
description,
kind: "enhanced",
inputSchema,
outputSchema: jsonOutput,
outputSchema: requireOutputSchema(enhancedOutputSchemas, name),
annotations: annotations(name, "enhanced"),
});
@@ -106,149 +93,192 @@ const session = (
description,
kind: "session",
inputSchema,
outputSchema: jsonOutput,
outputSchema: requireOutputSchema(sessionOutputSchemas, name),
annotations: annotations(name, "session"),
});
const requireOutputSchema = (
schemas: Readonly<Record<string, z.ZodObject>>,
name: string,
): z.ZodObject => {
const schema = schemas[name];
if (schema === undefined)
throw new Error(`Missing output schema for ${name}`);
return schema;
};
/** Bridge operations exposed without additional application composition. */
export const OFFICIAL_TOOL_CONTRACTS = [
official(
"address_name",
"Get the name at an address",
"Resolve the analyzed name at a code or data address, defaulting to Hopper's current cursor. Use before following a symbol into xrefs; null means Hopper has no name at that address.",
z.object({ document, address: optionalAddress }),
),
official(
"comment",
"Get the comment at an address",
"Read the regular analysis comment at an address, defaulting to the current cursor. This is read-only and returns null when no comment exists; use set_comment to persist a finding.",
z.object({ document, address: optionalAddress }),
),
official(
"current_address",
"Get the current address",
"Return Hopper's current cursor address for the selected document. Use only for interactive navigation state; prefer explicit addresses in reproducible investigations.",
z.object({ document }),
),
official(
"current_procedure",
"Get the current procedure",
"Return the analyzed procedure containing Hopper's current cursor. Use procedure_info or analyze_function next; this depends on GUI cursor state and is not an exhaustive lookup.",
z.object({ document }),
),
official("current_document", "Get the current document", z.object({})),
official(
"current_document",
"Return the document currently selected by REA's Hopper bridge. Use list_documents before switching when several documents are open.",
z.object({}),
),
official(
"goto_address",
"Navigate to an address",
"Move Hopper's GUI cursor to a hexadecimal address and return the resolved address. This changes navigation state but not analysis data; use explicit-address tools for headless workflows.",
z.object({ address, document }),
),
official(
"inline_comment",
"Get the inline comment at an address",
"Read the inline instruction comment at an address, defaulting to the current cursor. Returns null when absent; use set_inline_comment to write one.",
z.object({ document, address: optionalAddress }),
),
official("list_bookmarks", "List bookmarks", z.object({ document })),
official("list_documents", "List open documents", z.object({})),
official(
"list_bookmarks",
"List every bookmark in the selected Hopper document as address and name pairs. Use bookmarks as analyst-authored navigation aids; this does not discover code references.",
z.object({ document }),
),
official(
"list_documents",
"List all Hopper documents visible to the bridge. Use before set_current_document when a provider session contains multiple documents.",
z.object({}),
),
official(
"list_names",
"List names",
"Page through analyzed names as address/value pairs. Results are bounded by offset and limit; follow next_offset until has_more is false before claiming exhaustive symbol coverage.",
z.object({ document, address: optionalAddress, ...pagination }),
),
official(
"list_procedures",
"List procedures",
"Page through analyzed procedures as address/value pairs. Wait for Hopper analysis first, then follow next_offset for exhaustive coverage; use returned addresses with analyze_function or procedure_pseudo_code.",
z.object({ document, ...pagination }),
),
official("list_segments", "List segments", z.object({ document })),
official(
"list_segments",
"List all segments and sections in the selected document. Hopper's public API does not expose permissions, so writable and executable are null with explicit capability metadata.",
z.object({ document }),
),
official(
"list_strings",
"List strings",
"Page through analyzed strings, or filter to one address, as address/value pairs. Follow next_offset for exhaustive results and use xrefs on interesting string addresses.",
z.object({ document, address: optionalAddress, ...pagination }),
),
official(
"next_address",
"Get the next address",
"Return the next analyzed object address after an explicit address or current cursor. This is a navigation primitive, not instruction-flow or CFG analysis.",
z.object({ document, address: optionalAddress }),
),
official(
"prev_address",
"Get the previous address",
"Return the previous analyzed instruction start before an explicit address or current cursor. This is a navigation primitive and may fail at document boundaries.",
z.object({ document, address: optionalAddress }),
),
official(
"procedure_address",
"Resolve a procedure address",
"Resolve a procedure symbol name or hexadecimal address to its entry address. Use this to canonicalize user-supplied identifiers before xrefs, assembly, or decompilation.",
z.object({ procedure, document }),
),
official(
"procedure_assembly",
"Get procedure assembly",
"Return assembly for one analyzed procedure identified by symbol or hexadecimal address. Use when pseudocode loses calling-convention or instruction-level detail; output is currently returned as one unpaginated string.",
z.object({ procedure, document }),
),
official(
"procedure_callees",
"List procedure callees",
"Return Hopper's analyzed direct callees for one procedure identified by symbol or address. Indirect calls may be absent; use analyze_function and xrefs to corroborate the call path.",
z.object({ procedure, document }),
),
official(
"procedure_callers",
"List procedure callers",
"Return Hopper's analyzed direct callers for one procedure identified by symbol or address. Results reflect completed static analysis and may omit indirect references.",
z.object({ procedure, document }),
),
official(
"procedure_info",
"Get procedure metadata",
"Return bounded metadata for one procedure identified by symbol or address: entrypoint, signature, locals, size, and block count. Follow with decompilation or assembly for behavior.",
z.object({ procedure, document }),
),
official(
"procedure_references",
"Return a bounded set of raw incoming or outgoing reference edges for one procedure. Endpoint procedures are resolved only when Hopper reports containment; reference kinds remain explicitly unavailable.",
z.object({
procedure,
direction: z.enum(["incoming", "outgoing"]).default("outgoing"),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(500).default(100),
max_instructions: z.number().int().min(1).max(5000).default(500),
document,
}),
),
official(
"procedure_pseudo_code",
"Decompile a procedure",
"Decompile one analyzed procedure by symbol name or hexadecimal address. Returns Hopper pseudocode, not original source, and may return null; request procedure_assembly when instruction precision matters.",
z.object({ procedure, document }),
),
official(
"resolve_containing_procedure",
"Resolve an arbitrary address, including an xref source or interior instruction, to its Hopper-analyzed containing procedure. A negative result includes an explicit reason and is not guessed from nearby symbols.",
z.object({ address, document }),
),
official(
"search_procedures",
"Search procedure names",
"Regex-search all analyzed procedure names with optional case sensitivity. The current bridge returns an unpaginated address/name map, so constrain patterns and use list_procedures for controlled exhaustive traversal.",
z.object({ pattern, case_sensitive: caseSensitive, document }),
),
official(
"search_strings",
"Search strings",
"Regex-search all analyzed strings with optional case sensitivity. The current bridge is unpaginated and evaluates Python regex, so use narrow patterns and follow matches with xrefs.",
z.object({ pattern, case_sensitive: caseSensitive, document }),
),
official(
"set_address_name",
"Set an address name",
"Assign an analyst name to one hexadecimal address and report Hopper's boolean result. This mutates analysis metadata; read it back with address_name before relying on it.",
z.object({ address, name: z.string(), document }),
),
official(
"set_addresses_names",
"Set multiple address names",
"Assign analyst names to an address/name map and return per-address success booleans. This mutates analysis metadata; use for bounded batches and verify failures individually.",
z.object({ names: z.record(z.string(), z.string()), document }),
),
official(
"set_bookmark",
"Set a bookmark",
"Create or replace a bookmark at a hexadecimal address. This mutates navigation metadata; verify with list_bookmarks and do not treat bookmarks as binary evidence.",
z.object({ address, name: z.string().optional(), document }),
),
official(
"set_comment",
"Set an address comment",
"Write a regular analysis comment at a hexadecimal address and return whether readback matched. This mutates the Hopper document; use comments to record evidence IDs or reasoning.",
z.object({ address, comment: z.string(), document }),
),
official(
"set_current_document",
"Select the current document",
"Select an already-open Hopper document by exact document name. This changes subsequent default-document routing; call list_documents first and prefer explicit document inputs where reproducibility matters.",
z.object({ document: z.string() }),
),
official(
"set_inline_comment",
"Set an inline comment",
"Write an inline instruction comment at a hexadecimal address and return whether readback matched. This mutates analysis metadata; confirm with inline_comment.",
z.object({ address, comment: z.string(), document }),
),
official(
"unset_bookmark",
"Remove a bookmark",
"Remove the bookmark at a hexadecimal address and return whether it is absent. This mutates navigation metadata and does not alter binary bytes.",
z.object({ address, document }),
),
official(
"xrefs",
"Get cross-references to an address",
"Return analyzed references to a code or data address, defaulting to the current cursor. Use to connect strings, globals, selectors, and functions; bare addresses are untyped and indirect references may be incomplete.",
z.object({ document, address: optionalAddress }),
),
] as const satisfies readonly ToolContract[];
@@ -257,65 +287,78 @@ export const OFFICIAL_TOOL_CONTRACTS = [
export const ENHANCED_TOOL_CONTRACTS = [
enhanced(
"swift_classes",
"Discover Swift classes",
"Discover legacy-mangled Swift class procedures after exhaustively paging analyzed procedures. Returns at most 100 entries and scans at most 5,000 symbols; use analyze_swift_types for other Swift kinds.",
enhancedInputSchemas.swift_classes,
),
enhanced(
"get_objc_classes",
"Discover Objective-C classes",
"Discover and deduplicate Objective-C class labels after exhaustively paging names, optionally filtering by literal substring. Returns at most 100 classes; inspect matching metadata and references next.",
enhancedInputSchemas.get_objc_classes,
),
enhanced(
"get_objc_protocols",
"Discover Objective-C protocols",
"Discover and deduplicate Objective-C and Swift protocol labels after exhaustively paging names. Returns at most 100 entries; use xrefs or analyze_function to connect a protocol to implementations.",
enhancedInputSchemas.get_objc_protocols,
),
enhanced(
"batch_decompile",
"Decompile up to 20 procedures",
"Decompile up to 20 explicit procedure symbols or addresses concurrently. Per-item strings may contain errors or no-output markers, so validate each result; use analyze_function for a richer single-function dossier.",
enhancedInputSchemas.batch_decompile,
),
enhanced(
"get_call_graph",
"Traverse a bounded call graph",
"Traverse Hopper's caller or callee relationships from one symbol or address for at most five levels. Nodes preserve per-procedure errors; indirect calls may be missing and results are not a whole-program CFG.",
enhancedInputSchemas.get_call_graph,
),
enhanced(
"analyze_swift_types",
"Categorize Swift mangled names",
"Categorize exhaustively paged procedure names into Swift classes, structs, enums, protocols, extensions, and other symbols. Scans at most 5,000 names and returns at most 50 entries per category.",
enhancedInputSchemas.analyze_swift_types,
),
enhanced(
"find_xrefs_to_name",
"Find cross-references by name",
"Resolve a name through Hopper and return analyzed references to its address. Use when starting from a selector or symbol; resolution failure is returned explicitly and xrefs remain untyped.",
enhancedInputSchemas.find_xrefs_to_name,
),
enhanced(
"binary_overview",
"First call after opening an app: summarize the loaded binary",
"Use immediately after opening a target to summarize document, exhaustive procedure/string counts, and a bounded segment sample. detail controls segment fields and limit controls only the returned segment sample.",
enhancedInputSchemas.binary_overview,
),
enhanced(
"analyze_function",
"Preferred bounded function analysis; combines metadata, pseudocode, assembly, references, calls, strings, names, and blocks",
"Preferred bounded analysis for one procedure symbol or address. Returns identity, pseudocode, optional assembly, comments, calls, incoming references, and blocks; unsupported outgoing references and CFG edges carry explicit unavailable metadata.",
enhancedInputSchemas.analyze_function,
),
enhanced(
"trace_feature",
"Trace a bounded literal feature query through matching strings and procedures, xrefs, and truthful containing-procedure resolution. Returns the operation budget, truncation, and residual unknowns; it does not infer reference kinds.",
enhancedInputSchemas.trace_feature,
),
] as const satisfies readonly ToolContract[];
/** Target lifecycle tools available only on the long-lived MCP adapter. */
export const SESSION_TOOL_CONTRACTS = [
session(
"open_binary",
"Open or switch the active binary",
"Open a local executable, application bundle, or Hopper database, replacing the active target only after validation. This launches Hopper and may show UI; call binary_overview after success.",
z.object({ path: z.string().min(1) }),
),
session("close_binary", "Close the active binary", z.object({})),
session("binary_session", "Describe the active binary session", z.object({})),
session(
"close_binary",
"Close the active Hopper-backed target and release its provider process. The operation is idempotent; call binary_session to verify the session is closed.",
z.object({}),
),
session(
"binary_session",
"Report whether a target is open and, when open, its canonical path, format, and kind. Use before analysis calls or target switches; this performs no analysis.",
z.object({}),
),
] as const satisfies readonly ToolContract[];
/**
* Complete ordered public inventory used by registration and verification.
* Keep this collection at 43 tools unless a deliberate contract change updates
* Keep this collection at 46 tools unless a deliberate contract change updates
* snapshots, package verification, and real-Hopper verification together.
*/
export const TOOL_CONTRACTS = [
+287
View File
@@ -0,0 +1,287 @@
import { z } from "zod";
const evidenceMetadata = {
schema_version: z.literal(1),
artifact: z
.object({
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
format: z.enum(["hopper", "mach-o", "elf", "pe"]),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
})
.nullable(),
provider: z.object({ id: z.literal("hopper"), version: z.null() }),
operation: z.string().min(1),
parameters: z.record(z.string(), z.json()),
confidence: z.literal("observed"),
limitations: z.array(z.string()),
};
const resultOf = (schema: z.ZodType) =>
z.object({ ...evidenceMetadata, result: schema });
const lifecycleResultOf = (schema: z.ZodType) => z.object({ result: schema });
const nullableText = z.string().nullable();
const addressList = z.array(z.string());
const addressedEntry = z.object({ address: z.string(), name: z.string() });
const procedureIdentity = z.object({ address: z.string(), name: z.string() });
const containingProcedureResolution = z.discriminatedUnion("found", [
z.object({
query_address: z.string(),
found: z.literal(true),
procedure: procedureIdentity,
}),
z.object({
query_address: z.string(),
found: z.literal(false),
procedure: z.null(),
reason: z.enum(["outside_segments", "not_in_procedure"]),
}),
]);
const unavailable = z.object({
available: z.literal(false),
reason: z.string(),
});
const bounded = (item: z.ZodType) =>
z.object({
items: z.array(item),
total: z.number().int().min(0).nullable(),
returned: z.number().int().min(0),
truncated: z.boolean(),
next_offset: z.number().int().min(0).nullable(),
});
const pageOutput = z.object({
items: z.array(z.object({ address: z.string(), value: z.string() })),
offset: z.number().int().min(0),
limit: z.number().int().min(1),
total: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
has_more: z.boolean(),
});
const segmentOutput = resultOf(
z.array(
z.object({
name: z.string(),
start: z.string(),
end: z.string(),
writable: z.boolean().nullable(),
executable: z.boolean().nullable(),
permissions: unavailable,
sections: z.array(
z.object({ name: z.string(), start: z.string(), end: z.string() }),
),
}),
),
);
const procedureInfoOutput = resultOf(
z.object({
name: z.string(),
entrypoint: z.string(),
basicblock_count: z.number().int().min(0),
length: z.number().min(0),
signature: nullableText,
locals: z.array(z.json()),
}),
);
const symbolDiscoveryOutput = (property: "classes" | "protocols") =>
resultOf(
z.object({
count: z.number().int().min(0),
[property]: z.array(addressedEntry),
}),
);
const graphNode = z.union([
z.object({ address: z.string(), calls: z.array(z.string()) }),
z.object({ address: z.string(), error: z.string() }),
]);
const unavailableOrBoundedStrings = z.union([unavailable, bounded(z.string())]);
const functionDossierOutput = resultOf(
z.object({
procedure: z.object({
address: z.string(),
name: z.string(),
signature: nullableText,
locals: z.array(z.json()),
}),
pseudocode: z.object({
text: z.string(),
total_chars: z.number().int().min(0),
returned_chars: z.number().int().min(0),
truncated: z.boolean(),
next_offset: z.number().int().min(0).nullable(),
}),
assembly: bounded(z.string()),
comments: bounded(
z.object({
address: z.string(),
kind: z.enum(["comment", "inline"]),
text: z.string(),
}),
),
callers: bounded(z.string()),
callees: bounded(z.string()),
incoming_references: bounded(z.string()),
referenced_strings: unavailableOrBoundedStrings,
referenced_names: unavailableOrBoundedStrings,
basic_blocks: bounded(
z.object({
start: z.string(),
end: z.string(),
successors: z.union([unavailable, z.array(z.string())]),
}),
),
}),
);
/** Exact structured-content schemas for the direct Hopper operations. */
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
address_name: resultOf(nullableText),
comment: resultOf(nullableText),
current_address: resultOf(z.string()),
current_procedure: resultOf(z.string()),
current_document: resultOf(z.string()),
goto_address: resultOf(z.string()),
inline_comment: resultOf(nullableText),
list_bookmarks: resultOf(z.array(addressedEntry)),
list_documents: resultOf(z.array(z.string())),
list_names: resultOf(pageOutput),
list_procedures: resultOf(pageOutput),
list_segments: segmentOutput,
list_strings: resultOf(pageOutput),
next_address: resultOf(z.string()),
prev_address: resultOf(z.string()),
procedure_address: resultOf(z.string()),
procedure_assembly: resultOf(z.string()),
procedure_callees: resultOf(addressList),
procedure_callers: resultOf(addressList),
procedure_info: procedureInfoOutput,
procedure_references: resultOf(
z.object({
procedure: procedureIdentity,
direction: z.enum(["incoming", "outgoing"]),
references: bounded(
z.object({
source_address: z.string(),
target_address: z.string(),
source_procedure: procedureIdentity.nullable(),
target_procedure: procedureIdentity.nullable(),
kind: unavailable,
}),
),
instructions_scanned: z.number().int().min(0),
instruction_scan_truncated: z.boolean(),
}),
),
procedure_pseudo_code: resultOf(nullableText),
resolve_containing_procedure: resultOf(containingProcedureResolution),
search_procedures: resultOf(z.record(z.string(), z.string())),
search_strings: resultOf(z.record(z.string(), z.string())),
set_address_name: resultOf(z.boolean()),
set_addresses_names: resultOf(z.record(z.string(), z.boolean())),
set_bookmark: resultOf(z.boolean()),
set_comment: resultOf(z.boolean()),
set_current_document: resultOf(z.string()),
set_inline_comment: resultOf(z.boolean()),
unset_bookmark: resultOf(z.boolean()),
xrefs: resultOf(addressList),
};
/** Exact structured-content schemas for composed analysis workflows. */
export const enhancedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
swift_classes: symbolDiscoveryOutput("classes"),
get_objc_classes: symbolDiscoveryOutput("classes"),
get_objc_protocols: symbolDiscoveryOutput("protocols"),
batch_decompile: resultOf(
z.union([
z.object({ error: z.literal("No addresses provided") }),
z.record(z.string(), z.string()),
]),
),
get_call_graph: resultOf(z.record(z.string(), z.array(graphNode))),
analyze_swift_types: resultOf(
z.object({
total: z.number().int().min(0),
categories: z.record(
z.string(),
z.object({
count: z.number().int().min(0),
items: z.array(addressedEntry),
}),
),
}),
),
find_xrefs_to_name: resultOf(
z.union([
z.object({ xrefs: addressList }),
z.object({ error: z.string() }),
]),
),
binary_overview: resultOf(
z.object({
document: z.string(),
detail: z.enum(["concise", "detailed"]),
segments: z.array(
z.object({
name: z.string(),
start: z.string(),
end: z.string(),
length: z.number().min(0).optional(),
}),
),
segment_count: z.number().int().min(0),
procedure_count: z.number().int().min(0),
string_count: z.number().int().min(0),
}),
),
analyze_function: functionDossierOutput,
trace_feature: resultOf(
z.object({
query: z.string(),
search_mode: z.literal("literal"),
operations_used: z.number().int().min(0),
operation_budget: z.number().int().min(1),
matches: z.array(
z.object({
type: z.enum(["string", "procedure"]),
address: z.string(),
value: z.string(),
}),
),
references: z.array(
z.object({
target_address: z.string(),
source_address: z.string(),
containing_procedure: containingProcedureResolution,
}),
),
truncated: z.boolean(),
residual_unknowns: z.array(z.string()),
}),
),
};
/** Exact structured-content schemas for target lifecycle operations. */
export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
open_binary: lifecycleResultOf(
z.object({
path: z.string(),
format: z.enum(["hopper", "mach-o", "elf", "pe"]),
kind: z.enum(["executable", "database"]),
loaderArgs: z.array(z.string()),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
}),
),
close_binary: lifecycleResultOf(z.null()),
binary_session: lifecycleResultOf(
z.union([
z.object({ open: z.literal(false) }),
z.object({
open: z.literal(true),
path: z.string(),
format: z.enum(["hopper", "mach-o", "elf", "pe"]),
kind: z.enum(["executable", "database"]),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
}),
]),
),
};
+22 -2
View File
@@ -1,4 +1,6 @@
import { constants } from "node:fs";
import { createReadStream } from "node:fs";
import { createHash } from "node:crypto";
import {
access,
open,
@@ -25,6 +27,7 @@ type BinaryArchitecture = "x86" | "x86_64" | "arm" | "arm64";
*/
export interface BinaryTarget {
readonly path: string;
readonly sha256: string;
readonly kind: "executable" | "database";
readonly format: "hopper" | "mach-o" | "elf" | "pe";
readonly architecture?: BinaryArchitecture;
@@ -56,7 +59,13 @@ export const parseBinaryTarget = async (
targetKind === "database" ||
(targetKind === undefined && path.toLowerCase().endsWith(".hop"))
)
return ok({ path, kind: "database", format: "hopper", loaderArgs: [] });
return ok({
path,
sha256: await sha256File(path),
kind: "database",
format: "hopper",
loaderArgs: [],
});
const handle = await open(path, "r");
let detected: Result<ExecutableMetadata, string>;
try {
@@ -65,7 +74,12 @@ export const parseBinaryTarget = async (
await handle.close();
}
if (!detected.ok) return err(new BinaryTargetError(path, detected.error));
return ok({ path, kind: "executable", ...detected.value });
return ok({
path,
sha256: await sha256File(path),
kind: "executable",
...detected.value,
});
} catch (cause: unknown) {
return err(
new BinaryTargetError(candidate, "path is not readable", { cause }),
@@ -73,6 +87,12 @@ export const parseBinaryTarget = async (
}
};
const sha256File = async (path: string): Promise<string> => {
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) hash.update(chunk);
return hash.digest("hex");
};
const resolveAppBundle = async (
path: string,
): Promise<Result<string, BinaryTargetError>> => {
+13 -5
View File
@@ -1,8 +1,16 @@
/** Base class for expected Hopper integration failures. */
export abstract class HopperError extends Error {
/** Base class for expected analysis, provider, and session failures. */
export abstract class AnalysisError extends Error {
abstract readonly _tag: string;
}
/** Base class for failures produced specifically by the Hopper provider. */
export abstract class HopperError extends AnalysisError {}
/** Provider-neutral invalid analysis input or output at an application boundary. */
export class AnalysisProtocolError extends AnalysisError {
readonly _tag = "HopperProtocolError";
}
/** Hopper did not respond within the configured operation deadline. */
export class HopperTimeoutError extends HopperError {
readonly _tag = "HopperTimeoutError";
@@ -57,12 +65,12 @@ export class HopperStartError extends HopperError {
}
/** Runtime configuration could not be parsed safely. */
export class ConfigurationError extends HopperError {
export class ConfigurationError extends AnalysisError {
readonly _tag = "ConfigurationError";
}
/** No app or binary session exists for an analysis request. */
export class NoBinaryOpenError extends HopperError {
export class NoBinaryOpenError extends AnalysisError {
readonly _tag = "NoBinaryOpenError";
constructor() {
super(
@@ -72,7 +80,7 @@ export class NoBinaryOpenError extends HopperError {
}
/** A supplied target path could not be safely opened as a supported app or binary. */
export class BinaryTargetError extends HopperError {
export class BinaryTargetError extends AnalysisError {
readonly _tag = "BinaryTargetError";
constructor(
readonly path: string,
+62
View File
@@ -0,0 +1,62 @@
import { z } from "zod";
import type { BinaryTarget } from "./binaryTarget.js";
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
const artifactEvidenceSchema = z.object({
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
format: z.enum(["hopper", "mach-o", "elf", "pe"]),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
});
/** Strict JSON representation of one successful public analysis observation. */
export const evidenceSchema = z.object({
schema_version: z.literal(1),
artifact: artifactEvidenceSchema.nullable(),
provider: z.object({ id: z.literal("hopper"), version: z.null() }),
operation: z.string().min(1),
parameters: z.record(z.string(), jsonValueSchema),
result: jsonValueSchema,
confidence: z.literal("observed"),
limitations: z.array(z.string()),
});
export type Evidence = z.infer<typeof evidenceSchema>;
export interface EvidenceObservation {
readonly operation: string;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly result: JsonValue;
readonly limitations?: readonly string[];
}
/** Build deterministic evidence without claiming unavailable provider metadata. */
export const createEvidence = (
target: BinaryTarget | undefined,
observation: EvidenceObservation,
): Evidence =>
evidenceSchema.parse({
schema_version: 1,
artifact:
target === undefined
? null
: {
path: target.path,
sha256: target.sha256,
format: target.format,
architecture: target.architecture ?? null,
},
provider: { id: "hopper", version: null },
operation: observation.operation,
parameters: observation.parameters,
result: observation.result,
confidence: "observed",
limitations:
target === undefined
? [
"Artifact identity is unavailable for this fixed-target adapter.",
...(observation.limitations ?? []),
]
: [...(observation.limitations ?? [])],
});
+1 -1
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import type { JsonValue } from "../hopper/protocol.js";
import type { JsonValue } from "./jsonValue.js";
import { HopperProtocolError } from "./errors.js";
import { err, ok, type Result } from "./result.js";
+6
View File
@@ -0,0 +1,6 @@
import { z } from "zod";
/** JSON-safe value shared by domain, application, and adapter boundaries. */
export const jsonValueSchema = z.json();
export type JsonValue = z.infer<typeof jsonValueSchema>;
+1 -1
View File
@@ -1,4 +1,4 @@
import type { JsonValue } from "../hopper/protocol.js";
import type { JsonValue } from "./jsonValue.js";
import type { AddressedName } from "./hopperValues.js";
const MAX_SCANNED_SYMBOLS = 5_000;
+67
View File
@@ -0,0 +1,67 @@
import { fileURLToPath } from "node:url";
import type {
AnalysisClient,
AnalysisProvider,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import type { AppConfig } from "../config.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { Logger } from "../logger.js";
import { HopperApplicationLauncher } from "./BridgeLauncher.js";
import { HopperClient } from "./HopperClient.js";
const IDENTITY: ProviderIdentity = {
id: "hopper",
name: "Hopper Disassembler",
version: null,
};
const CAPABILITIES = [
"direct-analysis",
"decompilation",
"disassembly",
"cross-references",
"containing-procedure-resolution",
"procedure-references",
"analysis-metadata-mutation",
] as const;
/** Concrete analysis provider backed by REA's private Hopper bridge. */
export class HopperProvider implements AnalysisProvider {
constructor(
private readonly config: AppConfig,
private readonly logger: Logger,
) {}
identity(): ProviderIdentity {
return IDENTITY;
}
capabilities(): readonly string[] {
return CAPABILITIES;
}
createClient(target: BinaryTarget): AnalysisClient {
const client = new HopperClient({
launcher: new HopperApplicationLauncher({
launcherPath: this.config.hopperLauncherPath,
targetPath: target.path,
targetKind: target.kind,
loaderArgs:
this.config.hopperLoaderArgs.length > 0
? this.config.hopperLoaderArgs
: target.loaderArgs,
bridgeScriptPath: fileURLToPath(
new URL("../../bridge/hopper_bridge.py", import.meta.url),
),
}),
logger: this.logger.child({ layer: "bridge" }),
});
return {
execute: (operation, parameters, options) =>
client.callTool(operation, parameters, options),
close: () => client.close(),
};
}
}
+2 -2
View File
@@ -1,10 +1,10 @@
import { z } from "zod";
import { HopperProtocolError, HopperRemoteError } from "../domain/errors.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
export const jsonValueSchema = z.json();
export type JsonValue = z.infer<typeof jsonValueSchema>;
export { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
const responseSchema = z.union([
z.object({
+10 -8
View File
@@ -1,7 +1,7 @@
import { McpServer } from "@modelcontextprotocol/server";
import type { HopperToolPort } from "../application/HopperToolPort.js";
import type { BinarySession } from "../application/BinarySession.js";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { registerEnhancedTools } from "./registerEnhancedTools.js";
import { registerOfficialTools } from "./registerOfficialTools.js";
@@ -14,8 +14,8 @@ import { silentLogger, type Logger } from "../logger.js";
* fixed-target seam used by focused tests and embedders.
*/
export const createServer = (
hopper: HopperToolPort,
session?: BinarySession,
analysis: AnalysisOperationPort,
session?: BinarySessionPort,
logger: Logger = silentLogger,
): McpServer => {
const server = new McpServer(
@@ -24,13 +24,15 @@ export const createServer = (
capabilities: { tools: {} },
instructions:
session === undefined
? "Reverse-engineering tools for an active Hopper Disassembler target. Start with binary_overview."
: "Reverse-engineering tools for Hopper Disassembler. Open a target with open_binary, then start with binary_overview.",
? "Reverse-engineering tools for an active analysis target. Start with binary_overview."
: "Reverse-engineering tools for configured analysis providers. Open a target with open_binary, then start with binary_overview.",
},
);
const toolLogger = logger.child({ layer: "server" });
registerOfficialTools(server, hopper, toolLogger);
registerEnhancedTools(server, hopper, toolLogger);
const activeTarget =
session === undefined ? undefined : () => session.activeTarget();
registerOfficialTools(server, analysis, toolLogger, activeTarget);
registerEnhancedTools(server, analysis, toolLogger, activeTarget);
if (session !== undefined) registerSessionTools(server, session, toolLogger);
return server;
};
+40 -11
View File
@@ -1,7 +1,7 @@
import type { McpServer } from "@modelcontextprotocol/server";
import { EnhancedTools } from "../application/EnhancedTools.js";
import type { HopperToolPort } from "../application/HopperToolPort.js";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import { enhancedToolNameSchema } from "../contracts/enhancedInputs.js";
import {
ENHANCED_TOOL_CONTRACTS,
@@ -10,16 +10,21 @@ import {
import { toCallToolResult } from "./toolResult.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
/** Register composed workflows against the same port as direct bridge tools. */
export const registerEnhancedTools = (
server: McpServer,
hopper: HopperToolPort,
analysis: AnalysisOperationPort,
logger: Logger,
activeTarget?: () => BinaryTarget | undefined,
): void => {
const services = new EnhancedTools(hopper);
const services = new EnhancedTools(analysis);
for (const contract of ENHANCED_TOOL_CONTRACTS) {
registerEnhancedTool(server, services, contract, logger);
registerEnhancedTool(server, services, contract, { logger, activeTarget });
}
};
@@ -27,7 +32,10 @@ const registerEnhancedTool = (
server: McpServer,
services: EnhancedTools,
contract: ToolContract,
logger: Logger,
registration: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
},
): void => {
const name = enhancedToolNameSchema.parse(contract.name);
server.registerTool(
@@ -38,12 +46,33 @@ const registerEnhancedTool = (
outputSchema: contract.outputSchema,
annotations: contract.annotations,
},
async (input, context) =>
toCallToolResult(
await logToolExecution(logger, name, () =>
services.execute(name, input, context.mcpReq.signal),
),
async (input, context) => {
const parsedInput = jsonValueSchema.parse(
enhancedInputSchemas[name].parse(input),
);
if (
typeof parsedInput !== "object" ||
parsedInput === null ||
Array.isArray(parsedInput)
)
throw new Error("Validated enhanced input was not a JSON object");
const parameters: Record<string, JsonValue> = { ...parsedInput };
const result = await logToolExecution(registration.logger, name, () =>
services.execute(name, input, context.mcpReq.signal),
);
return toCallToolResult(
result.ok
? {
ok: true,
value: createEvidence(registration.activeTarget?.(), {
operation: name,
parameters,
result: result.value,
}),
}
: result,
contract,
),
);
},
);
};
+32 -11
View File
@@ -1,31 +1,37 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { HopperToolPort } from "../application/HopperToolPort.js";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import {
OFFICIAL_TOOL_CONTRACTS,
type ToolContract,
} from "../contracts/toolContracts.js";
import { jsonValueSchema, type JsonValue } from "../hopper/protocol.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { toCallToolResult } from "./toolResult.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence } from "../domain/evidence.js";
/** Register direct bridge proxies, preserving MCP cancellation and typed errors. */
export const registerOfficialTools = (
server: McpServer,
hopper: HopperToolPort,
analysis: AnalysisOperationPort,
logger: Logger,
activeTarget?: () => BinaryTarget | undefined,
): void => {
for (const contract of OFFICIAL_TOOL_CONTRACTS) {
registerOfficialTool(server, hopper, contract, logger);
registerOfficialTool(server, analysis, contract, { logger, activeTarget });
}
};
const registerOfficialTool = (
server: McpServer,
hopper: HopperToolPort,
analysis: AnalysisOperationPort,
contract: ToolContract,
logger: Logger,
registration: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
},
): void => {
server.registerTool(
contract.name,
@@ -37,12 +43,27 @@ const registerOfficialTool = (
},
async (input, context) => {
const arguments_ = projectOfficialArguments(contract, input);
const result = await logToolExecution(logger, contract.name, () =>
hopper.callTool(contract.name, arguments_, {
signal: context.mcpReq.signal,
}),
const result = await logToolExecution(
registration.logger,
contract.name,
() =>
analysis.execute(contract.name, arguments_, {
signal: context.mcpReq.signal,
}),
);
return toCallToolResult(
result.ok
? {
ok: true,
value: createEvidence(registration.activeTarget?.(), {
operation: contract.name,
parameters: arguments_,
result: result.value,
}),
}
: result,
contract,
);
return toCallToolResult(result, contract);
},
);
};
+4 -2
View File
@@ -1,7 +1,7 @@
import type { McpServer } from "@modelcontextprotocol/server";
import { z } from "zod";
import type { BinarySession } from "../application/BinarySession.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { SESSION_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import { toCallToolResult } from "./toolResult.js";
import type { Logger } from "../logger.js";
@@ -10,7 +10,7 @@ import { logToolExecution } from "./toolLogging.js";
/** Register MCP-only target lifecycle operations on a long-lived session. */
export const registerSessionTools = (
server: McpServer,
session: BinarySession,
session: BinarySessionPort,
logger: Logger,
): void => {
const [openContract, closeContract, statusContract] = SESSION_TOOL_CONTRACTS;
@@ -36,6 +36,8 @@ export const registerSessionTools = (
format: opened.value.format,
kind: opened.value.kind,
loaderArgs: [...opened.value.loaderArgs],
sha256: opened.value.sha256,
architecture: opened.value.architecture ?? null,
},
},
openContract,
+5 -9
View File
@@ -1,8 +1,8 @@
import type { CallToolResult } from "@modelcontextprotocol/server";
import type { HopperError } from "../domain/errors.js";
import type { AnalysisError } from "../domain/errors.js";
import type { Result } from "../domain/result.js";
import type { JsonValue } from "../hopper/protocol.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { ToolContract } from "../contracts/toolContracts.js";
/**
@@ -11,7 +11,7 @@ import type { ToolContract } from "../contracts/toolContracts.js";
* output, and other potentially sensitive details stay private.
*/
export const toCallToolResult = (
result: Result<JsonValue, HopperError>,
result: Result<JsonValue, AnalysisError>,
contract: ToolContract,
): CallToolResult =>
result.ok
@@ -30,18 +30,14 @@ const successResult = (
value: JsonValue,
contract: ToolContract,
): CallToolResult => {
const candidate = ["list_procedures", "list_names", "list_strings"].includes(
contract.name,
)
? value
: { result: value };
const candidate = contract.kind === "session" ? { result: value } : value;
const parsed = contract.outputSchema.safeParse(candidate);
if (!parsed.success) {
return {
content: [
{
type: "text",
text: "HopperProtocolError: Hopper returned output that does not match the tool contract",
text: "HopperProtocolError: Analysis output does not match the tool contract",
},
],
isError: true,