refactor(mcp): make analysis states unrepresentable (#468)

* refactor(config): parse capability settings into exact states

* refactor(runtime): encode replay and process outcomes exactly

* refactor: make analysis states unrepresentable

* refactor(mcp): register canonical schemas with SDK

* fix: preserve capability and catalog invariants

* fix(build): remove stale compiled modules

* fix(replay): update real verifier policy dependency

* fix(package): verify the complete MCP catalog

* fix(test): supply complete replay reload policy

* refactor(contracts): centralize output schema lookup

* refactor(mcp): delegate protocol boundaries to SDK

* fix(browser): approve real source capture

* fix(mcp): preserve catalog guidance
This commit is contained in:
morluto
2026-08-10 02:28:11 +08:00
committed by GitHub
parent 6901edc05d
commit b8a9da0c0f
271 changed files with 5970 additions and 5699 deletions
+222 -285
View File
@@ -1,36 +1,33 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { z } from "zod";
import type {
CallToolResult,
McpServer,
ServerContext,
} from "@modelcontextprotocol/server";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import {
EnhancedTools,
type ValidatedEnhancedCall,
} from "../application/EnhancedTools.js";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import {
enhancedInputSchemas,
enhancedToolNameSchema,
} from "../contracts/enhancedInputs.js";
import {
ENHANCED_TOOL_CONTRACTS,
type ToolContract,
} from "../contracts/toolContracts.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";
import type { JsonValue } from "../domain/jsonValue.js";
import { AnalysisInputError, UnknownRegistryError } from "../domain/errors.js";
import { ok, type Result } from "../domain/result.js";
import { mcpProgressReporter } from "./mcpProgress.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
} from "../application/InvestigationProviders.js";
import {
ENHANCED_TOOL_CONTRACTS,
type ToolContract,
} from "../contracts/toolContracts.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { UnknownRegistryError } from "../domain/errors.js";
import { createEvidence } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Logger } from "../logger.js";
import { mcpProgressReporter } from "./mcpProgress.js";
import { logToolExecution } from "./toolLogging.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { safeParseToolInput } from "./toolInputValidation.js";
import { toCallToolResult } from "./toolResult.js";
/** Optional session services used by enhanced tool registration. */
export interface EnhancedToolRegistration {
@@ -44,107 +41,219 @@ export interface EnhancedToolRegistration {
}
/** Register composed workflows against the same port as direct bridge tools. */
// oxlint-disable-next-line max-lines-per-function -- direct SDK calls retain each schema-handler type correlation.
export const registerEnhancedTools = (
server: McpServer,
analysis: AnalysisOperationPort,
options: EnhancedToolRegistration,
): void => {
for (const contract of ENHANCED_TOOL_CONTRACTS) {
registerEnhancedTool(server, analysis, contract, {
logger: options.logger,
activeTarget: options.activeTarget,
analysisProfile: options.analysisProfile,
recordEvidence: options.recordEvidence,
recordUnknown: options.recordUnknown,
});
}
const [
swiftClasses,
objcClasses,
objcProtocols,
batchDecompile,
callGraph,
swiftTypes,
xrefsToName,
binaryOverview,
analyzeFunction,
inspectNativeApi,
traceFeature,
codeForString,
traceCallPath,
] = ENHANCED_TOOL_CONTRACTS;
server.registerTool(
swiftClasses.name,
toolRegistrationOptions(swiftClasses),
(input, context) =>
executeEnhancedTool(analysis, options, swiftClasses, {
validatedCall: { name: "swift_classes", input },
context,
}),
);
server.registerTool(
objcClasses.name,
toolRegistrationOptions(objcClasses),
(input, context) =>
executeEnhancedTool(analysis, options, objcClasses, {
validatedCall: { name: "get_objc_classes", input },
context,
}),
);
server.registerTool(
objcProtocols.name,
toolRegistrationOptions(objcProtocols),
(input, context) =>
executeEnhancedTool(analysis, options, objcProtocols, {
validatedCall: { name: "get_objc_protocols", input },
context,
}),
);
server.registerTool(
batchDecompile.name,
toolRegistrationOptions(batchDecompile),
(input, context) =>
executeEnhancedTool(analysis, options, batchDecompile, {
validatedCall: { name: "batch_decompile", input },
context,
}),
);
server.registerTool(
callGraph.name,
toolRegistrationOptions(callGraph),
(input, context) =>
executeEnhancedTool(analysis, options, callGraph, {
validatedCall: { name: "get_call_graph", input },
context,
}),
);
server.registerTool(
swiftTypes.name,
toolRegistrationOptions(swiftTypes),
(input, context) =>
executeEnhancedTool(analysis, options, swiftTypes, {
validatedCall: { name: "analyze_swift_types", input },
context,
}),
);
server.registerTool(
xrefsToName.name,
toolRegistrationOptions(xrefsToName),
(input, context) =>
executeEnhancedTool(analysis, options, xrefsToName, {
validatedCall: { name: "find_xrefs_to_name", input },
context,
}),
);
server.registerTool(
binaryOverview.name,
toolRegistrationOptions(binaryOverview),
(input, context) =>
executeEnhancedTool(analysis, options, binaryOverview, {
validatedCall: { name: "binary_overview", input },
context,
}),
);
server.registerTool(
analyzeFunction.name,
toolRegistrationOptions(analyzeFunction),
(input, context) =>
executeEnhancedTool(analysis, options, analyzeFunction, {
validatedCall: { name: "analyze_function", input },
context,
}),
);
server.registerTool(
inspectNativeApi.name,
toolRegistrationOptions(inspectNativeApi),
(input, context) =>
executeEnhancedTool(analysis, options, inspectNativeApi, {
validatedCall: { name: "inspect_native_api", input },
context,
}),
);
server.registerTool(
traceFeature.name,
toolRegistrationOptions(traceFeature),
(input, context) =>
executeEnhancedTool(analysis, options, traceFeature, {
validatedCall: { name: "trace_feature", input },
context,
}),
);
server.registerTool(
codeForString.name,
toolRegistrationOptions(codeForString),
(input, context) =>
executeEnhancedTool(analysis, options, codeForString, {
validatedCall: { name: "find_code_for_string", input },
context,
}),
);
server.registerTool(
traceCallPath.name,
toolRegistrationOptions(traceCallPath),
(input, context) =>
executeEnhancedTool(analysis, options, traceCallPath, {
validatedCall: { name: "trace_call_path", input },
context,
}),
);
};
const registerEnhancedTool = (
server: McpServer,
const executeEnhancedTool = async (
analysis: AnalysisOperationPort,
registration: EnhancedToolRegistration,
contract: ToolContract,
registration: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly analysisProfile:
| (() => AnalysisProfileCommitment | undefined)
| undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
readonly recordUnknown: BinarySessionPort["recordUnknown"] | undefined;
request: {
readonly validatedCall: ValidatedEnhancedCall;
readonly context: ServerContext;
},
): void => {
const name = enhancedToolNameSchema.parse(contract.name);
server.registerTool(
name,
toolRegistrationOptions(contract),
async (input, context) => {
const progress = mcpProgressReporter(context);
await progress.report({
phase: name,
completed: 0,
total: 1,
message: "started",
});
const validatedCall = parseEnhancedCall(name, input);
if (!validatedCall.ok) return toCallToolResult(validatedCall, contract);
const parsedInput = validatedCall.value.input;
const parameters = jsonParameters(parsedInput);
const services = new EnhancedTools({
execute: (operation, operationParameters, executionOptions) =>
analysis.execute(operation, operationParameters, {
...executionOptions,
progress,
}),
});
const result = await logToolExecution(registration.logger, name, () =>
services.executeValidated(validatedCall.value, context.mcpReq.signal),
);
await progress.report({
phase: name,
completed: 1,
total: 1,
message: result.ok ? "completed" : "failed",
terminal: true,
});
if (result.ok) {
const upstreamProfile = registration.analysisProfile?.();
const evidence = createEvidence(
registration.activeTarget?.(),
REA_WORKFLOW_PROVIDER,
{
operation: name,
parameters,
result: result.value,
...(upstreamProfile === undefined
? {}
: {
analysisProfile: workflowAnalysisProfile(upstreamProfile),
}),
confidence: "derived",
limitations: [
"Derived by an REA workflow from one or more provider observations.",
],
},
);
const recorded = registration.recordEvidence?.(evidence);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, contract);
const unknowns = recordWorkflowUnknowns({
name,
input: parameters,
result: result.value,
evidenceId: evidence.evidence_id,
recordUnknown: registration.recordUnknown,
});
if (!unknowns.ok) return toCallToolResult(unknowns, contract);
return toCallToolResult({ ok: true, value: evidence }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
}
return toCallToolResult(result, contract);
},
): Promise<CallToolResult> => {
const { validatedCall, context } = request;
const name = validatedCall.name;
const progress = mcpProgressReporter(context);
await progress.report({
phase: name,
completed: 0,
total: 1,
message: "started",
});
const parsedInput = validatedCall.input;
const parameters = jsonParameters(parsedInput);
const services = new EnhancedTools({
execute: (operation, operationParameters, executionOptions) =>
analysis.execute(operation, operationParameters, {
...executionOptions,
progress,
}),
});
const result = await logToolExecution(registration.logger, name, () =>
services.executeValidated(validatedCall, context.mcpReq.signal),
);
await progress.report({
phase: name,
completed: 1,
total: 1,
message: result.ok ? "completed" : "failed",
terminal: true,
});
if (result.ok) {
const upstreamProfile = registration.analysisProfile?.();
const evidence = createEvidence(
registration.activeTarget?.(),
REA_WORKFLOW_PROVIDER,
{
operation: name,
parameters,
result: result.value,
...(upstreamProfile === undefined
? {}
: {
analysisProfile: workflowAnalysisProfile(upstreamProfile),
}),
confidence: "derived",
limitations: [
"Derived by an REA workflow from one or more provider observations.",
],
},
);
const recorded = registration.recordEvidence?.(evidence);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, contract);
const unknowns = recordWorkflowUnknowns({
name,
input: parameters,
result: result.value,
evidenceId: evidence.evidence_id,
recordUnknown: registration.recordUnknown,
});
if (!unknowns.ok) return toCallToolResult(unknowns, contract);
return toCallToolResult({ ok: true, value: evidence }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
}
return toCallToolResult(result, contract);
};
const jsonParameters = (
@@ -156,178 +265,6 @@ const jsonParameters = (
),
);
type EnhancedToolName = ValidatedEnhancedCall["name"];
type EnhancedInputOf<Name extends EnhancedToolName> = z.output<
(typeof enhancedInputSchemas)[Name]
>;
type EnhancedInputParser<Name extends EnhancedToolName> = (
input: unknown,
) => Result<EnhancedInputOf<Name>, AnalysisInputError>;
const ENHANCED_INPUT_PARSERS: {
[Name in EnhancedToolName]: EnhancedInputParser<Name>;
} = {
swift_classes: (input) =>
safeParseToolInput(
enhancedInputSchemas.swift_classes,
input,
"swift_classes",
),
get_objc_classes: (input) =>
safeParseToolInput(
enhancedInputSchemas.get_objc_classes,
input,
"get_objc_classes",
),
get_objc_protocols: (input) =>
safeParseToolInput(
enhancedInputSchemas.get_objc_protocols,
input,
"get_objc_protocols",
),
batch_decompile: (input) =>
safeParseToolInput(
enhancedInputSchemas.batch_decompile,
input,
"batch_decompile",
),
get_call_graph: (input) =>
safeParseToolInput(
enhancedInputSchemas.get_call_graph,
input,
"get_call_graph",
),
analyze_swift_types: (input) =>
safeParseToolInput(
enhancedInputSchemas.analyze_swift_types,
input,
"analyze_swift_types",
),
find_xrefs_to_name: (input) =>
safeParseToolInput(
enhancedInputSchemas.find_xrefs_to_name,
input,
"find_xrefs_to_name",
),
binary_overview: (input) =>
safeParseToolInput(
enhancedInputSchemas.binary_overview,
input,
"binary_overview",
),
analyze_function: (input) =>
safeParseToolInput(
enhancedInputSchemas.analyze_function,
input,
"analyze_function",
),
inspect_native_api: (input) =>
safeParseToolInput(
enhancedInputSchemas.inspect_native_api,
input,
"inspect_native_api",
),
trace_feature: (input) =>
safeParseToolInput(
enhancedInputSchemas.trace_feature,
input,
"trace_feature",
),
find_code_for_string: (input) =>
safeParseToolInput(
enhancedInputSchemas.find_code_for_string,
input,
"find_code_for_string",
),
trace_call_path: (input) =>
safeParseToolInput(
enhancedInputSchemas.trace_call_path,
input,
"trace_call_path",
),
};
const parseEnhancedCall = (
name: ValidatedEnhancedCall["name"],
input: unknown,
): Result<ValidatedEnhancedCall, AnalysisInputError> => {
switch (name) {
case "swift_classes":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.swift_classes(input),
(value) => ({ name, input: value }),
);
case "get_objc_classes":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.get_objc_classes(input),
(value) => ({ name, input: value }),
);
case "get_objc_protocols":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.get_objc_protocols(input),
(value) => ({ name, input: value }),
);
case "batch_decompile":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.batch_decompile(input),
(value) => ({ name, input: value }),
);
case "get_call_graph":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.get_call_graph(input),
(value) => ({ name, input: value }),
);
case "analyze_swift_types":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.analyze_swift_types(input),
(value) => ({ name, input: value }),
);
case "find_xrefs_to_name":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.find_xrefs_to_name(input),
(value) => ({ name, input: value }),
);
case "binary_overview":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.binary_overview(input),
(value) => ({ name, input: value }),
);
case "analyze_function":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.analyze_function(input),
(value) => ({ name, input: value }),
);
case "inspect_native_api":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.inspect_native_api(input),
(value) => ({ name, input: value }),
);
case "trace_feature":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.trace_feature(input),
(value) => ({ name, input: value }),
);
case "find_code_for_string":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.find_code_for_string(input),
(value) => ({ name, input: value }),
);
case "trace_call_path":
return mapEnhancedCall(
ENHANCED_INPUT_PARSERS.trace_call_path(input),
(value) => ({ name, input: value }),
);
}
};
const mapEnhancedCall = <Input, Call extends ValidatedEnhancedCall>(
parsed: Result<Input, AnalysisInputError>,
project: (input: Input) => Call,
): Result<Call, AnalysisInputError> =>
parsed.ok ? ok(project(parsed.value)) : parsed;
interface WorkflowUnknownInput {
readonly name: string;
readonly input: Readonly<Record<string, JsonValue>>;