mirror of
https://github.com/morluto/rea.git
synced 2026-11-07 07:16:13 +00:00
fix(reverse): reconcile cleanup ownership and mutation diagnostics (#2799)
* feat(process): add owned debugger shutdown lifecycle * feat(reverse): add local inspection commands * feat(gdb): add persistent debugger integration * feat(cutter): add Cutter bridge integration * test(reverse): enforce complete integration coverage * fix(process): preserve debugger shutdown ownership * fix(reverse): retain evidence across interrupted commands * fix(gdb): honor captured provider environment * test(process): cover debugger shutdown retries * fix(reverse): retain evidence for interrupted providers * test(process): cover debugger shutdown retries * fix(reverse): retain evidence for interrupted providers * fix(server): snapshot provider environment at creation * fix(reverse): close review gaps with complete coverage * fix(reverse): address inspection review findings * fix(gdb): bound sessions and retain cleanup ownership * fix(ci): require reverse-tools quality lane * fix(process): unref inherited debugger output pipes * fix(reverse): address remaining PR 1960 findings * fix(gdb): address remaining PR 1961 findings * fix(reverse): account for unrestricted provider execution * fix(process): retain debugger ownership until safe shutdown * fix(process): preserve replacement debugger sessions * fix(reverse): preserve admission and output provenance * fix(process): retain exited debugger until output settles * fix(mcp): bound provider admission and debugger cleanup * fix(reverse): preserve failure provenance and classify E2BIG * fix(gdb): preserve startup cleanup and detach safety * fix(process): retain debugger ownership after detach failure * fix(reverse): preserve mutation and failure provenance * fix(gdb): address debugger review findings * fix(reverse): rebind sessions after external mutation * fix(process): cap debugger output after exit * fix(gdb): protect one-shot detach verification * feat(debugger): add reverse tool coverage gate * test(debugger): cover integrated failure paths * fix(gdb): bound and preserve session observations * fix(gdb): address review regressions * style: format merged integration files * fix(reverse): preserve session and output evidence * refactor(gdb): share repeated test and partial result setup * fix(gdb): invalidate TTY proof for Python aliases * fix(reverse): retain failure output byte counts * test(process): synchronize late debugger output * fix(gdb): invalidate TTY proof for wrapped commands * fix(gdb): recognize wit command abbreviation * test(reverse): wait for cancelled descendant readiness * test(reverse): bound descendant cancellation cleanup * style(reverse): format integration tests and adapters * style: format reverse engineering integration files * test(reverse): remove duplicate environment harness * test(gdb): share session startup assertions * fix(gdb): invalidate output proof for command abbreviations * test(reverse): share composition edge case scenarios * fix(ci): recognize verification and mutation tool entries * test(rizin): cover successful fake inferior detach * test(cli): align full output failure envelope * test(cli): isolate reverse command lifecycle service * test(process): share debugger output fixture setup * fix(binary): preserve high-bit Windows signature bytes * style(binary): format Windows signature parser * test(mcp): preserve call coverage in unchanged comparison * fix(ci): include reverse tools Vitest configs in lint cache * fix(mcp): preserve target content on delivery errors * ci: align duplication ceiling with expanded suite * test(reverse): allow signal admission mutants * fix(reverse): bound retained cleanup failures to process owners * fix(test): replace drifting mutation ranges with owned selectors * fix(reverse): admit persistent commands and retain cleanup ownership * fix(cutter): recover timed-out commands from exact receipts * fix(cutter): reject unsupported bridge request kinds * fix(ci): repair client format and shared verification fixtures * fix(native): preserve debugger cleanup ownership and bridge authentication * test(native): retain diagnostics without perfect coverage requirements * chore(licenses): refresh locked dependency inventory and notices * fix(test): exclude transient command locks from mutation sandboxes * fix(gdb): admit only platforms with safe detach verification * fix(cutter): retain bounded completion receipts until acknowledgement * fix(cutter): acknowledge commands rejected before UI dispatch * test(reverse): fail cancellation checks before fixture teardown * test(gdb): clean up the retained broken-stdin fixture owner * docs(test): clarify focused provider verification scope * fix(rizin): retain close cleanup failures * fix(gdb): wait for inferior stop and bound MI buffering * fix(cutter): retain failed receipt acknowledgements * fix(rizin): return retained session identity on rebind failure * fix(gdb): preserve startup cancellation and lossy status * fix(rizin): retain launch provenance and assemble frames once * fix(cutter): recover receipts across callers and bound discovery * docs: describe debugger evidence and bridge recovery * fix(process): keep cleanup incomplete while writers remain Stopping a debugger no longer reports success when inherited output streams stay open, so BinarySession cannot reopen a binary a child is still changing. Concurrent Cutter cleanup retries share one receipt acknowledgement instead of treating a consumed receipt as failure. * fix(debuggers): recover cleanup with captured process identities * fix(analysis): retire sessions after unrestricted commands * fix(cli): preserve completed evidence after cleanup recovery * fix(cutter): bound frame collection and coalesce cleanup * fix(windows): resolve selected provider paths absolutely * fix(gdb): report decoding loss in failed startup evidence * fix(rizin): scope decoding loss to collected command frames * test(mcp): cover snapshot retirement in reverse tools CI --------- Co-authored-by: Daniel Gonçalves Araujo <47118053+dandgabr@users.noreply.github.com> Co-authored-by: REA Maintainers <noreply@github.com> Co-authored-by: OpenAI Codex <codex@users.noreply.github.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
168 files changed
+32703
-238
No files matched your search
@@ -8,6 +8,7 @@ import type { WasmArtifactService } from "../application/wasm/WasmArtifactServic
|
||||
import { wasmArtifactModule } from "../composition/wasm.js";
|
||||
import { registerWasmTools } from "./registerWasmTools.js";
|
||||
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
|
||||
import { captureProviderEnvironment } from "./providerEnvironment.js";
|
||||
import { createPeResourcesService } from "../composition/binaryDiagnostics.js";
|
||||
import type { PeResourcesService } from "../application/binaryDiagnostics/PeResourcesService.js";
|
||||
import { registerPeResourcesTool } from "./registerPeResourcesTool.js";
|
||||
@@ -122,6 +123,15 @@ import {
|
||||
type ServerAnalysisSource,
|
||||
} from "./analysisAdmission.js";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { createReverseEngineeringService } from "../composition/reverseEngineering.js";
|
||||
import { registerReverseEngineeringTools } from "./registerReverseEngineeringTools.js";
|
||||
import { CutterBridgeClient } from "../cutter/CutterBridgeClient.js";
|
||||
import { CutterBridgeService } from "../cutter/CutterBridgeService.js";
|
||||
import { registerCutterTools } from "./registerCutterTools.js";
|
||||
import { GdbSessionManager } from "../gdb/GdbSessionManager.js";
|
||||
import { registerGdbTools } from "./registerGdbTools.js";
|
||||
import { RizinDebugSessionManager } from "../rizin/RizinDebugSessionManager.js";
|
||||
import { registerRizinDebugTools } from "./registerRizinDebugTools.js";
|
||||
|
||||
const TARGET_FREE_INSTRUCTIONS =
|
||||
"REA provides reverse-engineering tools for local artifacts, native binaries, managed code, browser pages, and runtimes. Use the tool that directly answers the question; discover targets or inspect inventory only when needed. Tool results include inline Evidence and report their coverage and limitations.";
|
||||
@@ -139,6 +149,7 @@ export interface CreateServerOptions {
|
||||
readonly packetCapture?: PacketCaptureService;
|
||||
readonly signalRecording?: SignalRecordingService;
|
||||
readonly wasmArtifact?: WasmArtifactService;
|
||||
readonly providerEnvironment?: Readonly<NodeJS.ProcessEnv>;
|
||||
readonly evmInterface?: EvmInterfaceService;
|
||||
readonly sqliteDatabase?: SqliteDatabaseService;
|
||||
readonly logger?: Logger;
|
||||
@@ -272,6 +283,10 @@ export const createServer = (
|
||||
const session = source.kind === "session" ? source.session : undefined;
|
||||
const analysis = source.kind === "session" ? source.session : source.analysis;
|
||||
const environment = snapshotEnvironment(options.environment ?? process.env);
|
||||
const providerEnvironment = captureProviderEnvironment(
|
||||
options.providerEnvironment,
|
||||
environment,
|
||||
);
|
||||
const delivery = selectToolResultDelivery(environment, options.delivery);
|
||||
const evmInterface =
|
||||
options.evmInterface ?? evmInterfaceModule.create(environment);
|
||||
@@ -292,6 +307,8 @@ export const createServer = (
|
||||
const javascriptRecovery =
|
||||
options.javascriptRecovery ?? createJavaScriptRecoveryProvider(environment);
|
||||
const artifactResources = new ArtifactResourceScope();
|
||||
const reverseEngineering =
|
||||
createReverseEngineeringService(providerEnvironment);
|
||||
const firmwareAnalysis = new FirmwareAnalysisService(
|
||||
options.firmwareAnalysis ?? createFirmwareAnalysisProvider(environment),
|
||||
);
|
||||
@@ -314,6 +331,10 @@ export const createServer = (
|
||||
delivery,
|
||||
selectCompactInputSchemaPresentation(environment),
|
||||
);
|
||||
const gdbSessions = new GdbSessionManager({
|
||||
environment: providerEnvironment,
|
||||
});
|
||||
const rizinDebugSessions = new RizinDebugSessionManager(providerEnvironment);
|
||||
const android =
|
||||
options.androidAnalysis ?? createAndroidAnalysisProvider(environment);
|
||||
const pcap = options.pcapAnalysis ?? createPcapAnalysisProvider(environment);
|
||||
@@ -359,7 +380,10 @@ export const createServer = (
|
||||
webNetworkCapture.close(),
|
||||
javascriptRecovery.close?.() ?? Promise.resolve(),
|
||||
artifactResources.close(),
|
||||
reverseEngineering.close(),
|
||||
firmwareAnalysis.close(),
|
||||
gdbSessions.closeAll(),
|
||||
rizinDebugSessions.closeAll(),
|
||||
])
|
||||
.then((results) => {
|
||||
const failures = results.flatMap((result) =>
|
||||
@@ -405,6 +429,28 @@ export const createServer = (
|
||||
webNetworkCapture,
|
||||
};
|
||||
registerBinaryAnalysisTools(toolContext);
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
reverseEngineering,
|
||||
toolLogger,
|
||||
delivery,
|
||||
session === undefined
|
||||
? undefined
|
||||
: (evidence) => session.recordEvidence(evidence),
|
||||
analysisAdmission,
|
||||
session === undefined
|
||||
? undefined
|
||||
: () => session.invalidateSnapshotForExternalMutation(),
|
||||
session === undefined
|
||||
? undefined
|
||||
: (path, signal, operation, rebindFailure) =>
|
||||
session.withAdmittedExternalMutation(
|
||||
path,
|
||||
signal,
|
||||
operation,
|
||||
rebindFailure,
|
||||
),
|
||||
);
|
||||
registerFridaTools(
|
||||
server,
|
||||
fridaInstrumentation,
|
||||
@@ -412,7 +458,37 @@ export const createServer = (
|
||||
delivery,
|
||||
session === undefined
|
||||
? undefined
|
||||
: (input) => session.recordEvidence(input),
|
||||
: (evidence) => session.recordEvidence(evidence),
|
||||
);
|
||||
registerCutterTools(
|
||||
server,
|
||||
new CutterBridgeService(new CutterBridgeClient(providerEnvironment)),
|
||||
toolLogger,
|
||||
delivery,
|
||||
session === undefined
|
||||
? undefined
|
||||
: (evidence) => session.recordEvidence(evidence),
|
||||
session,
|
||||
);
|
||||
registerGdbTools(
|
||||
server,
|
||||
gdbSessions,
|
||||
toolLogger,
|
||||
delivery,
|
||||
session === undefined
|
||||
? undefined
|
||||
: (evidence) => session.recordEvidence(evidence),
|
||||
session,
|
||||
);
|
||||
registerRizinDebugTools(
|
||||
server,
|
||||
rizinDebugSessions,
|
||||
toolLogger,
|
||||
delivery,
|
||||
session === undefined
|
||||
? undefined
|
||||
: (evidence) => session.recordEvidence(evidence),
|
||||
session,
|
||||
);
|
||||
const previousOnclose = server.server.onclose;
|
||||
server.server.onclose = () => {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
|
||||
export type ExternalMutationAdmission = Pick<
|
||||
BinarySessionPort,
|
||||
"withAdmittedExternalMutation"
|
||||
>;
|
||||
|
||||
/** Shared MCP admission and failure preservation for unrestricted commands. */
|
||||
export const runWithExternalMutationAdmission = async <Value>(
|
||||
session: ExternalMutationAdmission | undefined,
|
||||
operationName: string,
|
||||
signal: AbortSignal | undefined,
|
||||
operation: () => Promise<Result<Value, AnalysisError>>,
|
||||
evidenceOf: ((value: Value) => Evidence) | undefined,
|
||||
cleanupRecovery?: (
|
||||
failure: AnalysisError | undefined,
|
||||
) => Promise<Result<null, AnalysisError>>,
|
||||
retainedDetails?: (value: Value) => Readonly<Record<string, string>>,
|
||||
): Promise<Result<Value, AnalysisError>> => {
|
||||
if (session === undefined) {
|
||||
const recovered = await cleanupRecovery?.(undefined);
|
||||
if (recovered !== undefined && !recovered.ok) return recovered;
|
||||
return operation();
|
||||
}
|
||||
const admitted = await session.withAdmittedExternalMutation(
|
||||
undefined,
|
||||
signal,
|
||||
operation,
|
||||
(value, cause) =>
|
||||
value.ok
|
||||
? new AnalysisOutputError(
|
||||
operationName,
|
||||
"The external command may have changed the bound artifact, but the active analysis session could not be retired.",
|
||||
{
|
||||
cause,
|
||||
...(evidenceOf === undefined
|
||||
? {}
|
||||
: { partialObservation: evidenceOf(value.value) }),
|
||||
...(cause.cleanup === undefined
|
||||
? {}
|
||||
: { cleanup: cause.cleanup }),
|
||||
...(cause.capturedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: cause.capturedOutput }),
|
||||
...(retainedDetails === undefined
|
||||
? {}
|
||||
: { diagnostics: retainedDetails(value.value) }),
|
||||
},
|
||||
)
|
||||
: value.error.retainSecondaryFailure(cause, {
|
||||
retirement_error: projectAnalysisError(cause),
|
||||
}),
|
||||
operationName,
|
||||
cleanupRecovery,
|
||||
);
|
||||
return admitted.ok ? admitted.value : err(admitted.error);
|
||||
};
|
||||
|
||||
/** Admit an owned close once, including when it is recovering its own blocker. */
|
||||
export const runOwnedCleanupWithExternalMutationAdmission = async <Value>(
|
||||
session: ExternalMutationAdmission | undefined,
|
||||
operationName: string,
|
||||
signal: AbortSignal | undefined,
|
||||
resourceId: string,
|
||||
cleanup: () => Promise<Result<Value, AnalysisError>>,
|
||||
): Promise<Result<Value, AnalysisError>> => {
|
||||
let completed: Result<Value, AnalysisError> | undefined;
|
||||
const cleanupOnce = async (): Promise<Result<Value, AnalysisError>> => {
|
||||
completed ??= await cleanup();
|
||||
return completed;
|
||||
};
|
||||
const admitted = await runWithExternalMutationAdmission(
|
||||
session,
|
||||
operationName,
|
||||
signal,
|
||||
cleanupOnce,
|
||||
undefined,
|
||||
async (failure) => {
|
||||
if (
|
||||
failure === undefined ||
|
||||
!failure.cleanup?.resources.includes(resourceId)
|
||||
)
|
||||
return failure === undefined
|
||||
? { ok: true, value: null }
|
||||
: { ok: false, error: failure };
|
||||
const recovered = await cleanupOnce();
|
||||
return recovered.ok ? { ok: true, value: null } : recovered;
|
||||
},
|
||||
);
|
||||
return admitted;
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
|
||||
|
||||
/** Capture the selected provider environment at server construction time. */
|
||||
export const captureProviderEnvironment = (
|
||||
providerEnvironment: Readonly<NodeJS.ProcessEnv> | undefined,
|
||||
serverEnvironment: Readonly<NodeJS.ProcessEnv>,
|
||||
): Readonly<NodeJS.ProcessEnv> =>
|
||||
snapshotEnvironment(providerEnvironment ?? serverEnvironment);
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { CutterBridgeService } from "../cutter/CutterBridgeService.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import {
|
||||
runWithExternalMutationAdmission,
|
||||
type ExternalMutationAdmission,
|
||||
} from "./externalMutationAdmission.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import type { ToolResultDelivery } from "./toolResult.js";
|
||||
|
||||
/** Register Cutter discovery and command tools against their named contracts. */
|
||||
export const registerCutterTools = (
|
||||
server: McpServer,
|
||||
service: CutterBridgeService,
|
||||
logger: Logger,
|
||||
delivery: ToolResultDelivery,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
session?: ExternalMutationAdmission,
|
||||
): void => {
|
||||
const list = toolContract("list_cutter_sessions");
|
||||
const command = toolContract("cutter_command");
|
||||
server.registerTool(list.name, toolRegistrationOptions(list), async () => {
|
||||
const result = await logToolExecution(logger, list.name, async () =>
|
||||
ok(await service.listSessions()),
|
||||
);
|
||||
if (!result.ok) return delivery.toCallToolResult(result, list);
|
||||
return delivery.toCallToolResult(
|
||||
{
|
||||
ok: true,
|
||||
value: { ...result.value, sessions: [...result.value.sessions] },
|
||||
},
|
||||
list,
|
||||
);
|
||||
});
|
||||
server.registerTool(
|
||||
command.name,
|
||||
toolRegistrationOptions(command),
|
||||
async (input, context) => {
|
||||
const result = await runWithExternalMutationAdmission(
|
||||
session,
|
||||
command.name,
|
||||
context.mcpReq.signal,
|
||||
() =>
|
||||
logToolExecution(logger, command.name, () =>
|
||||
service.execute(input, { signal: context.mcpReq.signal }),
|
||||
),
|
||||
(value) => value,
|
||||
() => service.retryCleanup(),
|
||||
);
|
||||
if (!result.ok) {
|
||||
const partial = evidenceSchema.safeParse(
|
||||
result.error.partialObservation,
|
||||
);
|
||||
if (partial.success) {
|
||||
const recorded = recordEvidence?.(partial.data);
|
||||
if (recorded !== undefined)
|
||||
return delivery.toRecordedPartialErrorToolResult(
|
||||
result.error,
|
||||
partial.data.evidence_id,
|
||||
recorded,
|
||||
command.returnsTargetContent,
|
||||
);
|
||||
}
|
||||
return delivery.toCallToolResult(result, command);
|
||||
}
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value,
|
||||
command,
|
||||
recordEvidence?.(result.value),
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,156 @@
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { GdbSessionManager } from "../gdb/GdbSessionManager.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
runOwnedCleanupWithExternalMutationAdmission,
|
||||
runWithExternalMutationAdmission,
|
||||
type ExternalMutationAdmission,
|
||||
} from "./externalMutationAdmission.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import type { ToolResultDelivery } from "./toolResult.js";
|
||||
|
||||
export type GdbToolManager = Pick<
|
||||
GdbSessionManager,
|
||||
"start" | "execute" | "status" | "close" | "retryCleanupFailures"
|
||||
>;
|
||||
|
||||
/** Register persistent GDB session operations on the existing REA MCP server. */
|
||||
export const registerGdbTools = (
|
||||
server: McpServer,
|
||||
manager: GdbToolManager,
|
||||
logger: Logger,
|
||||
delivery: ToolResultDelivery,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
session?: ExternalMutationAdmission,
|
||||
): void => {
|
||||
const start = toolContract("start_gdb_session");
|
||||
const consoleContract = toolContract("gdb_console");
|
||||
const status = toolContract("gdb_session_status");
|
||||
const close = toolContract("close_gdb_session");
|
||||
server.registerTool(
|
||||
start.name,
|
||||
toolRegistrationOptions(start),
|
||||
async (input, context: ServerContext) => {
|
||||
const result = await logToolExecution(logger, start.name, () =>
|
||||
manager.start(
|
||||
context.mcpReq.signal,
|
||||
input.inferior_tty === undefined
|
||||
? {}
|
||||
: { inferiorTty: input.inferior_tty },
|
||||
),
|
||||
);
|
||||
if (result.ok)
|
||||
return delivery.toCallToolResult(
|
||||
{ ok: true, value: result.value },
|
||||
start,
|
||||
);
|
||||
const partial = result.error.partialObservation;
|
||||
const parsed = evidenceSchema.safeParse(partial);
|
||||
if (parsed.success) {
|
||||
const recorded = recordEvidence?.(parsed.data);
|
||||
if (recorded !== undefined)
|
||||
return delivery.toRecordedPartialErrorToolResult(
|
||||
result.error,
|
||||
parsed.data.evidence_id,
|
||||
recorded,
|
||||
start.returnsTargetContent,
|
||||
);
|
||||
}
|
||||
return delivery.toCallToolResult(result, start);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
consoleContract.name,
|
||||
toolRegistrationOptions(consoleContract),
|
||||
async (input, context: ServerContext) => {
|
||||
const execute = () =>
|
||||
logToolExecution(logger, consoleContract.name, () =>
|
||||
manager.execute(
|
||||
input.session_id,
|
||||
input.command,
|
||||
context.mcpReq.signal,
|
||||
),
|
||||
);
|
||||
const result = await runWithExternalMutationAdmission(
|
||||
session,
|
||||
consoleContract.name,
|
||||
context.mcpReq.signal,
|
||||
execute,
|
||||
(value) => value.evidence,
|
||||
() => manager.retryCleanupFailures(),
|
||||
);
|
||||
if (!result.ok) {
|
||||
const partial = result.error.partialObservation;
|
||||
const parsed = evidenceSchema.safeParse(partial);
|
||||
if (parsed.success) {
|
||||
const recorded = recordEvidence?.(parsed.data);
|
||||
if (recorded !== undefined)
|
||||
return delivery.toRecordedPartialErrorToolResult(
|
||||
result.error,
|
||||
parsed.data.evidence_id,
|
||||
recorded,
|
||||
consoleContract.returnsTargetContent,
|
||||
);
|
||||
}
|
||||
return delivery.toCallToolResult(result, consoleContract);
|
||||
}
|
||||
const recorded = recordEvidence?.(result.value.evidence);
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value.evidence,
|
||||
consoleContract,
|
||||
recorded,
|
||||
);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
status.name,
|
||||
toolRegistrationOptions(status),
|
||||
async (input) => {
|
||||
const result = manager.status(input.session_id);
|
||||
if (result === undefined)
|
||||
return delivery.toCallToolResult(
|
||||
err(invalidSession("gdb_session_status")),
|
||||
status,
|
||||
);
|
||||
return delivery.toCallToolResult(
|
||||
{
|
||||
ok: true,
|
||||
value: {
|
||||
...result,
|
||||
recent_mi_records: [...result.recent_mi_records],
|
||||
},
|
||||
},
|
||||
status,
|
||||
);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
close.name,
|
||||
toolRegistrationOptions(close),
|
||||
async (input, context: ServerContext) => {
|
||||
const result = await runOwnedCleanupWithExternalMutationAdmission(
|
||||
session,
|
||||
close.name,
|
||||
context.mcpReq.signal,
|
||||
input.session_id,
|
||||
() =>
|
||||
logToolExecution(logger, close.name, () =>
|
||||
manager.close(input.session_id),
|
||||
),
|
||||
);
|
||||
return result.ok
|
||||
? delivery.toCallToolResult({ ok: true, value: result.value }, close)
|
||||
: delivery.toCallToolResult(result, close);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const invalidSession = (operation: string): AnalysisInputError =>
|
||||
new AnalysisInputError(operation);
|
||||
@@ -0,0 +1,207 @@
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type {
|
||||
CallToolResult,
|
||||
McpServer,
|
||||
ServerContext,
|
||||
} from "@modelcontextprotocol/server";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { ReverseEngineeringService } from "../application/reverse/ReverseEngineeringService.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import type { ToolResultDelivery } from "./toolResult.js";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { rizinInputSchema } from "../domain/reverseEngineering.js";
|
||||
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
|
||||
/** Register objdump and Rizin operations against their exact named contracts. */
|
||||
export const registerReverseEngineeringTools = (
|
||||
server: McpServer,
|
||||
service: ReverseEngineeringService,
|
||||
logger: Logger,
|
||||
delivery: ToolResultDelivery,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
withAdmittedAnalysis?: WithAdmittedAnalysis,
|
||||
invalidateSnapshotForExternalMutation?: () => void,
|
||||
withAdmittedExternalMutation?: <Value>(
|
||||
path: string | undefined,
|
||||
signal: AbortSignal | undefined,
|
||||
operation: () => Promise<Result<Value, AnalysisError>>,
|
||||
retirementFailure: (
|
||||
value: Result<Value, AnalysisError>,
|
||||
error: AnalysisError,
|
||||
) => AnalysisError,
|
||||
) => Promise<Result<Result<Value, AnalysisError>, AnalysisError>>,
|
||||
): void => {
|
||||
const objdump = toolContract("inspect_with_objdump");
|
||||
const rizin = toolContract("execute_rizin_command");
|
||||
server.registerTool(
|
||||
objdump.name,
|
||||
toolRegistrationOptions(objdump),
|
||||
(input, context: ServerContext) =>
|
||||
runAdmitted(
|
||||
objdump,
|
||||
context,
|
||||
withAdmittedAnalysis,
|
||||
delivery,
|
||||
async () => {
|
||||
const result = await logToolExecution(logger, objdump.name, () =>
|
||||
service.inspectWithObjdump(input, {
|
||||
signal: context.mcpReq.signal,
|
||||
}),
|
||||
);
|
||||
if (!result.ok)
|
||||
return deliverFailure(
|
||||
result.error,
|
||||
objdump,
|
||||
delivery,
|
||||
recordEvidence,
|
||||
);
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value,
|
||||
objdump,
|
||||
recordEvidence?.(result.value),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
server.registerTool(
|
||||
rizin.name,
|
||||
toolRegistrationOptions(rizin),
|
||||
async (input, context: ServerContext) => {
|
||||
const parsed = rizinInputSchema.safeParse(input);
|
||||
if (parsed.success && withAdmittedExternalMutation !== undefined) {
|
||||
const cleanup = await service.retryCleanup(rizin.name);
|
||||
if (!cleanup.ok)
|
||||
return deliverFailure(cleanup.error, rizin, delivery, recordEvidence);
|
||||
const admitted = await withAdmittedExternalMutation(
|
||||
parsed.data.path,
|
||||
context.mcpReq.signal,
|
||||
async () => {
|
||||
invalidateSnapshotForExternalMutation?.();
|
||||
return logToolExecution(logger, rizin.name, () =>
|
||||
service.executeRizinCommand(parsed.data, {
|
||||
signal: context.mcpReq.signal,
|
||||
}),
|
||||
);
|
||||
},
|
||||
(value, cause) => {
|
||||
if (!value.ok)
|
||||
return value.error.retainSecondaryFailure(cause, {
|
||||
retirement_error: projectAnalysisError(cause),
|
||||
});
|
||||
const observation = value.value;
|
||||
return new AnalysisOutputError(
|
||||
rizin.name,
|
||||
"Rizin may have changed the bound artifact, but the active analysis session could not be retired.",
|
||||
{
|
||||
cause,
|
||||
...(cause.cleanup === undefined
|
||||
? {}
|
||||
: { cleanup: cause.cleanup }),
|
||||
...(cause.capturedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: cause.capturedOutput }),
|
||||
...(observation === undefined
|
||||
? {}
|
||||
: { partialObservation: observation }),
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
if (!admitted.ok)
|
||||
return deliverFailure(
|
||||
admitted.error,
|
||||
rizin,
|
||||
delivery,
|
||||
recordEvidence,
|
||||
);
|
||||
const result = admitted.value;
|
||||
if (!result.ok)
|
||||
return deliverFailure(result.error, rizin, delivery, recordEvidence);
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value,
|
||||
rizin,
|
||||
recordEvidence?.(result.value),
|
||||
);
|
||||
}
|
||||
return runAdmitted(
|
||||
rizin,
|
||||
context,
|
||||
withAdmittedAnalysis,
|
||||
delivery,
|
||||
async () => {
|
||||
if (
|
||||
invalidateSnapshotForExternalMutation !== undefined &&
|
||||
rizinInputSchema.safeParse(input).success
|
||||
)
|
||||
invalidateSnapshotForExternalMutation();
|
||||
const result = await logToolExecution(logger, rizin.name, () =>
|
||||
service.executeRizinCommand(input, {
|
||||
signal: context.mcpReq.signal,
|
||||
}),
|
||||
);
|
||||
if (!result.ok)
|
||||
return deliverFailure(
|
||||
result.error,
|
||||
rizin,
|
||||
delivery,
|
||||
recordEvidence,
|
||||
);
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value,
|
||||
rizin,
|
||||
recordEvidence?.(result.value),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const runAdmitted = async (
|
||||
contract: ToolContract,
|
||||
context: ServerContext,
|
||||
admission: WithAdmittedAnalysis | undefined,
|
||||
delivery: ToolResultDelivery,
|
||||
operation: () => Promise<CallToolResult>,
|
||||
): Promise<CallToolResult> => {
|
||||
if (admission === undefined) return operation();
|
||||
const admitted = await admission(
|
||||
contract.name,
|
||||
context.mcpReq.signal,
|
||||
async () => operation(),
|
||||
);
|
||||
return admitted.ok
|
||||
? admitted.value
|
||||
: delivery.toErrorToolResult(admitted.error, contract.returnsTargetContent);
|
||||
};
|
||||
|
||||
const deliverFailure = (
|
||||
error: import("../domain/analysisErrorBase.js").AnalysisError,
|
||||
contract: ToolContract,
|
||||
delivery: ToolResultDelivery,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
) => {
|
||||
const partial = error.partialObservation;
|
||||
if (isEvidence(partial) && recordEvidence !== undefined)
|
||||
return delivery.toRecordedPartialErrorToolResult(
|
||||
error,
|
||||
partial.evidence_id,
|
||||
recordEvidence(partial),
|
||||
contract.returnsTargetContent,
|
||||
);
|
||||
return delivery.toErrorToolResult(error, contract.returnsTargetContent);
|
||||
};
|
||||
|
||||
const isEvidence = (value: unknown): value is Evidence =>
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"evidence_id" in value &&
|
||||
typeof value.evidence_id === "string";
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import type { RizinDebugSessionManager } from "../rizin/RizinDebugSessionManager.js";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import {
|
||||
runOwnedCleanupWithExternalMutationAdmission,
|
||||
runWithExternalMutationAdmission,
|
||||
type ExternalMutationAdmission,
|
||||
} from "./externalMutationAdmission.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import type { ToolResultDelivery } from "./toolResult.js";
|
||||
|
||||
export type RizinDebugToolManager = Pick<
|
||||
RizinDebugSessionManager,
|
||||
"start" | "execute" | "status" | "close" | "retryCleanupFailures"
|
||||
>;
|
||||
|
||||
/** Register persistent Rizin debugger operations on the existing REA MCP server. */
|
||||
export const registerRizinDebugTools = (
|
||||
server: McpServer,
|
||||
manager: RizinDebugToolManager,
|
||||
logger: Logger,
|
||||
delivery: ToolResultDelivery,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
session?: ExternalMutationAdmission,
|
||||
): void => {
|
||||
const start = toolContract("start_rizin_debug_session");
|
||||
const command = toolContract("rizin_debug_command");
|
||||
const status = toolContract("rizin_debug_session_status");
|
||||
const close = toolContract("close_rizin_debug_session");
|
||||
server.registerTool(
|
||||
start.name,
|
||||
toolRegistrationOptions(start),
|
||||
async (input, context: ServerContext) => {
|
||||
const result = await runWithExternalMutationAdmission(
|
||||
session,
|
||||
start.name,
|
||||
context.mcpReq.signal,
|
||||
() =>
|
||||
logToolExecution(logger, start.name, () =>
|
||||
manager.start(
|
||||
{
|
||||
path: input.path,
|
||||
inferior_tty: input.inferior_tty,
|
||||
...(input.backend === undefined
|
||||
? {}
|
||||
: { backend: input.backend }),
|
||||
},
|
||||
context.mcpReq.signal,
|
||||
),
|
||||
),
|
||||
undefined,
|
||||
() => manager.retryCleanupFailures(),
|
||||
(value) => ({ session_id: value.session_id }),
|
||||
);
|
||||
return result.ok
|
||||
? delivery.toCallToolResult({ ok: true, value: result.value }, start)
|
||||
: delivery.toCallToolResult(result, start);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
command.name,
|
||||
toolRegistrationOptions(command),
|
||||
async (input, context: ServerContext) => {
|
||||
const result = await runWithExternalMutationAdmission(
|
||||
session,
|
||||
command.name,
|
||||
context.mcpReq.signal,
|
||||
() =>
|
||||
logToolExecution(logger, command.name, () =>
|
||||
manager.execute(
|
||||
input.session_id,
|
||||
input.command,
|
||||
context.mcpReq.signal,
|
||||
),
|
||||
),
|
||||
(value) => value.evidence,
|
||||
() => manager.retryCleanupFailures(),
|
||||
);
|
||||
if (!result.ok) {
|
||||
const partial = evidenceSchema.safeParse(
|
||||
result.error.partialObservation,
|
||||
);
|
||||
if (partial.success) {
|
||||
const recorded = recordEvidence?.(partial.data);
|
||||
if (recorded !== undefined)
|
||||
return delivery.toRecordedPartialErrorToolResult(
|
||||
result.error,
|
||||
partial.data.evidence_id,
|
||||
recorded,
|
||||
command.returnsTargetContent,
|
||||
);
|
||||
}
|
||||
return delivery.toCallToolResult(result, command);
|
||||
}
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value.evidence,
|
||||
command,
|
||||
recordEvidence?.(result.value.evidence),
|
||||
);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
status.name,
|
||||
toolRegistrationOptions(status),
|
||||
async (input) => {
|
||||
const result = manager.status(input.session_id);
|
||||
if (result === undefined)
|
||||
return delivery.toCallToolResult(
|
||||
{ ok: false, error: new AnalysisInputError(status.name) },
|
||||
status,
|
||||
);
|
||||
return delivery.toCallToolResult(
|
||||
{
|
||||
ok: true,
|
||||
value: { ...result, recent_output: [...result.recent_output] },
|
||||
},
|
||||
status,
|
||||
);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
close.name,
|
||||
toolRegistrationOptions(close),
|
||||
async (input, context: ServerContext) => {
|
||||
const result = await runOwnedCleanupWithExternalMutationAdmission(
|
||||
session,
|
||||
close.name,
|
||||
context.mcpReq.signal,
|
||||
input.session_id,
|
||||
() =>
|
||||
logToolExecution(logger, close.name, () =>
|
||||
manager.close(input.session_id),
|
||||
),
|
||||
);
|
||||
return result.ok
|
||||
? delivery.toCallToolResult({ ok: true, value: result.value }, close)
|
||||
: delivery.toCallToolResult(result, close);
|
||||
},
|
||||
);
|
||||
};
|
||||
Reference in new issue
Block a user