refactor(mcp): simplify tool inputs and inline results

This commit is contained in:
morluto
2026-09-29 11:22:00 +08:00
parent bd0e341572
commit f55c2b9267
70 changed files with 468 additions and 741 deletions
@@ -51,8 +51,6 @@ const compareApplicationVersionsFacts = {
right_native_observations:
compareApplicationVersionsInputSchema.shape.right_native_observations,
right_native_observation_evidence_ids: z.array(evidenceIdSchema).default([]),
unknown_registry_approved:
compareApplicationVersionsInputSchema.shape.unknown_registry_approved,
} as const;
const applicationEvidenceReferenceSchema = z.union([
@@ -95,9 +93,6 @@ export const compareApplicationVersionsRequestSchema = z
const compareSourceToBundleFacts = {
reference: compareSourceToBundleInputSchema.shape.reference,
limits: compareSourceToBundleInputSchema.shape.limits,
unknown_registry_approved:
compareSourceToBundleInputSchema.shape.unknown_registry_approved,
} as const;
/** Historical-source comparison accepting full application Evidence or a ledger reference. */
@@ -121,8 +116,6 @@ const compareJavaScriptExportShapesFacts = {
compareJavaScriptExportShapesInputSchema.shape.right_module_path,
right_export_name:
compareJavaScriptExportShapesInputSchema.shape.right_export_name,
unknown_registry_approved:
compareJavaScriptExportShapesInputSchema.shape.unknown_registry_approved,
} as const;
/** MCP/CLI export-shape request accepting full Evidence or ledger references. */
+6 -49
View File
@@ -1,7 +1,7 @@
import type { ToolContract } from "./toolContracts.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemas.js";
import { browserScenarioSchema } from "../domain/browserScenario.js";
import { browserScenarioInputSchema } from "../domain/browserScenario.js";
import { browserScenarioCaptureSchema } from "../domain/browserScenarioCapture.js";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -15,56 +15,13 @@ const example: Record<string, JsonValue> = {
},
start_url: { url: "https://app.example.test/", query: [] },
allowed_origins: ["https://app.example.test"],
environment: {
viewport: { width: 1_280, height: 720, device_scale_factor: 1 },
locale: "en-US",
timezone: "UTC",
color_scheme: "light",
reduced_motion: "reduce",
service_workers: "block",
},
actions: [
{
step_id: "ready",
action: "wait_for",
locator: { kind: "test_id", value: "application-ready" },
state: "visible",
step_id: "settle",
action: "wait_for_timeout",
duration_ms: 250,
},
],
storage: { cookies: [], local_storage: [], session_storage: [] },
request_replay: { mode: "disabled" },
secrets: [],
redaction: {
secret_values: "replace-with-secret-reference",
query_parameter_names: [],
header_names: [
"authorization",
"cookie",
"proxy-authorization",
"set-cookie",
],
},
capture: {
after_each_step: ["screenshot", "url", "accessibility"],
at_end: ["dom", "history", "storage"],
events: ["console", "page-errors", "network", "websockets"],
},
limits: {
max_duration_ms: 60_000,
action_timeout_ms: 5_000,
navigation_timeout_ms: 10_000,
max_events: 2_000,
max_frames: 100,
max_workers: 20,
max_popups: 10,
max_websockets: 100,
max_dom_nodes: 10_000,
max_accessibility_nodes: 10_000,
max_screenshots: 16,
max_screenshot_bytes: 4_194_304,
max_storage_entries: 256,
max_total_metadata_bytes: 4_194_304,
},
};
/** Controlled browser scenario contract shared by MCP and catalog generation. */
@@ -73,9 +30,9 @@ export const BROWSER_SCENARIO_TOOL_CONTRACTS = [
name: "capture_browser_scenario",
...toolContractMetadata("capture_browser_scenario"),
description:
"Run one approved, bounded browser scenario through Playwright. Launch mode owns and terminates a temporary browser profile; connect mode attaches to one exact loopback CDP target and disconnects without terminating the external browser. Only the fixed action vocabulary is accepted. Navigation, storage, requests, redirects, secrets, redaction, captures, and limits must be declared before execution. Returns step-indexed Evidence with screenshots, DOM, accessibility, URL/history/storage state, runtime events, explicit missing/truncated sections, and equality eligibility.",
"Run a controlled browser scenario when passive observation cannot exercise the application. Choose launch mode with an approved executable or connect mode with an approved loopback CDP target, declare the exact start origin scope, and provide explicit actions. Environment, empty storage, disabled request replay, redaction, and a URL-only final capture have safe defaults; declare secrets, initial storage, exact request replay, or additional retained artifacts only when needed. Provider-owned duration and collection budgets are fixed. Returns step-indexed Evidence with explicit missing/truncated sections and equality eligibility.",
kind: "browser-provider",
inputSchema: browserScenarioSchema,
inputSchema: browserScenarioInputSchema,
outputSchema: evidenceResultOf(browserScenarioCaptureSchema),
examples: [
{ title: "Capture a deterministic browser scenario", input: example },
+1 -34
View File
@@ -138,7 +138,7 @@ 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.",
"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.",
kind: "browser-provider",
inputSchema: inspectWebPageInputSchema,
outputSchema: inspectionOutputSchema,
@@ -149,38 +149,6 @@ export const BROWSER_TOOL_CONTRACTS = [
cdp_endpoint: endpoint,
allowed_origins: [origin],
target_id: "TARGET_ID_FROM_LIST_BROWSER_TARGETS",
observation_ms: 500,
include_accessibility_text: false,
include_console_text: false,
include_json_body_shapes: false,
include_websocket_shapes: false,
include_script_sources: false,
include_storage_keys: false,
include_storage_fingerprints: false,
limits: {
max_frames: 200,
max_dom_nodes: 2_000,
max_ax_nodes: 2_000,
max_ax_text_field_bytes: 1_024,
max_total_ax_text_bytes: 65_536,
max_scripts: 200,
max_resources: 2_000,
max_workers: 500,
max_storage_keys: 1_000,
max_script_source_bytes: 1_048_576,
max_total_script_source_bytes: 4_194_304,
max_network_events: 1_000,
max_console_events: 200,
max_console_text_field_bytes: 1_024,
max_total_console_text_bytes: 65_536,
max_json_body_bytes: 1_048_576,
max_total_json_body_bytes: 4_194_304,
max_json_shape_nodes: 5_000,
max_json_shape_depth: 20,
max_websocket_events: 500,
max_websocket_shape_bytes: 65_536,
max_total_websocket_shape_bytes: 1_048_576,
},
},
},
],
@@ -327,7 +295,6 @@ export const BROWSER_TOOL_CONTRACTS = [
function exampleScreenshot() {
return {
uri: "rea://web-screenshot/sha256/153cf6c9a526a63053a37b10234c2fd85df38887c2dc0a800d90abfa6631d01c",
sha256: "153cf6c9a526a63053a37b10234c2fd85df38887c2dc0a800d90abfa6631d01c",
bytes: 70,
media_type: "image/png",
-11
View File
@@ -83,17 +83,6 @@ export const ELECTRON_TOOL_CONTRACTS = [
cdp_endpoint: endpoint,
allowed_file_roots: [root],
target_id: "TARGET_ID_FROM_LIST_ELECTRON_TARGETS",
observation_ms: 100,
include_script_sources: false,
limits: {
max_frames: 200,
max_dom_nodes: 2_000,
max_scripts: 500,
max_resources: 2_000,
max_workers: 500,
max_script_source_bytes: 1_048_576,
max_total_script_source_bytes: 4_194_304,
},
},
},
],
+12 -18
View File
@@ -3,15 +3,10 @@ import { z } from "zod";
const traceLiteralInputSchema = z.strictObject({
query: z.string().min(1),
case_sensitive: z.boolean().default(false),
unknown_registry_approved: z
.literal(true)
.optional()
.describe("Explicit approval to record bounded residuals durably"),
});
/** Input schemas shared by MCP registration and enhanced application dispatch. */
export const enhancedInputSchemas = {
swift_classes: z.strictObject({ pattern: z.string().default("") }),
get_objc_classes: z.strictObject({ pattern: z.string().default("") }),
get_objc_protocols: z.strictObject({}),
batch_decompile: z.strictObject({
@@ -23,7 +18,18 @@ export const enhancedInputSchemas = {
address: z.string().describe("A provider-normalized procedure address"),
direction: z.enum(["forward", "backward"]).default("forward"),
}),
analyze_swift_types: z.strictObject({}),
analyze_swift_types: z.strictObject({
category: z
.enum(["classes", "structs", "enums", "protocols", "extensions", "other"])
.optional()
.describe("Limit results to one Swift symbol category."),
pattern: z
.string()
.optional()
.describe(
"Case-sensitive literal filter applied to mangled symbol names.",
),
}),
find_xrefs_to_name: z.strictObject({ name: z.string() }),
binary_overview: z.strictObject({}),
analyze_function: z.strictObject({
@@ -31,12 +37,6 @@ export const enhancedInputSchemas = {
}),
inspect_native_api: z.strictObject({
procedure: z.string().describe("A procedure name or address"),
unknown_registry_approved: z
.literal(true)
.optional()
.describe(
"Explicit approval to record unsupported native API branches durably",
),
}),
trace_feature: traceLiteralInputSchema,
find_code_for_string: traceLiteralInputSchema,
@@ -47,12 +47,6 @@ export const enhancedInputSchemas = {
.describe("An optional provider-normalized destination address")
.optional(),
direction: z.enum(["forward", "backward"]).default("forward"),
unknown_registry_approved: z
.literal(true)
.optional()
.describe(
"Explicit approval to record unresolved provider results durably",
),
}),
} as const;
@@ -36,10 +36,10 @@ const functionWorkflow = <Name extends FunctionWorkflowName>(
export const FUNCTION_WORKFLOW_TOOL_CONTRACTS = [
functionWorkflow(
"analyze_function",
"Return one complete function dossier inline, including identity, provider-specific pseudocode and assembly, comments, calls, references, referenced strings/names, local CFG blocks, and any available native API boundary observations.",
"Use for a specific native function when you need its behavior and surrounding evidence in one call. Pass a procedure symbol/name or provider-returned address, typically selected from search_procedures or list_procedures. Returns identity, provider-specific pseudocode and assembly, comments, calls, references, referenced strings/names, local CFG blocks, and available native API boundary observations. For only one facet, use the focused procedure tool; for structured native API reconstruction, use inspect_native_api.",
),
functionWorkflow(
"inspect_native_api",
"Reconstruct one native function boundary with structured return/parameter types, confidence, evidence, jump-table dispatch/data/target mappings, unsupported branches, and residual unknowns.",
"Use after identifying a function that calls or implements a native API boundary when you need structured return/parameter types and dispatch evidence. Pass its procedure symbol/name or provider-returned address. Returns confidence, evidence, jump-table dispatch/data/target mappings, unsupported branches, and residual unknowns; use analyze_function for a general function dossier.",
),
] as const satisfies readonly ToolContract[];
@@ -46,16 +46,7 @@ export const JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS = [
input: {
inspector_endpoint: endpoint,
allowed_file_roots: [root],
allowed_origins: [],
target_id: "TARGET_ID_FROM_LIST_JAVASCRIPT_RUNTIME_TARGETS",
observation_ms: 100,
limits: {
max_events: 10_000,
max_scripts: 2_000,
max_execution_contexts: 1_000,
max_location_bytes: 16_384,
max_total_metadata_bytes: 4_194_304,
},
},
},
],
@@ -1,7 +1,5 @@
import { z } from "zod";
import { compareManagedMembersInputSchema } from "../domain/managedMemberComparison.js";
import { managedNativeVerificationInputSchema } from "../domain/managedNativeVerification.js";
import { managedReconstructionImportInputSchema } from "../domain/managedReconstruction.js";
import { managedRuntimeCorrelationInputSchema } from "../domain/managedRuntimeCorrelation.js";
import type { ToolContract } from "./toolContracts.js";
@@ -35,8 +33,6 @@ export const compareManagedMembersReferenceInputSchema = z
.strictObject({
left_evidence_id: managedEvidenceIdSchema,
right_evidence_id: managedEvidenceIdSchema,
unknown_registry_approved:
compareManagedMembersInputSchema.shape.unknown_registry_approved,
})
.superRefine((input, context) => {
if (input.left_evidence_id === input.right_evidence_id)
@@ -67,8 +63,6 @@ export const managedNativeVerificationReferenceInputSchema = z
.array(nativeObservationEvidenceIdSchema)
.min(1)
.describe("Unique session-owned native observation Evidence IDs"),
unknown_registry_approved:
managedNativeVerificationInputSchema.shape.unknown_registry_approved,
})
.superRefine((input, context) => {
const ids = new Set<string>();
+2 -2
View File
@@ -223,7 +223,7 @@ export const PROMPT_CONTRACTS = [
name: "verify_reconstruction",
title: "Verify a reconstruction",
description:
"Evaluate a finite reconstruction specification against retained Evidence v2 comparisons without broadening pass results into global equivalence claims.",
"Evaluate a finite reconstruction specification against retained Evidence comparisons without broadening pass results into global equivalence claims.",
objective:
"Produce per-claim pass, fail, or unknown results backed by compatible comparison Evidence and exact authority requirements.",
arguments: {
@@ -416,7 +416,7 @@ export const PROMPT_CONTRACTS = [
{
tools: ["record_unknown"],
instruction:
"Treat sampling gaps, truncated output, external behavior, and cleanup uncertainty as residual unknowns; persist them only with separate explicit approval.",
"Treat sampling gaps, truncated output, external behavior, and cleanup uncertainty as residual unknowns; support them with relevant Evidence IDs and focused recommended probes.",
},
],
},
-4
View File
@@ -44,10 +44,6 @@ export const processComparisonInputSchema = z.strictObject({
right_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
trace_spec: processTraceSpecificationSchema.optional(),
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. */
+1
View File
@@ -35,6 +35,7 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
get_call_graph: { address: "0x1000" },
find_xrefs_to_name: { name: "malloc" },
analyze_function: { procedure: "main" },
analyze_swift_types: { category: "classes", pattern: "Account" },
inspect_native_api: { procedure: "main" },
trace_feature: { query: "license" },
find_code_for_string: { query: "authorization failed" },
+1 -1
View File
@@ -16,7 +16,7 @@ import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
describe("tool contract inventory", () => {
it("publishes the canonical analysis and session tool inventory", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(36);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(13);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(12);
expect(NATIVE_TOOL_CONTRACTS).toHaveLength(5);
expect(ARTIFACT_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"inspect_artifact",
+10 -24
View File
@@ -68,25 +68,16 @@ const official = <Name extends string, Schema extends z.ZodObject>(
name: Name,
description: string,
inputSchema: Schema,
) => {
const trackedInputSchema = inputSchema.extend({
unknown_registry_approved: z
.literal(true)
.optional()
.describe(
"Explicit approval to record typed capability unavailability as a residual unknown",
),
});
return {
) =>
({
name,
...toolContractMetadata(name),
description,
kind: "official-proxy",
inputSchema: trackedInputSchema,
inputSchema,
outputSchema: requireOutputSchema(officialOutputSchemas, name),
examples: examplesFor(name, trackedInputSchema),
} satisfies ToolContract<Name, typeof trackedInputSchema>;
};
examples: examplesFor(name, inputSchema),
}) satisfies ToolContract<Name, Schema>;
const enhanced = <Name extends string, Schema extends z.ZodObject>(
name: Name,
@@ -304,11 +295,6 @@ export type OfficialToolName = (typeof OFFICIAL_TOOL_CONTRACTS)[number]["name"];
/** Bounded workflows composed from one or more bridge operations. */
export const ENHANCED_TOOL_CONTRACTS = [
enhanced(
"swift_classes",
"Discover legacy-mangled Swift class procedures by scanning analyzed procedures; returns every matching entry. Use analyze_swift_types for other Swift kinds.",
enhancedInputSchemas.swift_classes,
),
enhanced(
"get_objc_classes",
"Discover and deduplicate every Objective-C class label, optionally filtering by literal substring; inspect matching metadata and references next.",
@@ -331,7 +317,7 @@ export const ENHANCED_TOOL_CONTRACTS = [
),
enhanced(
"analyze_swift_types",
"Categorize all analyzed procedure names into Swift classes, structs, enums, protocols, extensions, and other symbols.",
'Categorize analyzed procedure names into Swift classes, structs, enums, protocols, extensions, and other symbols. Returns deduplicated names grouped with counts. Optionally select one category and/or apply a case-sensitive literal name filter; for example, use {category: "classes", pattern: "Account"} to find matching class symbols.',
enhancedInputSchemas.analyze_swift_types,
),
enhanced(
@@ -341,13 +327,13 @@ export const ENHANCED_TOOL_CONTRACTS = [
),
enhanced(
"binary_overview",
"Use immediately after opening a target to summarize the document, every segment with its length, and exhaustive procedure/string counts.",
"Use after opening a native binary for target metadata, every segment with its length, and exhaustive procedure/string counts. To choose a function, follow with search_procedures or list_procedures, then pass a returned name or address to analyze_function for a complete dossier.",
enhancedInputSchemas.binary_overview,
),
...FUNCTION_WORKFLOW_TOOL_CONTRACTS,
enhanced(
"trace_feature",
"Trace a literal feature query through every matching string and procedure, their xrefs, and truthful containing-procedure resolution. Returns observations, operation count, and residual unknowns; unknown_registry_approved: true records residual unknowns without inferring reference kinds.",
"Trace a literal feature query through every matching string and procedure, their xrefs, and truthful containing-procedure resolution. Returns observations, operation count, and residual unknowns without inferring reference kinds.",
enhancedInputSchemas.trace_feature,
),
enhanced(
@@ -392,12 +378,12 @@ export const SESSION_TOOL_CONTRACTS = [
),
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.",
"Read a bounded local JSON bundle beneath an operator-approved root, validate every Evidence ID and canonical manifest, then atomically merge it. Imported content is data only and is never executed.",
importEvidenceBundleInputSchema,
),
session(
"capture_process_scenario",
"Run one bounded process under a PTY using operator-approved executable and working roots. Produces process capture Evidence; unknown_registry_approved: true separately records capture residuals. Captures raw and xterm-rendered terminal frames, scripted interactions, lifecycle filesystem checkpoints, process ownership, declarative command shims, and loopback replay. Disabled unless operator policy enables it; not a security sandbox.",
"Run one bounded process under a PTY using operator-approved executable and working roots. Produces process capture Evidence and records residual unknowns linked to that Evidence. Captures raw and xterm-rendered terminal frames, scripted interactions, lifecycle filesystem checkpoints, process ownership, declarative command shims, and loopback replay. Disabled unless operator policy enables it; not a security sandbox.",
processScenarioSchema,
),
session(
-1
View File
@@ -80,7 +80,6 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
mayDiscardData: true,
}),
xrefs: evidence,
swift_classes: evidence,
get_objc_classes: evidence,
get_objc_protocols: evidence,
batch_decompile: evidence,
+4 -5
View File
@@ -207,7 +207,6 @@ const callPathTraceOutput = resultOf(
/** Exact structured-content schemas for composed analysis workflows. */
export const enhancedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
swift_classes: symbolDiscoveryOutput("classes"),
get_objc_classes: symbolDiscoveryOutput("classes"),
get_objc_protocols: symbolDiscoveryOutput("protocols"),
batch_decompile: resultOf(
@@ -282,7 +281,7 @@ export const enhancedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
trace_call_path: callPathTraceOutput,
};
/** Exact Evidence v2 schemas for provider-neutral native inspection. */
/** Exact Evidence schemas for provider-neutral native inspection. */
export const nativeOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_macho: resultOf(inspectMachoSchema),
inspect_signature: resultOf(inspectSignatureSchema),
@@ -291,13 +290,13 @@ export const nativeOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
demangle_swift: resultOf(demangleSwiftSchema),
};
/** Exact Evidence v2 schemas for provider-neutral artifact graph operations. */
/** Exact Evidence schemas for provider-neutral artifact graph operations. */
export const artifactOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_artifact: resultOf(artifactInspectionResultSchema),
extract_artifact: resultOf(artifactExtractionResultSchema),
};
/** Exact Evidence v2 schema for execution-free managed static analysis. */
/** Exact Evidence schema for execution-free managed static analysis. */
export const managedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_managed_artifact: resultOf(managedArtifactInspectionSchema),
inspect_managed_members: resultOf(managedMemberInspectionSchema),
@@ -306,7 +305,7 @@ export const managedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
),
};
/** Exact Evidence v2 schema for provider-neutral managed workflows. */
/** Exact Evidence schema for provider-neutral managed workflows. */
export const managedWorkflowOutputSchemas: Readonly<
Record<string, z.ZodObject>
> = {
+4 -6
View File
@@ -17,8 +17,8 @@ const PROPERTY_DESCRIPTIONS: Readonly<Record<string, string>> = {
direction: "Direction in which to traverse or compare relationships.",
document: "Exact provider document or program identity.",
error: "Structured, caller-actionable error when the operation fails.",
evidence: "Evidence v2 record produced by this operation.",
evidence_id: "Stable identifier of the recorded Evidence v2 observation.",
evidence: "Evidence record produced by this operation.",
evidence_id: "Stable identifier of the recorded Evidence observation.",
executable: "Approved absolute path of the executable to run.",
format: "Declared input artifact format.",
name: "Exact name used by this operation.",
@@ -44,8 +44,6 @@ const PROPERTY_DESCRIPTIONS: Readonly<Record<string, string>> = {
symbols: "Ordered bounded Swift symbols to demangle.",
target_id: "Exact authorized CDP target identifier.",
unknown_id: "Exact residual-unknown identifier.",
unknown_registry_approved:
"Explicit approval to record bounded residual uncertainty in the session registry.",
};
/** Attach caller guidance to a canonical schema for the SDK wire projection. */
@@ -124,9 +122,9 @@ const fallbackPropertyDescription = (property: string): string => {
if (property.endsWith("_sha256"))
return `Exact SHA-256 digest of ${words.slice(0, -7)}.`;
if (property.endsWith("_evidence_id"))
return `Exact Evidence v2 identifier for the ${words.slice(0, -12)} observation.`;
return `Exact Evidence identifier for the ${words.slice(0, -12)} observation.`;
if (property.endsWith("_evidence_ids"))
return `Ordered Evidence v2 identifiers for the ${words.slice(0, -13)} observations.`;
return `Ordered Evidence identifiers for the ${words.slice(0, -13)} observations.`;
if (property.endsWith("_path"))
return `Local filesystem path for ${words.slice(0, -5)}.`;
if (property.endsWith("_uri"))