refactor: return complete tool results inline

This commit is contained in:
morluto
2026-09-29 07:08:46 +08:00
parent 2160d4fae5
commit 0d96275b68
535 changed files with 4084 additions and 13537 deletions
+4 -47
View File
@@ -29,7 +29,7 @@ import { PRODUCT_IDENTITY } from "../identity.js";
import { silentLogger, type Logger } from "../logger.js";
import { LinuxJavaScriptReplayRunner } from "../replay/LinuxJavaScriptReplayRunner.js";
import { SystemJavaScriptReplayHost } from "../replay/SystemJavaScriptReplayHost.js";
import { mcpClientMetadata, mcpEnvelopeValue } from "./mcpClientMetadata.js";
import { mcpEnvelopeValue } from "./mcpClientMetadata.js";
import {
PROCESS_CAPTURE_ELICITATION_POLICY,
type ProcessCaptureElicitationState,
@@ -40,7 +40,6 @@ import { registerBrowserScenarioTool } from "./registerBrowserScenarioTool.js";
import { registerBrowserTools } from "./registerBrowserTools.js";
import { registerElectronTools } from "./registerElectronTools.js";
import { registerEnhancedTools } from "./registerEnhancedTools.js";
import { registerEvidenceResources } from "./registerEvidenceResources.js";
import { registerJavaScriptRuntimeObservationTools } from "./registerJavaScriptRuntimeObservationTools.js";
import { registerManagedTools } from "./registerManagedTools.js";
import { registerManagedWorkflowTools } from "./registerManagedWorkflowTools.js";
@@ -56,16 +55,15 @@ import {
} from "./sessionToolPolicies.js";
const TARGET_FREE_INSTRUCTIONS =
"ASAR/JavaScript -> analyze_javascript_application; archive/package -> open_binary(path), then inspect_artifact/inventory_artifact (active target); managed PE/CLI -> inspect_managed_artifact; browser/Electron -> list_browser_targets/list_electron_targets; approved -> capture_browser_scenario/capture_electron_scenario; Node/Electron Inspector -> list_javascript_runtime_targets; native binary/database -> open_binary, then binary_overview. Start with binary_session; use tools/list; capabilities via binary_session. Use summaries, cite Evidence IDs; Never repeat identical analysis or read full Evidence.";
"ASAR/JavaScript -> analyze_javascript_application; archive/package -> open_binary(path), then inspect_artifact/inventory_artifact; managed PE/CLI -> inspect_managed_artifact; browser/Electron -> list_browser_targets/list_electron_targets; capture_browser_scenario/capture_electron_scenario; Node/Electron Inspector -> list_javascript_runtime_targets; native binary/database -> open_binary, then binary_overview. Start with binary_session; use tools/list; capabilities via binary_session.";
const ACTIVE_TARGET_INSTRUCTIONS =
"REA analyzes the active reverse-engineering target. Start native analysis with binary_overview, then narrow with analyze_function, literal search, callers, callees, and xrefs. Prefer summary views, never repeat an identical call, and read full Evidence only when the task requires it.";
"REA analyzes the active reverse-engineering target. Start native analysis with binary_overview, then use analyze_function, literal search, callers, callees, and xrefs as needed.";
export interface CreateServerOptions {
readonly logger?: Logger;
readonly processPolicy?: () => ProcessExecutionPolicy;
readonly evidenceFilePolicy?: EvidenceFilePolicy;
readonly investigationInputRoots?: readonly string[];
readonly analysisSnapshotFilePolicy?: EvidenceFilePolicy;
readonly permissionAuthority?: PermissionAuthority;
readonly browserObservation?: BrowserObservationPort;
@@ -90,7 +88,6 @@ const installSessionToolAvailability = (
const policy = sessionAvailabilityPolicy(options.availabilityPolicy, {
processPolicy: options.processPolicy?.() ?? DENY_PROCESS_POLICY,
evidenceFilePolicy: options.evidenceFilePolicy ?? DENY_EVIDENCE_FILE_POLICY,
investigationInputRoots: options.investigationInputRoots ?? [],
optionalFeatures: {
browserObservationEnabled: options.browserObservation !== undefined,
browserScenarioEnabled: options.browserScenarioCapture !== undefined,
@@ -157,9 +154,7 @@ const createMcpServer = (
version: PRODUCT_IDENTITY.packageVersion,
},
{
capabilities: {
resources: { subscribe: true },
},
capabilities: {},
inputRequired: {
maxRounds: 3,
roundTimeoutMs: PROCESS_CAPTURE_ELICITATION_POLICY.roundTimeoutMs,
@@ -196,7 +191,6 @@ export const createServer = (
server.server.onclose = () => {
permissionAuthority?.clearSessionGrants();
};
registerServerIdentityResource(server, startedAt);
const toolLogger = logger.child({ layer: "server" });
const { activeTarget, recordEvidence, recordEvidenceWithUnknown } =
createSessionRecorders(server, session);
@@ -218,7 +212,6 @@ export const createServer = (
registerObservationTools(toolContext);
registerGuidedPrompts(server, analysis, session);
if (session !== undefined) {
registerEvidenceResources(server, session);
registerSessionTools(server, session, toolLogger, {
...options,
...(availability === undefined
@@ -373,39 +366,3 @@ const registerObservationTools = ({
},
});
};
const registerServerIdentityResource = (
server: McpServer,
startedAt: string,
): void => {
server.registerResource(
"server-identity",
"rea://server/identity",
{
title: "REA server identity",
description: "Live package, SDK, protocol, and catalog identity.",
mimeType: "application/json",
},
async (uri, context) => {
const { createServerIdentity } = await import("../serverIdentity.js");
const { client, protocolVersion } = mcpClientMetadata(context);
return {
contents: [
{
uri: uri.href,
mimeType: "application/json",
text: JSON.stringify(
createServerIdentity({
startedAt,
...(client === undefined ? {} : { client }),
...(protocolVersion === undefined ? {} : { protocolVersion }),
}),
null,
2,
),
},
],
};
},
);
};
-137
View File
@@ -1,137 +0,0 @@
import type { Evidence } from "../domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../domain/javascriptApplicationAnalysis.js";
import { compareCodePoints } from "../domain/javascriptApplicationGraph.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { javascriptApplicationAnalysisSummarySchema } from "../contracts/electronToolContracts.js";
const DEFAULT_GRAPH_PAGE_LIMIT = 100;
const ROOT_SAMPLE_LIMIT = 10;
const TOP_FINDING_LIMIT = 20;
const FINDING_PRIORITY: Readonly<Record<string, number>> = {
"browser-window": 0,
"electron-preload": 1,
"context-bridge-api": 2,
"ipc-channel": 3,
"ipc-handler": 4,
"electron-utility": 5,
endpoint: 6,
storage: 7,
worker: 8,
"service-worker": 9,
"native-addon": 10,
"native-export": 11,
"source-map": 12,
};
/** Project complete JavaScript application Evidence into a bounded agent result. */
export const summarizeJavaScriptApplicationEvidence = (
evidence: Evidence,
): JsonValue => {
const result = javascriptApplicationAnalysisResultSchema.parse(
evidence.normalized_result,
);
const nodeKinds = new Map<string, number>();
for (const node of result.graph.nodes)
nodeKinds.set(node.kind, (nodeKinds.get(node.kind) ?? 0) + 1);
const rootItems = result.graph.root_node_ids.slice(0, ROOT_SAMPLE_LIMIT);
const pageRoot = `rea://evidence/${evidence.evidence_id}/application-graph`;
const topFindings = [...result.graph.nodes]
.sort(
(left, right) =>
(FINDING_PRIORITY[left.kind] ?? Number.MAX_SAFE_INTEGER) -
(FINDING_PRIORITY[right.kind] ?? Number.MAX_SAFE_INTEGER) ||
compareCodePoints(left.node_id, right.node_id),
)
.slice(0, TOP_FINDING_LIMIT)
.map((node) => {
const observation = node.observations[0];
if (observation === undefined)
throw new TypeError("Application graph node has no observation");
return {
node_id: node.node_id,
kind: node.kind,
label: observation.label,
authority: observation.evidence.authority,
state: observation.evidence.state,
confidence: observation.evidence.confidence,
location: observation.evidence.location,
};
});
const summary =
result.schema_version === 1 ? omitGraph(result) : omitGraphs(result);
const unknowns = new Set([
...result.limitations,
...result.graph.limitations,
]);
if (result.statistics.parse_failures > 0)
unknowns.add(
`${String(result.statistics.parse_failures)} JavaScript file(s) could not be parsed.`,
);
if (result.statistics.truncated_scopes > 0)
unknowns.add(
`${String(result.statistics.truncated_scopes)} analysis scope(s) were truncated.`,
);
if (result.graph.coverage.status !== "complete")
unknowns.add(
`Application graph coverage is ${result.graph.coverage.status}; omitted facts remain unknown.`,
);
return javascriptApplicationAnalysisSummarySchema.parse({
...summary,
...(result.schema_version === 1
? {}
: {
semantic_graph: {
graph_id: result.semantic_graph.graph_id,
nodes: result.semantic_graph.nodes.length,
relations: result.semantic_graph.relations.length,
unknown_frontiers: result.semantic_graph.unknowns.length,
fingerprints: result.semantic_graph.fingerprints.length,
coverage: result.semantic_graph.coverage.status,
query_tool: "trace_javascript_semantics",
},
}),
unknowns: [...unknowns],
graph: {
graph_id: result.graph.graph_id,
node_count: result.graph.nodes.length,
edge_count: result.graph.edges.length,
roots: {
items: rootItems,
total: result.graph.root_node_ids.length,
truncated: rootItems.length < result.graph.root_node_ids.length,
},
node_kinds: [...nodeKinds]
.sort(([left], [right]) => compareCodePoints(left, right))
.map(([kind, count]) => ({ kind, count })),
top_findings: topFindings,
coverage: result.graph.coverage,
limitations: result.graph.limitations,
pages: {
nodes: `${pageRoot}/nodes/offset/0/limit/${String(DEFAULT_GRAPH_PAGE_LIMIT)}`,
edges: `${pageRoot}/edges/offset/0/limit/${String(DEFAULT_GRAPH_PAGE_LIMIT)}`,
page_limit: DEFAULT_GRAPH_PAGE_LIMIT,
},
},
});
};
const omitGraph = (
result: Extract<
ReturnType<typeof javascriptApplicationAnalysisResultSchema.parse>,
{ readonly schema_version: 1 }
>,
) => {
const { graph: _graph, ...summary } = result;
return summary;
};
const omitGraphs = (
result: Extract<
ReturnType<typeof javascriptApplicationAnalysisResultSchema.parse>,
{ readonly schema_version: 2 }
>,
) => {
const { graph: _graph, semantic_graph: _semanticGraph, ...summary } = result;
return summary;
};
+23 -54
View File
@@ -4,13 +4,8 @@ import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import type { PromptCompletionKind } from "../contracts/promptContracts.js";
import { artifactInventoryResultSchema } from "../domain/artifactGraph.js";
import { parseAddressedPage } from "../domain/hopperValues.js";
import { processCaptureSchema } from "../domain/processCapture.js";
const COMPLETION_SCAN_LIMIT = 10_000;
const PROCEDURE_PAGE_SIZE = 500;
const MAX_COMPLETION_VALUE_LENGTH = 4_096;
const documentListSchema = z.array(z.string().min(1));
const providerStatusSchema = z.object({
providers: z.array(z.object({ id: z.string().min(1) })),
@@ -32,13 +27,12 @@ export interface PromptCompletionSource {
): Promise<readonly string[]>;
}
/** Build bounded live completion over the active provider and session ledger. */
/** Build live completion over the active provider and session ledger. */
export const createPromptCompletionSource = (
analysis: AnalysisOperationPort,
session?: BinarySessionPort,
): PromptCompletionSource => ({
async complete(kind, value, context) {
if (value.length > MAX_COMPLETION_VALUE_LENGTH) return [];
const candidates = await completionCandidates(
kind,
analysis,
@@ -46,9 +40,9 @@ export const createPromptCompletionSource = (
context,
);
const prefix = normalize(value);
return uniqueSorted(candidates)
.filter((candidate) => normalize(candidate).startsWith(prefix))
.slice(0, COMPLETION_SCAN_LIMIT);
return uniqueSorted(candidates).filter((candidate) =>
normalize(candidate).startsWith(prefix),
);
},
});
@@ -81,38 +75,25 @@ const documentCandidates = async (
const result = await analysis.execute("list_documents", {});
if (!result.ok) return [];
const parsed = documentListSchema.safeParse(result.value.result);
return parsed.success ? parsed.data.slice(0, COMPLETION_SCAN_LIMIT) : [];
return parsed.success ? parsed.data : [];
};
const procedureCandidates = async (
analysis: AnalysisOperationPort,
document: string | undefined,
): Promise<readonly string[]> => {
if (document !== undefined && document.length > MAX_COMPLETION_VALUE_LENGTH)
return [];
const byAddress = new Map<string, string>();
let offset = 0;
let exhaustive = false;
while (byAddress.size < COMPLETION_SCAN_LIMIT / 2) {
const result = await analysis.execute("list_procedures", {
offset,
limit: PROCEDURE_PAGE_SIZE,
...(document === undefined || document.length === 0 ? {} : { document }),
});
if (!result.ok) break;
const parsed = parseAddressedPage(result.value.result);
if (!parsed.ok) break;
for (const item of parsed.value.items) {
if (byAddress.size >= COMPLETION_SCAN_LIMIT / 2) break;
if (!byAddress.has(item.address)) byAddress.set(item.address, item.name);
}
const nextOffset = parsed.value.nextOffset;
if (!parsed.value.hasMore) {
exhaustive = true;
break;
}
if (nextOffset === null || nextOffset <= offset) break;
offset = nextOffset;
const input =
document === undefined || document.length === 0 ? {} : { document };
const result = await analysis.execute("list_procedures", input);
if (result.ok) {
const parsed = z
.array(z.object({ address: z.string(), value: z.string() }))
.safeParse(result.value.result);
if (parsed.success)
for (const item of parsed.data)
if (!byAddress.has(item.address))
byAddress.set(item.address, item.value);
}
const addressesByName = new Map<string, Set<string>>();
@@ -122,9 +103,8 @@ const procedureCandidates = async (
addressesByName.set(name, addresses);
}
const candidates = [...byAddress.keys()];
if (exhaustive)
for (const [name, addresses] of addressesByName)
if (addresses.size === 1 && name.length > 0) candidates.push(name);
for (const [name, addresses] of addressesByName)
if (addresses.size === 1 && name.length > 0) candidates.push(name);
return candidates;
};
@@ -140,7 +120,7 @@ const providerCandidates = (
({ provider }) => provider.id,
) ?? [])
: parsed.data.providers.map(({ id }) => id);
return ["auto", ...candidates].slice(0, COMPLETION_SCAN_LIMIT);
return ["auto", ...candidates];
};
const evidenceCandidates = (
@@ -149,11 +129,8 @@ const evidenceCandidates = (
): readonly string[] => {
if (session === undefined) return [];
const candidates: string[] = [];
for (const evidence of session.exportEvidenceBundle().records) {
const remaining = COMPLETION_SCAN_LIMIT - candidates.length;
candidates.push(...evidenceValues(kind, evidence).slice(0, remaining));
if (candidates.length >= COMPLETION_SCAN_LIMIT) break;
}
for (const evidence of session.exportEvidenceBundle().records)
candidates.push(...evidenceValues(kind, evidence));
return candidates;
};
@@ -191,18 +168,10 @@ const unknownCandidates = (
: session
.listUnknowns()
.filter(({ status }) => status !== "resolved")
.map(({ unknown_id: id }) => id)
.slice(0, COMPLETION_SCAN_LIMIT);
.map(({ unknown_id: id }) => id);
const uniqueSorted = (values: readonly string[]): string[] =>
[
...new Set(
values.filter(
(value) =>
value.length > 0 && value.length <= MAX_COMPLETION_VALUE_LENGTH,
),
),
].sort(compareText);
[...new Set(values.filter((value) => value.length > 0))].sort(compareText);
const compareText = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
@@ -52,9 +52,7 @@ export const registerCharacterizationTools = (
);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, prepareContract);
return toCallToolResult(result, prepareContract, {
evidenceResourcesAvailable: options.recordEvidence !== undefined,
});
return toCallToolResult(result, prepareContract);
},
);
server.registerTool(
@@ -85,9 +83,7 @@ export const registerCharacterizationTools = (
sources,
);
if (!recorded.ok) return toCallToolResult(recorded, executeContract);
return toCallToolResult(result, executeContract, {
evidenceResourcesAvailable: options.recordEvidence !== undefined,
});
return toCallToolResult(result, executeContract);
},
);
};
@@ -47,10 +47,7 @@ export const registerControlledReplayTool = (
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, replayContract);
}
return toCallToolResult(result, replayContract, {
evidenceResourcesAvailable:
output.phase === "execute" && options.recordEvidence !== undefined,
});
return toCallToolResult(result, replayContract);
},
);
};
@@ -19,7 +19,6 @@ import { err } from "../../domain/result.js";
import { logToolExecution } from "../toolLogging.js";
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
import { toCallToolResult } from "../toolResult.js";
import { coverageWorkspaceUri } from "./helpers.js";
import type { ApplicationToolRegistration } from "./types.js";
const commitContract = applicationToolContract(
@@ -78,19 +77,7 @@ const registerCommitTool = (
);
if (!result.ok) return toCallToolResult(result, commitContract);
options.retainCoverageWorkspace?.(input.workspace);
return toCallToolResult(result, commitContract, {
resourceLinks:
options.retainCoverageWorkspace === undefined
? []
: [
{
uri: coverageWorkspaceUri(input.workspace),
name: input.workspace.workspace_id,
description:
"Session-retained reconstruction coverage workspace revision",
},
],
});
return toCallToolResult(result, commitContract);
},
);
};
@@ -3,12 +3,6 @@ import type { Evidence } from "../../domain/evidence.js";
import { toCallToolResult } from "../toolResult.js";
import type { ApplicationToolRegistration } from "./types.js";
export const coverageWorkspaceUri = (workspace: {
readonly workspace_id: string;
readonly revision: number;
}): string =>
`rea://reconstruction-coverage/${workspace.workspace_id}/revision/${String(workspace.revision)}`;
export const recordResult = (
options: ApplicationToolRegistration,
contract: (typeof APPLICATION_TOOL_CONTRACTS)[number],
@@ -27,9 +21,7 @@ export const recordResult = (
);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, contract);
return toCallToolResult({ ok: true, value: evidence }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
return toCallToolResult({ ok: true, value: evidence }, contract);
};
const unknownRegistration = (
@@ -6,7 +6,6 @@ import {
resolveReconstructionReadinessRequest,
} from "../../application/ReconstructionReadinessService.js";
import { applicationToolContract } from "../../contracts/applicationToolContracts.js";
import { reconstructionReadinessReportSchema } from "../../domain/reconstructionReadinessSchemas.js";
import { logToolExecution } from "../toolLogging.js";
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
import { toCallToolResult } from "../toolResult.js";
@@ -40,33 +39,7 @@ export const registerReconstructionReadinessTool = (
const recordedResult = options.recordEvidence?.(result.value);
if (recordedResult !== undefined && !recordedResult.ok)
return toCallToolResult(recordedResult, contract);
const report = reconstructionReadinessReportSchema.parse(
result.value.normalized_result,
);
const reportUri = `rea://evidence/${result.value.evidence_id}/reconstruction-readiness-report`;
const projection = {
schema: report.schema,
schema_version: report.schema_version,
report_id: report.report_id,
source_digest: report.source_digest,
report_digest: report.report_digest,
status: report.status,
summary: report.summary,
metrics: report.metrics,
report_resource_uri: reportUri,
};
return toCallToolResult({ ok: true, value: result.value }, contract, {
evidenceResourcesAvailable: recordedResult !== undefined,
evidenceResultProjection: projection,
evidenceTextProjection: projection,
resourceLinks: [
{
uri: reportUri,
name: report.report_id,
description: "Full deterministic reconstruction readiness report",
},
],
});
return toCallToolResult({ ok: true, value: result.value }, contract);
},
);
};
+1 -3
View File
@@ -39,9 +39,7 @@ export const registerBrowserScenarioTool = (
const recorded = options.recordEvidence?.(result.value);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, contract)
: toCallToolResult({ ok: true, value: result.value }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
: toCallToolResult({ ok: true, value: result.value }, contract);
},
);
};
+1 -3
View File
@@ -220,7 +220,5 @@ const evidenceResult = (
const recorded = options.recordEvidence?.(evidence);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, contract)
: toCallToolResult({ ok: true, value: evidence }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
: toCallToolResult({ ok: true, value: evidence }, contract);
};
+5 -42
View File
@@ -16,10 +16,8 @@ import { ELECTRON_TOOL_CONTRACTS } from "../contracts/electronToolContracts.js";
import type { ToolContract } from "../contracts/toolContracts.js";
import type { AnalysisError } from "../domain/errors.js";
import type { Evidence } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Result } from "../domain/result.js";
import type { Logger } from "../logger.js";
import { summarizeJavaScriptApplicationEvidence } from "./javascriptApplicationResult.js";
import { mcpProgressReporter } from "./mcpProgress.js";
import { logToolExecution } from "./toolLogging.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
@@ -98,22 +96,9 @@ export const registerElectronTools = (
runElectronTool(
options,
analyzeContract,
{
input,
context,
projectEvidence: (evidence, parsed) => {
const summary = summarizeJavaScriptApplicationEvidence(evidence);
return parsed.detail === "full"
? { structured: evidence.normalized_result, text: summary }
: { structured: summary };
},
},
{ input, context },
(parsed, { signal, progress }) =>
analyzeJavaScriptApplicationValidated(
options.permissionAuthority,
parsed,
{ signal, progress },
),
analyzeJavaScriptApplicationValidated(parsed, { signal, progress }),
),
);
server.registerTool(
@@ -153,17 +138,13 @@ const runElectronTool = async <Input>(
request: {
readonly input: Input;
readonly context: ServerContext;
readonly projectEvidence?: (
evidence: Evidence,
input: Input,
) => { readonly structured: JsonValue; readonly text?: JsonValue };
},
execute: (
input: Input,
context: ElectronToolContext,
) => Promise<Result<Evidence, AnalysisError>>,
) => {
const { input, context, projectEvidence } = request;
const { input, context } = request;
const result = await logToolExecution(options.logger, contract.name, () =>
execute(input, {
signal: context.mcpReq.signal,
@@ -171,34 +152,16 @@ const runElectronTool = async <Input>(
}),
);
if (!result.ok) return toCallToolResult(result, contract);
return evidenceResult(
options,
contract,
result.value,
projectEvidence?.(result.value, input),
);
return evidenceResult(options, contract, result.value);
};
const evidenceResult = (
options: ElectronToolRegistration,
contract: ToolContract,
evidence: Evidence,
projection:
| { readonly structured: JsonValue; readonly text?: JsonValue }
| undefined,
) => {
const recorded = options.recordEvidence?.(evidence);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, contract)
: toCallToolResult({ ok: true, value: evidence }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
...(projection === undefined
? {}
: {
evidenceResultProjection: projection.structured,
...(projection.text === undefined
? {}
: { evidenceTextProjection: projection.text }),
}),
});
: toCallToolResult({ ok: true, value: evidence }, contract);
};
+2 -4
View File
@@ -249,9 +249,7 @@ const executeEnhancedTool = async (
recordUnknown: registration.recordUnknown,
});
if (!unknowns.ok) return toCallToolResult(unknowns, contract);
return toCallToolResult({ ok: true, value: evidence }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
return toCallToolResult({ ok: true, value: evidence }, contract);
}
return toCallToolResult(result, contract);
};
@@ -315,7 +313,7 @@ const recordWorkflowUnknowns = ({
rationale:
name === "inspect_native_api"
? "Confirm the unsupported boundary with a capable provider or ABI probe."
: "Continue with a larger bounded budget.",
: "Continue with a focused query or another available provider.",
},
],
relationships: [],
-422
View File
@@ -1,422 +0,0 @@
import {
ResourceNotFoundError,
ResourceTemplate,
type McpServer,
} from "@modelcontextprotocol/server";
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import type { BinarySessionPort } from "../application/BinarySessionPort.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { registerJavaScriptApplicationGraphResource } from "./registerJavaScriptApplicationGraphResource.js";
import { registerReconstructionObligationLedgerResource } from "./registerReconstructionObligationLedgerResource.js";
import { registerReconstructionReadinessResource } from "./registerReconstructionReadinessResource.js";
import { jsonResource } from "./resourceResult.js";
/** Expose immutable session-owned Evidence v2 records as MCP resources. */
export const registerEvidenceResources = (
server: McpServer,
session: BinarySessionPort,
): void => {
registerReconstructionCoverageResource(server, session);
registerInvestigationWorkspaceResource(server, session);
registerSessionEvidenceResource(server, session);
registerEvidenceBundleResource(server, session);
registerAnalysisSnapshotResource(server, session);
registerArtifactPageResource(server, session);
registerFunctionDossierResource(server, session);
registerEvidenceSectionResource(server, session);
registerReconstructionObligationLedgerResource(server, session);
registerReconstructionReadinessResource(server, session);
registerJavaScriptApplicationGraphResource(server, session);
registerResidualUnknownResource(server, session);
session.onAnalysisSnapshotChanged?.(() => {
void server.server
.sendResourceUpdated({ uri: "rea://snapshot/current" })
.catch(() => undefined);
});
};
const registerReconstructionCoverageResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"reconstruction-coverage-revision",
new ResourceTemplate(
"rea://reconstruction-coverage/{workspaceId}/revision/{revision}",
{
list: undefined,
},
),
{
title: "Reconstruction coverage revision",
description:
"Canonical CAS-linked surfaces, owners, claims, verifiers, evidence, and completion boundaries.",
mimeType: "application/json",
},
(uri, variables) => {
const workspaceId = stringVariable(variables.workspaceId, uri.href);
const revisionText = stringVariable(variables.revision, uri.href);
if (!/^\d+$/u.test(revisionText))
throw new ResourceNotFoundError(uri.href);
const workspace = session.reconstructionCoverageWorkspace(
workspaceId,
Number(revisionText),
);
if (workspace === undefined) throw new ResourceNotFoundError(uri.href);
return jsonResource(uri.href, workspace);
},
);
};
const registerInvestigationWorkspaceResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"investigation-workspace-revision",
new ResourceTemplate("rea://workspace/{workspaceId}/revision/{revision}", {
list: undefined,
}),
{
title: "Investigation workspace revision",
description: "Immutable session-retained workspace with CAS linkage.",
mimeType: "application/json",
},
(uri, variables) => {
const workspaceId = stringVariable(variables.workspaceId, uri.href);
const revisionText = stringVariable(variables.revision, uri.href);
if (!/^\d+$/u.test(revisionText))
throw new ResourceNotFoundError(uri.href);
const workspace = session.investigationWorkspace(
workspaceId,
Number(revisionText),
);
if (workspace === undefined) throw new ResourceNotFoundError(uri.href);
return jsonResource(uri.href, workspace);
},
);
};
const registerSessionEvidenceResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"session-evidence",
new ResourceTemplate("rea://evidence/{evidenceId}", {
list: undefined,
}),
{
title: "Session evidence",
description: "Immutable Evidence v2 records owned by this REA session.",
mimeType: "application/json",
},
(uri, variables) => {
const evidenceId = variables.evidenceId;
if (typeof evidenceId !== "string")
throw new ResourceNotFoundError(uri.href);
const evidence = session.evidenceById(evidenceId);
if (evidence === undefined) throw new ResourceNotFoundError(uri.href);
return jsonResource(uri.href, evidence);
},
);
};
const registerEvidenceBundleResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"evidence-bundle",
new ResourceTemplate("rea://evidence-bundle/{bundleDigest}", {
list: undefined,
}),
{
title: "Evidence bundle",
description: "Immutable session-retained canonical Evidence v2 bundle.",
mimeType: "application/json",
},
(uri, variables) => {
const digest = stringVariable(variables.bundleDigest, uri.href);
if (!/^[a-f0-9]{64}$/u.test(digest))
throw new ResourceNotFoundError(uri.href);
const text = session.retainedEvidenceBundle(digest);
if (text === undefined) throw new ResourceNotFoundError(uri.href);
return {
contents: [
{
uri: uri.href,
mimeType: "application/json",
text,
},
],
};
},
);
};
const registerAnalysisSnapshotResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"analysis-snapshot",
"rea://snapshot/current",
{
title: "Analysis snapshot",
description:
"Mutable provider-neutral analysis snapshot for the current native target.",
mimeType: "application/json",
},
(uri) => {
const snapshot = session.exportAnalysisSnapshot();
if (!snapshot.ok)
return jsonResource(uri.href, {
state: "unavailable",
reason: snapshot.error.message,
remediation:
"Open a native target with a concrete analysis profile. After metadata mutation, call open_binary again for the current target to begin a fresh cache.",
});
return jsonResource(uri.href, {
state: "available",
target: snapshot.value.target,
profile: snapshot.value.binding,
content_digest: contentDigest(snapshot.value),
entry_count: snapshot.value.entries.length,
snapshot: snapshot.value,
});
},
);
};
const registerArtifactPageResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"artifact-page",
new ResourceTemplate("rea://artifact/{manifestId}/{collection}", {
list: undefined,
complete: {
collection: (prefix) =>
["nodes", "occurrences", "edges"].filter((value) =>
value.startsWith(prefix),
),
},
}),
{
title: "Artifact graph page",
description: "Deterministically paged artifact graph collection.",
mimeType: "application/json",
},
(uri, variables) => {
const manifestId = stringVariable(variables.manifestId, uri.href);
const collection = stringVariable(variables.collection, uri.href);
if (!ARTIFACT_COLLECTIONS.has(collection))
throw new ResourceNotFoundError(uri.href);
const evidence = session
.exportEvidenceBundle()
.records.find(
(record) =>
artifactManifestId(record.normalized_result) === manifestId,
);
if (evidence === undefined) throw new ResourceNotFoundError(uri.href);
const result = objectValue(evidence.normalized_result);
const page = result?.[collection];
if (page === undefined) throw new ResourceNotFoundError(uri.href);
return jsonResource(uri.href, {
evidence_id: evidence.evidence_id,
manifest_id: manifestId,
collection,
page,
provider: evidence.provider,
limitations: evidence.limitations,
});
},
);
};
const registerFunctionDossierResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"function-dossier",
new ResourceTemplate("rea://function/{targetSha256}/{address}", {
list: undefined,
}),
{
title: "Function dossier",
description: "Session-owned analyze_function dossier with provenance.",
mimeType: "application/json",
},
(uri, variables) => {
const targetSha256 = stringVariable(variables.targetSha256, uri.href);
const address = stringVariable(variables.address, uri.href);
const evidence = session
.exportEvidenceBundle()
.records.find(
(record) =>
record.operation === "analyze_function" &&
record.subject?.digest.sha256 === targetSha256 &&
functionAddress(record.normalized_result) === address,
);
if (evidence === undefined) throw new ResourceNotFoundError(uri.href);
return jsonResource(uri.href, evidence);
},
);
};
const registerEvidenceSectionResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"evidence-section",
new ResourceTemplate("rea://evidence/{evidenceId}/section/{section}", {
list: undefined,
complete: {
section: (prefix) =>
EVIDENCE_SECTIONS.filter((section) => section.startsWith(prefix)),
},
}),
{
title: "Evidence section",
description:
"One independently useful bounded section of session Evidence v2.",
mimeType: "application/json",
},
(uri, variables) => {
const evidenceId = stringVariable(variables.evidenceId, uri.href);
const section = stringVariable(variables.section, uri.href);
const evidence = session.evidenceById(evidenceId);
if (evidence === undefined) throw new ResourceNotFoundError(uri.href);
const value = evidenceSection(evidence.normalized_result, section);
if (value === undefined) throw new ResourceNotFoundError(uri.href);
return jsonResource(uri.href, {
evidence_id: evidence.evidence_id,
operation: evidence.operation,
authority: evidence.authority,
confidence: evidence.confidence,
provider: evidence.provider,
limitations: evidence.limitations,
section,
value,
});
},
);
};
const registerResidualUnknownResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"residual-unknown",
new ResourceTemplate("rea://unknown/{unknownId}", {
list: undefined,
}),
{
title: "Residual unknown",
description: "Current session-owned residual unknown head.",
mimeType: "application/json",
},
(uri, variables) => {
const unknownId = stringVariable(variables.unknownId, uri.href);
const unknown = session
.listUnknowns()
.find(({ unknown_id }) => unknown_id === unknownId);
if (unknown === undefined) throw new ResourceNotFoundError(uri.href);
const history = session
.exportEvidenceBundle()
.unknowns.filter(({ unknown_id }) => unknown_id === unknownId);
return jsonResource(uri.href, { current: unknown, history });
},
);
};
const EVIDENCE_SECTIONS = [
"result",
"terminal",
"filesystem",
"process",
"protocol",
"nodes",
"occurrences",
"edges",
] as const;
const stringVariable = (value: unknown, uri: string): string => {
if (typeof value !== "string") throw new ResourceNotFoundError(uri);
return value;
};
const evidenceSection = (
result: JsonValue,
section: string,
): JsonValue | undefined => {
if (section === "result") return result;
if (typeof result !== "object" || result === null || Array.isArray(result))
return undefined;
if (section === "terminal")
return pick(result, ["frames", "rendered_frames", "interaction_events"]);
if (section === "filesystem")
return pick(result, [
"filesystem_checkpoints",
"filesystem_effects",
"files_before",
"files_after",
]);
if (section === "process")
return pick(result, ["process_samples", "exit", "settlement", "cleanup"]);
if (section === "protocol")
return pick(result, [
"protocol_events",
"replay_transitions",
"shim_events",
]);
const value = result[section];
return value === undefined ? undefined : value;
};
const pick = (
result: Readonly<Record<string, JsonValue>>,
names: readonly string[],
): JsonValue | undefined => {
const entries = names.flatMap((name) =>
result[name] === undefined ? [] : [[name, result[name]] as const],
);
return entries.length === 0 ? undefined : Object.fromEntries(entries);
};
const ARTIFACT_COLLECTIONS = new Set(["nodes", "occurrences", "edges"]);
const objectValue = (
value: JsonValue,
): Readonly<Record<string, JsonValue>> | undefined =>
typeof value === "object" && value !== null && !Array.isArray(value)
? value
: undefined;
const artifactManifestId = (value: JsonValue): string | undefined => {
const manifest = objectValue(objectValue(value)?.manifest ?? null);
return typeof manifest?.manifest_id === "string"
? manifest.manifest_id
: undefined;
};
const functionAddress = (value: JsonValue): string | undefined => {
const result = objectValue(value);
const procedure = objectValue(result?.procedure ?? null);
const candidate = procedure?.address ?? result?.address;
return typeof candidate === "string" ? candidate : undefined;
};
const contentDigest = (value: JsonValue): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Resource is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
+2 -4
View File
@@ -29,7 +29,7 @@ interface EvidenceToolRegistration {
) => readonly Evidence[];
}
/** Register provider-backed contracts that return atomic Evidence v2 observations. */
/** Register provider-backed contracts that return atomic Evidence observations. */
export const registerEvidenceTools = (
server: McpServer,
analysis: AnalysisOperationPort,
@@ -103,9 +103,7 @@ export const registerEvidenceTools = (
const recorded = options.recordEvidence?.(evidence);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, contract)
: toCallToolResult({ ok: true, value: evidence }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
: toCallToolResult({ ok: true, value: evidence }, contract);
},
);
}
+12 -10
View File
@@ -29,20 +29,24 @@ export const registerFunctionComparisonTool = (
};
const left = resolveSessionEvidenceIds(
session,
input.left_evidence_ids,
[input.left_evidence_id],
expected,
);
if (!left.ok) return toCallToolResult(left, contract);
const right = resolveSessionEvidenceIds(
session,
input.right_evidence_ids,
[input.right_evidence_id],
expected,
);
if (!right.ok) return toCallToolResult(right, contract);
const leftIds = left.value.map(({ evidence_id: id }) => id);
const rightIds = right.value.map(({ evidence_id: id }) => id);
const leftEvidence = left.value[0];
const rightEvidence = right.value[0];
if (leftEvidence === undefined || rightEvidence === undefined)
throw new Error("Function comparison Evidence was not resolved");
const leftIds = [leftEvidence.evidence_id];
const rightIds = [rightEvidence.evidence_id];
const computed = await runDerivedOperation(context, contract.name, () =>
compareFunctions(left.value, right.value, input.offset, input.limit),
compareFunctions(leftEvidence, rightEvidence),
);
if (!computed.ok) return toCallToolResult(computed, contract);
const comparison = computed.value;
@@ -50,10 +54,8 @@ export const registerFunctionComparisonTool = (
predicateType: "rea.function-comparison/v1",
operation: contract.name,
parameters: {
left_evidence_ids: leftIds,
right_evidence_ids: rightIds,
offset: input.offset,
limit: input.limit,
left_evidence_id: leftEvidence.evidence_id,
right_evidence_id: rightEvidence.evidence_id,
},
result: jsonValueSchema.parse(comparison),
confidence: "derived",
@@ -102,7 +104,7 @@ const functionUnknownInput = ({
{
operation: "analyze_function",
rationale:
"Capture complete dossiers for both functions under the same target context and analysis limits.",
"Capture complete dossiers for both functions under the same target context.",
},
],
relationships: [],
+3 -35
View File
@@ -5,7 +5,6 @@ import type { BinarySessionPort } from "../application/BinarySession.js";
import { runCrossVersionInvestigationValidated } from "../application/CrossVersionInvestigation.js";
import {
authorizeFileReadWithDeferredWrite,
authorizeRootPermission,
type DeferredFileWriteAuthorization,
} from "../application/DeferredFileAuthorization.js";
import { SESSION_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
@@ -15,11 +14,9 @@ import {
changedBehaviorResultSchema,
findChangedBehavior,
} from "../domain/changedBehavior.js";
import { type AnalysisError } from "../domain/errors.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { verifyReconstruction } from "../domain/reconstructionVerification.js";
import type { Result } from "../domain/result.js";
import { correlateStaticAndRuntime } from "../domain/staticRuntimeCorrelation.js";
import { mcpProgressReporter } from "./mcpProgress.js";
import {
@@ -150,9 +147,6 @@ const runAutomaticInvestigation = async (input: {
const { policies, investigationRun, contract, session } = input;
const progress = mcpProgressReporter(input.context);
let workspaceAuthorization: DeferredFileWriteAuthorization | undefined;
let authorizeInputRead:
| (() => Promise<Result<null, AnalysisError>>)
| undefined;
if (policies.permissionAuthority !== undefined) {
const authority = policies.permissionAuthority;
const authorizedWorkspace = await authorizeFileReadWithDeferredWrite(
@@ -167,13 +161,6 @@ const runAutomaticInvestigation = async (input: {
if (!authorizedWorkspace.ok)
return toCallToolResult(authorizedWorkspace, contract);
workspaceAuthorization = authorizedWorkspace.value;
authorizeInputRead = () =>
authorizeRootPermission(authority, {
capability: "investigation_input",
roots: [investigationRun.left_path, investigationRun.right_path],
access: "read",
operation: contract.name,
});
}
const investigated = await runCrossVersionInvestigationValidated(
investigationRun,
@@ -182,7 +169,6 @@ const runAutomaticInvestigation = async (input: {
...investigationContext({
session,
signal: input.context.mcpReq.signal,
inputRoots: policies.inputRoots,
integrityContinueEnabled:
policies.integrityContinueEnabled?.() ?? false,
progress,
@@ -190,12 +176,10 @@ const runAutomaticInvestigation = async (input: {
...(workspaceAuthorization === undefined
? {}
: { authorizeWorkspaceWrite: workspaceAuthorization.authorizeWrite }),
...(authorizeInputRead === undefined ? {} : { authorizeInputRead }),
},
);
if (!investigated.ok) return toCallToolResult(investigated, contract);
const workspace = investigated.value.workspace;
session.retainInvestigationWorkspace(workspace);
session.retainInvestigationWorkspace(investigated.value.workspace);
const result = changedBehaviorResultSchema.parse(
investigated.value.evidence.normalized_result,
);
@@ -221,19 +205,7 @@ const runAutomaticInvestigation = async (input: {
),
contract,
);
return {
...toolResult,
content: [
...toolResult.content,
{
type: "resource_link" as const,
uri: `rea://workspace/${workspace.workspace_id}/revision/${String(workspace.revision)}`,
name: `${workspace.workspace_id} revision ${String(workspace.revision)}`,
description: "Immutable CAS-linked investigation workspace revision",
mimeType: "application/json",
},
],
};
return toolResult;
};
const registerCallPath = (
@@ -262,10 +234,6 @@ const registerCallPath = (
parameters: {
start: input.start.address,
goal: input.goal.address,
max_depth: input.max_depth,
max_paths: input.max_paths,
offset: input.offset,
limit: input.limit,
},
result: jsonValueSchema.parse(result),
confidence: "derived",
@@ -277,7 +245,7 @@ const registerCallPath = (
session,
evidence,
input.unknown_registry_approved,
result.status === "unknown" || result.status === "truncated",
result.status === "unknown",
{
question:
"Can the requested call path be established from complete analysis?",
@@ -17,25 +17,21 @@ import { AnalysisInputError } from "../../domain/errors.js";
export const investigationContext = ({
session,
signal,
inputRoots,
integrityContinueEnabled,
progress,
}: {
readonly session: BinarySessionPort;
readonly signal: AbortSignal;
readonly inputRoots: readonly string[];
readonly integrityContinueEnabled: boolean;
readonly progress?: ProgressReporter;
}): {
readonly session: BinarySessionPort;
readonly signal: AbortSignal;
readonly inputRoots: readonly string[];
readonly integrityContinueEnabled: boolean;
readonly progress?: ProgressReporter;
} => ({
session,
signal,
inputRoots,
integrityContinueEnabled,
...(progress === undefined ? {} : { progress }),
});
@@ -51,14 +47,8 @@ export const comparisonClosure = (comparisons: readonly Evidence[]): string[] =>
]),
);
export const functionEvidenceIds = (
groups: readonly (Evidence | readonly Evidence[])[],
): string[] =>
uniqueIds(
groups.flatMap((group) =>
(Array.isArray(group) ? group : [group]).map(({ evidence_id: id }) => id),
),
);
export const functionEvidenceIds = (records: readonly Evidence[]): string[] =>
uniqueIds(records.map(({ evidence_id }) => evidence_id));
const uniqueIds = (ids: readonly string[]): string[] =>
[...new Set(ids)].sort((left, right) => left.localeCompare(right));
@@ -4,7 +4,6 @@ import type { PermissionAuthority } from "../../application/PermissionAuthority.
/** Policy inputs shared by all investigation workflow tools. */
export interface InvestigationToolPolicies {
readonly evidenceFiles: EvidenceFilePolicy;
readonly inputRoots: readonly string[];
readonly permissionAuthority?: PermissionAuthority;
readonly integrityContinueEnabled?: () => boolean;
}
@@ -1,86 +0,0 @@
import {
ResourceNotFoundError,
ResourceTemplate,
type McpServer,
} from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySessionPort.js";
import { javascriptApplicationAnalysisResultSchema } from "../domain/javascriptApplicationAnalysis.js";
import { jsonResource } from "./resourceResult.js";
/** Register deterministic pages over one authenticated JavaScript graph. */
export const registerJavaScriptApplicationGraphResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"javascript-application-graph-page",
new ResourceTemplate(
"rea://evidence/{evidenceId}/application-graph/{collection}/offset/{offset}/limit/{limit}",
{
list: undefined,
complete: {
collection: (prefix) =>
["nodes", "edges"].filter((name) => name.startsWith(prefix)),
},
},
),
{
title: "JavaScript application graph page",
description:
"One deterministic bounded node or edge page from authenticated JavaScript application Evidence.",
mimeType: "application/json",
},
(uri, variables) => {
const evidenceId = stringVariable(variables.evidenceId, uri.href);
const collection = stringVariable(variables.collection, uri.href);
if (collection !== "nodes" && collection !== "edges")
throw new ResourceNotFoundError(uri.href);
const offset = pageInteger(variables.offset, uri.href, 0, 100_000);
const limit = pageInteger(variables.limit, uri.href, 1, 500);
const evidence = session.evidenceById(evidenceId);
if (
evidence === undefined ||
evidence.operation !== "analyze_javascript_application"
)
throw new ResourceNotFoundError(uri.href);
const analysis = javascriptApplicationAnalysisResultSchema.safeParse(
evidence.normalized_result,
);
if (!analysis.success) throw new ResourceNotFoundError(uri.href);
const values = analysis.data.graph[collection];
const items = values.slice(offset, offset + limit);
const nextOffset = offset + items.length;
return jsonResource(uri.href, {
evidence_id: evidence.evidence_id,
graph_id: analysis.data.graph.graph_id,
collection,
items,
offset,
limit,
total: values.length,
next_offset: nextOffset < values.length ? nextOffset : null,
has_more: nextOffset < values.length,
});
},
);
};
const stringVariable = (value: unknown, uri: string): string => {
if (typeof value !== "string") throw new ResourceNotFoundError(uri);
return value;
};
const pageInteger = (
value: unknown,
uri: string,
minimum: number,
maximum: number,
): number => {
const text = stringVariable(value, uri);
if (!/^\d+$/u.test(text)) throw new ResourceNotFoundError(uri);
const parsed = Number(text);
if (!Number.isSafeInteger(parsed) || parsed < minimum || parsed > maximum)
throw new ResourceNotFoundError(uri);
return parsed;
};
@@ -84,7 +84,5 @@ const runRuntimeTool = async <Input>(
const recorded = options.recordEvidence?.(result.value);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, contract)
: toCallToolResult({ ok: true, value: result.value }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
: toCallToolResult({ ok: true, value: result.value }, contract);
};
@@ -78,9 +78,6 @@ export const registerCompareManagedMembers = (
return toCallToolResult(
{ ok: true, value: result.value },
compareContract,
{
evidenceResourcesAvailable: output !== undefined,
},
);
},
);
@@ -49,9 +49,7 @@ export const registerImportManagedReconstruction = (
const recorded = options.recordEvidence?.(result.value);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, reconstructionContract);
return toCallToolResult(result, reconstructionContract, {
evidenceResourcesAvailable: recorded !== undefined,
});
return toCallToolResult(result, reconstructionContract);
},
);
};
@@ -51,9 +51,7 @@ export const registerPlanManagedRuntimeCorrelation = (
const recorded = options.recordEvidence?.(result.value);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, runtimeContract);
return toCallToolResult(result, runtimeContract, {
evidenceResourcesAvailable: recorded !== undefined,
});
return toCallToolResult(result, runtimeContract);
},
);
};
@@ -54,7 +54,6 @@ export const registerProjectManagedApplicationGraph = (
if (managedBoundaries !== undefined && !managedBoundaries.ok)
return toCallToolResult(managedBoundaries, graphContract);
const parsed = {
limits: input.limits,
managed_artifact: managedArtifact?.value[0],
managed_members: managedMembers?.value[0],
managed_native_boundaries: managedBoundaries?.value[0],
@@ -74,9 +73,7 @@ export const registerProjectManagedApplicationGraph = (
const recorded = options.recordEvidence?.(result.value);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, graphContract);
return toCallToolResult(result, graphContract, {
evidenceResourcesAvailable: recorded !== undefined,
});
return toCallToolResult(result, graphContract);
},
);
};
@@ -101,9 +101,7 @@ export const registerVerifyManagedNativeBoundaries = (
: options.recordEvidence?.(result.value);
if (output !== undefined && !output.ok)
return toCallToolResult(output, nativeVerificationContract);
return toCallToolResult(result, nativeVerificationContract, {
evidenceResourcesAvailable: output !== undefined,
});
return toCallToolResult(result, nativeVerificationContract);
},
);
};
+1 -3
View File
@@ -108,9 +108,7 @@ const registerOfficialTool = (
const recorded = registration.recordEvidence?.(evidence);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, contract);
return toCallToolResult({ ok: true, value: evidence }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
return toCallToolResult({ ok: true, value: evidence }, contract);
},
);
};
+3 -6
View File
@@ -20,7 +20,7 @@ import { toCallToolResult } from "./toolResult.js";
const PROCESS_CAPTURE_EVIDENCE = {
operation: "capture_process_scenario",
predicate: "rea.process-capture/v4",
predicate: "rea.process-capture",
} as const;
const sourceLocations = (
@@ -80,17 +80,14 @@ export const registerProcessComparisonTool = (
new EvidenceIntegrityError(
cause instanceof Error
? cause.message
: "Invalid Process Capture v4",
: "Invalid process capture",
),
),
contract,
);
}
const evidence = createEvidence(undefined, PROCESS_PROVIDER, {
predicateType:
input.trace_spec === undefined
? "rea.process-comparison/v3"
: "rea.process-comparison/v4",
predicateType: "rea.process-comparison",
operation: contract.name,
parameters: {
left_evidence_id: input.left_evidence_id,
@@ -1,50 +0,0 @@
import {
ResourceNotFoundError,
ResourceTemplate,
type McpServer,
} from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySessionPort.js";
import { reconstructionObligationLedgerPageSchema } from "../domain/reconstructionObligationLedgerSchemas.js";
import { jsonResource } from "./resourceResult.js";
/** Expose retained obligation-ledger pages as typed Evidence resources. */
export const registerReconstructionObligationLedgerResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"reconstruction-obligation-ledger-page",
new ResourceTemplate(
"rea://evidence/{evidenceId}/reconstruction-obligation-ledger",
{
list: undefined,
},
),
{
title: "Reconstruction obligation ledger page",
description:
"One deterministic Evidence v2-backed obligation page with full-ledger closure digest and summaries.",
mimeType: "application/json",
},
(uri, variables) => {
const evidenceId = variables.evidenceId;
if (typeof evidenceId !== "string")
throw new ResourceNotFoundError(uri.href);
const evidence = session.evidenceById(evidenceId);
if (
evidence === undefined ||
evidence.predicate_type !== "rea.reconstruction-obligation-ledger/v1"
)
throw new ResourceNotFoundError(uri.href);
const page = reconstructionObligationLedgerPageSchema.safeParse(
evidence.normalized_result,
);
if (!page.success) throw new ResourceNotFoundError(uri.href);
return jsonResource(uri.href, {
evidence_id: evidence.evidence_id,
page: page.data,
});
},
);
};
@@ -1,50 +0,0 @@
import {
ResourceNotFoundError,
ResourceTemplate,
type McpServer,
} from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySessionPort.js";
import { reconstructionReadinessReportSchema } from "../domain/reconstructionReadinessSchemas.js";
import { jsonResource } from "./resourceResult.js";
/** Expose retained full readiness reports outside compact tool responses. */
export const registerReconstructionReadinessResource = (
server: McpServer,
session: BinarySessionPort,
): void => {
server.registerResource(
"reconstruction-readiness-report",
new ResourceTemplate(
"rea://evidence/{evidenceId}/reconstruction-readiness-report",
{
list: undefined,
},
),
{
title: "Reconstruction readiness report",
description:
"Full deterministic nine-stage conformance report and replay identity.",
mimeType: "application/json",
},
(uri, variables) => {
const evidenceId = variables.evidenceId;
if (typeof evidenceId !== "string")
throw new ResourceNotFoundError(uri.href);
const evidence = session.evidenceById(evidenceId);
if (
evidence === undefined ||
evidence.predicate_type !== "rea.reconstruction-readiness-report/v1"
)
throw new ResourceNotFoundError(uri.href);
const report = reconstructionReadinessReportSchema.safeParse(
evidence.normalized_result,
);
if (!report.success) throw new ResourceNotFoundError(uri.href);
return jsonResource(uri.href, {
evidence_id: evidence.evidence_id,
report: report.data,
});
},
);
};
+5 -134
View File
@@ -23,7 +23,6 @@ interface EvidenceToolRegistration {
readonly exportContract: (typeof SESSION_TOOL_CONTRACTS)[3];
readonly importContract: (typeof SESSION_TOOL_CONTRACTS)[4];
readonly snapshotContract: (typeof SESSION_TOOL_CONTRACTS)[19];
readonly releaseContract: (typeof SESSION_TOOL_CONTRACTS)[20];
readonly filePolicy: EvidenceFilePolicy;
readonly permissionAuthority?: PermissionAuthority;
}
@@ -35,66 +34,6 @@ export const registerEvidenceTools = (
registerExportEvidenceTool(registration);
registerImportEvidenceTool(registration);
registerSnapshotEvidenceTool(registration);
registerReleaseEvidenceTool(registration);
};
const registerReleaseEvidenceTool = ({
server,
session,
releaseContract,
permissionAuthority,
}: EvidenceToolRegistration): void => {
server.registerTool(
releaseContract.name,
toolRegistrationOptions(releaseContract),
async (input) => {
const denied = await authorizeEvidenceWrite({
authority: permissionAuthority,
operationIdentity: `release_evidence:${input.bundle_digest}`,
});
if (denied !== undefined)
return toCallToolResult(denied, releaseContract);
const released = session.releaseEvidenceBundle(input.bundle_digest);
if (released)
void server.server
.sendResourceUpdated({
uri: `rea://evidence-bundle/${input.bundle_digest}`,
})
.catch(() => undefined);
return toCallToolResult(
ok({
bundle_digest: input.bundle_digest,
released,
}),
releaseContract,
);
},
);
};
const authorizeEvidenceWrite = async ({
authority,
operationIdentity,
}: {
readonly authority: PermissionAuthority | undefined;
readonly operationIdentity: string;
}): Promise<Result<never, AnalysisError> | undefined> => {
if (authority === undefined) return undefined;
const authorized = await authority.authorize(
{
capability: "evidence_write",
roots: [],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: operationIdentity,
},
"write",
);
return authorized.ok
? undefined
: err(projectPermissionFailure(authorized.error));
};
const registerExportEvidenceTool = ({
@@ -146,29 +85,8 @@ const registerSnapshotEvidenceTool = ({
server.registerTool(
snapshotContract.name,
toolRegistrationOptions(snapshotContract),
() => {
const snapshot = session.snapshotEvidenceBundle();
if (!snapshot.ok) return toCallToolResult(snapshot, snapshotContract);
const value = {
bundle_digest: snapshot.value.bundleDigest,
bundle_version: snapshot.value.bundleVersion,
bytes: snapshot.value.bytes,
records: snapshot.value.records,
unknowns: snapshot.value.unknowns,
scope: snapshot.value.scope,
survives_session: snapshot.value.survivesSession,
bundle_uri: snapshot.value.uri,
} as const;
return toCallToolResult(ok(value), snapshotContract, {
resourceLinks: [
{
uri: snapshot.value.uri,
name: snapshot.value.bundleDigest,
description: "Immutable session-retained Evidence v2 bundle",
},
],
});
},
() =>
toCallToolResult(ok(session.exportEvidenceBundle()), snapshotContract),
);
};
@@ -275,33 +193,12 @@ const registerListUnknownsTool = ({
: { severity: filters.severity }),
...(filters.domain === undefined ? {} : { domain: filters.domain }),
});
const items = all
.slice(filters.offset, filters.offset + filters.limit)
.map((unknown) => ({
unknown,
uri: `rea://unknown/${unknown.unknown_id}`,
}));
const nextOffset =
filters.offset + items.length < all.length
? filters.offset + items.length
: null;
return toCallToolResult(
ok({
items,
offset: filters.offset,
limit: filters.limit,
items: all,
total: all.length,
next_offset: nextOffset,
has_more: nextOffset !== null,
}),
listContract,
{
resourceLinks: items.map((unknown) => ({
uri: unknown.uri,
name: unknown.unknown.unknown_id,
description: `Current ${unknown.unknown.status} residual unknown revision`,
})),
},
);
},
);
@@ -318,17 +215,7 @@ const registerRecordUnknownTool = ({
toolRegistrationOptions(recordContract),
(input) => {
const result = session.recordUnknown(input);
return result.ok
? toCallToolResult(result, recordContract, {
resourceLinks: [
{
uri: `rea://unknown/${result.value.unknown_id}`,
name: result.value.unknown_id,
description: "Current residual unknown head",
},
],
})
: toCallToolResult(result, recordContract);
return toCallToolResult(result, recordContract);
},
);
};
@@ -344,23 +231,7 @@ const registerUpdateUnknownTool = ({
toolRegistrationOptions(updateContract),
(input) => {
const result = session.updateUnknown(input);
if (result.ok)
void server.server
.sendResourceUpdated({
uri: `rea://unknown/${result.value.unknown_id}`,
})
.catch(() => undefined);
return result.ok
? toCallToolResult(result, updateContract, {
resourceLinks: [
{
uri: `rea://unknown/${result.value.unknown_id}`,
name: result.value.unknown_id,
description: "Updated residual unknown head",
},
],
})
: toCallToolResult(result, updateContract);
return toCallToolResult(result, updateContract);
},
);
};
+7 -94
View File
@@ -1,12 +1,8 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { z } from "zod";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { buildCapabilityInventory } from "../application/CapabilityInventory.js";
import {
binarySessionInputSchema,
SESSION_TOOL_CONTRACTS,
} from "../contracts/toolContracts.js";
import { SESSION_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import type { ClientFeatureAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import { createServerIdentity } from "../serverIdentity.js";
@@ -15,7 +11,6 @@ import type { SessionAvailability } from "./sessionAvailabilityPolicy.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { toCallToolResult } from "./toolResult.js";
type BinarySessionInput = z.output<typeof binarySessionInputSchema>;
type ToolAvailability = ReturnType<typeof buildCapabilityInventory>[number];
/** Inputs required to register the binary session status tool. */
@@ -65,7 +60,6 @@ export const registerSessionStatusTool = (
{
ok: true,
value: projectSessionStatus({
input: input,
status: statusObject,
toolAvailability,
serverIdentity,
@@ -79,97 +73,16 @@ export const registerSessionStatusTool = (
};
const projectSessionStatus = (options: {
readonly input: BinarySessionInput;
readonly status: Readonly<
Record<string, import("../domain/jsonValue.js").JsonValue>
>;
readonly toolAvailability: readonly ToolAvailability[];
readonly serverIdentity: ReturnType<typeof createServerIdentity>;
readonly clientFeatures: ClientFeatureAvailability;
}) => {
if (options.input.detail === "full")
return jsonObjectSchema.parse({
view: "full",
...options.status,
tool_availability: options.toolAvailability,
client_features: options.clientFeatures,
server_identity: options.serverIdentity,
});
const open = options.status.open === true;
const activeProvider = activeProviderFrom(options.status);
if (options.input.detail === "capabilities") {
const filtered =
options.input.capability_family === undefined
? options.toolAvailability
: options.toolAvailability.filter(
({ surface }) => surface === options.input.capability_family,
);
const items = filtered.slice(
options.input.cursor,
options.input.cursor + options.input.limit,
);
const nextCursor = options.input.cursor + items.length;
return jsonObjectSchema.parse({
view: "capabilities",
open,
provider: options.status.provider,
active_provider: activeProvider,
capability_family: options.input.capability_family ?? null,
capabilities: {
items,
cursor: options.input.cursor,
limit: options.input.limit,
total: filtered.length,
next_cursor: nextCursor < filtered.length ? nextCursor : null,
has_more: nextCursor < filtered.length,
},
client_features: options.clientFeatures,
});
}
return jsonObjectSchema.parse({
view: "summary",
open,
provider: options.status.provider,
active_provider: activeProvider,
target: open ? targetFrom(options.status) : null,
alignment: options.serverIdentity.alignment,
analysis_activity: options.status.analysis_activity,
recommended_actions: recommendedActions(
open,
options.serverIdentity.alignment.state,
),
}) =>
jsonObjectSchema.parse({
...options.status,
tool_availability: options.toolAvailability,
client_features: options.clientFeatures,
server_identity: options.serverIdentity,
});
};
const activeProviderFrom = (
status: Readonly<Record<string, import("../domain/jsonValue.js").JsonValue>>,
) => {
const binding = jsonObjectSchema.safeParse(status.analysis_provider_binding);
return binding.success ? (binding.data.provider ?? null) : null;
};
const targetFrom = (
status: Readonly<Record<string, import("../domain/jsonValue.js").JsonValue>>,
) => ({
path: status.path,
format: status.format,
kind: status.kind,
sha256: status.sha256,
architecture: status.architecture ?? null,
});
const recommendedActions = (
open: boolean,
alignment: string,
): readonly string[] => [
...(alignment === "mcp_server_restart_required"
? ["Restart the registered MCP server or client before continuing."]
: []),
...(!open
? [
"For a supplied target, route by format: ASAR/JavaScript to analyze_javascript_application; archive/package to open_binary(path), then inspect_artifact or inventory_artifact on the active target; managed PE/CLI to inspect_managed_artifact; browser/Electron runtimes to their list-target tools; native binaries to open_binary.",
]
: [
"Continue from the active target with binary_overview or a bounded target-specific query.",
]),
];
+2 -7
View File
@@ -281,7 +281,6 @@ const registerOpenLifecycleTool = ({
export interface SessionToolOptions {
readonly processPolicy?: () => ProcessExecutionPolicy;
readonly evidenceFilePolicy?: EvidenceFilePolicy;
readonly investigationInputRoots?: readonly string[];
readonly analysisSnapshotFilePolicy?: EvidenceFilePolicy;
readonly startedAt?: string;
readonly permissionAuthority?: PermissionAuthority;
@@ -307,8 +306,8 @@ const registerContextTools = (
server: McpServer,
session: BinarySessionPort,
): void => {
const navigationContract = SESSION_TOOL_CONTRACTS[21];
const addressContract = SESSION_TOOL_CONTRACTS[22];
const navigationContract = SESSION_TOOL_CONTRACTS[20];
const addressContract = SESSION_TOOL_CONTRACTS[21];
server.registerTool(
navigationContract.name,
toolRegistrationOptions(navigationContract),
@@ -359,7 +358,6 @@ export const registerSessionTools = (
reconstructionContract,
] = SESSION_TOOL_CONTRACTS;
const snapshotContract = SESSION_TOOL_CONTRACTS[19];
const releaseContract = SESSION_TOOL_CONTRACTS[20];
registerLifecycleTools({
server,
session,
@@ -370,7 +368,6 @@ export const registerSessionTools = (
availabilityPolicy: sessionAvailabilityPolicy(options.availabilityPolicy, {
processPolicy: processPolicy(),
evidenceFilePolicy,
investigationInputRoots: options.investigationInputRoots ?? [],
}),
...(options.permissionAuthority === undefined
? {}
@@ -382,7 +379,6 @@ export const registerSessionTools = (
exportContract,
importContract,
snapshotContract,
releaseContract,
filePolicy: evidenceFilePolicy,
...(options.permissionAuthority === undefined
? {}
@@ -418,7 +414,6 @@ export const registerSessionTools = (
] as const;
registerInvestigationTools(server, session, investigationContracts, {
evidenceFiles: evidenceFilePolicy,
inputRoots: options.investigationInputRoots ?? [],
...(options.artifactIntegrityContinueEnabled === undefined
? {}
: {
-12
View File
@@ -1,12 +0,0 @@
import type { JsonValue } from "../domain/jsonValue.js";
/** Encode one JSON value as an MCP resource with its requested URI. */
export const jsonResource = (uri: string, value: JsonValue) => ({
contents: [
{
uri,
mimeType: "application/json" as const,
text: JSON.stringify(value, null, 2),
},
],
});
-2
View File
@@ -7,7 +7,6 @@ export type SessionAvailability = AvailabilityPolicy;
export interface SessionAvailabilityDefaults {
readonly processPolicy: ProcessExecutionPolicy;
readonly evidenceFilePolicy: EvidenceFilePolicy;
readonly investigationInputRoots: readonly string[];
readonly optionalFeatures?: Pick<
SessionAvailability,
| "browserObservationEnabled"
@@ -29,7 +28,6 @@ export const sessionAvailabilityPolicy = (
(() => ({
processCaptureEnabled: defaults.processPolicy.status === "enabled",
evidenceFileRoots: defaults.evidenceFilePolicy.roots.length,
investigationInputRoots: defaults.investigationInputRoots.length,
browserObservationEnabled:
defaults.optionalFeatures?.browserObservationEnabled ?? false,
browserScenarioEnabled:
+15 -85
View File
@@ -5,17 +5,6 @@ import { projectAnalysisError, type AnalysisError } from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Result } from "../domain/result.js";
interface ToolResultOptions {
readonly evidenceResourcesAvailable?: boolean;
readonly evidenceResultProjection?: JsonValue;
readonly evidenceTextProjection?: JsonValue;
readonly resourceLinks?: readonly {
readonly uri: string;
readonly name: string;
readonly description: string;
}[];
}
/**
* Translate an application result into MCP text content.
* Error tags and safe messages remain visible while underlying causes, process
@@ -24,11 +13,8 @@ interface ToolResultOptions {
export const toCallToolResult = (
result: Result<JsonValue, AnalysisError>,
contract: ToolContract,
options: ToolResultOptions = {},
): CallToolResult =>
result.ok
? successResult(result.value, contract, options)
: errorResult(result.error);
result.ok ? successResult(result.value, contract) : errorResult(result.error);
const errorResult = (error: AnalysisError): CallToolResult => {
const projected = projectAnalysisError(error);
@@ -48,62 +34,22 @@ const errorResult = (error: AnalysisError): CallToolResult => {
const successResult = (
value: JsonValue,
contract: ToolContract,
options: ToolResultOptions,
): CallToolResult => {
const candidate =
compactEvidence(value, options.evidenceResultProjection) ??
compactEvidence(value) ??
(contract.kind === "session" ? { result: value } : value);
return {
content: [
{
type: "text",
text: JSON.stringify(
options.evidenceTextProjection === undefined
? candidate
: (compactEvidence(value, options.evidenceTextProjection) ??
options.evidenceTextProjection),
),
text: JSON.stringify(candidate),
},
...(hasResourceLinks(value, contract, options)
? [
{
type: "text" as const,
text: "Full detail is available through MCP resources/read. Copy the opaque URI exactly. In Codex, call read_mcp_resource.",
},
]
: []),
...evidenceResourceLinks(
value,
contract.kind === "session" ||
options.evidenceResourcesAvailable === true,
),
...(options.resourceLinks ?? []).map((resource) => ({
type: "resource_link" as const,
...resource,
mimeType: "application/json" as const,
})),
],
structuredContent: candidate,
};
};
const hasResourceLinks = (
value: JsonValue,
contract: ToolContract,
options: ToolResultOptions,
): boolean =>
options.resourceLinks !== undefined && options.resourceLinks.length > 0
? true
: evidenceResourceLinks(
value,
contract.kind === "session" ||
options.evidenceResourcesAvailable === true,
).length > 0;
const compactEvidence = (
value: JsonValue,
resultProjection: JsonValue | undefined,
): JsonValue | undefined => {
const compactEvidence = (value: JsonValue): JsonValue | undefined => {
if (
typeof value !== "object" ||
value === null ||
@@ -113,33 +59,17 @@ const compactEvidence = (
!("normalized_result" in value)
)
return undefined;
const evidence = value as Record<string, JsonValue>;
const normalizedResult = evidence.normalized_result;
const evidenceId = evidence.evidence_id;
if (normalizedResult === undefined || typeof evidenceId !== "string")
return undefined;
const inlineEvidence = Object.fromEntries(
Object.entries(evidence).filter(([key]) => key !== "normalized_result"),
);
return {
result: resultProjection ?? value.normalized_result,
evidence_id: value.evidence_id,
evidence_uri: `rea://evidence/${value.evidence_id}`,
result: normalizedResult,
evidence_id: evidenceId,
evidence: inlineEvidence,
};
};
const evidenceResourceLinks = (
value: JsonValue,
available: boolean,
): CallToolResult["content"] => {
if (
!available ||
typeof value !== "object" ||
value === null ||
Array.isArray(value) ||
typeof value.evidence_id !== "string" ||
!/^ev_[a-f0-9]{64}$/u.test(value.evidence_id)
)
return [];
return [
{
type: "resource_link",
uri: `rea://evidence/${value.evidence_id}`,
name: value.evidence_id,
description: "Session-owned Evidence v2 record",
mimeType: "application/json",
},
];
};