mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 11:43:20 +00:00
refactor(mcp): bind close_binary and reset_investigation through the shared table (#11647)
* refactor(mcp): bind close_binary and reset_investigation through the shared table * refactor(mcp): bind provider operations through the shared table (#11649) * refactor(mcp): bind provider operations through the shared table * fix(mcp): bind a provider operation only to the contract of the same name * refactor(mcp): bind objdump and Rizin commands through the shared table (#11653) * refactor(mcp): bind objdump and Rizin commands through the shared table * test(rizin): keep the pre-admission Rizin checks under the mutation sweep * refactor(mcp): bind the desktop build tools through the shared table
This commit is contained in:
1 parent
07c5a54fee
commit
b7fe131123
35 files changed
+1158
-1160
No files matched your search
@@ -87,7 +87,6 @@ const PATH_SCOPES = {
|
||||
"src/rizin/**",
|
||||
"src/contracts/*ToolContracts.ts",
|
||||
"src/server/externalMutationAdmission.ts",
|
||||
"src/server/registerReverseEngineeringTools.ts",
|
||||
"src/server/providerEnvironment.ts",
|
||||
"src/process/ExecFileOutput.ts",
|
||||
"src/process/ExecFileOutput.test.ts",
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
{
|
||||
"src/server/registerCloseLifecycleTool.ts": 1,
|
||||
"src/server/registerDesktopBuildTools.ts": 2,
|
||||
"src/server/registerElectronTools.ts": 6,
|
||||
"src/server/registerEvidenceTools.ts": 1,
|
||||
"src/server/registerResetInvestigationTool.ts": 1,
|
||||
"src/server/registerReverseEngineeringTools.ts": 2
|
||||
"src/server/registerElectronTools.ts": 6
|
||||
}
|
||||
@@ -394,10 +394,6 @@ export class BinarySession
|
||||
return routeAllowsSnapshotReplay(this.#active?.route, operation);
|
||||
}
|
||||
|
||||
invalidateSnapshotForExternalMutation(): void {
|
||||
this.invalidateSnapshot();
|
||||
}
|
||||
|
||||
/** Return the selected immutable profile, optionally scoped to an operation. */
|
||||
analysisProfile(
|
||||
operation?: AnalysisOperation,
|
||||
|
||||
@@ -158,8 +158,6 @@ export interface BinarySessionPort
|
||||
operation?: AnalysisOperation,
|
||||
): AnalysisProfileCommitment | undefined;
|
||||
allowsSnapshotReplay(operation: AnalysisOperation): boolean;
|
||||
/** Invalidate cached Evidence before an external command may mutate the target. */
|
||||
invalidateSnapshotForExternalMutation(): void;
|
||||
recordWorkflowSnapshot(
|
||||
input: WorkflowSnapshotRecordInput,
|
||||
): Result<null, EvidenceIntegrityError>;
|
||||
|
||||
@@ -20,7 +20,10 @@ import type { Evidence } from "../domain/evidence.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { invariantViolation } from "../domain/internalInvariant.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import type {
|
||||
CallToolResult,
|
||||
ServerContext,
|
||||
} from "@modelcontextprotocol/server";
|
||||
import {
|
||||
optionalProviderUnavailable,
|
||||
type OptionalProviderLoadFailure,
|
||||
@@ -47,6 +50,11 @@ import {
|
||||
} from "./contractToolHandler.js";
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import type { ExternalMutationAdmission } from "./externalMutationAdmission.js";
|
||||
import {
|
||||
createProviderOperationToolHandler,
|
||||
type ProviderOperation,
|
||||
type ProviderOperationOptions,
|
||||
} from "./providerOperationToolHandler.js";
|
||||
import {
|
||||
createExternalMutationToolHandler,
|
||||
type ExternalMutation,
|
||||
@@ -100,6 +108,7 @@ type EvidenceBinding<Input = unknown> = (
|
||||
readonly analyze?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
}
|
||||
| {
|
||||
readonly admission: "application";
|
||||
@@ -112,6 +121,7 @@ type EvidenceBinding<Input = unknown> = (
|
||||
readonly analyze?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
}
|
||||
) & {
|
||||
/**
|
||||
@@ -140,6 +150,11 @@ type ValueOperation<Input> = (
|
||||
*/
|
||||
type ValueBinding<Input = unknown> = {
|
||||
readonly admitted?: true;
|
||||
/**
|
||||
* Rewrite every response this tool delivers, its refusals included, such
|
||||
* as replacing secrets the caller typed with their handles.
|
||||
*/
|
||||
readonly presentResult?: (result: CallToolResult) => CallToolResult;
|
||||
} & (
|
||||
| {
|
||||
readonly admission: "sdk";
|
||||
@@ -152,6 +167,7 @@ type ValueBinding<Input = unknown> = {
|
||||
readonly analyze?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
}
|
||||
| {
|
||||
readonly admission: "application";
|
||||
@@ -164,6 +180,7 @@ type ValueBinding<Input = unknown> = {
|
||||
readonly analyze?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
}
|
||||
);
|
||||
|
||||
@@ -190,6 +207,30 @@ interface QueryBinding<Input> {
|
||||
readonly workflow?: never;
|
||||
readonly analyze?: never;
|
||||
readonly mutation?: never;
|
||||
readonly provider?: never;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the named provider operation on the analysis admission grants and
|
||||
* deliver its observation as atomic Evidence (see
|
||||
* `createProviderOperationToolHandler`). A server that admits no analysis
|
||||
* refuses the binding at startup.
|
||||
*/
|
||||
interface ProviderBinding<Operation extends ProviderOperation> {
|
||||
readonly admission: "sdk";
|
||||
readonly provider: ProviderOperationOptions & {
|
||||
/** The contract's own name: a binding runs only its named operation. */
|
||||
readonly operation: Operation;
|
||||
};
|
||||
readonly run?: never;
|
||||
readonly summary?: never;
|
||||
readonly value?: never;
|
||||
readonly derive?: never;
|
||||
readonly acquire?: never;
|
||||
readonly workflow?: never;
|
||||
readonly analyze?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -218,6 +259,7 @@ type DerivedBinding = {
|
||||
readonly analyze?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
} & (
|
||||
| {
|
||||
readonly derive: (
|
||||
@@ -256,6 +298,7 @@ interface RetainedSummaryBinding<Input> {
|
||||
readonly analyze?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -280,6 +323,7 @@ interface ApplicationWorkflowBinding<Input> {
|
||||
readonly analyze?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
}
|
||||
|
||||
/** An application-admitted workflow validates the raw request itself. */
|
||||
@@ -305,6 +349,7 @@ type AnalysisBinding<Input> = {
|
||||
readonly view?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
} & (Input extends { readonly detail: "complete" | "summary" }
|
||||
? {
|
||||
readonly detail: "delivery";
|
||||
@@ -337,6 +382,7 @@ interface ExternalMutationBinding<Input> {
|
||||
readonly workflow?: never;
|
||||
readonly analyze?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
}
|
||||
|
||||
/** How one named contract runs over MCP; only summary-capable contracts take `summary`. */
|
||||
@@ -350,6 +396,8 @@ export type ContractToolBinding<Name extends CatalogToolName> =
|
||||
| AnalysisBinding<ContractInput<Name>>
|
||||
| ExternalMutationBinding<EvidenceRequestFrameInput<ContractInput<Name>>>
|
||||
| QueryBinding<ContractInput<Name>>
|
||||
// Only a provider operation binds a provider, and only to its own name.
|
||||
| (Name extends ProviderOperation ? ProviderBinding<Name> : never)
|
||||
| (ContractInput<Name> extends { readonly detail: "complete" | "summary" }
|
||||
? RetainedSummaryBinding<ContractInput<Name>>
|
||||
: never);
|
||||
@@ -484,9 +532,11 @@ export const registerContractTools = (
|
||||
readonly run?: never;
|
||||
readonly mutation?: never;
|
||||
readonly query?: never;
|
||||
readonly provider?: never;
|
||||
}
|
||||
| ExternalMutationBinding<unknown>
|
||||
| QueryBinding<unknown>
|
||||
| ProviderBinding<ProviderOperation>
|
||||
| RetainedSummaryBinding<Readonly<Record<string, unknown>>>
|
||||
| undefined
|
||||
>
|
||||
@@ -497,6 +547,13 @@ export const registerContractTools = (
|
||||
const binding = table[contract.name];
|
||||
if (binding === undefined) continue;
|
||||
unbound.delete(contract.name);
|
||||
if (
|
||||
binding.provider !== undefined &&
|
||||
binding.provider.operation !== contract.name
|
||||
)
|
||||
throw invariantViolation(
|
||||
`MCP tool ${contract.name} binds provider operation ${binding.provider.operation}`,
|
||||
);
|
||||
const registration =
|
||||
binding.admission === "sdk"
|
||||
? toolRegistrationOptions(contract)
|
||||
@@ -504,79 +561,103 @@ export const registerContractTools = (
|
||||
const handler =
|
||||
binding.run !== undefined && binding.unavailable !== undefined
|
||||
? unavailableToolHandler(server, contract, binding.unavailable)
|
||||
: binding.mutation !== undefined
|
||||
? createExternalMutationToolHandler(
|
||||
: binding.provider !== undefined
|
||||
? createProviderOperationToolHandler(
|
||||
server,
|
||||
binding.session,
|
||||
binding.mutation,
|
||||
logger,
|
||||
retention,
|
||||
binding.provider.operation,
|
||||
binding.provider,
|
||||
{
|
||||
logger,
|
||||
recordEvidence,
|
||||
evidenceById,
|
||||
withAdmittedAnalysis: requiredAdmission(
|
||||
withAdmittedAnalysis,
|
||||
contract.name,
|
||||
),
|
||||
},
|
||||
)(contract)
|
||||
: binding.analyze !== undefined
|
||||
? createAnalysisToolHandler(
|
||||
: binding.mutation !== undefined
|
||||
? createExternalMutationToolHandler(
|
||||
server,
|
||||
binding.analyze,
|
||||
binding.session,
|
||||
binding.mutation,
|
||||
logger,
|
||||
retention,
|
||||
requiredAdmission(withAdmittedAnalysis, contract.name),
|
||||
binding.detail === "delivery",
|
||||
)(contract)
|
||||
: binding.query !== undefined
|
||||
? createValueToolHandler(
|
||||
: binding.analyze !== undefined
|
||||
? createAnalysisToolHandler(
|
||||
server,
|
||||
analysisQuery(binding.query, contract.name),
|
||||
binding.analyze,
|
||||
logger,
|
||||
retention,
|
||||
requiredAdmission(withAdmittedAnalysis, contract.name),
|
||||
recordEvidence,
|
||||
binding.detail === "delivery",
|
||||
)(contract)
|
||||
: binding.value !== undefined
|
||||
: binding.query !== undefined
|
||||
? createValueToolHandler(
|
||||
server,
|
||||
binding.value,
|
||||
analysisQuery(binding.query, contract.name),
|
||||
logger,
|
||||
binding.admitted === true
|
||||
? withAdmittedAnalysis
|
||||
: undefined,
|
||||
requiredAdmission(withAdmittedAnalysis, contract.name),
|
||||
recordEvidence,
|
||||
)(contract)
|
||||
: binding.workflow !== undefined
|
||||
? createApplicationToolHandler(
|
||||
: binding.value !== undefined
|
||||
? createValueToolHandler(
|
||||
server,
|
||||
binding,
|
||||
binding.value,
|
||||
logger,
|
||||
{
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
evidenceById,
|
||||
},
|
||||
withAdmittedAnalysis,
|
||||
binding.admitted === true
|
||||
? withAdmittedAnalysis
|
||||
: undefined,
|
||||
recordEvidence,
|
||||
)(contract)
|
||||
: binding.derive !== undefined ||
|
||||
binding.acquire !== undefined
|
||||
? createDerivedToolHandler(
|
||||
: binding.workflow !== undefined
|
||||
? createApplicationToolHandler(
|
||||
server,
|
||||
binding.session,
|
||||
derivedAcquisition(binding),
|
||||
binding,
|
||||
logger,
|
||||
)(contract)
|
||||
: binding.run !== undefined
|
||||
? createEvidenceToolHandler(
|
||||
server,
|
||||
binding.run,
|
||||
logger,
|
||||
{
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
binding.viewSource,
|
||||
)(contract)
|
||||
: createRetainedSummaryToolHandler(
|
||||
recordEvidenceWithUnknown,
|
||||
evidenceById,
|
||||
},
|
||||
withAdmittedAnalysis,
|
||||
)(contract)
|
||||
: binding.derive !== undefined ||
|
||||
binding.acquire !== undefined
|
||||
? createDerivedToolHandler(
|
||||
server,
|
||||
contract as SummaryContract,
|
||||
binding.summary,
|
||||
binding.session,
|
||||
derivedAcquisition(binding),
|
||||
logger,
|
||||
retention,
|
||||
withAdmittedAnalysis,
|
||||
);
|
||||
server.registerTool(contract.name, registration, handler);
|
||||
)(contract)
|
||||
: binding.run !== undefined
|
||||
? createEvidenceToolHandler(
|
||||
server,
|
||||
binding.run,
|
||||
logger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
binding.viewSource,
|
||||
)(contract)
|
||||
: createRetainedSummaryToolHandler(
|
||||
server,
|
||||
contract as SummaryContract,
|
||||
binding.summary,
|
||||
logger,
|
||||
retention,
|
||||
withAdmittedAnalysis,
|
||||
);
|
||||
const present =
|
||||
binding.value === undefined ? undefined : binding.presentResult;
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
registration,
|
||||
present === undefined
|
||||
? handler
|
||||
: async (input: unknown, context: ServerContext) =>
|
||||
present(await handler(input, context)),
|
||||
);
|
||||
}
|
||||
if (unbound.size > 0)
|
||||
throw invariantViolation(
|
||||
|
||||
@@ -216,6 +216,17 @@ export class ReducibleValue {
|
||||
) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A value followed by content blocks an upstream tool returned (a build
|
||||
* computer's screenshot, say), delivered unchanged after REA's JSON.
|
||||
*/
|
||||
export class ForwardedValue {
|
||||
constructor(
|
||||
readonly value: JsonValue,
|
||||
readonly content: readonly Readonly<Record<string, JsonValue>>[],
|
||||
) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A failure delivered with facts its operation observed alongside the error
|
||||
* (an open's selection at failure, say), added to the error's details.
|
||||
@@ -229,7 +240,7 @@ export class DetailedFailure {
|
||||
|
||||
/** What a value workflow returns. */
|
||||
export type ValueOutcome = Result<
|
||||
JsonValue | CommittedValue | ReducibleValue,
|
||||
JsonValue | CommittedValue | ReducibleValue | ForwardedValue,
|
||||
AnalysisError | DetailedFailure
|
||||
>;
|
||||
|
||||
@@ -295,7 +306,13 @@ export const createValueToolHandler =
|
||||
{},
|
||||
value.alternatives,
|
||||
)
|
||||
: server.delivery.toCallToolResult(ok(value), contract);
|
||||
: value instanceof ForwardedValue
|
||||
? server.delivery.toForwardedToolResult(
|
||||
ok(value.value),
|
||||
contract,
|
||||
value.content,
|
||||
)
|
||||
: server.delivery.toCallToolResult(ok(value), contract);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
+65
-46
@@ -9,12 +9,19 @@ import { AnalysisSettings } from "../application/AnalysisSettings.js";
|
||||
import { parseMcpInputBudget } from "../config/mcpInputBudget.js";
|
||||
import { serverInstructions } from "./serverInstructions.js";
|
||||
import { registerServiceTools } from "./serviceToolBindings.js";
|
||||
import {
|
||||
artifactExecutionParameters,
|
||||
managedAnalysisForAdmission,
|
||||
} from "./providerOperationFamilies.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "../contracts/artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "../contracts/managed/managedToolContracts.js";
|
||||
import { promptsForToolFamilies } from "../contracts/promptToolFamilyScope.js";
|
||||
import { retainedDebuggerDiagnostics } from "../process/ownedDebuggerCleanupError.js";
|
||||
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
|
||||
import { captureProviderEnvironment } from "./providerEnvironment.js";
|
||||
import { createByteEntropyService } from "../composition/binaryDiagnostics.js";
|
||||
import { registerDesktopBuildTools } from "./registerDesktopBuildTools.js";
|
||||
import { FridaInstrumentationService } from "../application/frida/FridaInstrumentationService.js";
|
||||
import { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import { catalogIdentityForToolFamilies } from "../contracts/catalog/catalogIdentity.js";
|
||||
@@ -30,18 +37,14 @@ import type { BinarySessionPort } from "../application/binary/BinarySessionPort.
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { silentLogger } from "../logger.js";
|
||||
import type { Logger } from "pino";
|
||||
import { registerArtifactTools } from "./registerArtifactTools.js";
|
||||
import { registerNativeTools } from "./registerNativeTools.js";
|
||||
import { JavaScriptRecoveryService } from "../application/javascript/JavaScriptRecoveryService.js";
|
||||
import { registerElectronTools } from "./registerElectronTools.js";
|
||||
import { registerManagedTools } from "./registerManagedTools.js";
|
||||
import { AndroidAnalysisService } from "../application/android/AndroidAnalysisService.js";
|
||||
import { JebAnalysisService } from "../application/jeb/JebAnalysisService.js";
|
||||
import { PcapAnalysisService } from "../application/pcap/PcapAnalysisService.js";
|
||||
import { ApktoolResourceAnalysisService } from "../application/apktool/ApktoolResourceAnalysisService.js";
|
||||
import { FlutterBuildAnalysisService } from "../application/flutter/FlutterBuildAnalysisService.js";
|
||||
import { AdbDeviceAnalysisService } from "../application/adb/AdbDeviceAnalysisService.js";
|
||||
import { registerOfficialTools } from "./registerOfficialTools.js";
|
||||
import { registerGuidedPrompts } from "./registerPrompts.js";
|
||||
import { registerSessionTools } from "./registerSessionTools.js";
|
||||
import type { AvailabilityPolicy } from "../application/CapabilityInventory.js";
|
||||
@@ -50,7 +53,6 @@ import {
|
||||
withAdmittedAnalysis,
|
||||
type ServerAnalysisSource,
|
||||
} from "./analysisAdmission.js";
|
||||
import { registerReverseEngineeringTools } from "./registerReverseEngineeringTools.js";
|
||||
import {
|
||||
resolveMcpOutputSchemaProfile,
|
||||
type McpOutputSchemaProfile,
|
||||
@@ -319,22 +321,6 @@ export const createServer = (
|
||||
if (failures.length > 1)
|
||||
throw new AggregateError(failures, "REA server cleanup failed");
|
||||
};
|
||||
const analysisOptions = {
|
||||
logger: toolLogger,
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
evidenceById,
|
||||
withAdmittedAnalysis: analysisAdmission,
|
||||
...(session === undefined
|
||||
? {}
|
||||
: { admitRecovery: session.admitRecoveryObservation.bind(session) }),
|
||||
};
|
||||
const evidenceOptions = {
|
||||
logger: toolLogger,
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis: analysisAdmission,
|
||||
};
|
||||
const common = {
|
||||
logger: toolLogger,
|
||||
recordEvidence,
|
||||
@@ -351,7 +337,22 @@ export const createServer = (
|
||||
javascriptRecovery,
|
||||
);
|
||||
registerToolFamilies({
|
||||
direct: () => registerOfficialTools(server, analysisOptions),
|
||||
direct: () =>
|
||||
registerServiceTools(
|
||||
server,
|
||||
{
|
||||
providerOperations: {
|
||||
contracts: OFFICIAL_TOOL_CONTRACTS,
|
||||
activeTarget,
|
||||
...(session === undefined
|
||||
? {}
|
||||
: {
|
||||
admitRecovery: session.admitRecoveryObservation.bind(session),
|
||||
}),
|
||||
},
|
||||
},
|
||||
contractTools,
|
||||
),
|
||||
enhanced: () =>
|
||||
registerServiceTools(
|
||||
server,
|
||||
@@ -359,27 +360,20 @@ export const createServer = (
|
||||
contractTools,
|
||||
),
|
||||
native: () => {
|
||||
registerNativeTools(server, { ...evidenceOptions, evidenceById });
|
||||
registerReverseEngineeringTools(
|
||||
registerServiceTools(
|
||||
server,
|
||||
reverseEngineering,
|
||||
toolLogger,
|
||||
delivery,
|
||||
recordEvidence,
|
||||
analysisAdmission,
|
||||
session === undefined
|
||||
? undefined
|
||||
: () => session.invalidateSnapshotForExternalMutation(),
|
||||
session === undefined
|
||||
? undefined
|
||||
: (path, signal, operation, rebindFailure) =>
|
||||
session.withAdmittedExternalMutation(
|
||||
path,
|
||||
signal,
|
||||
operation,
|
||||
rebindFailure,
|
||||
),
|
||||
evidenceById,
|
||||
{
|
||||
providerOperations: {
|
||||
contracts: NATIVE_TOOL_CONTRACTS,
|
||||
activeTarget,
|
||||
},
|
||||
},
|
||||
contractTools,
|
||||
);
|
||||
registerServiceTools(
|
||||
server,
|
||||
{ reverseEngineering: { service: reverseEngineering, session } },
|
||||
contractTools,
|
||||
);
|
||||
registerServiceTools(
|
||||
server,
|
||||
@@ -416,7 +410,17 @@ export const createServer = (
|
||||
);
|
||||
},
|
||||
artifact: () => {
|
||||
registerArtifactTools(server, { ...evidenceOptions, evidenceById });
|
||||
registerServiceTools(
|
||||
server,
|
||||
{
|
||||
providerOperations: {
|
||||
contracts: ARTIFACT_TOOL_CONTRACTS,
|
||||
activeTarget,
|
||||
parametersForExecution: artifactExecutionParameters,
|
||||
},
|
||||
},
|
||||
contractTools,
|
||||
);
|
||||
registerServiceTools(
|
||||
server,
|
||||
{
|
||||
@@ -440,7 +444,17 @@ export const createServer = (
|
||||
);
|
||||
},
|
||||
managed: () => {
|
||||
registerManagedTools(server, { ...evidenceOptions, evidenceById });
|
||||
registerServiceTools(
|
||||
server,
|
||||
{
|
||||
providerOperations: {
|
||||
contracts: MANAGED_TOOL_CONTRACTS,
|
||||
activeTarget,
|
||||
analysisForAdmission: managedAnalysisForAdmission(activeTarget),
|
||||
},
|
||||
},
|
||||
contractTools,
|
||||
);
|
||||
if (session !== undefined)
|
||||
registerServiceTools(
|
||||
server,
|
||||
@@ -572,7 +586,12 @@ export const createServer = (
|
||||
},
|
||||
contractTools,
|
||||
);
|
||||
registerDesktopBuildTools(server, desktopBuildComputers, toolLogger);
|
||||
// Build tool responses are redacted as a whole; they record nothing.
|
||||
registerServiceTools(
|
||||
server,
|
||||
{ desktopBuild: desktopBuildComputers },
|
||||
{ logger: toolLogger },
|
||||
);
|
||||
},
|
||||
session: () => {
|
||||
if (session === undefined) return;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { DesktopBuildComputers } from "../application/desktop/DesktopBuildComputers.js";
|
||||
import type { ProgressReporter } from "../ports/ProgressReporter.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
|
||||
/** The build computers the desktop build tools drive. */
|
||||
export type DesktopBuildToolComputers = Pick<
|
||||
DesktopBuildComputers,
|
||||
"start" | "act" | "close" | "steps" | "measure" | "redaction" | "progressMs"
|
||||
>;
|
||||
|
||||
/**
|
||||
* Report progress every `intervalMs` while a long build step works, so a
|
||||
* client's request timeout can reset; the step reports on the same
|
||||
* reporter, whose notifications keep one order.
|
||||
*/
|
||||
export const withHeartbeat = async <Value>(
|
||||
progress: ProgressReporter,
|
||||
phase: string,
|
||||
intervalMs: number,
|
||||
run: (progress: ProgressReporter) => Promise<Value>,
|
||||
): Promise<Value> => {
|
||||
const startedAt = Date.now();
|
||||
const timer = setInterval(() => {
|
||||
void progress
|
||||
.report({
|
||||
phase,
|
||||
completed: 0,
|
||||
total: null,
|
||||
message: `working (${String(Math.round((Date.now() - startedAt) / 1000))} s)`,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, intervalMs);
|
||||
try {
|
||||
return await run(progress);
|
||||
} finally {
|
||||
clearInterval(timer);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A result with each typed secret's value replaced by its handle, in its
|
||||
* text and structured content; images pass as they are.
|
||||
*/
|
||||
export const redactedResult = (
|
||||
result: CallToolResult,
|
||||
redact: DesktopBuildComputers["redaction"],
|
||||
): CallToolResult => ({
|
||||
...result,
|
||||
content: result.content.map((block) =>
|
||||
block.type === "text"
|
||||
? { ...block, text: redact.redact(block.text) }
|
||||
: block,
|
||||
),
|
||||
...(result.structuredContent === undefined
|
||||
? {}
|
||||
: {
|
||||
structuredContent: redact.redactJson(
|
||||
result.structuredContent as JsonValue,
|
||||
) as Record<string, unknown>,
|
||||
}),
|
||||
});
|
||||
@@ -30,6 +30,11 @@ export interface MutationValue {
|
||||
readonly retained?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
/** A prepared command that observes through an owned resource. */
|
||||
export type EvidenceCommand = (
|
||||
signal: AbortSignal,
|
||||
) => Promise<Result<Evidence, AnalysisError>>;
|
||||
|
||||
/**
|
||||
* What one command that may change the bound artifact does:
|
||||
*
|
||||
@@ -46,15 +51,30 @@ export interface MutationValue {
|
||||
* command and stays owned for the next retry.
|
||||
*/
|
||||
export type ExternalMutation<Input = unknown> =
|
||||
| {
|
||||
| ({
|
||||
readonly kind: "evidence";
|
||||
readonly detail?: "delivery";
|
||||
readonly run: (
|
||||
input: Input,
|
||||
signal: AbortSignal,
|
||||
) => Promise<Result<Evidence, AnalysisError>>;
|
||||
readonly retryCleanup: () => Promise<Result<null, AnalysisError>>;
|
||||
}
|
||||
} & (
|
||||
| {
|
||||
readonly run: (
|
||||
input: Input,
|
||||
signal: AbortSignal,
|
||||
) => Promise<Result<Evidence, AnalysisError>>;
|
||||
readonly prepare?: never;
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* Validate the request and settle the owner's cleanup before
|
||||
* admission, returning the command to run. A refusal here never
|
||||
* reaches admission, so the bound target stays open.
|
||||
*/
|
||||
readonly prepare: (
|
||||
input: Input,
|
||||
) => Promise<Result<EvidenceCommand, AnalysisError>>;
|
||||
readonly run?: never;
|
||||
}
|
||||
))
|
||||
| {
|
||||
readonly kind: "value";
|
||||
readonly run: (
|
||||
@@ -125,11 +145,17 @@ export const createExternalMutationToolHandler =
|
||||
const ready = requireAnalysisViewRetention(name, retention);
|
||||
if (!ready.ok) return server.delivery.toCallToolResult(ready, contract);
|
||||
}
|
||||
const prepared: Result<EvidenceCommand, AnalysisError> =
|
||||
mutation.prepare === undefined
|
||||
? ok((commandSignal) => mutation.run(input, commandSignal))
|
||||
: await mutation.prepare(input);
|
||||
if (!prepared.ok) return failed(prepared.error);
|
||||
const command = prepared.value;
|
||||
const observed = await runWithExternalMutationAdmission(
|
||||
session,
|
||||
name,
|
||||
signal,
|
||||
() => logToolExecution(logger, name, () => mutation.run(input, signal)),
|
||||
() => logToolExecution(logger, name, () => command(signal)),
|
||||
(evidence) => evidence,
|
||||
mutation.retryCleanup,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { AnalysisOperationPort } from "../ports/AnalysisProvider.js";
|
||||
import { isManagedToolName } from "../contracts/managed/managedToolContracts.js";
|
||||
import { artifactExtractionInputSchema } from "../contracts/artifactToolContracts.js";
|
||||
import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import { runManagedProviderExecution } from "../composition/directAnalysis.js";
|
||||
import type { ProviderOperation } from "./providerOperationToolHandler.js";
|
||||
|
||||
/**
|
||||
* Route managed PE/CLI operations to the execution-free managed reader. A
|
||||
* call without `path` reads the managed file last selected through this
|
||||
* server, else the active target when it is a managed PE; the selection
|
||||
* lasts as long as the returned router.
|
||||
*/
|
||||
export const managedAnalysisForAdmission = (
|
||||
activeTarget: (() => BinaryTarget | undefined) | undefined,
|
||||
): ((analysis: AnalysisOperationPort) => AnalysisOperationPort) => {
|
||||
let selectedManagedPath: string | undefined;
|
||||
return (analysis) => ({
|
||||
execute: async (operation, parameters, executionOptions) => {
|
||||
if (!isManagedToolName(operation))
|
||||
return analysis.execute(operation, parameters, executionOptions);
|
||||
const requestedPath = parameters.path;
|
||||
const target = activeTarget?.();
|
||||
const path =
|
||||
typeof requestedPath === "string"
|
||||
? requestedPath
|
||||
: (selectedManagedPath ??
|
||||
(target?.format === "pe" && target.managed
|
||||
? target.path
|
||||
: undefined));
|
||||
if (path === undefined)
|
||||
return err(
|
||||
new AnalysisInputError(operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "missing_argument",
|
||||
message:
|
||||
"Provide a managed PE/CLI path or first select one with inspect_managed_artifact.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const execution = await runManagedProviderExecution(
|
||||
path,
|
||||
operation,
|
||||
executionOptions?.signal,
|
||||
parameters,
|
||||
);
|
||||
if (execution.ok && typeof requestedPath === "string")
|
||||
selectedManagedPath = requestedPath;
|
||||
return execution;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
/** Extraction writes under a destination REA creates for the caller's root. */
|
||||
export const artifactExecutionParameters = (
|
||||
operation: ProviderOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
): Readonly<Record<string, JsonValue>> => {
|
||||
if (operation !== "extract_artifact") return parameters;
|
||||
const execution = artifactExtractionInputSchema.parse(parameters);
|
||||
return {
|
||||
...execution,
|
||||
output_root: createArtifactExtractionDestination(execution.output_root),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,184 @@
|
||||
import type {
|
||||
CallToolResult,
|
||||
ServerContext,
|
||||
} from "@modelcontextprotocol/server";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import { sessionEvidenceForExecution } from "../application/binary/SessionEvidenceReuse.js";
|
||||
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import {
|
||||
retainedSummaryDelivery,
|
||||
withoutDeliveryDetail,
|
||||
} from "./retainedSummaryDelivery.js";
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
} from "../ports/AnalysisProvider.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import { admitCompletedAnalysis } from "../application/investigation/admitCompletedAnalysis.js";
|
||||
import type { RecoveryAdmission } from "../application/investigation/InvestigationRetention.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { recordEvidenceSources } from "../application/investigation/recordEvidenceSources.js";
|
||||
import {
|
||||
reportOperationStart,
|
||||
reportOperationEnd,
|
||||
} from "./operationProgress.js";
|
||||
|
||||
/** A provider operation a tool contract names. */
|
||||
export type ProviderOperation = Exclude<AnalysisOperation, "health">;
|
||||
|
||||
/**
|
||||
* How one family's provider operations run: the target their observations
|
||||
* are about when the provider names none, the recovery admission a completed
|
||||
* analysis passes, and the family's own routing of the admitted analysis and
|
||||
* of execution parameters.
|
||||
*/
|
||||
export interface ProviderOperationOptions {
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly admitRecovery?: RecoveryAdmission | undefined;
|
||||
readonly analysisForAdmission?:
|
||||
| ((analysis: AnalysisOperationPort) => AnalysisOperationPort)
|
||||
| undefined;
|
||||
readonly parametersForExecution?:
|
||||
| ((
|
||||
operation: ProviderOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
) => Readonly<Record<string, JsonValue>>)
|
||||
| undefined;
|
||||
}
|
||||
|
||||
/** The shared logging, recording and admission a provider operation runs under. */
|
||||
export interface ProviderOperationDependencies {
|
||||
readonly logger: Logger;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly evidenceById: EvidenceLookup | undefined;
|
||||
readonly withAdmittedAnalysis: WithAdmittedAnalysis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one provider operation on the analysis admission grants and deliver its
|
||||
* observation as atomic Evidence: the session's reusable record when it
|
||||
* already holds the same observation, else a new record admitted against the
|
||||
* completed analysis. A `detail: "summary"` request is refused before analysis
|
||||
* when nothing retains the complete Evidence, and never reaches the provider
|
||||
* of a contract that declares a retained summary.
|
||||
*/
|
||||
export const createProviderOperationToolHandler =
|
||||
(
|
||||
server: EvidenceMcpServer,
|
||||
operation: ProviderOperation,
|
||||
options: ProviderOperationOptions,
|
||||
dependencies: ProviderOperationDependencies,
|
||||
) =>
|
||||
(contract: ToolContract) => {
|
||||
const delivery =
|
||||
contract.retainedSummary === undefined
|
||||
? undefined
|
||||
: retainedSummaryDelivery(contract.name, dependencies);
|
||||
return async (
|
||||
input: unknown,
|
||||
context: ServerContext,
|
||||
): Promise<CallToolResult> => {
|
||||
const parameters = jsonObjectSchema.parse(input);
|
||||
const ready = delivery?.preflight(parameters) ?? ok(null);
|
||||
if (!ready.ok) return server.delivery.toCallToolResult(ready, contract);
|
||||
const admitted = await dependencies.withAdmittedAnalysis(
|
||||
contract.name,
|
||||
context.mcpReq.signal,
|
||||
async (admittedAnalysis) => {
|
||||
const analysis =
|
||||
options.analysisForAdmission?.(admittedAnalysis) ??
|
||||
admittedAnalysis;
|
||||
const progress = mcpProgressReporter(context);
|
||||
await reportOperationStart(progress, contract.name);
|
||||
const providerParameters =
|
||||
contract.retainedSummary === undefined
|
||||
? parameters
|
||||
: withoutDeliveryDetail(parameters);
|
||||
const executionParameters =
|
||||
options.parametersForExecution?.(operation, providerParameters) ??
|
||||
providerParameters;
|
||||
const execution = await logToolExecution(
|
||||
dependencies.logger,
|
||||
contract.name,
|
||||
() =>
|
||||
analysis.execute(operation, executionParameters, {
|
||||
signal: context.mcpReq.signal,
|
||||
progress,
|
||||
isOperationAdvertised: (advertised) =>
|
||||
server.advertisesTool(advertised),
|
||||
}),
|
||||
);
|
||||
await reportOperationEnd(progress, contract.name, execution.ok);
|
||||
if (!execution.ok)
|
||||
return server.delivery.toCallToolResult(execution, contract);
|
||||
const sourceEvidence = execution.value.sourceEvidence ?? [];
|
||||
const sourceRecorded = recordEvidenceSources(
|
||||
dependencies.recordEvidence,
|
||||
sourceEvidence,
|
||||
);
|
||||
if (!sourceRecorded.ok)
|
||||
return server.delivery.toCallToolResult(sourceRecorded, contract);
|
||||
const evidenceParameters =
|
||||
contract.retainedSummary?.evidenceParameters === "omit-detail"
|
||||
? providerParameters
|
||||
: parameters;
|
||||
const observation = {
|
||||
...execution.value,
|
||||
subject:
|
||||
execution.value.subject === undefined
|
||||
? (options.activeTarget?.() ?? null)
|
||||
: execution.value.subject,
|
||||
};
|
||||
const reusable =
|
||||
dependencies.evidenceById === undefined
|
||||
? undefined
|
||||
: sessionEvidenceForExecution(
|
||||
execution.value,
|
||||
operation,
|
||||
evidenceParameters,
|
||||
dependencies.evidenceById,
|
||||
);
|
||||
if (reusable === undefined) {
|
||||
const admitted = admitCompletedAnalysis(
|
||||
operation,
|
||||
evidenceParameters,
|
||||
observation,
|
||||
options.admitRecovery,
|
||||
);
|
||||
if (!admitted.ok)
|
||||
return server.delivery.toCallToolResult(admitted, contract);
|
||||
}
|
||||
const evidence =
|
||||
reusable ??
|
||||
createAnalysisExecutionEvidence(
|
||||
operation,
|
||||
evidenceParameters,
|
||||
observation,
|
||||
"observed",
|
||||
);
|
||||
const projected =
|
||||
delivery?.projectEvidence(parameters, evidence) ?? ok(evidence);
|
||||
if (!projected.ok)
|
||||
return server.delivery.toCallToolResult(projected, contract);
|
||||
const recorded = dependencies.recordEvidence?.(projected.value);
|
||||
return server.delivery.toEvidenceToolResult(
|
||||
projected.value,
|
||||
contract,
|
||||
recorded,
|
||||
);
|
||||
},
|
||||
);
|
||||
return admitted.ok
|
||||
? admitted.value
|
||||
: server.delivery.toCallToolResult(admitted, contract);
|
||||
};
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
|
||||
import {
|
||||
ARTIFACT_TOOL_CONTRACTS,
|
||||
artifactExtractionInputSchema,
|
||||
} from "../contracts/artifactToolContracts.js";
|
||||
import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js";
|
||||
import { registerEvidenceTools } from "./registerEvidenceTools.js";
|
||||
import type { EvidenceToolFamilyOptions } from "./retainedSummaryDelivery.js";
|
||||
|
||||
/** Register deterministic artifact inventory and safe extraction operations. */
|
||||
export const registerArtifactTools = (
|
||||
server: EvidenceMcpServer,
|
||||
options: EvidenceToolFamilyOptions,
|
||||
): void => {
|
||||
registerEvidenceTools(server, ARTIFACT_TOOL_CONTRACTS, {
|
||||
...options,
|
||||
parametersForExecution: (operation, parameters) => {
|
||||
if (operation !== "extract_artifact") return parameters;
|
||||
const execution = artifactExtractionInputSchema.parse(parameters);
|
||||
return {
|
||||
...execution,
|
||||
output_root: createArtifactExtractionDestination(execution.output_root),
|
||||
};
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -1,239 +0,0 @@
|
||||
import type {
|
||||
CallToolResult,
|
||||
ServerContext,
|
||||
} from "@modelcontextprotocol/server";
|
||||
import type { Logger } from "pino";
|
||||
import { z } from "zod";
|
||||
|
||||
import type {
|
||||
DesktopBuildComputers,
|
||||
ForwardedResult,
|
||||
} from "../application/desktop/DesktopBuildComputers.js";
|
||||
import type { ProgressReporter } from "../ports/ProgressReporter.js";
|
||||
import { DesktopBuildSteps } from "../application/desktop/DesktopBuildSteps.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { applicationToolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
|
||||
/** Parse a tool's own input so a refusal names the field. */
|
||||
const admit = <Schema extends z.ZodType>(
|
||||
contract: { readonly name: string; readonly inputSchema: Schema },
|
||||
raw: unknown,
|
||||
): Result<z.output<Schema>, AnalysisError> => {
|
||||
const parsed = z.safeParse(contract.inputSchema, raw);
|
||||
return parsed.success
|
||||
? ok(parsed.data)
|
||||
: err(
|
||||
analysisInputErrorFromIssues(contract.name, parsed.error.issues, raw, {
|
||||
cause: parsed.error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Report progress every `intervalMs` while a long build step works, so a
|
||||
* client's request timeout can reset; the step reports on the same
|
||||
* reporter, whose notifications keep one order.
|
||||
*/
|
||||
const withHeartbeat = async <Value>(
|
||||
context: ServerContext,
|
||||
phase: string,
|
||||
intervalMs: number,
|
||||
run: (progress: ProgressReporter) => Promise<Value>,
|
||||
): Promise<Value> => {
|
||||
const progress = mcpProgressReporter(context);
|
||||
const startedAt = Date.now();
|
||||
const timer = setInterval(() => {
|
||||
void progress
|
||||
.report({
|
||||
phase,
|
||||
completed: 0,
|
||||
total: null,
|
||||
message: `working (${String(Math.round((Date.now() - startedAt) / 1000))} s)`,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, intervalMs);
|
||||
try {
|
||||
return await run(progress);
|
||||
} finally {
|
||||
clearInterval(timer);
|
||||
}
|
||||
};
|
||||
|
||||
/** How results show secrets typed on this server's build computers: by their handles. */
|
||||
type Redactor = DesktopBuildComputers["redaction"];
|
||||
|
||||
/** A result with each typed secret's value replaced by its handle, in its text and structured content; images pass as they are. */
|
||||
const redacted = (
|
||||
result: CallToolResult,
|
||||
redact: Redactor,
|
||||
): CallToolResult => ({
|
||||
...result,
|
||||
content: result.content.map((block) =>
|
||||
block.type === "text"
|
||||
? { ...block, text: redact.redact(block.text) }
|
||||
: block,
|
||||
),
|
||||
...(result.structuredContent === undefined
|
||||
? {}
|
||||
: {
|
||||
structuredContent: redact.redactJson(
|
||||
result.structuredContent as JsonValue,
|
||||
) as Record<string, unknown>,
|
||||
}),
|
||||
});
|
||||
|
||||
/** Registration of one build tool: the server, its logger, the tool's contract and how its results show typed secrets. */
|
||||
interface Registration<Schema extends z.ZodType> {
|
||||
readonly server: EvidenceMcpServer;
|
||||
readonly logger: Logger;
|
||||
readonly contract: ToolContract & {
|
||||
readonly name: string;
|
||||
readonly inputSchema: Schema;
|
||||
};
|
||||
readonly redact: Redactor;
|
||||
}
|
||||
|
||||
/** Register a tool whose result carries a forwarded driver answer, such as a screenshot, after REA's JSON. */
|
||||
const registerForwarded = <Schema extends z.ZodType>(
|
||||
{ server, logger, contract, redact }: Registration<Schema>,
|
||||
run: (
|
||||
input: z.output<Schema>,
|
||||
context: ServerContext,
|
||||
) => Promise<Result<ForwardedResult<JsonValue>, AnalysisError>>,
|
||||
): void => {
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
applicationToolRegistrationOptions(contract),
|
||||
async (raw: unknown, context: ServerContext): Promise<CallToolResult> => {
|
||||
const input = admit(contract, raw);
|
||||
if (!input.ok)
|
||||
return redacted(
|
||||
server.delivery.toCallToolResult(input, contract),
|
||||
redact,
|
||||
);
|
||||
const result = await logToolExecution(logger, contract.name, () =>
|
||||
run(input.value, context),
|
||||
);
|
||||
return redacted(
|
||||
result.ok
|
||||
? server.delivery.toForwardedToolResult(
|
||||
ok(result.value.value),
|
||||
contract,
|
||||
result.value.content,
|
||||
)
|
||||
: server.delivery.toCallToolResult(result, contract),
|
||||
redact,
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
/** Register a tool with a plain JSON result. */
|
||||
const registerPlain = <Schema extends z.ZodType>(
|
||||
{ server, logger, contract, redact }: Registration<Schema>,
|
||||
run: (
|
||||
input: z.output<Schema>,
|
||||
context: ServerContext,
|
||||
) => Promise<Result<JsonValue, AnalysisError>>,
|
||||
): void => {
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
applicationToolRegistrationOptions(contract),
|
||||
async (raw: unknown, context: ServerContext): Promise<CallToolResult> => {
|
||||
const input = admit(contract, raw);
|
||||
if (!input.ok)
|
||||
return redacted(
|
||||
server.delivery.toCallToolResult(input, contract),
|
||||
redact,
|
||||
);
|
||||
return redacted(
|
||||
server.delivery.toCallToolResult(
|
||||
await logToolExecution(logger, contract.name, () =>
|
||||
run(input.value, context),
|
||||
),
|
||||
contract,
|
||||
),
|
||||
redact,
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
/** Register the build computer session tools and the build steps on them on the REA MCP server; no result shows a typed secret's value. */
|
||||
export const registerDesktopBuildTools = (
|
||||
server: EvidenceMcpServer,
|
||||
computers: Pick<
|
||||
DesktopBuildComputers,
|
||||
"start" | "act" | "close" | "steps" | "measure" | "redaction" | "progressMs"
|
||||
>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
const heartbeat = <Value>(
|
||||
context: ServerContext,
|
||||
phase: string,
|
||||
run: (progress: ProgressReporter) => Promise<Value>,
|
||||
) => withHeartbeat(context, phase, computers.progressMs, run);
|
||||
const tool = <Name extends Parameters<typeof toolContract>[0]>(
|
||||
name: Name,
|
||||
) => ({
|
||||
server,
|
||||
logger,
|
||||
contract: toolContract(name),
|
||||
redact: computers.redaction,
|
||||
});
|
||||
const steps = new DesktopBuildSteps(computers);
|
||||
registerForwarded(tool("start_build_computer"), (input, context) =>
|
||||
computers.start(input, context.mcpReq.signal, mcpProgressReporter(context)),
|
||||
);
|
||||
// An action can wait for the call before it on its computer, and a reset for the relaunched app, which can take minutes.
|
||||
registerForwarded(tool("act_on_build_computer"), (input, context) =>
|
||||
heartbeat(context, "act_on_build_computer", () =>
|
||||
computers.act(input, context.mcpReq.signal),
|
||||
),
|
||||
);
|
||||
registerForwarded(tool("start_build_capture"), (input, context) =>
|
||||
heartbeat(context, "start_build_capture", () =>
|
||||
steps.startCapture(input, context.mcpReq.signal),
|
||||
),
|
||||
);
|
||||
registerPlain(tool("mark_build_checkpoint"), (input, context) =>
|
||||
heartbeat(context, "mark_build_checkpoint", () =>
|
||||
steps.markCheckpoint(input, context.mcpReq.signal),
|
||||
),
|
||||
);
|
||||
registerPlain(tool("stop_build_capture"), (input, context) =>
|
||||
heartbeat(context, "stop_build_capture", () =>
|
||||
steps.stopCapture(input, context.mcpReq.signal),
|
||||
),
|
||||
);
|
||||
registerPlain(tool("export_build_environment"), (input, context) =>
|
||||
heartbeat(context, "export_build_environment", () =>
|
||||
steps.exportEnvironment(input, context.mcpReq.signal),
|
||||
),
|
||||
);
|
||||
registerPlain(tool("check_build_task"), (input, context) =>
|
||||
heartbeat(context, "check_build_task", (progress) =>
|
||||
steps.checkTask(input, context.mcpReq.signal, progress),
|
||||
),
|
||||
);
|
||||
// Solves run one at a time for minutes each, so progress keeps the client waiting.
|
||||
registerPlain(tool("measure_build_task"), (input, context) =>
|
||||
heartbeat(context, "measure_build_task", (progress) =>
|
||||
computers.measure(input, context.mcpReq.signal, progress),
|
||||
),
|
||||
);
|
||||
registerPlain(tool("record_build_consent"), (input, context) =>
|
||||
steps.recordConsent(input, context.mcpReq.signal),
|
||||
);
|
||||
registerPlain(tool("close_build_computer"), (input) =>
|
||||
computers.close(input.computer_id),
|
||||
);
|
||||
};
|
||||
@@ -1,161 +0,0 @@
|
||||
import { sessionEvidenceForExecution } from "../application/binary/SessionEvidenceReuse.js";
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import {
|
||||
retainedSummaryDelivery,
|
||||
withoutDeliveryDetail,
|
||||
type EvidenceToolFamilyOptions,
|
||||
} from "./retainedSummaryDelivery.js";
|
||||
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
} from "../ports/AnalysisProvider.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import { admitCompletedAnalysis } from "../application/investigation/admitCompletedAnalysis.js";
|
||||
import type { RecoveryAdmission } from "../application/investigation/InvestigationRetention.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Logger } from "pino";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { recordEvidenceSources } from "../application/investigation/recordEvidenceSources.js";
|
||||
import {
|
||||
reportOperationStart,
|
||||
reportOperationEnd,
|
||||
} from "./operationProgress.js";
|
||||
|
||||
interface EvidenceToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly evidenceById?: EvidenceToolFamilyOptions["evidenceById"];
|
||||
readonly admitRecovery?: RecoveryAdmission;
|
||||
readonly withAdmittedAnalysis: WithAdmittedAnalysis;
|
||||
readonly analysisForAdmission?: (
|
||||
analysis: AnalysisOperationPort,
|
||||
) => AnalysisOperationPort;
|
||||
readonly parametersForExecution?: (
|
||||
operation: Exclude<AnalysisOperation, "health">,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
) => Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
/** Register provider-backed contracts that return atomic Evidence observations. */
|
||||
export const registerEvidenceTools = (
|
||||
server: EvidenceMcpServer,
|
||||
contracts: readonly ToolContract<Exclude<AnalysisOperation, "health">>[],
|
||||
options: EvidenceToolRegistration,
|
||||
): void => {
|
||||
for (const contract of contracts) {
|
||||
const delivery =
|
||||
contract.retainedSummary === undefined
|
||||
? undefined
|
||||
: retainedSummaryDelivery(contract.name, options);
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async (input, context) => {
|
||||
const parameters = jsonObjectSchema.parse(input);
|
||||
const ready = delivery?.preflight(parameters) ?? ok(null);
|
||||
if (!ready.ok) return server.delivery.toCallToolResult(ready, contract);
|
||||
const admitted = await options.withAdmittedAnalysis(
|
||||
contract.name,
|
||||
context.mcpReq.signal,
|
||||
async (admittedAnalysis) => {
|
||||
const analysis =
|
||||
options.analysisForAdmission?.(admittedAnalysis) ??
|
||||
admittedAnalysis;
|
||||
const progress = mcpProgressReporter(context);
|
||||
await reportOperationStart(progress, contract.name);
|
||||
const providerParameters =
|
||||
contract.retainedSummary === undefined
|
||||
? parameters
|
||||
: withoutDeliveryDetail(parameters);
|
||||
const executionParameters =
|
||||
options.parametersForExecution?.(
|
||||
contract.name,
|
||||
providerParameters,
|
||||
) ?? providerParameters;
|
||||
const execution = await logToolExecution(
|
||||
options.logger,
|
||||
contract.name,
|
||||
() =>
|
||||
analysis.execute(contract.name, executionParameters, {
|
||||
signal: context.mcpReq.signal,
|
||||
progress,
|
||||
isOperationAdvertised: (operation) =>
|
||||
server.advertisesTool(operation),
|
||||
}),
|
||||
);
|
||||
await reportOperationEnd(progress, contract.name, execution.ok);
|
||||
if (!execution.ok)
|
||||
return server.delivery.toCallToolResult(execution, contract);
|
||||
const sourceEvidence = execution.value.sourceEvidence ?? [];
|
||||
const sourceRecorded = recordEvidenceSources(
|
||||
options.recordEvidence,
|
||||
sourceEvidence,
|
||||
);
|
||||
if (!sourceRecorded.ok)
|
||||
return server.delivery.toCallToolResult(sourceRecorded, contract);
|
||||
const evidenceParameters =
|
||||
contract.retainedSummary?.evidenceParameters === "omit-detail"
|
||||
? providerParameters
|
||||
: parameters;
|
||||
const observation = {
|
||||
...execution.value,
|
||||
subject:
|
||||
execution.value.subject === undefined
|
||||
? (options.activeTarget?.() ?? null)
|
||||
: execution.value.subject,
|
||||
};
|
||||
const reusable =
|
||||
options.evidenceById === undefined
|
||||
? undefined
|
||||
: sessionEvidenceForExecution(
|
||||
execution.value,
|
||||
contract.name,
|
||||
evidenceParameters,
|
||||
options.evidenceById,
|
||||
);
|
||||
if (reusable === undefined) {
|
||||
const admitted = admitCompletedAnalysis(
|
||||
contract.name,
|
||||
evidenceParameters,
|
||||
observation,
|
||||
options.admitRecovery,
|
||||
);
|
||||
if (!admitted.ok)
|
||||
return server.delivery.toCallToolResult(admitted, contract);
|
||||
}
|
||||
const evidence =
|
||||
reusable ??
|
||||
createAnalysisExecutionEvidence(
|
||||
contract.name,
|
||||
evidenceParameters,
|
||||
observation,
|
||||
"observed",
|
||||
);
|
||||
const projected =
|
||||
delivery?.projectEvidence(parameters, evidence) ?? ok(evidence);
|
||||
if (!projected.ok)
|
||||
return server.delivery.toCallToolResult(projected, contract);
|
||||
const recorded = options.recordEvidence?.(projected.value);
|
||||
return server.delivery.toEvidenceToolResult(
|
||||
projected.value,
|
||||
contract,
|
||||
recorded,
|
||||
);
|
||||
},
|
||||
);
|
||||
return admitted.ok
|
||||
? admitted.value
|
||||
: server.delivery.toCallToolResult(admitted, contract);
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1,60 +0,0 @@
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import type { AnalysisOperationPort } from "../ports/AnalysisProvider.js";
|
||||
import {
|
||||
MANAGED_TOOL_CONTRACTS,
|
||||
isManagedToolName,
|
||||
} from "../contracts/managed/managedToolContracts.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import { registerEvidenceTools } from "./registerEvidenceTools.js";
|
||||
import type { EvidenceToolFamilyOptions } from "./retainedSummaryDelivery.js";
|
||||
import { runManagedProviderExecution } from "../composition/directAnalysis.js";
|
||||
|
||||
/** Register execution-free managed PE/CLI inspection. */
|
||||
export const registerManagedTools = (
|
||||
server: EvidenceMcpServer,
|
||||
options: EvidenceToolFamilyOptions,
|
||||
): void => {
|
||||
let selectedManagedPath: string | undefined;
|
||||
const analysisForAdmission = (
|
||||
analysis: AnalysisOperationPort,
|
||||
): AnalysisOperationPort => ({
|
||||
execute: async (operation, parameters, executionOptions) => {
|
||||
if (!isManagedToolName(operation))
|
||||
return analysis.execute(operation, parameters, executionOptions);
|
||||
const requestedPath = parameters.path;
|
||||
const activeTarget = options.activeTarget?.();
|
||||
const path =
|
||||
typeof requestedPath === "string"
|
||||
? requestedPath
|
||||
: (selectedManagedPath ??
|
||||
(activeTarget?.format === "pe" && activeTarget.managed
|
||||
? activeTarget.path
|
||||
: undefined));
|
||||
if (path === undefined)
|
||||
return err(
|
||||
new AnalysisInputError(operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "missing_argument",
|
||||
message:
|
||||
"Provide a managed PE/CLI path or first select one with inspect_managed_artifact.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const execution = await runManagedProviderExecution(
|
||||
path,
|
||||
operation,
|
||||
executionOptions?.signal,
|
||||
parameters,
|
||||
);
|
||||
if (execution.ok && typeof requestedPath === "string")
|
||||
selectedManagedPath = requestedPath;
|
||||
return execution;
|
||||
},
|
||||
});
|
||||
registerEvidenceTools(server, MANAGED_TOOL_CONTRACTS, {
|
||||
...options,
|
||||
analysisForAdmission,
|
||||
});
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
|
||||
import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js";
|
||||
import { registerEvidenceTools } from "./registerEvidenceTools.js";
|
||||
import type { EvidenceToolFamilyOptions } from "./retainedSummaryDelivery.js";
|
||||
|
||||
/** Register macOS native contracts; Mach-O inspection can deliver a retained summary. */
|
||||
export const registerNativeTools = (
|
||||
server: EvidenceMcpServer,
|
||||
options: EvidenceToolFamilyOptions,
|
||||
): void => {
|
||||
registerEvidenceTools(server, NATIVE_TOOL_CONTRACTS, options);
|
||||
};
|
||||
@@ -1,12 +0,0 @@
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js";
|
||||
import { registerEvidenceTools } from "./registerEvidenceTools.js";
|
||||
import type { EvidenceToolFamilyOptions } from "./retainedSummaryDelivery.js";
|
||||
|
||||
/** Direct tools share Evidence recording/projection with the other provider-backed tools. */
|
||||
export const registerOfficialTools = (
|
||||
server: EvidenceMcpServer,
|
||||
options: EvidenceToolFamilyOptions,
|
||||
): void => {
|
||||
registerEvidenceTools(server, OFFICIAL_TOOL_CONTRACTS, options);
|
||||
};
|
||||
@@ -1,68 +0,0 @@
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
bindArtifactFileCleanup,
|
||||
} from "../resources/index.js";
|
||||
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import type { LifecycleToolRegistration } from "./registerSessionTools.js";
|
||||
|
||||
/** The shared session owns admission, checkpoint publication and reset completion. */
|
||||
export const registerResetInvestigationTool = ({
|
||||
server,
|
||||
session,
|
||||
artifactResources,
|
||||
closeProcessResources,
|
||||
}: Pick<
|
||||
LifecycleToolRegistration,
|
||||
"server" | "session" | "artifactResources" | "closeProcessResources"
|
||||
>): void => {
|
||||
const contract = toolContract("reset_investigation");
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async (input, context) => {
|
||||
const result = await session.resetInvestigation({
|
||||
...(input.save_path === undefined ? {} : { savePath: input.save_path }),
|
||||
overwrite: input.overwrite,
|
||||
signal: context.mcpReq.signal,
|
||||
retryCleanup: async () => {
|
||||
// Both adapter owners settle under the session's reset drain. Retry
|
||||
// keeps the shared artifact scope open for the next investigation.
|
||||
const [process, artifacts] = await Promise.all([
|
||||
closeProcessResources(),
|
||||
artifactResources.retryCleanup().then(
|
||||
() => ok(null),
|
||||
(cause: unknown) => {
|
||||
const observation = ArtifactReaderFailure.cleanupObservation(
|
||||
cause,
|
||||
"MCP artifact resources",
|
||||
);
|
||||
const error = new ProviderCleanupError(
|
||||
"rea",
|
||||
observation.resources,
|
||||
{ reason: observation.reason },
|
||||
{ cause, operation: contract.name },
|
||||
);
|
||||
bindArtifactFileCleanup(cause, error);
|
||||
return err(error);
|
||||
},
|
||||
),
|
||||
]);
|
||||
if (!process.ok && !artifacts.ok)
|
||||
return err(
|
||||
analysisErrorWithCleanupDependencies(
|
||||
process.error,
|
||||
artifacts.error,
|
||||
contract.name,
|
||||
),
|
||||
);
|
||||
return process.ok ? artifacts : process;
|
||||
},
|
||||
});
|
||||
return server.delivery.toCallToolResult(result, contract);
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -1,181 +0,0 @@
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import {
|
||||
resolveRizinCommandRequest,
|
||||
type ReverseEngineeringService,
|
||||
} from "../application/reverse/ReverseEngineeringService.js";
|
||||
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import type { ToolResultDelivery } from "./ToolResultDelivery.js";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { retainExternalMutationCancellation } from "./externalMutationAdmission.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>>,
|
||||
completionFailure: (
|
||||
value: Result<Value, AnalysisError>,
|
||||
error: AnalysisError,
|
||||
) => AnalysisError,
|
||||
) => Promise<Result<Result<Value, AnalysisError>, AnalysisError>>,
|
||||
evidenceById?: EvidenceLookup,
|
||||
): void => {
|
||||
const objdump = toolContract("inspect_with_objdump");
|
||||
const rizin = toolContract("execute_rizin_command");
|
||||
server.registerTool(
|
||||
objdump.name,
|
||||
toolRegistrationOptions(objdump),
|
||||
(input, context: ServerContext) =>
|
||||
runAdmittedToolOperation(
|
||||
{ delivery },
|
||||
withAdmittedAnalysis,
|
||||
objdump.name,
|
||||
context.mcpReq.signal,
|
||||
async () => {
|
||||
const result = await logToolExecution(logger, objdump.name, () =>
|
||||
service.inspectWithObjdump(
|
||||
input,
|
||||
{
|
||||
signal: context.mcpReq.signal,
|
||||
},
|
||||
{ recordEvidence, evidenceById },
|
||||
),
|
||||
);
|
||||
if (!result.ok)
|
||||
return delivery.toPartialErrorToolResult(
|
||||
result.error,
|
||||
objdump.returnsTargetContent,
|
||||
recordEvidence,
|
||||
);
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value,
|
||||
objdump,
|
||||
recordEvidence?.(result.value),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
server.registerTool(
|
||||
rizin.name,
|
||||
toolRegistrationOptions(rizin),
|
||||
async (input, context: ServerContext) => {
|
||||
const parsed = resolveRizinCommandRequest(input);
|
||||
if (parsed.ok && withAdmittedExternalMutation !== undefined) {
|
||||
const cleanup = await service.retryCleanup(rizin.name);
|
||||
if (!cleanup.ok)
|
||||
return delivery.toPartialErrorToolResult(
|
||||
cleanup.error,
|
||||
rizin.returnsTargetContent,
|
||||
recordEvidence,
|
||||
);
|
||||
const admitted = await withAdmittedExternalMutation(
|
||||
parsed.value.path,
|
||||
context.mcpReq.signal,
|
||||
async () => {
|
||||
invalidateSnapshotForExternalMutation?.();
|
||||
return logToolExecution(logger, rizin.name, () =>
|
||||
service.executeRizinCommandValidated(parsed.value, {
|
||||
signal: context.mcpReq.signal,
|
||||
}),
|
||||
);
|
||||
},
|
||||
(value, cause) => {
|
||||
if (cause instanceof AnalysisCancelledError) {
|
||||
return retainExternalMutationCancellation(
|
||||
value,
|
||||
cause,
|
||||
(evidence) => evidence,
|
||||
);
|
||||
}
|
||||
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.capturedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: cause.capturedOutput }),
|
||||
...(observation === undefined
|
||||
? {}
|
||||
: { partialObservation: observation }),
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
if (!admitted.ok)
|
||||
return delivery.toPartialErrorToolResult(
|
||||
admitted.error,
|
||||
rizin.returnsTargetContent,
|
||||
recordEvidence,
|
||||
);
|
||||
const result = admitted.value;
|
||||
if (!result.ok)
|
||||
return delivery.toPartialErrorToolResult(
|
||||
result.error,
|
||||
rizin.returnsTargetContent,
|
||||
recordEvidence,
|
||||
);
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value,
|
||||
rizin,
|
||||
recordEvidence?.(result.value),
|
||||
);
|
||||
}
|
||||
return runAdmittedToolOperation(
|
||||
{ delivery },
|
||||
withAdmittedAnalysis,
|
||||
rizin.name,
|
||||
context.mcpReq.signal,
|
||||
async () => {
|
||||
if (invalidateSnapshotForExternalMutation !== undefined && parsed.ok)
|
||||
invalidateSnapshotForExternalMutation();
|
||||
const result = await logToolExecution(logger, rizin.name, () =>
|
||||
parsed.ok
|
||||
? service.executeRizinCommandValidated(parsed.value, {
|
||||
signal: context.mcpReq.signal,
|
||||
})
|
||||
: Promise.resolve(parsed),
|
||||
);
|
||||
if (!result.ok)
|
||||
return delivery.toPartialErrorToolResult(
|
||||
result.error,
|
||||
rizin.returnsTargetContent,
|
||||
recordEvidence,
|
||||
);
|
||||
return delivery.toEvidenceToolResult(
|
||||
result.value,
|
||||
rizin,
|
||||
recordEvidence?.(result.value),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -5,38 +5,29 @@ import type { ArtifactResourceScope } from "../resources/index.js";
|
||||
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
|
||||
import { ProcessCaptureResourceScope } from "../process/capture/ProcessCaptureLifecycle.js";
|
||||
import { ProcessCaptureError } from "../process/capture/ProcessCaptureError.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { ProviderAvailability } from "../ports/AnalysisProvider.js";
|
||||
import { registerCloseLifecycleTool } from "./registerCloseLifecycleTool.js";
|
||||
import { registerResetInvestigationTool } from "./registerResetInvestigationTool.js";
|
||||
import { registerServiceTools } from "./serviceToolBindings.js";
|
||||
import type { SessionLifecycleOptions } from "./sessionLifecycle.js";
|
||||
import type { SessionStatusToolOptions } from "./sessionStatusTool.js";
|
||||
import { sessionAvailabilityPolicy } from "./sessionAvailabilityPolicy.js";
|
||||
import type { AvailabilityPolicy } from "../application/CapabilityInventory.js";
|
||||
import { withAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { errorMessage } from "../kernel/errorMessage.js";
|
||||
|
||||
export interface LifecycleToolRegistration extends CapabilityAvailabilityProbes {
|
||||
readonly server: EvidenceMcpServer;
|
||||
readonly session: BinarySessionPort;
|
||||
readonly logger: Logger;
|
||||
readonly closeContract: ReturnType<typeof toolContract<"close_binary">>;
|
||||
readonly startedAt: string;
|
||||
readonly availabilityPolicy: () => AvailabilityPolicy;
|
||||
readonly artifactResources: ArtifactResourceScope;
|
||||
readonly closeProcessResources: () => Promise<Result<null, AnalysisError>>;
|
||||
}
|
||||
/** What the lifecycle and status tools of one session need. */
|
||||
interface LifecycleToolRegistration
|
||||
extends SessionStatusToolOptions, SessionLifecycleOptions {}
|
||||
|
||||
/** Close, reset and status run outside analysis admission; the session orders them. */
|
||||
const registerLifecycleTools = (
|
||||
registration: LifecycleToolRegistration,
|
||||
): void => {
|
||||
registerCloseLifecycleTool(registration);
|
||||
registerResetInvestigationTool(registration);
|
||||
registerServiceTools(
|
||||
registration.server,
|
||||
{ sessionStatus: registration },
|
||||
{ sessionLifecycle: registration, sessionStatus: registration },
|
||||
{ logger: registration.logger },
|
||||
);
|
||||
};
|
||||
@@ -58,14 +49,12 @@ export const registerSessionTools = (
|
||||
logger: Logger,
|
||||
options: SessionToolOptions,
|
||||
): void => {
|
||||
const closeContract = toolContract("close_binary");
|
||||
const processResources = new ProcessCaptureResourceScope();
|
||||
registerLifecycleTools({
|
||||
...options,
|
||||
server,
|
||||
session,
|
||||
logger,
|
||||
closeContract,
|
||||
startedAt: options.startedAt ?? new Date().toISOString(),
|
||||
availabilityPolicy: sessionAvailabilityPolicy(
|
||||
options.availabilityPolicy,
|
||||
|
||||
@@ -4,21 +4,9 @@ import {
|
||||
requireAnalysisViewRetention,
|
||||
summarizeRetainedAnalysis,
|
||||
} from "../application/analysisView/AnalysisViewService.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
|
||||
/** Registration inputs shared by provider-backed Evidence tool families. */
|
||||
export interface EvidenceToolFamilyOptions {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly evidenceById?: EvidenceLookup | undefined;
|
||||
readonly withAdmittedAnalysis: WithAdmittedAnalysis;
|
||||
}
|
||||
|
||||
type Parameters = Readonly<Record<string, JsonValue>>;
|
||||
|
||||
@@ -28,7 +16,10 @@ type Parameters = Readonly<Record<string, JsonValue>>;
|
||||
*/
|
||||
export const retainedSummaryDelivery = (
|
||||
operation: string,
|
||||
options: Pick<EvidenceToolFamilyOptions, "recordEvidence" | "evidenceById">,
|
||||
options: {
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly evidenceById?: EvidenceLookup | undefined;
|
||||
},
|
||||
) => {
|
||||
const retention = {
|
||||
recordEvidence: options.recordEvidence,
|
||||
|
||||
@@ -127,12 +127,17 @@ import type { FridaInstrumentationService } from "../application/frida/FridaInst
|
||||
import type { BrowserObservationPort } from "../ports/BrowserObservationPort.js";
|
||||
import type { GdbSessionManager } from "../gdb/GdbSessionManager.js";
|
||||
import type { RizinDebugSessionManager } from "../rizin/RizinDebugSessionManager.js";
|
||||
import {
|
||||
resolveRizinCommandRequest,
|
||||
type ReverseEngineeringService,
|
||||
} from "../application/reverse/ReverseEngineeringService.js";
|
||||
import {
|
||||
GDB_SESSION_TOOLS,
|
||||
RIZIN_DEBUG_SESSION_TOOLS,
|
||||
unknownDebuggerSessionError,
|
||||
} from "../domain/debuggerSessionErrors.js";
|
||||
import type { ExternalMutationAdmission } from "./externalMutationAdmission.js";
|
||||
import type { EvidenceCommand } from "./externalMutationToolHandler.js";
|
||||
import {
|
||||
optionalProviderUnavailable,
|
||||
type OptionalProviderLoadFailure,
|
||||
@@ -174,8 +179,20 @@ import type { ArtifactResourceScope } from "../resources/index.js";
|
||||
import {
|
||||
CommittedValue,
|
||||
DetailedFailure,
|
||||
ForwardedValue,
|
||||
ReducibleValue,
|
||||
type ValueOutcome,
|
||||
type ValueToolRequest,
|
||||
} from "./contractToolHandler.js";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import type { ForwardedResult } from "../application/desktop/DesktopBuildComputers.js";
|
||||
import { DesktopBuildSteps } from "../application/desktop/DesktopBuildSteps.js";
|
||||
import type { ProgressReporter } from "../ports/ProgressReporter.js";
|
||||
import {
|
||||
redactedResult,
|
||||
withHeartbeat,
|
||||
type DesktopBuildToolComputers,
|
||||
} from "./desktopBuildDelivery.js";
|
||||
import {
|
||||
getNavigationContext,
|
||||
inspectAddressContext,
|
||||
@@ -202,7 +219,22 @@ import {
|
||||
type ContractToolDependencies,
|
||||
} from "./contractToolBindings.js";
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import type {
|
||||
ProviderOperation,
|
||||
ProviderOperationOptions,
|
||||
} from "./providerOperationToolHandler.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import { retainedSummaryDelivery } from "./retainedSummaryDelivery.js";
|
||||
import {
|
||||
CLOSE_RETRY,
|
||||
closeWithProcessResources,
|
||||
resetCleanupRetry,
|
||||
type SessionLifecycleOptions,
|
||||
} from "./sessionLifecycle.js";
|
||||
import {
|
||||
reportOperationEnd,
|
||||
reportOperationStart,
|
||||
} from "./operationProgress.js";
|
||||
import {
|
||||
readSessionStatus,
|
||||
type SessionStatusToolOptions,
|
||||
@@ -255,6 +287,31 @@ export interface RizinDebugToolOptions {
|
||||
readonly session: ExternalMutationAdmission | undefined;
|
||||
}
|
||||
|
||||
/** objdump and Rizin commands, and the session a Rizin command may change. */
|
||||
export interface ReverseEngineeringToolOptions {
|
||||
readonly service: Pick<
|
||||
ReverseEngineeringService,
|
||||
"inspectWithObjdump" | "executeRizinCommandValidated" | "retryCleanup"
|
||||
>;
|
||||
readonly session: ExternalMutationAdmission | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a Rizin request and settle earlier inspection cleanup before
|
||||
* external-mutation admission, so either refusal leaves the bound target open.
|
||||
*/
|
||||
const prepareRizinCommand =
|
||||
(service: ReverseEngineeringToolOptions["service"]) =>
|
||||
async (input: unknown): Promise<Result<EvidenceCommand, AnalysisError>> => {
|
||||
const request = resolveRizinCommandRequest(input);
|
||||
if (!request.ok) return request;
|
||||
const cleanup = await service.retryCleanup("execute_rizin_command");
|
||||
if (!cleanup.ok) return cleanup;
|
||||
return ok((signal) =>
|
||||
service.executeRizinCommandValidated(request.value, { signal }),
|
||||
);
|
||||
};
|
||||
|
||||
/** GDB sessions a manager owns and the session their commands may change. */
|
||||
export interface GdbToolOptions {
|
||||
readonly manager: Pick<
|
||||
@@ -297,6 +354,24 @@ export interface JavaScriptRuntimeToolOptions {
|
||||
readonly loadFailure?: OptionalProviderLoadFailure | undefined;
|
||||
}
|
||||
|
||||
/** One family's provider operations and how they run. */
|
||||
export interface ProviderOperationToolOptions extends ProviderOperationOptions {
|
||||
readonly contracts: readonly ToolContract<ProviderOperation>[];
|
||||
}
|
||||
|
||||
/** The tools that drive build computers. */
|
||||
type DesktopBuildTool =
|
||||
| "start_build_computer"
|
||||
| "act_on_build_computer"
|
||||
| "start_build_capture"
|
||||
| "mark_build_checkpoint"
|
||||
| "stop_build_capture"
|
||||
| "export_build_environment"
|
||||
| "check_build_task"
|
||||
| "measure_build_task"
|
||||
| "record_build_consent"
|
||||
| "close_build_computer";
|
||||
|
||||
/** The artifact resource scope application workflows read caller-named files under. */
|
||||
export interface ApplicationWorkflowToolOptions {
|
||||
readonly resources: ArtifactResourceScope;
|
||||
@@ -1279,6 +1354,26 @@ const SERVICE_TOOL_BINDINGS = {
|
||||
value: async (input) => session.verifyUnknownResolution(input.unknown_id),
|
||||
},
|
||||
})) satisfies Bind<SessionDerivedToolOptions>,
|
||||
// objdump inspects under analysis admission. A Rizin command may change
|
||||
// the bound artifact, so it runs under external-mutation admission once
|
||||
// its request is valid and earlier inspection cleanup has settled; a
|
||||
// refusal before then leaves the bound target open.
|
||||
reverseEngineering: (({ service, session }, retention) => ({
|
||||
inspect_with_objdump: {
|
||||
admission: "sdk",
|
||||
run: (input, options) =>
|
||||
service.inspectWithObjdump(input, options, retention),
|
||||
},
|
||||
execute_rizin_command: {
|
||||
admission: "sdk",
|
||||
session,
|
||||
mutation: {
|
||||
kind: "evidence",
|
||||
retryCleanup: () => service.retryCleanup("execute_rizin_command"),
|
||||
prepare: prepareRizinCommand(service),
|
||||
},
|
||||
},
|
||||
})) satisfies Bind<ReverseEngineeringToolOptions>,
|
||||
// Rizin debugger sessions may change the bound artifact; each command
|
||||
// runs under external-mutation admission and keeps a failed cleanup owned.
|
||||
rizinDebug: (({ manager, session }) => {
|
||||
@@ -1610,6 +1705,60 @@ const SERVICE_TOOL_BINDINGS = {
|
||||
captureSessionProcessScenario(options, input, request),
|
||||
},
|
||||
})) satisfies Bind<ProcessSessionCaptureOptions>,
|
||||
// Close and reset order themselves in the session, so they run outside
|
||||
// analysis admission; process-capture and artifact cleanup settle with them.
|
||||
sessionLifecycle: ((options) => {
|
||||
const { session } = options;
|
||||
const close = closeWithProcessResources(options);
|
||||
return {
|
||||
close_binary: {
|
||||
admission: "sdk",
|
||||
value: async (input, { progress }) => {
|
||||
const snapshotPath = input.snapshot_path;
|
||||
if (snapshotPath === undefined) {
|
||||
// Enqueue the transition before awaiting progress transport so a
|
||||
// later open request cannot overtake this close.
|
||||
const closing = close(() =>
|
||||
session.close({ progress, cleanupRetry: CLOSE_RETRY }),
|
||||
);
|
||||
await reportOperationStart(progress, "close_binary");
|
||||
const closed = await closing;
|
||||
await reportOperationEnd(progress, "close_binary", closed.ok);
|
||||
return closed;
|
||||
}
|
||||
const closing = close(
|
||||
() =>
|
||||
session.closeWithSnapshot(snapshotPath, input.overwrite, {
|
||||
progress,
|
||||
cleanupRetry: CLOSE_RETRY,
|
||||
}),
|
||||
(receipt) => receipt,
|
||||
);
|
||||
await reportOperationStart(
|
||||
progress,
|
||||
"close_binary",
|
||||
"saving snapshot; closing provider",
|
||||
);
|
||||
const closed = await closing;
|
||||
await reportOperationEnd(progress, "close_binary", closed.ok);
|
||||
return closed.ok ? ok({ ...closed.value }) : closed;
|
||||
},
|
||||
},
|
||||
// The session owns admission, checkpoint publication and completion.
|
||||
reset_investigation: {
|
||||
admission: "sdk",
|
||||
value: (input, { signal }) =>
|
||||
session.resetInvestigation({
|
||||
...(input.save_path === undefined
|
||||
? {}
|
||||
: { savePath: input.save_path }),
|
||||
overwrite: input.overwrite,
|
||||
signal,
|
||||
retryCleanup: resetCleanupRetry(options, "reset_investigation"),
|
||||
}),
|
||||
},
|
||||
};
|
||||
}) satisfies Bind<SessionLifecycleOptions>,
|
||||
sessionStatus: ((options) => ({
|
||||
binary_session: {
|
||||
admission: "sdk",
|
||||
@@ -1727,6 +1876,136 @@ const SERVICE_TOOL_BINDINGS = {
|
||||
observeJavaScriptRuntime(runtime, input, options),
|
||||
},
|
||||
})) satisfies Bind<JavaScriptRuntimeToolOptions>,
|
||||
// Provider operations whose observation becomes atomic Evidence, run on
|
||||
// the analysis admission grants; each family routes its own operations.
|
||||
providerOperations: (({ contracts, ...options }): ContractToolBindings =>
|
||||
Object.fromEntries(
|
||||
contracts.map((contract) => [
|
||||
contract.name,
|
||||
{
|
||||
admission: "sdk",
|
||||
provider: { ...options, operation: contract.name },
|
||||
},
|
||||
]),
|
||||
)) satisfies Bind<ProviderOperationToolOptions>,
|
||||
// Build computer sessions and the build steps on them. Each tool parses
|
||||
// its own request so a refusal names the field; long steps report a
|
||||
// heartbeat so a client's request timeout can reset; no response, refusals
|
||||
// included, shows a typed secret's value.
|
||||
desktopBuild: ((computers) => {
|
||||
const steps = new DesktopBuildSteps(computers);
|
||||
const presentResult = (result: CallToolResult) =>
|
||||
redactedResult(result, computers.redaction);
|
||||
const tool = <Schema extends z.ZodType>(
|
||||
contract: { readonly name: string; readonly inputSchema: Schema },
|
||||
run: (
|
||||
input: z.output<Schema>,
|
||||
request: ValueToolRequest,
|
||||
) => Promise<ValueOutcome>,
|
||||
) => {
|
||||
return {
|
||||
admission: "application" as const,
|
||||
presentResult,
|
||||
value: async (raw: unknown, request: ValueToolRequest) => {
|
||||
const parsed = z.safeParse(contract.inputSchema, raw);
|
||||
return parsed.success
|
||||
? run(parsed.data, request)
|
||||
: err(
|
||||
analysisInputErrorFromIssues(
|
||||
contract.name,
|
||||
parsed.error.issues,
|
||||
raw,
|
||||
{ cause: parsed.error },
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
};
|
||||
const heartbeat = <Value>(
|
||||
{ progress }: ValueToolRequest,
|
||||
phase: DesktopBuildTool,
|
||||
run: (progress: ProgressReporter) => Promise<Value>,
|
||||
) => withHeartbeat(progress, phase, computers.progressMs, run);
|
||||
// A forwarded driver answer, such as a screenshot, follows REA's JSON.
|
||||
const forwarded = (
|
||||
result: Result<ForwardedResult<JsonValue>, AnalysisError>,
|
||||
): ValueOutcome =>
|
||||
result.ok
|
||||
? ok(new ForwardedValue(result.value.value, result.value.content))
|
||||
: result;
|
||||
return {
|
||||
start_build_computer: tool(
|
||||
toolContract("start_build_computer"),
|
||||
async (input, { signal, progress }) =>
|
||||
forwarded(await computers.start(input, signal, progress)),
|
||||
),
|
||||
// An action can wait for the call before it on its computer, and a
|
||||
// reset for the relaunched app, which can take minutes.
|
||||
act_on_build_computer: tool(
|
||||
toolContract("act_on_build_computer"),
|
||||
async (input, request) =>
|
||||
forwarded(
|
||||
await heartbeat(request, "act_on_build_computer", () =>
|
||||
computers.act(input, request.signal),
|
||||
),
|
||||
),
|
||||
),
|
||||
start_build_capture: tool(
|
||||
toolContract("start_build_capture"),
|
||||
async (input, request) =>
|
||||
forwarded(
|
||||
await heartbeat(request, "start_build_capture", () =>
|
||||
steps.startCapture(input, request.signal),
|
||||
),
|
||||
),
|
||||
),
|
||||
mark_build_checkpoint: tool(
|
||||
toolContract("mark_build_checkpoint"),
|
||||
(input, request) =>
|
||||
heartbeat(request, "mark_build_checkpoint", () =>
|
||||
steps.markCheckpoint(input, request.signal),
|
||||
),
|
||||
),
|
||||
stop_build_capture: tool(
|
||||
toolContract("stop_build_capture"),
|
||||
(input, request) =>
|
||||
heartbeat(request, "stop_build_capture", () =>
|
||||
steps.stopCapture(input, request.signal),
|
||||
),
|
||||
),
|
||||
export_build_environment: tool(
|
||||
toolContract("export_build_environment"),
|
||||
(input, request) =>
|
||||
heartbeat(request, "export_build_environment", () =>
|
||||
steps.exportEnvironment(input, request.signal),
|
||||
),
|
||||
),
|
||||
check_build_task: tool(
|
||||
toolContract("check_build_task"),
|
||||
(input, request) =>
|
||||
heartbeat(request, "check_build_task", (progress) =>
|
||||
steps.checkTask(input, request.signal, progress),
|
||||
),
|
||||
),
|
||||
// Solves run one at a time for minutes each, so progress keeps the
|
||||
// client waiting.
|
||||
measure_build_task: tool(
|
||||
toolContract("measure_build_task"),
|
||||
(input, request) =>
|
||||
heartbeat(request, "measure_build_task", (progress) =>
|
||||
computers.measure(input, request.signal, progress),
|
||||
),
|
||||
),
|
||||
record_build_consent: tool(
|
||||
toolContract("record_build_consent"),
|
||||
(input, { signal }) => steps.recordConsent(input, signal),
|
||||
),
|
||||
close_build_computer: tool(
|
||||
toolContract("close_build_computer"),
|
||||
(input) => computers.close(input.computer_id),
|
||||
),
|
||||
};
|
||||
}) satisfies Bind<DesktopBuildToolComputers>,
|
||||
// Provider-free access to the guided prompts this server advertises.
|
||||
guidedWorkflows: ((prompts) => ({
|
||||
guided_workflows: {
|
||||
|
||||
@@ -1,21 +1,32 @@
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
|
||||
import {
|
||||
retainSavedAnalysisSnapshot,
|
||||
type SavedAnalysisSnapshot,
|
||||
} from "../domain/savedAnalysisSnapshot.js";
|
||||
import {
|
||||
reportOperationEnd,
|
||||
reportOperationStart,
|
||||
} from "./operationProgress.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js";
|
||||
import type { AnalysisCleanupRetry } from "../domain/analysisErrorRecovery.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import type { LifecycleToolRegistration } from "./registerSessionTools.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { errorMessage } from "../kernel/errorMessage.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
bindArtifactFileCleanup,
|
||||
type ArtifactResourceScope,
|
||||
} from "../resources/index.js";
|
||||
|
||||
/**
|
||||
* The session whose target the lifecycle tools close or reset, and the
|
||||
* adapter-owned resources that close with it.
|
||||
*/
|
||||
export interface SessionLifecycleOptions {
|
||||
readonly session: BinarySessionPort;
|
||||
readonly logger: Logger;
|
||||
readonly artifactResources: ArtifactResourceScope;
|
||||
readonly closeProcessResources: () => Promise<Result<null, AnalysisError>>;
|
||||
}
|
||||
|
||||
/** Expected lifecycle failures keep the same typed result when a child rejects. */
|
||||
const closeResult = async <Value>(
|
||||
@@ -29,22 +40,24 @@ const closeResult = async <Value>(
|
||||
}
|
||||
};
|
||||
|
||||
/** This tool retries the session and process-capture cleanup it retains. */
|
||||
const CLOSE_RETRY: AnalysisCleanupRetry = { operation: "close_binary" };
|
||||
/** close_binary retries the session and process-capture cleanup it retains. */
|
||||
export const CLOSE_RETRY: AnalysisCleanupRetry = { operation: "close_binary" };
|
||||
|
||||
/** The process-capture scope keeps failed leases for the next close_binary. */
|
||||
const retainedProcessCleanup = (error: AnalysisError): AnalysisError =>
|
||||
error.cleanupIncomplete ? error.bindCleanupRetry(CLOSE_RETRY) : error;
|
||||
|
||||
/** Register provider cleanup and optional pre-close snapshot persistence. */
|
||||
export const registerCloseLifecycleTool = ({
|
||||
server,
|
||||
session,
|
||||
logger,
|
||||
closeContract,
|
||||
closeProcessResources,
|
||||
}: LifecycleToolRegistration): void => {
|
||||
const closeWithResources = async <Value>(
|
||||
/**
|
||||
* Close the session together with the process-capture resources it owns.
|
||||
* Both settle; a failed resource cleanup is kept for the next close_binary,
|
||||
* and a saved snapshot stays reported when only the resources failed.
|
||||
*/
|
||||
export const closeWithProcessResources =
|
||||
({
|
||||
logger,
|
||||
closeProcessResources,
|
||||
}: Pick<SessionLifecycleOptions, "logger" | "closeProcessResources">) =>
|
||||
async <Value>(
|
||||
closeSession: () => Promise<Result<Value, AnalysisError>>,
|
||||
savedSnapshot?: (value: Value) => SavedAnalysisSnapshot,
|
||||
): Promise<Result<Value, AnalysisError>> => {
|
||||
@@ -92,46 +105,50 @@ export const registerCloseLifecycleTool = ({
|
||||
: retainSavedAnalysisSnapshot(retained, savedSnapshot(closed.value)),
|
||||
);
|
||||
};
|
||||
server.registerTool(
|
||||
closeContract.name,
|
||||
toolRegistrationOptions(closeContract),
|
||||
async (input, context) => {
|
||||
const progress = mcpProgressReporter(context);
|
||||
const snapshotPath = input.snapshot_path;
|
||||
if (snapshotPath === undefined) {
|
||||
// Enqueue the lifecycle transition before awaiting progress transport so
|
||||
// a later open request cannot overtake this close.
|
||||
const closing = logToolExecution(logger, closeContract.name, () =>
|
||||
closeWithResources(() =>
|
||||
session.close({ progress, cleanupRetry: CLOSE_RETRY }),
|
||||
),
|
||||
);
|
||||
await reportOperationStart(progress, closeContract.name);
|
||||
const closed = await closing;
|
||||
await reportOperationEnd(progress, closeContract.name, closed.ok);
|
||||
return server.delivery.toCallToolResult(closed, closeContract);
|
||||
}
|
||||
const closing = logToolExecution(logger, closeContract.name, () =>
|
||||
closeWithResources(
|
||||
() =>
|
||||
session.closeWithSnapshot(snapshotPath, input.overwrite, {
|
||||
progress,
|
||||
cleanupRetry: CLOSE_RETRY,
|
||||
}),
|
||||
(receipt) => receipt,
|
||||
|
||||
/**
|
||||
* Retry the adapter-owned cleanup a reset joins under the session's drain.
|
||||
* Retry keeps the shared artifact scope open for the next investigation.
|
||||
*/
|
||||
export const resetCleanupRetry =
|
||||
(
|
||||
{
|
||||
artifactResources,
|
||||
closeProcessResources,
|
||||
}: Pick<
|
||||
SessionLifecycleOptions,
|
||||
"artifactResources" | "closeProcessResources"
|
||||
>,
|
||||
operation: string,
|
||||
) =>
|
||||
async (): Promise<Result<null, AnalysisError>> => {
|
||||
const [process, artifacts] = await Promise.all([
|
||||
closeProcessResources(),
|
||||
artifactResources.retryCleanup().then(
|
||||
() => ok(null),
|
||||
(cause: unknown) => {
|
||||
const observation = ArtifactReaderFailure.cleanupObservation(
|
||||
cause,
|
||||
"MCP artifact resources",
|
||||
);
|
||||
const error = new ProviderCleanupError(
|
||||
"rea",
|
||||
observation.resources,
|
||||
{ reason: observation.reason },
|
||||
{ cause, operation },
|
||||
);
|
||||
bindArtifactFileCleanup(cause, error);
|
||||
return err(error);
|
||||
},
|
||||
),
|
||||
]);
|
||||
if (!process.ok && !artifacts.ok)
|
||||
return err(
|
||||
analysisErrorWithCleanupDependencies(
|
||||
process.error,
|
||||
artifacts.error,
|
||||
operation,
|
||||
),
|
||||
);
|
||||
await reportOperationStart(
|
||||
progress,
|
||||
closeContract.name,
|
||||
"saving snapshot; closing provider",
|
||||
);
|
||||
const closed = await closing;
|
||||
await reportOperationEnd(progress, closeContract.name, closed.ok);
|
||||
return server.delivery.toCallToolResult(
|
||||
closed.ok ? ok({ ...closed.value }) : closed,
|
||||
closeContract,
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
return process.ok ? artifacts : process;
|
||||
};
|
||||
+8
-2
@@ -104,10 +104,16 @@ export default {
|
||||
name: "captureProviderEnvironment",
|
||||
},
|
||||
]),
|
||||
...mutationRanges("src/server/registerReverseEngineeringTools.ts", [
|
||||
...mutationRanges("src/server/externalMutationToolHandler.ts", [
|
||||
{
|
||||
kind: "declaration",
|
||||
name: "registerReverseEngineeringTools",
|
||||
name: "createExternalMutationToolHandler",
|
||||
},
|
||||
]),
|
||||
...mutationRanges("src/server/serviceToolBindings.ts", [
|
||||
{
|
||||
kind: "declaration",
|
||||
name: "prepareRizinCommand",
|
||||
},
|
||||
]),
|
||||
...mutationRanges("src/gdb/GdbSessionManager.ts", [
|
||||
|
||||
@@ -16,7 +16,7 @@ import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js"
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
|
||||
import { withAdmittedAnalysis } from "../../../src/server/analysisAdmission.js";
|
||||
import { registerEvidenceTools } from "../../../src/server/registerEvidenceTools.js";
|
||||
import { registerServiceTools } from "../../../src/server/serviceToolBindings.js";
|
||||
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -141,12 +141,16 @@ for (const missingSource of [false, true])
|
||||
session.recordEvidence.bind(session),
|
||||
createToolResultDelivery(undefined),
|
||||
);
|
||||
registerEvidenceTools(
|
||||
registerServiceTools(
|
||||
server,
|
||||
[toolContract("inspect_managed_artifact")],
|
||||
{
|
||||
providerOperations: {
|
||||
contracts: [toolContract("inspect_managed_artifact")],
|
||||
activeTarget: () => session.activeTarget(),
|
||||
},
|
||||
},
|
||||
{
|
||||
logger: silentLogger,
|
||||
activeTarget: () => session.activeTarget(),
|
||||
recordEvidence: session.recordEvidence.bind(session),
|
||||
withAdmittedAnalysis: withAdmittedAnalysis({
|
||||
kind: "session",
|
||||
|
||||
@@ -3,7 +3,6 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import pino from "pino";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
|
||||
import { registerReverseEngineeringTools } from "../../../src/server/registerReverseEngineeringTools.js";
|
||||
import {
|
||||
registerServiceTools,
|
||||
type GdbToolOptions,
|
||||
@@ -85,20 +84,13 @@ const connect = async (retain = true) => {
|
||||
);
|
||||
const service = new TestReverseEngineeringService({ runOwned: run });
|
||||
const logger = pino({ enabled: false });
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
logger,
|
||||
delivery,
|
||||
retain ? record : undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
retain ? lookup : undefined,
|
||||
);
|
||||
registerServiceTools(
|
||||
server,
|
||||
{ analysisView: {}, gdb: { manager, session: undefined } },
|
||||
{
|
||||
analysisView: {},
|
||||
gdb: { manager, session: undefined },
|
||||
reverseEngineering: { service, session: undefined },
|
||||
},
|
||||
{
|
||||
logger,
|
||||
evidenceById: retain ? lookup : undefined,
|
||||
|
||||
@@ -239,3 +239,32 @@ mcpTest(
|
||||
]).toEqual([true, true, true, true]);
|
||||
},
|
||||
);
|
||||
|
||||
mcpTest(
|
||||
"binds a provider operation only to the contract of the same name",
|
||||
() => {
|
||||
const mismatched: ContractToolBindings = {
|
||||
xrefs: {
|
||||
admission: "sdk",
|
||||
// @ts-expect-error A provider binding runs only its own operation.
|
||||
provider: { operation: "extract_artifact", activeTarget: undefined },
|
||||
},
|
||||
};
|
||||
const notProvider: ContractToolBindings = {
|
||||
inspect_pe_imports: {
|
||||
admission: "sdk",
|
||||
// @ts-expect-error A tool that is no provider operation binds no provider.
|
||||
provider: { operation: "xrefs", activeTarget: undefined },
|
||||
},
|
||||
};
|
||||
expect(() =>
|
||||
registerContractTools(evidenceServer(), mismatched, {
|
||||
logger: silentLogger,
|
||||
withAdmittedAnalysis: async () => {
|
||||
throw new Error("not called");
|
||||
},
|
||||
}),
|
||||
).toThrow("MCP tool xrefs binds provider operation extract_artifact");
|
||||
expect(notProvider).toBeDefined();
|
||||
},
|
||||
);
|
||||
@@ -23,7 +23,9 @@ import {
|
||||
} from "../../../src/domain/jsonValue.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { registerOfficialTools } from "../../../src/server/registerOfficialTools.js";
|
||||
import { registerServiceTools } from "../../../src/server/serviceToolBindings.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../../../src/contracts/officialToolContracts.js";
|
||||
import type { WithAdmittedAnalysis } from "../../../src/server/analysisAdmission.js";
|
||||
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { mcpResponseOverflowProjection } from "../../../src/server/ToolResultDelivery.js";
|
||||
import {
|
||||
@@ -61,20 +63,29 @@ const callPseudoCode = async (
|
||||
recordEvidence,
|
||||
delivery,
|
||||
);
|
||||
registerOfficialTools(server, {
|
||||
logger: silentLogger,
|
||||
activeTarget: undefined,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis: async (_operationName, _signal, operation) =>
|
||||
ok(
|
||||
await operation({
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
ok(createAnalysisExecution(payload, provider, { rawResult })),
|
||||
),
|
||||
}),
|
||||
),
|
||||
});
|
||||
const withAdmittedAnalysis: WithAdmittedAnalysis = async (
|
||||
_operationName,
|
||||
_signal,
|
||||
operation,
|
||||
) =>
|
||||
ok(
|
||||
await operation({
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
ok(createAnalysisExecution(payload, provider, { rawResult })),
|
||||
),
|
||||
}),
|
||||
);
|
||||
registerServiceTools(
|
||||
server,
|
||||
{
|
||||
providerOperations: {
|
||||
contracts: OFFICIAL_TOOL_CONTRACTS,
|
||||
activeTarget: undefined,
|
||||
},
|
||||
},
|
||||
{ logger: silentLogger, recordEvidence, withAdmittedAnalysis },
|
||||
);
|
||||
const client = new Client({ name: "complete-evidence-client", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
|
||||
@@ -191,15 +191,17 @@ it.each(["returned", "thrown", "synchronous"] as const)(
|
||||
});
|
||||
const callClose = () =>
|
||||
resources.client.callTool({ name: "close_binary", arguments: {} });
|
||||
const delivery = vi.spyOn(ToolResultDelivery.prototype, "toCallToolResult");
|
||||
const delivery = vi.spyOn(
|
||||
ToolResultDelivery.prototype,
|
||||
"toPartialErrorToolResult",
|
||||
);
|
||||
|
||||
await withVerifierCleanup(async () => {
|
||||
const failed = parseMcpToolError(await callClose());
|
||||
const firstWire = JSON.stringify(failed);
|
||||
const delivered = delivery.mock.calls.at(-1)?.[0];
|
||||
if (delivered === undefined || delivered.ok)
|
||||
const composed = delivery.mock.calls.at(-1)?.[0];
|
||||
if (composed === undefined)
|
||||
throw new Error("Expected the composed lifecycle error at delivery");
|
||||
const composed = delivered.error;
|
||||
// The session failure did not retire its target under a retained
|
||||
// cleanup, so its own recovery applies before any close retry.
|
||||
expect(failed.error).not.toHaveProperty("recovery");
|
||||
|
||||
@@ -26,10 +26,10 @@ import { EvidenceIntegrityError } from "../../../src/domain/evidenceErrors.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
import type { WithAdmittedAnalysis } from "../../../src/server/analysisAdmission.js";
|
||||
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { registerReverseEngineeringTools } from "../../../src/server/registerReverseEngineeringTools.js";
|
||||
import {
|
||||
createReverseEngineeringMcpHarness,
|
||||
invokeWithLiveSignal,
|
||||
registerReverseEngineeringTools,
|
||||
} from "../../support/reverseEngineeringMcpHarness.js";
|
||||
|
||||
const createTimedOutRizinService = (): ReverseEngineeringService =>
|
||||
@@ -58,13 +58,9 @@ it("keeps a non-Evidence partial with a caller-selected evidence_id inline in a
|
||||
const service = new ReverseEngineeringService();
|
||||
vi.spyOn(service, "inspectWithObjdump").mockResolvedValue(err(failure));
|
||||
const recordEvidence = vi.fn(() => ok("added" as const));
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
recordEvidence,
|
||||
);
|
||||
});
|
||||
|
||||
const result = (await invokeWithLiveSignal(handler("inspect_with_objdump"), {
|
||||
path: "package.json",
|
||||
@@ -90,13 +86,9 @@ it("records partial Evidence and references it in the original MCP error", async
|
||||
const { server, handler } = createReverseEngineeringMcpHarness();
|
||||
const service = createTimedOutRizinService();
|
||||
const recordEvidence = vi.fn(() => ok("added" as const));
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
recordEvidence,
|
||||
);
|
||||
});
|
||||
const invoke = handler("execute_rizin_command");
|
||||
|
||||
const response = (await invokeWithLiveSignal(invoke, {
|
||||
@@ -121,7 +113,7 @@ it("records partial Evidence and references it in the original MCP error", async
|
||||
});
|
||||
});
|
||||
|
||||
it("admits Rizin mutation after invalidating before dispatch", async () => {
|
||||
it("admits Rizin mutation before dispatch", async () => {
|
||||
const { server, handler } = createReverseEngineeringMcpHarness();
|
||||
const events: string[] = [];
|
||||
const service = new ReverseEngineeringService({
|
||||
@@ -130,19 +122,14 @@ it("admits Rizin mutation after invalidating before dispatch", async () => {
|
||||
return ownedOutput("rizin output");
|
||||
},
|
||||
});
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
undefined,
|
||||
undefined,
|
||||
() => events.push("invalidate"),
|
||||
async (_path, _signal, operation) => {
|
||||
events.push("admit");
|
||||
return ok(await operation());
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
session: {
|
||||
withAdmittedExternalMutation: async (_path, _signal, operation) => {
|
||||
events.push("admit");
|
||||
return ok(await operation());
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
const invoke = handler("execute_rizin_command");
|
||||
|
||||
await invoke(
|
||||
@@ -150,51 +137,44 @@ it("admits Rizin mutation after invalidating before dispatch", async () => {
|
||||
{ mcpReq: { signal: new AbortController().signal } },
|
||||
);
|
||||
|
||||
expect(events).toEqual(["admit", "invalidate", "dispatch"]);
|
||||
expect(events).toEqual(["admit", "dispatch"]);
|
||||
});
|
||||
|
||||
it("invalidates the snapshot in the legacy Rizin admission path", async () => {
|
||||
it("refuses a Rizin command before admission while inspection cleanup still fails", async () => {
|
||||
const { server, handler } = createReverseEngineeringMcpHarness();
|
||||
const invalidateSnapshot = vi.fn();
|
||||
const service = new ReverseEngineeringService({
|
||||
runOwned: async () => ownedOutput("rizin output"),
|
||||
const cleanup = new AnalysisInputError("execute_rizin_command");
|
||||
const executeRizinCommandValidated = vi.fn();
|
||||
const service = {
|
||||
retryCleanup: async () => err(cleanup),
|
||||
executeRizinCommandValidated,
|
||||
} as unknown as ReverseEngineeringService;
|
||||
const withAdmittedExternalMutation = vi.fn();
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
session: { withAdmittedExternalMutation },
|
||||
});
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
undefined,
|
||||
undefined,
|
||||
invalidateSnapshot,
|
||||
);
|
||||
const invoke = handler("execute_rizin_command");
|
||||
|
||||
const response = (await invokeWithLiveSignal(invoke, {
|
||||
path: "package.json",
|
||||
command: "iI",
|
||||
})) as { readonly isError?: boolean };
|
||||
})) as CallToolResult;
|
||||
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(invalidateSnapshot).toHaveBeenCalledOnce();
|
||||
expect(response.isError).toBe(true);
|
||||
expect(withAdmittedExternalMutation).not.toHaveBeenCalled();
|
||||
expect(executeRizinCommandValidated).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips snapshot invalidation for malformed Rizin input", async () => {
|
||||
it("refuses malformed Rizin input before admission", async () => {
|
||||
const { server, handler } = createReverseEngineeringMcpHarness();
|
||||
const invalidateSnapshot = vi.fn();
|
||||
const executeRizinCommandValidated = vi.fn();
|
||||
const service = {
|
||||
retryCleanup: async () => ok(null),
|
||||
executeRizinCommandValidated,
|
||||
} as unknown as ReverseEngineeringService;
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
undefined,
|
||||
undefined,
|
||||
invalidateSnapshot,
|
||||
);
|
||||
const withAdmittedExternalMutation = vi.fn();
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
session: { withAdmittedExternalMutation },
|
||||
});
|
||||
const invoke = handler("execute_rizin_command");
|
||||
|
||||
const response = (await invokeWithLiveSignal(invoke, {
|
||||
@@ -210,7 +190,7 @@ it("skips snapshot invalidation for malformed Rizin input", async () => {
|
||||
},
|
||||
});
|
||||
expect(executeRizinCommandValidated).not.toHaveBeenCalled();
|
||||
expect(invalidateSnapshot).not.toHaveBeenCalled();
|
||||
expect(withAdmittedExternalMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("delivers failed Rizin execution after external admission", async () => {
|
||||
@@ -220,16 +200,12 @@ it("delivers failed Rizin execution after external admission", async () => {
|
||||
throw new Error("Rizin command failed");
|
||||
},
|
||||
});
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
async (_path, _signal, operation) => ok(await operation()),
|
||||
);
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
session: {
|
||||
withAdmittedExternalMutation: async (_path, _signal, operation) =>
|
||||
ok(await operation()),
|
||||
},
|
||||
});
|
||||
const invoke = handler("execute_rizin_command");
|
||||
|
||||
const response = (await invokeWithLiveSignal(invoke, {
|
||||
@@ -252,20 +228,20 @@ it("preserves the Rizin operation error when analysis retirement also fails", as
|
||||
executeRizinCommandValidated: async () => err(primary),
|
||||
} as unknown as ReverseEngineeringService;
|
||||
const observedOperationResult = vi.fn();
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
async (_path, _signal, operation, rebindFailure) => {
|
||||
const result = await operation();
|
||||
observedOperationResult(result);
|
||||
return err(rebindFailure(result, retirement));
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
session: {
|
||||
withAdmittedExternalMutation: async (
|
||||
_path,
|
||||
_signal,
|
||||
operation,
|
||||
rebindFailure,
|
||||
) => {
|
||||
const result = await operation();
|
||||
observedOperationResult(result);
|
||||
return err(rebindFailure(result, retirement));
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
const invoke = handler("execute_rizin_command");
|
||||
|
||||
const response = (await invoke(
|
||||
@@ -319,22 +295,10 @@ it.each(["success", "timeout"])(
|
||||
},
|
||||
});
|
||||
const recordEvidence = vi.fn(() => ok("added" as const));
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
recordEvidence,
|
||||
undefined,
|
||||
() => session.invalidateSnapshotForExternalMutation(),
|
||||
(path, signal, operation, rebindFailure) =>
|
||||
session.withAdmittedExternalMutation(
|
||||
path,
|
||||
signal,
|
||||
operation,
|
||||
rebindFailure,
|
||||
),
|
||||
);
|
||||
session,
|
||||
});
|
||||
const invoke = handler("execute_rizin_command");
|
||||
|
||||
const response = (await invoke(
|
||||
@@ -383,13 +347,9 @@ it("preserves a partial MCP error without claiming failed Evidence retention", a
|
||||
const recordEvidence = vi.fn((_evidence: unknown) =>
|
||||
err(new EvidenceIntegrityError("retention failed")),
|
||||
);
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
recordEvidence,
|
||||
);
|
||||
});
|
||||
const invoke = handler("execute_rizin_command");
|
||||
|
||||
const response = (await invokeWithLiveSignal(invoke, {
|
||||
@@ -423,12 +383,7 @@ it("delivers pathless objdump capability Evidence and input errors through its n
|
||||
runOwned: async () => ownedOutput("objdump output"),
|
||||
});
|
||||
const delivery = createToolResultDelivery(2 * 1024 * 1024);
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
delivery,
|
||||
);
|
||||
registerReverseEngineeringTools(server, service);
|
||||
const context = { mcpReq: { signal: new AbortController().signal } };
|
||||
const objdump = handler("inspect_with_objdump");
|
||||
const rizin = handler("execute_rizin_command");
|
||||
@@ -480,16 +435,13 @@ it("does not treat a malformed partial observation as retained Evidence", async
|
||||
);
|
||||
const service = {
|
||||
inspectWithObjdump: async () => err(invalidError),
|
||||
retryCleanup: async () => ok(null),
|
||||
executeRizinCommandValidated: async () => err(invalidError),
|
||||
} as unknown as ReverseEngineeringService;
|
||||
const recordEvidence = vi.fn(() => ok("added" as const));
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
recordEvidence,
|
||||
);
|
||||
});
|
||||
const invoke = handler("execute_rizin_command");
|
||||
|
||||
const response = (await invoke(
|
||||
@@ -520,14 +472,10 @@ it("keeps provider execution and Evidence recording inside analysis admission",
|
||||
events.push("admission-end");
|
||||
return ok(result);
|
||||
};
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
recordEvidence,
|
||||
admission,
|
||||
);
|
||||
withAdmittedAnalysis: admission,
|
||||
});
|
||||
const invoke = handler("inspect_with_objdump");
|
||||
|
||||
await invoke(
|
||||
@@ -552,14 +500,9 @@ it("returns admission failures without invoking a reverse-engineering provider",
|
||||
} as unknown as ReverseEngineeringService;
|
||||
const admission: WithAdmittedAnalysis = async () =>
|
||||
err(new AnalysisInputError("inspect_with_objdump"));
|
||||
registerReverseEngineeringTools(
|
||||
server,
|
||||
service,
|
||||
pino({ enabled: false }),
|
||||
createToolResultDelivery(2 * 1024 * 1024),
|
||||
undefined,
|
||||
admission,
|
||||
);
|
||||
registerReverseEngineeringTools(server, service, {
|
||||
withAdmittedAnalysis: admission,
|
||||
});
|
||||
const invoke = handler("inspect_with_objdump");
|
||||
|
||||
const response = (await invoke(
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
type WithAdmittedAnalysis,
|
||||
} from "../../../src/server/analysisAdmission.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { registerEvidenceTools } from "../../../src/server/registerEvidenceTools.js";
|
||||
import { registerServiceTools } from "../../../src/server/serviceToolBindings.js";
|
||||
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { createTestProviderRouter } from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -106,22 +106,30 @@ it.each(["normal", "copied", "parameters", "forged", "source"] as const)(
|
||||
({ name }) => name === "xrefs",
|
||||
);
|
||||
if (contract === undefined) throw new Error("Missing xrefs contract");
|
||||
registerEvidenceTools(server, [contract], {
|
||||
logger: silentLogger,
|
||||
activeTarget: () => session.activeTarget(),
|
||||
recordEvidence: session.recordEvidence.bind(session),
|
||||
evidenceById: session.evidenceForAnalysis.bind(session),
|
||||
admitRecovery: session.admitRecoveryObservation.bind(session),
|
||||
withAdmittedAnalysis: admitted,
|
||||
...(mode === "parameters"
|
||||
? {
|
||||
parametersForExecution: (_operation, parameters) => ({
|
||||
...parameters,
|
||||
address: "0x300",
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
registerServiceTools(
|
||||
server,
|
||||
{
|
||||
providerOperations: {
|
||||
contracts: [contract],
|
||||
activeTarget: () => session.activeTarget(),
|
||||
admitRecovery: session.admitRecoveryObservation.bind(session),
|
||||
...(mode === "parameters"
|
||||
? {
|
||||
parametersForExecution: (_operation, parameters) => ({
|
||||
...parameters,
|
||||
address: "0x300",
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
{
|
||||
logger: silentLogger,
|
||||
recordEvidence: session.recordEvidence.bind(session),
|
||||
evidenceById: session.evidenceForAnalysis.bind(session),
|
||||
withAdmittedAnalysis: admitted,
|
||||
},
|
||||
);
|
||||
const client = new Client({ name: "reuse-control", version: "1" });
|
||||
const [ct, st] = InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
|
||||
@@ -590,7 +590,7 @@ describe.each(["apple", "inventory", "extraction"])(
|
||||
["../../application/Workflow.js", false],
|
||||
["../../composition/android.js", false],
|
||||
["../../cli.js", false],
|
||||
["../../server/registerEvidenceTools.js", false],
|
||||
["../../server/providerOperationToolHandler.js", false],
|
||||
["../../main.ts", false],
|
||||
["../../domain/apple/plistValue.js", true],
|
||||
["../../domain/artifactInventorySnapshot.js", true],
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import pino from "pino";
|
||||
|
||||
import type { EvidenceLookup } from "../../src/application/EvidenceInputResolver.js";
|
||||
import type { EvidenceWriter } from "../../src/application/investigation/InvestigationRecordPort.js";
|
||||
import type { WithAdmittedAnalysis } from "../../src/server/analysisAdmission.js";
|
||||
import type { EvidenceMcpServer } from "../../src/server/EvidenceMcpServer.js";
|
||||
import type { ExternalMutationAdmission } from "../../src/server/externalMutationAdmission.js";
|
||||
import {
|
||||
registerServiceTools,
|
||||
type ReverseEngineeringToolOptions,
|
||||
} from "../../src/server/serviceToolBindings.js";
|
||||
import { createToolResultDelivery } from "../../src/server/toolResult.js";
|
||||
|
||||
type RegisteredHandler = (input: unknown, context: unknown) => Promise<unknown>;
|
||||
|
||||
@@ -8,18 +19,23 @@ export const invokeWithLiveSignal = (
|
||||
): Promise<unknown> =>
|
||||
handler(input, { mcpReq: { signal: new AbortController().signal } });
|
||||
|
||||
/**
|
||||
* A server that keeps each registered handler for direct invocation, with
|
||||
* the delivery the shared binding loop reads.
|
||||
*/
|
||||
export const createReverseEngineeringMcpHarness = (): {
|
||||
server: McpServer;
|
||||
server: EvidenceMcpServer;
|
||||
handler: (name: string) => RegisteredHandler;
|
||||
} => {
|
||||
const registrations = new Map<string, RegisteredHandler>();
|
||||
const server = {
|
||||
delivery: createToolResultDelivery(2 * 1024 * 1024),
|
||||
registerTool: (
|
||||
name: string,
|
||||
_options: unknown,
|
||||
handler: RegisteredHandler,
|
||||
) => registrations.set(name, handler),
|
||||
} as unknown as McpServer;
|
||||
} as unknown as EvidenceMcpServer;
|
||||
|
||||
return {
|
||||
server,
|
||||
@@ -31,3 +47,25 @@ export const createReverseEngineeringMcpHarness = (): {
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Bind objdump and Rizin through the shared table, as composition does. */
|
||||
export const registerReverseEngineeringTools = (
|
||||
server: EvidenceMcpServer,
|
||||
service: ReverseEngineeringToolOptions["service"],
|
||||
options: {
|
||||
readonly recordEvidence?: EvidenceWriter["recordEvidence"];
|
||||
readonly evidenceById?: EvidenceLookup;
|
||||
readonly withAdmittedAnalysis?: WithAdmittedAnalysis;
|
||||
readonly session?: ExternalMutationAdmission;
|
||||
} = {},
|
||||
): void =>
|
||||
registerServiceTools(
|
||||
server,
|
||||
{ reverseEngineering: { service, session: options.session } },
|
||||
{
|
||||
logger: pino({ enabled: false }),
|
||||
recordEvidence: options.recordEvidence,
|
||||
evidenceById: options.evidenceById,
|
||||
withAdmittedAnalysis: options.withAdmittedAnalysis,
|
||||
},
|
||||
);
|
||||
@@ -10,7 +10,8 @@
|
||||
"src/objdump/ObjdumpCommand.ts",
|
||||
"src/process/ownedDebuggerSession.ts",
|
||||
"src/process/ExecFileOutput.ts",
|
||||
"src/server/registerReverseEngineeringTools.ts",
|
||||
"src/server/externalMutationToolHandler.ts",
|
||||
"src/server/serviceToolBindings.ts",
|
||||
"src/server/providerEnvironment.ts",
|
||||
"src/rizin/RizinCommand.ts",
|
||||
"src/rizin/RizinDebugSessionManager.ts",
|
||||
|
||||
@@ -9,7 +9,8 @@ const REVERSE_TOOL_MODULES = [
|
||||
"src/objdump/ObjdumpCommand.ts",
|
||||
"src/process/ownedDebuggerSession.ts",
|
||||
"src/process/ExecFileOutput.ts",
|
||||
"src/server/registerReverseEngineeringTools.ts",
|
||||
"src/server/externalMutationToolHandler.ts",
|
||||
"src/server/serviceToolBindings.ts",
|
||||
"src/server/externalMutationAdmission.ts",
|
||||
"src/server/providerEnvironment.ts",
|
||||
"src/rizin/RizinCommand.ts",
|
||||
|
||||
Reference in new issue
Block a user