feat(mcp)!: harden contracts and evidence references

BREAKING CHANGE: comparison tools now require session-owned Evidence IDs or approved bundle paths, and structured Evidence results use compact references.
This commit is contained in:
morluto
2026-07-16 19:49:58 +08:00
parent ad398a17f5
commit ee1cd40405
47 changed files with 1387 additions and 672 deletions
+9 -25
View File
@@ -6,39 +6,33 @@ import {
applicationFeatureTraceResultSchema,
traceApplicationFeatureInputSchema,
} from "../domain/javascriptFeatureTraceSchemas.js";
import { evidenceEnvelopeSchema } from "../domain/evidence.js";
import {
controlledReplayInputSchema,
controlledReplayOutputSchema,
} from "../domain/javascriptReplay.js";
import type { ToolContract } from "./toolContracts.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemas.js";
import {
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
} from "./javascriptApplicationWorkflowExamples.js";
const traceOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: applicationFeatureTraceResultSchema });
const comparisonOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: applicationVersionComparisonResultSchema });
const traceOutputSchema = evidenceResultOf(applicationFeatureTraceResultSchema);
const comparisonOutputSchema = evidenceResultOf(
applicationVersionComparisonResultSchema,
);
/** Provider-neutral graph workflow contracts shared by MCP and CLI adapters. */
export const APPLICATION_TOOL_CONTRACTS = [
{
name: "trace_application_feature",
...toolContractMetadata("trace_application_feature"),
description:
"Trace a typed literal seed through an authenticated JavaScript Application Graph with explicit direction, depth, node, edge, and path bounds. Original static, native, passive-runtime, inferred, and unknown authorities remain distinct; native addon handoffs never open a provider or execute the application.",
kind: "application",
inputSchema: traceApplicationFeatureInputSchema,
outputSchema: traceOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Trace one module seed through a retained application graph",
@@ -48,17 +42,12 @@ export const APPLICATION_TOOL_CONTRACTS = [
},
{
name: "compare_application_versions",
...toolContractMetadata("compare_application_versions"),
description:
"Compare two authenticated JavaScript Application Graph versions using unique-only exact digest, module source digest, source-map identity, structural fingerprint, and non-module semantic-key tiers. Reports added, removed, changed, ambiguous, and unknown entities plus a bounded changed_from graph without fuzzy or module-ordinal pairing.",
kind: "application",
inputSchema: compareApplicationVersionsInputSchema,
outputSchema: comparisonOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Compare authenticated static and reconciled application graphs",
@@ -68,17 +57,12 @@ export const APPLICATION_TOOL_CONTRACTS = [
},
{
name: "run_controlled_replay",
...toolContractMetadata("run_controlled_replay"),
description:
"Plan or execute a content-bound extracted-module JavaScript replay inside the Linux Bubblewrap, seccomp, and cgroup boundary. Execution requires approved: true and the exact plan digest. Supports deterministic boundary cases and optional left/right differential comparison; observations have controlled-replay authority and do not claim real application runtime behavior.",
kind: "application",
inputSchema: controlledReplayInputSchema,
outputSchema: controlledReplayOutputSchema,
annotations: {
readOnlyHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Plan one extracted ESM parser replay",
+2 -9
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import type { ToolContract } from "./toolContracts.js";
import { artifactOutputSchemas } from "./toolOutputSchemas.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { toolContractMetadata } from "./toolEffects.js";
const pageInput = {
node_offset: z.number().int().min(0).default(0),
@@ -81,23 +82,17 @@ const artifact = <Name extends string>(
name: Name,
description: string,
inputSchema: z.ZodObject,
mutatesFilesystem: boolean,
): ToolContract<Name> => {
const outputSchema = artifactOutputSchemas[name];
if (outputSchema === undefined)
throw new Error(`Missing artifact output schema for ${name}`);
return {
name,
...toolContractMetadata(name),
description,
kind: "artifact-provider",
inputSchema,
outputSchema,
annotations: {
readOnlyHint: !mutatesFilesystem,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: `Example ${name.replaceAll("_", " ")} request`,
@@ -113,13 +108,11 @@ export const ARTIFACT_TOOL_CONTRACTS = [
"inventory_artifact",
"Inventory the active application or package as a deterministic, content-addressed artifact graph. Returns bounded node and edge pages without extracting or mounting by default.",
artifactInventoryInputSchema,
false,
),
artifact(
"extract_artifact",
"Extract selected graph artifacts beneath an explicit output root. Requires approval, rejects traversal and symlink escapes, never overwrites, enforces bomb limits, and verifies cleanup.",
artifactExtractionInputSchema,
true,
),
] as const satisfies readonly ToolContract[];
+16 -63
View File
@@ -1,6 +1,4 @@
import type { ToolContract } from "./toolContracts.js";
import { z } from "zod";
import { evidenceEnvelopeSchema } from "../domain/evidence.js";
import {
browserTargetListSchema,
inspectWebPageInputSchema,
@@ -29,21 +27,16 @@ import {
webScreenshotDiffSchema,
webScreenshotSchema,
} from "../domain/webScreenshot.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemas.js";
const evidenceResult = <Schema extends z.ZodType>(schema: Schema) =>
evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: schema });
const evidenceResult = evidenceResultOf;
const listOutputSchema = evidenceResult(browserTargetListSchema);
const inspectionOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: webPageInspectionSchema });
const bundleOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: webBundleAnalysisSchema });
const observationSessionOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: webObservationSessionSchema });
const inspectionOutputSchema = evidenceResult(webPageInspectionSchema);
const bundleOutputSchema = evidenceResult(webBundleAnalysisSchema);
const observationSessionOutputSchema = evidenceResult(
webObservationSessionSchema,
);
const webMcpOutputSchema = evidenceResult(webMcpDiscoverySchema);
const captureDiffOutputSchema = evidenceResult(webCaptureDiffSchema);
const screenshotOutputSchema = evidenceResult(webScreenshotSchema);
@@ -56,17 +49,12 @@ const origin = "https://app.example.test";
export const BROWSER_TOOL_CONTRACTS = [
{
name: "list_browser_targets",
...toolContractMetadata("list_browser_targets"),
description:
"List bounded page targets from an approved user-owned loopback Chrome DevTools Protocol endpoint. Only targets whose current URL matches an approved exact origin are returned; URL credentials, query values, and fragments are redacted.",
kind: "browser-provider",
inputSchema: listBrowserTargetsInputSchema,
outputSchema: listOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
examples: [
{
title: "List approved browser page targets",
@@ -82,17 +70,12 @@ export const BROWSER_TOOL_CONTRACTS = [
},
{
name: "inspect_web_page",
...toolContractMetadata("inspect_web_page"),
description:
"Passively inspect one approved page target through CDP without evaluating JavaScript, navigating, clicking, closing, or mutating the page. Returns bounded DOM structure, accessibility, scripts, resources, attach-window network and console metadata, workers, and redacted storage inventory as Evidence v2.",
kind: "browser-provider",
inputSchema: inspectWebPageInputSchema,
outputSchema: inspectionOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
examples: [
{
title: "Inspect one approved browser page",
@@ -141,17 +124,12 @@ export const BROWSER_TOOL_CONTRACTS = [
},
{
name: "analyze_web_bundle",
...toolContractMetadata("analyze_web_bundle"),
description:
"Capture explicitly approved JavaScript source from one approved CDP page and statically derive a bounded chunk graph, route and endpoint candidates, vendor fingerprints, page-declared WebMCP metadata, and optional separately approved source-map evidence. JavaScript is parsed but never executed.",
kind: "browser-provider",
inputSchema: analyzeWebBundleInputSchema,
outputSchema: bundleOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
examples: [
{
title: "Analyze an approved page bundle",
@@ -182,17 +160,12 @@ export const BROWSER_TOOL_CONTRACTS = [
},
{
name: "observe_web_session",
...toolContractMetadata("observe_web_session"),
description:
"Arm a bounded CDP observation window while the user operates the page. Allows approved same-origin reload and SPA navigation, records ordered navigation, redirect, lifecycle, and failure metadata, and stops before retaining an out-of-policy destination.",
kind: "browser-provider",
inputSchema: observeWebSessionInputSchema,
outputSchema: observationSessionOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true,
},
examples: [
{
title: "Observe one external user action",
@@ -209,17 +182,12 @@ export const BROWSER_TOOL_CONTRACTS = [
},
{
name: "discover_webmcp_tools",
...toolContractMetadata("discover_webmcp_tools"),
description:
"Passively inventory page-registered WebMCP tools using the experimental CDP WebMCP domain. Metadata is bounded and page-declared-untrusted; REA never registers or invokes discovered tools.",
kind: "browser-provider",
inputSchema: discoverWebMcpToolsInputSchema,
outputSchema: webMcpOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
examples: [
{
title: "Discover current WebMCP declarations",
@@ -239,17 +207,12 @@ export const BROWSER_TOOL_CONTRACTS = [
},
{
name: "compare_web_captures",
...toolContractMetadata("compare_web_captures"),
description:
"Compare two normalized web captures across DOM, scripts, resources, network, safe metadata, and optional WebMCP inventories. Stable observed changes are distinguished from unknown absence caused by incomplete capture coverage.",
kind: "browser-provider",
inputSchema: compareWebCapturesInputSchema,
outputSchema: captureDiffOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Compare two normalized captures",
@@ -263,17 +226,12 @@ export const BROWSER_TOOL_CONTRACTS = [
},
{
name: "capture_web_screenshot",
...toolContractMetadata("capture_web_screenshot"),
description:
"Capture the current visible viewport of one approved page as a bounded, content-addressed PNG artifact. Screenshot capture requires separate explicit approval and never scrolls, navigates, or evaluates page JavaScript.",
kind: "browser-provider",
inputSchema: captureWebScreenshotInputSchema,
outputSchema: screenshotOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true,
},
examples: [
{
title: "Capture an approved viewport",
@@ -290,17 +248,12 @@ export const BROWSER_TOOL_CONTRACTS = [
},
{
name: "compare_web_screenshots",
...toolContractMetadata("compare_web_screenshots"),
description:
"Compare two self-verifying PNG screenshot artifacts with bounded local pixel metrics. Returns exact changed-pixel ratios and channel deltas without OCR or external services.",
kind: "browser-provider",
inputSchema: compareWebScreenshotsInputSchema,
outputSchema: screenshotDiffOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Compare two screenshot artifacts",
+14 -37
View File
@@ -1,5 +1,6 @@
import type { ToolContract } from "./toolContracts.js";
import { evidenceEnvelopeSchema } from "../domain/evidence.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemas.js";
import {
electronPageInspectionSchema,
electronTargetListSchema,
@@ -16,18 +17,14 @@ import {
} from "../domain/javascriptRuntimeReconciliationSchemas.js";
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "./javascriptRuntimeReconciliationExample.js";
const listOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: electronTargetListSchema });
const inspectionOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: electronPageInspectionSchema });
const applicationOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: javascriptApplicationAnalysisResultSchema });
const reconciliationOutputSchema = evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: javascriptRuntimeReconciliationResultSchema });
const listOutputSchema = evidenceResultOf(electronTargetListSchema);
const inspectionOutputSchema = evidenceResultOf(electronPageInspectionSchema);
const applicationOutputSchema = evidenceResultOf(
javascriptApplicationAnalysisResultSchema,
);
const reconciliationOutputSchema = evidenceResultOf(
javascriptRuntimeReconciliationResultSchema,
);
const endpoint = "http://127.0.0.1:9223";
const root = "/Applications/Example.app/Contents/Resources";
@@ -36,17 +33,12 @@ const root = "/Applications/Example.app/Contents/Resources";
export const ELECTRON_TOOL_CONTRACTS = [
{
name: "list_electron_targets",
...toolContractMetadata("list_electron_targets"),
description:
"List Electron file:// page targets from an approved user-owned loopback CDP endpoint. Every path is canonicalized and must remain contained by an approved filesystem root, including after symlink resolution.",
kind: "electron-provider",
inputSchema: listElectronTargetsInputSchema,
outputSchema: listOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
examples: [
{
title: "List approved Electron file pages",
@@ -62,17 +54,12 @@ export const ELECTRON_TOOL_CONTRACTS = [
},
{
name: "inspect_electron_page",
...toolContractMetadata("inspect_electron_page"),
description:
"Passively inspect one approved Electron file page through CDP. Returns root-confined frames, DOM structure, resource paths, and scripts without evaluating renderer JavaScript or invoking Electron APIs; script contents require separate approval.",
kind: "electron-provider",
inputSchema: inspectElectronPageInputSchema,
outputSchema: inspectionOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
examples: [
{
title: "Inspect an approved Electron page",
@@ -99,17 +86,12 @@ export const ELECTRON_TOOL_CONTRACTS = [
},
{
name: "analyze_javascript_application",
...toolContractMetadata("analyze_javascript_application"),
description:
"Statically reconstruct one approved local ASAR or extracted JavaScript application as Evidence v2 and JavaScript Application Graph v1. Maps BrowserWindow preferences, preload and contextBridge APIs, literal and dynamic IPC, handler locations, sender-validation observations, utility processes, and requested native addon bindings without executing JavaScript; source-map contents require separate approval.",
kind: "electron-provider",
inputSchema: analyzeJavaScriptApplicationInputSchema,
outputSchema: applicationOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Analyze one approved local Electron application",
@@ -124,17 +106,12 @@ export const ELECTRON_TOOL_CONTRACTS = [
},
{
name: "reconcile_javascript_runtime",
...toolContractMetadata("reconcile_javascript_runtime"),
description:
"Reconcile verified static JavaScript application graphs with existing passive web or Electron CDP Evidence. Exact captured-source digests take priority over caller-declared file/URL mappings; target, frame, script, and worker ambiguity remains explicit, and source-map authority stays separate.",
kind: "electron-provider",
inputSchema: reconcileJavaScriptRuntimeInputSchema,
outputSchema: reconciliationOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Reconcile one passive Electron capture",
-6
View File
@@ -1,7 +1,6 @@
import { compareFunctions } from "../domain/functionComparison.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import {
compareProcessCaptures,
processCaptureSchema,
@@ -130,10 +129,5 @@ export const INVESTIGATION_EXAMPLES = {
},
],
},
evidence_bundle: createEvidenceBundle([
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
]),
},
};
+2 -6
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import type { ToolContract } from "./toolContracts.js";
import { managedOutputSchemas } from "./toolOutputSchemas.js";
import { toolContractMetadata } from "./toolEffects.js";
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
export const managedArtifactInputSchema = z.object({
@@ -119,17 +120,12 @@ if (nativeBoundaryOutputSchema === undefined)
export const MANAGED_TOOL_CONTRACTS = [
{
name: "inspect_managed_artifact",
...toolContractMetadata("inspect_managed_artifact"),
description:
"Classify the active PE/CLI artifact and inventory exact assembly/module identity, target framework evidence, references, resources, and custom attributes without loading or executing target code. Returns bounded pages and explicit partial or malformed coverage.",
kind: "managed-provider",
inputSchema: managedArtifactInputSchema,
outputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Example inspect managed artifact request",
+2 -6
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import type { ToolContract } from "./toolContracts.js";
import { nativeOutputSchemas } from "./toolOutputSchemas.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { toolContractMetadata } from "./toolEffects.js";
const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
inspect_macho: {},
@@ -22,16 +23,11 @@ const native = <Name extends string>(
throw new Error(`Missing native output schema for ${name}`);
return {
name,
...toolContractMetadata(name),
description,
kind: "native-provider",
inputSchema,
outputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: `Example ${name.replaceAll("_", " ")} request`,
+10 -25
View File
@@ -1,5 +1,4 @@
import type { JsonValue } from "../domain/jsonValue.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js";
import { UNKNOWN_CONTRACT_EXAMPLES } from "./unknownContractExamples.js";
import { ARTIFACT_COMPARISON_EXAMPLE } from "./artifactComparisonExample.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "./functionComparisonExample.js";
@@ -42,32 +41,18 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
},
compare_process_captures: {
left_evidence_id: `ev_${"0".repeat(64)}`,
left: EMPTY_PROCESS_CAPTURE_EXAMPLE,
right_evidence_id: `ev_${"1".repeat(64)}`,
right: EMPTY_PROCESS_CAPTURE_EXAMPLE,
},
compare_artifacts: ARTIFACT_COMPARISON_EXAMPLE,
compare_functions: FUNCTION_COMPARISON_EXAMPLE,
compare_artifacts: {
left_evidence_ids: [ARTIFACT_COMPARISON_EXAMPLE.left.evidence_id],
right_evidence_ids: [ARTIFACT_COMPARISON_EXAMPLE.right.evidence_id],
},
compare_functions: {
left_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
},
compare_bundles: {
left: {
bundle_version: 2,
artifacts: [],
providers: [],
environments: [],
scenarios: [],
captures: [],
unknowns: [],
records: [],
},
right: {
bundle_version: 2,
artifacts: [],
providers: [],
environments: [],
scenarios: [],
captures: [],
unknowns: [],
records: [],
},
left_bundle_path: "/approved/left-evidence.json",
right_bundle_path: "/approved/right-evidence.json",
},
};
+5 -2
View File
@@ -1,9 +1,10 @@
import type { z } from "zod";
import type { JsonValue } from "../domain/jsonValue.js";
import type { ToolEffects } from "./toolEffects.js";
/** Caller-visible MCP execution hints. */
export interface ToolAnnotations {
interface ToolAnnotations {
readonly readOnlyHint: boolean;
readonly destructiveHint: boolean;
readonly idempotentHint: boolean;
@@ -17,7 +18,7 @@ export interface ToolExample {
}
/** Adapter family responsible for implementing a public MCP tool. */
export type ToolKind =
type ToolKind =
| "official-proxy"
| "enhanced"
| "native-provider"
@@ -31,10 +32,12 @@ export type ToolKind =
/** Single source of truth for a public MCP tool. */
export interface ToolContract<Name extends string = string> {
readonly name: Name;
readonly title: string;
readonly description: string;
readonly kind: ToolKind;
readonly inputSchema: z.ZodObject;
readonly outputSchema: z.ZodObject;
readonly effects: ToolEffects;
readonly annotations: ToolAnnotations;
readonly examples: readonly ToolExample[];
}
+48 -63
View File
@@ -1,9 +1,6 @@
import { z } from "zod";
import { jsonValueSchema } from "../domain/jsonValue.js";
import {
processCaptureSchema,
processScenarioSchema,
} from "../domain/processCapture.js";
import { processScenarioSchema } from "../domain/processCapture.js";
import {
recordUnknownInputSchema,
updateUnknownInputSchema,
@@ -35,18 +32,10 @@ import {
closeBinaryInputSchema,
openBinaryInputSchema,
} from "./sessionLifecycleInputs.js";
import type {
ToolAnnotations,
ToolContract,
ToolExample,
ToolKind,
} from "./toolContractTypes.js";
import type { ToolContract, ToolExample } from "./toolContractTypes.js";
import { toolContractMetadata } from "./toolEffects.js";
export type {
ToolAnnotations,
ToolContract,
ToolExample,
} from "./toolContractTypes.js";
export type { ToolContract, ToolExample } from "./toolContractTypes.js";
const document = z.string().optional().describe("The document name");
const address = z
@@ -92,27 +81,6 @@ const examplesFor = (
];
};
const annotations = (name: string, kind: ToolKind): ToolAnnotations => ({
readOnlyHint:
(kind === "enhanced" && name !== "trace_feature") ||
name === "binary_session" ||
name === "list_unknowns" ||
name === "verify_unknown_resolution",
destructiveHint:
name === "export_evidence_bundle" ||
name === "close_binary" ||
name === "unset_bookmark" ||
name === "set_address_name" ||
name === "set_addresses_names" ||
name === "set_comment" ||
name === "set_inline_comment",
idempotentHint:
name !== "close_binary" &&
name !== "record_unknown" &&
name !== "update_unknown",
openWorldHint: name === "capture_process_scenario",
});
const official = <Name extends string>(
name: Name,
description: string,
@@ -128,11 +96,11 @@ const official = <Name extends string>(
});
return {
name,
...toolContractMetadata(name),
description,
kind: "official-proxy",
inputSchema: trackedInputSchema,
outputSchema: requireOutputSchema(officialOutputSchemas, name),
annotations: annotations(name, "official-proxy"),
examples: examplesFor(name, trackedInputSchema),
};
};
@@ -143,11 +111,11 @@ const enhanced = <Name extends string>(
inputSchema: z.ZodObject,
): ToolContract<Name> => ({
name,
...toolContractMetadata(name),
description,
kind: "enhanced",
inputSchema,
outputSchema: requireOutputSchema(enhancedOutputSchemas, name),
annotations: annotations(name, "enhanced"),
examples: examplesFor(name, inputSchema),
});
@@ -157,11 +125,11 @@ const session = <Name extends string>(
inputSchema: z.ZodObject,
): ToolContract<Name> => ({
name,
...toolContractMetadata(name),
description,
kind: "session",
inputSchema,
outputSchema: requireOutputSchema(sessionOutputSchemas, name),
annotations: annotations(name, "session"),
examples: examplesFor(name, inputSchema),
});
@@ -408,6 +376,42 @@ export const binarySessionInputSchema = z.object({
expected_server_path: z.string().min(1).optional(),
});
/** Session-owned Evidence bundle export options. */
export const exportEvidenceBundleInputSchema = z.strictObject({
path: z.string().min(1).optional(),
overwrite: z.boolean().default(false),
});
/** Session-owned Evidence bundle import options. */
export const importEvidenceBundleInputSchema = z.strictObject({
path: z.string().min(1),
});
/** Evidence references for deterministic process comparison. */
export const processComparisonInputSchema = z.strictObject({
left_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
right_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
max_capture_age_ms: z.number().int().nonnegative().optional(),
unknown_registry_approved: z
.literal(true)
.optional()
.describe("Explicit approval to record capture disagreement durably"),
});
/** Residual-unknown list filters. */
export const listUnknownsInputSchema = z.strictObject({
status: z
.enum(["open", "investigating", "blocked", "contradicted", "resolved"])
.optional(),
severity: z.enum(["low", "medium", "high", "critical"]).optional(),
domain: z.string().trim().min(1).max(100).optional(),
});
/** Exact residual-unknown identity to revalidate. */
export const verifyUnknownResolutionInputSchema = z.strictObject({
unknown_id: z.string().regex(/^unk_[a-f0-9]{64}$/u),
});
/** Target lifecycle tools available only on the long-lived MCP adapter. */
export const SESSION_TOOL_CONTRACTS = [
session(
@@ -428,15 +432,12 @@ export const SESSION_TOOL_CONTRACTS = [
session(
"export_evidence_bundle",
"Return the session's deterministic Evidence v2 bundle, or atomically write it beneath an operator-approved root. Existing files require overwrite: true; records and manifests use canonical byte-stable ordering.",
z.object({
path: z.string().min(1).optional(),
overwrite: z.boolean().default(false),
}),
exportEvidenceBundleInputSchema,
),
session(
"import_evidence_bundle",
"Read a bounded local JSON bundle beneath an operator-approved root, validate every Evidence v2 ID and canonical manifest, then atomically merge it. Imported content is data only and is never executed.",
z.object({ path: z.string().min(1) }),
importEvidenceBundleInputSchema,
),
session(
"capture_process_scenario",
@@ -446,17 +447,7 @@ export const SESSION_TOOL_CONTRACTS = [
session(
"compare_process_captures",
"Compare two compatible Process Capture v4 observations across terminal, interaction, exit, settlement, process, filesystem, command-shim, HTTP, and WebSocket evidence, returning the first bounded divergence. Process Capture v3 is unsupported and must be recaptured with capture_process_scenario. Missing or truncated observations are never treated as equivalent.",
z.object({
left_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
left: processCaptureSchema,
right_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
right: processCaptureSchema,
max_capture_age_ms: z.number().int().nonnegative().optional(),
unknown_registry_approved: z
.literal(true)
.optional()
.describe("Explicit approval to record capture disagreement durably"),
}),
processComparisonInputSchema,
),
session(
"compare_artifacts",
@@ -496,13 +487,7 @@ export const SESSION_TOOL_CONTRACTS = [
session(
"list_unknowns",
"List current residual-unknown heads in deterministic ID order, with optional exact status, severity, and domain filters. This is read-only; unresolved, contradicted, and non-truth dispositions remain distinct.",
z.object({
status: z
.enum(["open", "investigating", "blocked", "contradicted", "resolved"])
.optional(),
severity: z.enum(["low", "medium", "high", "critical"]).optional(),
domain: z.string().trim().min(1).max(100).optional(),
}),
listUnknownsInputSchema,
),
session(
"record_unknown",
@@ -517,7 +502,7 @@ export const SESSION_TOOL_CONTRACTS = [
session(
"verify_unknown_resolution",
"Revalidate the current residual-unknown head against live bundled evidence, exact authority/confidence/environment requirements, and revision integrity. Withdrawn and out-of-scope dispositions are not truth claims.",
z.object({ unknown_id: z.string().regex(/^unk_[a-f0-9]{64}$/u) }),
verifyUnknownResolutionInputSchema,
),
] as const satisfies readonly ToolContract[];
+181
View File
@@ -0,0 +1,181 @@
/** Canonical side effects for one caller-visible tool. */
export interface ToolEffects {
readonly mutatesTarget: boolean;
readonly mutatesSession: boolean;
readonly writesFilesystem: boolean;
readonly launchesProcess: boolean;
readonly accessesNetwork: boolean;
readonly changesUiState: boolean;
readonly mayDiscardData: boolean;
readonly idempotent: boolean;
}
/** MCP execution hints derived only from canonical effects. */
export interface DerivedToolAnnotations {
readonly readOnlyHint: boolean;
readonly destructiveHint: boolean;
readonly idempotentHint: boolean;
readonly openWorldHint: boolean;
}
const effects = (overrides: Partial<ToolEffects> = {}): ToolEffects => ({
mutatesTarget: false,
mutatesSession: false,
writesFilesystem: false,
launchesProcess: false,
accessesNetwork: false,
changesUiState: false,
mayDiscardData: false,
idempotent: true,
...overrides,
});
const evidence = effects({ mutatesSession: true });
const nativeEvidence = effects({ mutatesSession: true, launchesProcess: true });
const browserEvidence = effects({
mutatesSession: true,
accessesNetwork: true,
});
const sessionEvidence = effects({ mutatesSession: true });
/** Explicit effect audit for every public tool. */
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
address_name: evidence,
comment: evidence,
current_address: evidence,
current_procedure: evidence,
current_document: evidence,
goto_address: effects({ mutatesSession: true, changesUiState: true }),
inline_comment: evidence,
list_bookmarks: evidence,
list_documents: evidence,
list_names: evidence,
list_procedures: evidence,
list_segments: evidence,
list_strings: evidence,
next_address: evidence,
prev_address: evidence,
procedure_address: evidence,
procedure_assembly: evidence,
procedure_callees: evidence,
procedure_callers: evidence,
procedure_info: evidence,
procedure_references: evidence,
procedure_pseudo_code: evidence,
resolve_containing_procedure: evidence,
search_procedures: evidence,
search_strings: evidence,
set_address_name: effects({ mutatesTarget: true, mutatesSession: true }),
set_addresses_names: effects({ mutatesTarget: true, mutatesSession: true }),
set_bookmark: effects({ mutatesTarget: true, mutatesSession: true }),
set_comment: effects({ mutatesTarget: true, mutatesSession: true }),
set_current_document: effects({ mutatesSession: true, changesUiState: true }),
set_inline_comment: effects({ mutatesTarget: true, mutatesSession: true }),
unset_bookmark: effects({
mutatesTarget: true,
mutatesSession: true,
mayDiscardData: true,
}),
xrefs: evidence,
swift_classes: evidence,
get_objc_classes: evidence,
get_objc_protocols: evidence,
batch_decompile: evidence,
get_call_graph: evidence,
analyze_swift_types: evidence,
find_xrefs_to_name: evidence,
binary_overview: evidence,
analyze_function: evidence,
trace_feature: effects({ mutatesSession: true, idempotent: false }),
inspect_macho: nativeEvidence,
inspect_signature: nativeEvidence,
inspect_plist: nativeEvidence,
list_architectures: nativeEvidence,
demangle_swift: nativeEvidence,
inventory_artifact: evidence,
extract_artifact: effects({ mutatesSession: true, writesFilesystem: true }),
inspect_managed_artifact: evidence,
list_browser_targets: browserEvidence,
inspect_web_page: browserEvidence,
analyze_web_bundle: browserEvidence,
observe_web_session: browserEvidence,
discover_webmcp_tools: browserEvidence,
compare_web_captures: browserEvidence,
capture_web_screenshot: browserEvidence,
compare_web_screenshots: browserEvidence,
list_electron_targets: browserEvidence,
inspect_electron_page: browserEvidence,
analyze_javascript_application: evidence,
reconcile_javascript_runtime: evidence,
trace_application_feature: evidence,
compare_application_versions: evidence,
run_controlled_replay: effects({
mutatesSession: true,
writesFilesystem: true,
launchesProcess: true,
}),
open_binary: effects({ mutatesSession: true, launchesProcess: true }),
close_binary: effects({
mutatesSession: true,
writesFilesystem: true,
mayDiscardData: true,
idempotent: false,
}),
binary_session: effects(),
export_evidence_bundle: effects({
writesFilesystem: true,
mayDiscardData: true,
}),
import_evidence_bundle: effects({ mutatesSession: true }),
capture_process_scenario: effects({
mutatesSession: true,
writesFilesystem: true,
launchesProcess: true,
idempotent: false,
}),
compare_process_captures: sessionEvidence,
compare_artifacts: sessionEvidence,
compare_functions: sessionEvidence,
compare_bundles: effects({ mutatesSession: true }),
find_changed_behavior: sessionEvidence,
build_call_path: sessionEvidence,
correlate_static_and_runtime: sessionEvidence,
verify_reconstruction: sessionEvidence,
list_unknowns: effects(),
record_unknown: effects({ mutatesSession: true, idempotent: false }),
update_unknown: effects({ mutatesSession: true, idempotent: false }),
verify_unknown_resolution: effects(),
};
/** Derive MCP annotations without tool-name or tool-family heuristics. */
export const annotationsFromEffects = (
value: ToolEffects,
): DerivedToolAnnotations => ({
readOnlyHint: !(
value.mutatesTarget ||
value.mutatesSession ||
value.writesFilesystem ||
value.launchesProcess ||
value.accessesNetwork ||
value.changesUiState ||
value.mayDiscardData
),
destructiveHint: value.mayDiscardData,
idempotentHint: value.idempotent,
openWorldHint: value.launchesProcess || value.accessesNetwork,
});
/** Resolve the audited metadata for one public tool. */
export const toolContractMetadata = (name: string) => {
const audited = TOOL_EFFECTS[name];
if (audited === undefined)
throw new Error(`Missing effect audit for ${name}`);
return {
title: name
.split("_")
.map((word) => word[0]?.toUpperCase() + word.slice(1))
.join(" "),
effects: audited,
annotations: annotationsFromEffects(audited),
};
};
+27 -50
View File
@@ -1,5 +1,4 @@
import { z } from "zod";
import { evidenceEnvelopeSchema } from "../domain/evidence.js";
import {
processCaptureComparisonSchema,
processCaptureSchema,
@@ -46,10 +45,14 @@ import {
type ProviderRejectionCode,
} from "./providerSelection.js";
const resultOf = (schema: z.ZodType) =>
evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: schema });
/** Compact MCP result with an immutable link to complete session Evidence. */
export const evidenceResultOf = (schema: z.ZodType) =>
z.strictObject({
result: schema,
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
evidence_uri: z.string().regex(/^rea:\/\/evidence\/ev_[a-f0-9]{64}$/u),
});
const resultOf = evidenceResultOf;
const lifecycleResultOf = (schema: z.ZodType) => z.object({ result: schema });
/** Resolve a required named output schema or reject contract drift. */
@@ -194,6 +197,16 @@ const sessionProvider = z.object({
"policy_disabled",
]),
remediation: z.string().nullable(),
effects: z.strictObject({
mutatesTarget: z.boolean(),
mutatesSession: z.boolean(),
writesFilesystem: z.boolean(),
launchesProcess: z.boolean(),
accessesNetwork: z.boolean(),
changesUiState: z.boolean(),
mayDiscardData: z.boolean(),
idempotent: z.boolean(),
}),
annotations: z.object({
read_only: z.boolean(),
destructive: z.boolean(),
@@ -610,51 +623,15 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
total: z.number().int().min(0),
}),
),
capture_process_scenario: lifecycleResultOf(
evidenceEnvelopeSchema
.omit({ normalized_result: true })
.extend({ normalized_result: processCaptureSchema }),
),
compare_process_captures: lifecycleResultOf(
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
normalized_result: processCaptureComparisonSchema,
}),
),
compare_artifacts: lifecycleResultOf(
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
normalized_result: artifactComparisonResultSchema,
}),
),
compare_functions: lifecycleResultOf(
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
normalized_result: functionComparisonResultSchema,
}),
),
compare_bundles: lifecycleResultOf(
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
normalized_result: bundleComparisonResultSchema,
}),
),
find_changed_behavior: lifecycleResultOf(
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
normalized_result: changedBehaviorResultSchema,
}),
),
build_call_path: lifecycleResultOf(
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
normalized_result: callPathResultSchema,
}),
),
correlate_static_and_runtime: lifecycleResultOf(
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
normalized_result: staticRuntimeCorrelationResultSchema,
}),
),
verify_reconstruction: lifecycleResultOf(
evidenceEnvelopeSchema.omit({ normalized_result: true }).extend({
normalized_result: reconstructionVerificationResultSchema,
}),
),
capture_process_scenario: resultOf(processCaptureSchema),
compare_process_captures: resultOf(processCaptureComparisonSchema),
compare_artifacts: resultOf(artifactComparisonResultSchema),
compare_functions: resultOf(functionComparisonResultSchema),
compare_bundles: resultOf(bundleComparisonResultSchema),
find_changed_behavior: resultOf(changedBehaviorResultSchema),
build_call_path: resultOf(callPathResultSchema),
correlate_static_and_runtime: resultOf(staticRuntimeCorrelationResultSchema),
verify_reconstruction: resultOf(reconstructionVerificationResultSchema),
list_unknowns: lifecycleResultOf(z.array(residualUnknownSchema)),
record_unknown: lifecycleResultOf(residualUnknownSchema),
update_unknown: lifecycleResultOf(residualUnknownSchema),