feat(mcp): add typed bounded analysis tools
This commit is contained in:
@@ -4,9 +4,8 @@ import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
import { HopperProtocolError, type HopperError } from "../domain/errors.js";
|
||||
import {
|
||||
parseDocuments,
|
||||
parseAddressedPage,
|
||||
parseListCount,
|
||||
parseNames,
|
||||
parseProcedures,
|
||||
parseRelatedAddresses,
|
||||
parseSegments,
|
||||
} from "../domain/hopperValues.js";
|
||||
@@ -70,31 +69,35 @@ export class EnhancedTools {
|
||||
? this.#findXrefs(parsed.data.name, signal)
|
||||
: invalidInput(name, parsed.error);
|
||||
}
|
||||
case "binary_overview":
|
||||
return this.#binaryOverview(signal);
|
||||
case "binary_overview": {
|
||||
const parsed = enhancedInputSchemas.binary_overview.safeParse(input);
|
||||
return parsed.success
|
||||
? this.#binaryOverview(parsed.data, signal)
|
||||
: invalidInput(name, parsed.error);
|
||||
}
|
||||
case "analyze_function": {
|
||||
const parsed = enhancedInputSchemas.analyze_function.safeParse(input);
|
||||
return parsed.success
|
||||
? this.#call("analyze_function", parsed.data, signal)
|
||||
: invalidInput(name, parsed.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #swiftClasses(pattern: string, signal?: AbortSignal): EnhancedResult {
|
||||
const result = await this.#call("list_procedures", {}, signal);
|
||||
if (!result.ok) return result;
|
||||
const procedures = parseProcedures(result.value);
|
||||
const procedures = await this.#allProcedures(signal);
|
||||
return procedures.ok
|
||||
? ok(discoverSwiftClasses(procedures.value, pattern))
|
||||
: procedures;
|
||||
}
|
||||
|
||||
async #objcClasses(pattern: string, signal?: AbortSignal): EnhancedResult {
|
||||
const result = await this.#call("list_names", {}, signal);
|
||||
if (!result.ok) return result;
|
||||
const names = parseNames(result.value);
|
||||
const names = await this.#allAddressed("list_names", signal);
|
||||
return names.ok ? ok(discoverObjcClasses(names.value, pattern)) : names;
|
||||
}
|
||||
|
||||
async #objcProtocols(signal?: AbortSignal): EnhancedResult {
|
||||
const result = await this.#call("list_names", {}, signal);
|
||||
if (!result.ok) return result;
|
||||
const names = parseNames(result.value);
|
||||
const names = await this.#allAddressed("list_names", signal);
|
||||
return names.ok ? ok(discoverObjcProtocols(names.value)) : names;
|
||||
}
|
||||
|
||||
@@ -187,9 +190,7 @@ export class EnhancedTools {
|
||||
}
|
||||
|
||||
async #analyzeSwiftTypes(signal?: AbortSignal): EnhancedResult {
|
||||
const result = await this.#call("list_procedures", {}, signal);
|
||||
if (!result.ok) return result;
|
||||
const procedures = parseProcedures(result.value);
|
||||
const procedures = await this.#allProcedures(signal);
|
||||
return procedures.ok
|
||||
? ok(categorizeSwiftTypes(procedures.value))
|
||||
: procedures;
|
||||
@@ -213,39 +214,68 @@ export class EnhancedTools {
|
||||
);
|
||||
}
|
||||
|
||||
async #binaryOverview(signal?: AbortSignal): EnhancedResult {
|
||||
const [segmentsResult, documentsResult, proceduresResult, stringsResult] =
|
||||
async #binaryOverview(
|
||||
input: { detail: "concise" | "detailed"; limit: number },
|
||||
signal?: AbortSignal,
|
||||
): EnhancedResult {
|
||||
const [segmentsResult, documentsResult, procedures, stringsResult] =
|
||||
await Promise.all([
|
||||
this.#call("list_segments", {}, signal),
|
||||
this.#call("list_documents", {}, signal),
|
||||
this.#call("list_procedures", {}, signal),
|
||||
this.#allProcedures(signal),
|
||||
this.#call("list_strings", {}, signal),
|
||||
]);
|
||||
if (!segmentsResult.ok) return segmentsResult;
|
||||
if (!documentsResult.ok) return documentsResult;
|
||||
if (!proceduresResult.ok) return proceduresResult;
|
||||
if (!procedures.ok) return procedures;
|
||||
if (!stringsResult.ok) return stringsResult;
|
||||
|
||||
const segments = parseSegments(segmentsResult.value);
|
||||
if (!segments.ok) return segments;
|
||||
const documents = parseDocuments(documentsResult.value);
|
||||
if (!documents.ok) return documents;
|
||||
const procedures = parseProcedures(proceduresResult.value);
|
||||
if (!procedures.ok) return procedures;
|
||||
const stringCount = parseListCount(stringsResult.value, "strings");
|
||||
if (!stringCount.ok) return stringCount;
|
||||
|
||||
return ok({
|
||||
document: documents.value[0] ?? "unknown",
|
||||
detail: input.detail,
|
||||
segments: segments.value
|
||||
.slice(0, 10)
|
||||
.map(({ name, start, end }) => ({ name, start, end })),
|
||||
.slice(0, input.limit)
|
||||
.map(({ name, start, end }) =>
|
||||
input.detail === "detailed"
|
||||
? { name, start, end, length: addressDistance(start, end) }
|
||||
: { name, start, end },
|
||||
),
|
||||
segment_count: segments.value.length,
|
||||
procedure_count: procedures.value.length,
|
||||
string_count: stringCount.value,
|
||||
});
|
||||
}
|
||||
|
||||
async #allProcedures(signal?: AbortSignal) {
|
||||
return this.#allAddressed("list_procedures", signal);
|
||||
}
|
||||
|
||||
async #allAddressed(
|
||||
tool: "list_names" | "list_procedures",
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const entries: Array<{ address: string; name: string }> = [];
|
||||
let offset = 0;
|
||||
while (true) {
|
||||
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;
|
||||
entries.push(...page.value.items);
|
||||
if (!page.value.hasMore || page.value.nextOffset === null) {
|
||||
return ok(entries);
|
||||
}
|
||||
offset = page.value.nextOffset;
|
||||
}
|
||||
}
|
||||
|
||||
#call(
|
||||
name: string,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
@@ -278,3 +308,6 @@ const resolveAddress = (value: JsonValue): string | undefined => {
|
||||
? candidate
|
||||
: undefined;
|
||||
};
|
||||
|
||||
const addressDistance = (start: string, end: string): number =>
|
||||
Math.max(0, Number.parseInt(end, 16) - Number.parseInt(start, 16));
|
||||
|
||||
@@ -18,7 +18,17 @@ export const enhancedInputSchemas = {
|
||||
}),
|
||||
analyze_swift_types: z.object({}),
|
||||
find_xrefs_to_name: z.object({ name: z.string() }),
|
||||
binary_overview: z.object({}),
|
||||
binary_overview: z.object({
|
||||
detail: z.enum(["concise", "detailed"]).default("concise"),
|
||||
limit: z.number().int().min(1).max(50).default(10),
|
||||
}),
|
||||
analyze_function: z.object({
|
||||
procedure: z.string().describe("A procedure name or address"),
|
||||
include_assembly: z.boolean().default(false),
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
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),
|
||||
}),
|
||||
} as const;
|
||||
|
||||
export type EnhancedToolName = keyof typeof enhancedInputSchemas;
|
||||
@@ -33,4 +43,5 @@ export const enhancedToolNameSchema = z.enum([
|
||||
"analyze_swift_types",
|
||||
"find_xrefs_to_name",
|
||||
"binary_overview",
|
||||
"analyze_function",
|
||||
]);
|
||||
|
||||
@@ -11,6 +11,33 @@ const caseSensitive = z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Whether to match case");
|
||||
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;
|
||||
readonly destructiveHint: boolean;
|
||||
readonly idempotentHint: true;
|
||||
readonly openWorldHint: false;
|
||||
}
|
||||
|
||||
/** Adapter family responsible for implementing a public MCP tool. */
|
||||
type ToolKind = "official-proxy" | "enhanced" | "session";
|
||||
@@ -21,25 +48,67 @@ export interface ToolContract {
|
||||
readonly description: string;
|
||||
readonly kind: ToolKind;
|
||||
readonly inputSchema: z.ZodObject;
|
||||
readonly outputSchema: z.ZodObject;
|
||||
readonly annotations: ToolAnnotations;
|
||||
}
|
||||
|
||||
const annotations = (name: string, kind: ToolKind): ToolAnnotations => ({
|
||||
readOnlyHint:
|
||||
kind === "enhanced" ||
|
||||
(!name.startsWith("set_") &&
|
||||
name !== "unset_bookmark" &&
|
||||
name !== "goto_address" &&
|
||||
kind !== "session"),
|
||||
destructiveHint:
|
||||
name === "unset_bookmark" ||
|
||||
name === "set_address_name" ||
|
||||
name === "set_addresses_names" ||
|
||||
name === "set_comment" ||
|
||||
name === "set_inline_comment",
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
});
|
||||
|
||||
const official = (
|
||||
name: string,
|
||||
description: string,
|
||||
inputSchema: z.ZodObject,
|
||||
): ToolContract => ({ name, description, kind: "official-proxy", inputSchema });
|
||||
): ToolContract => ({
|
||||
name,
|
||||
description,
|
||||
kind: "official-proxy",
|
||||
inputSchema,
|
||||
outputSchema: ["list_procedures", "list_names", "list_strings"].includes(name)
|
||||
? pageOutput
|
||||
: jsonOutput,
|
||||
annotations: annotations(name, "official-proxy"),
|
||||
});
|
||||
|
||||
const enhanced = (
|
||||
name: string,
|
||||
description: string,
|
||||
inputSchema: z.ZodObject,
|
||||
): ToolContract => ({ name, description, kind: "enhanced", inputSchema });
|
||||
): ToolContract => ({
|
||||
name,
|
||||
description,
|
||||
kind: "enhanced",
|
||||
inputSchema,
|
||||
outputSchema: jsonOutput,
|
||||
annotations: annotations(name, "enhanced"),
|
||||
});
|
||||
|
||||
const session = (
|
||||
name: string,
|
||||
description: string,
|
||||
inputSchema: z.ZodObject,
|
||||
): ToolContract => ({ name, description, kind: "session", inputSchema });
|
||||
): ToolContract => ({
|
||||
name,
|
||||
description,
|
||||
kind: "session",
|
||||
inputSchema,
|
||||
outputSchema: jsonOutput,
|
||||
annotations: annotations(name, "session"),
|
||||
});
|
||||
|
||||
/** Bridge operations exposed without additional application composition. */
|
||||
export const OFFICIAL_TOOL_CONTRACTS = [
|
||||
@@ -79,14 +148,18 @@ export const OFFICIAL_TOOL_CONTRACTS = [
|
||||
official(
|
||||
"list_names",
|
||||
"List names",
|
||||
z.object({ document, address: optionalAddress }),
|
||||
z.object({ document, address: optionalAddress, ...pagination }),
|
||||
),
|
||||
official(
|
||||
"list_procedures",
|
||||
"List procedures",
|
||||
z.object({ document, ...pagination }),
|
||||
),
|
||||
official("list_procedures", "List procedures", z.object({ document })),
|
||||
official("list_segments", "List segments", z.object({ document })),
|
||||
official(
|
||||
"list_strings",
|
||||
"List strings",
|
||||
z.object({ document, address: optionalAddress }),
|
||||
z.object({ document, address: optionalAddress, ...pagination }),
|
||||
),
|
||||
official(
|
||||
"next_address",
|
||||
@@ -219,9 +292,14 @@ export const ENHANCED_TOOL_CONTRACTS = [
|
||||
),
|
||||
enhanced(
|
||||
"binary_overview",
|
||||
"Summarize the loaded binary",
|
||||
"First call after opening an app: summarize the loaded binary",
|
||||
enhancedInputSchemas.binary_overview,
|
||||
),
|
||||
enhanced(
|
||||
"analyze_function",
|
||||
"Preferred bounded function analysis; combines metadata, pseudocode, assembly, references, calls, strings, names, and blocks",
|
||||
enhancedInputSchemas.analyze_function,
|
||||
),
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
/** Target lifecycle tools available only on the long-lived MCP adapter. */
|
||||
@@ -237,7 +315,7 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
|
||||
/**
|
||||
* Complete ordered public inventory used by registration and verification.
|
||||
* Keep this collection at 42 tools unless a deliberate contract change updates
|
||||
* Keep this collection at 43 tools unless a deliberate contract change updates
|
||||
* snapshots, package verification, and real-Hopper verification together.
|
||||
*/
|
||||
export const TOOL_CONTRACTS = [
|
||||
|
||||
@@ -15,6 +15,12 @@ export interface SegmentSummary {
|
||||
readonly end: string;
|
||||
}
|
||||
|
||||
export interface AddressedPage {
|
||||
readonly items: readonly AddressedName[];
|
||||
readonly nextOffset: number | null;
|
||||
readonly hasMore: boolean;
|
||||
}
|
||||
|
||||
const procedureMapSchema = z.record(z.string(), z.string());
|
||||
const addressedNamesSchema = z.array(
|
||||
z.object({ address: z.string(), name: z.string() }),
|
||||
@@ -25,11 +31,35 @@ const segmentSchema = z.object({
|
||||
start: z.string().default(""),
|
||||
end: z.string().default(""),
|
||||
});
|
||||
const addressedPageSchema = z.object({
|
||||
items: z.array(z.object({ address: z.string(), value: z.string() })),
|
||||
next_offset: z.number().int().min(0).nullable(),
|
||||
has_more: z.boolean(),
|
||||
});
|
||||
|
||||
/** Parse page entries and continuation metadata returned by list operations. */
|
||||
export const parseAddressedPage = (
|
||||
value: JsonValue,
|
||||
): Result<AddressedPage, HopperProtocolError> => {
|
||||
const parsed = addressedPageSchema.safeParse(value);
|
||||
return parsed.success
|
||||
? ok({
|
||||
items: parsed.data.items.map(({ address, value: name }) => ({
|
||||
address,
|
||||
name,
|
||||
})),
|
||||
nextOffset: parsed.data.next_offset,
|
||||
hasMore: parsed.data.has_more,
|
||||
})
|
||||
: invalid("addressed page", parsed.error);
|
||||
};
|
||||
|
||||
/** Parse Hopper's direct or wrapped procedure map into stable entries. */
|
||||
export const parseProcedures = (
|
||||
value: JsonValue,
|
||||
): Result<readonly AddressedName[], HopperProtocolError> => {
|
||||
const page = parseAddressedPage(value);
|
||||
if (page.ok) return ok(page.value.items);
|
||||
const parsed = procedureMapSchema.safeParse(
|
||||
unwrapProperty(value, "procedures"),
|
||||
);
|
||||
@@ -40,7 +70,7 @@ export const parseProcedures = (
|
||||
name,
|
||||
})),
|
||||
)
|
||||
: invalid("procedure map", parsed.error);
|
||||
: page;
|
||||
};
|
||||
|
||||
/** Parse Hopper's direct or wrapped list of address/name records. */
|
||||
@@ -48,6 +78,15 @@ export const parseNames = (
|
||||
value: JsonValue,
|
||||
): Result<readonly AddressedName[], HopperProtocolError> => {
|
||||
const unwrapped = unwrapProperty(value, "names");
|
||||
const page = z
|
||||
.object({
|
||||
items: z.array(z.object({ address: z.string(), value: z.string() })),
|
||||
})
|
||||
.safeParse(unwrapped);
|
||||
if (page.success)
|
||||
return ok(
|
||||
page.data.items.map(({ address, value: name }) => ({ address, name })),
|
||||
);
|
||||
const records = addressedNamesSchema.safeParse(unwrapped);
|
||||
if (records.success) return ok(records.data);
|
||||
const map = addressedNameMapSchema.safeParse(unwrapped);
|
||||
@@ -97,6 +136,12 @@ export const parseListCount = (
|
||||
property: string,
|
||||
): Result<number, HopperProtocolError> => {
|
||||
const unwrapped = unwrapProperty(value, property);
|
||||
const pageTotal = z
|
||||
.object({ total: z.number().int().min(0) })
|
||||
.safeParse(unwrapped);
|
||||
if (pageTotal.success) return ok(pageTotal.data.total);
|
||||
const page = z.object({ items: z.array(z.unknown()) }).safeParse(unwrapped);
|
||||
if (page.success) return ok(page.data.items.length);
|
||||
const list = z.array(z.unknown()).safeParse(unwrapped);
|
||||
if (list.success) return ok(list.data.length);
|
||||
const map = z.record(z.string(), z.unknown()).safeParse(unwrapped);
|
||||
|
||||
@@ -32,12 +32,18 @@ const registerEnhancedTool = (
|
||||
const name = enhancedToolNameSchema.parse(contract.name);
|
||||
server.registerTool(
|
||||
name,
|
||||
{ description: contract.description, inputSchema: contract.inputSchema },
|
||||
{
|
||||
description: contract.description,
|
||||
inputSchema: contract.inputSchema,
|
||||
outputSchema: contract.outputSchema,
|
||||
annotations: contract.annotations,
|
||||
},
|
||||
async (input, context) =>
|
||||
toCallToolResult(
|
||||
await logToolExecution(logger, name, () =>
|
||||
services.execute(name, input, context.mcpReq.signal),
|
||||
),
|
||||
contract,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -32,6 +32,8 @@ const registerOfficialTool = (
|
||||
{
|
||||
description: contract.description,
|
||||
inputSchema: contract.inputSchema,
|
||||
outputSchema: contract.outputSchema,
|
||||
annotations: contract.annotations,
|
||||
},
|
||||
async (input, context) => {
|
||||
const arguments_ = projectOfficialArguments(contract, input);
|
||||
@@ -40,7 +42,7 @@ const registerOfficialTool = (
|
||||
signal: context.mcpReq.signal,
|
||||
}),
|
||||
);
|
||||
return toCallToolResult(result);
|
||||
return toCallToolResult(result, contract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
@@ -19,6 +19,8 @@ export const registerSessionTools = (
|
||||
{
|
||||
description: openContract.description,
|
||||
inputSchema: openContract.inputSchema,
|
||||
outputSchema: openContract.outputSchema,
|
||||
annotations: openContract.annotations,
|
||||
},
|
||||
async (input, context) => {
|
||||
const parsed = z.object({ path: z.string().min(1) }).parse(input);
|
||||
@@ -26,16 +28,19 @@ export const registerSessionTools = (
|
||||
session.open(parsed.path, { signal: context.mcpReq.signal }),
|
||||
);
|
||||
return opened.ok
|
||||
? toCallToolResult({
|
||||
ok: true,
|
||||
value: {
|
||||
path: opened.value.path,
|
||||
format: opened.value.format,
|
||||
kind: opened.value.kind,
|
||||
loaderArgs: [...opened.value.loaderArgs],
|
||||
? toCallToolResult(
|
||||
{
|
||||
ok: true,
|
||||
value: {
|
||||
path: opened.value.path,
|
||||
format: opened.value.format,
|
||||
kind: opened.value.kind,
|
||||
loaderArgs: [...opened.value.loaderArgs],
|
||||
},
|
||||
},
|
||||
})
|
||||
: toCallToolResult(opened);
|
||||
openContract,
|
||||
)
|
||||
: toCallToolResult(opened, openContract);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
@@ -43,12 +48,15 @@ export const registerSessionTools = (
|
||||
{
|
||||
description: closeContract.description,
|
||||
inputSchema: closeContract.inputSchema,
|
||||
outputSchema: closeContract.outputSchema,
|
||||
annotations: closeContract.annotations,
|
||||
},
|
||||
async () =>
|
||||
toCallToolResult(
|
||||
await logToolExecution(logger, closeContract.name, () =>
|
||||
session.close(),
|
||||
),
|
||||
closeContract,
|
||||
),
|
||||
);
|
||||
server.registerTool(
|
||||
@@ -56,7 +64,10 @@ export const registerSessionTools = (
|
||||
{
|
||||
description: statusContract.description,
|
||||
inputSchema: statusContract.inputSchema,
|
||||
outputSchema: statusContract.outputSchema,
|
||||
annotations: statusContract.annotations,
|
||||
},
|
||||
() => toCallToolResult({ ok: true, value: session.status() }),
|
||||
() =>
|
||||
toCallToolResult({ ok: true, value: session.status() }, statusContract),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import type { HopperError } from "../domain/errors.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { JsonValue } from "../hopper/protocol.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
|
||||
/**
|
||||
* Translate an application result into MCP text content.
|
||||
@@ -11,9 +12,10 @@ import type { JsonValue } from "../hopper/protocol.js";
|
||||
*/
|
||||
export const toCallToolResult = (
|
||||
result: Result<JsonValue, HopperError>,
|
||||
contract: ToolContract,
|
||||
): CallToolResult =>
|
||||
result.ok
|
||||
? { content: [{ type: "text", text: formatValue(result.value) }] }
|
||||
? successResult(result.value, contract)
|
||||
: {
|
||||
content: [
|
||||
{
|
||||
@@ -24,6 +26,33 @@ export const toCallToolResult = (
|
||||
isError: true,
|
||||
};
|
||||
|
||||
const successResult = (
|
||||
value: JsonValue,
|
||||
contract: ToolContract,
|
||||
): CallToolResult => {
|
||||
const candidate = ["list_procedures", "list_names", "list_strings"].includes(
|
||||
contract.name,
|
||||
)
|
||||
? value
|
||||
: { result: 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",
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
content: [{ type: "text", text: formatValue(value) }],
|
||||
structuredContent: candidate,
|
||||
};
|
||||
};
|
||||
|
||||
const formatValue = (value: JsonValue): string => {
|
||||
if (value === null) return "OK";
|
||||
if (typeof value === "string") return value;
|
||||
|
||||
Reference in New Issue
Block a user