refactor(mcp): make analysis states unrepresentable (#468)

* refactor(config): parse capability settings into exact states

* refactor(runtime): encode replay and process outcomes exactly

* refactor: make analysis states unrepresentable

* refactor(mcp): register canonical schemas with SDK

* fix: preserve capability and catalog invariants

* fix(build): remove stale compiled modules

* fix(replay): update real verifier policy dependency

* fix(package): verify the complete MCP catalog

* fix(test): supply complete replay reload policy

* refactor(contracts): centralize output schema lookup

* refactor(mcp): delegate protocol boundaries to SDK

* fix(browser): approve real source capture

* fix(mcp): preserve catalog guidance
This commit is contained in:
morluto
2026-08-10 02:28:11 +08:00
committed by GitHub
parent 6901edc05d
commit b8a9da0c0f
271 changed files with 5970 additions and 5699 deletions
+39 -5
View File
@@ -114,7 +114,6 @@ const NODE_PREPARATION_EXAMPLE = jsonObjectSchema.parse({
entry_export: "selected",
},
cases: [{ case_id: "empty", arguments: [""] }],
approved: false,
},
});
@@ -280,7 +279,6 @@ export const APPLICATION_TOOL_CONTRACTS = [
result_depth: 16,
result_nodes: 10000,
},
approved: false,
},
},
],
@@ -409,13 +407,49 @@ export const APPLICATION_TOOL_CONTRACTS = [
] as const satisfies readonly ToolContract[];
/** Resolve one named application contract without relying on array position. */
export const applicationToolContract = (
export function applicationToolContract(
name: "trace_application_feature",
): (typeof APPLICATION_TOOL_CONTRACTS)[0];
export function applicationToolContract(
name: "trace_javascript_semantics",
): (typeof APPLICATION_TOOL_CONTRACTS)[1];
export function applicationToolContract(
name: "compare_application_versions",
): (typeof APPLICATION_TOOL_CONTRACTS)[2];
export function applicationToolContract(
name: "compare_source_to_bundle",
): (typeof APPLICATION_TOOL_CONTRACTS)[3];
export function applicationToolContract(
name: "compare_javascript_export_shapes",
): (typeof APPLICATION_TOOL_CONTRACTS)[4];
export function applicationToolContract(
name: "run_controlled_replay",
): (typeof APPLICATION_TOOL_CONTRACTS)[5];
export function applicationToolContract(
name: "prepare_node_characterization",
): (typeof APPLICATION_TOOL_CONTRACTS)[6];
export function applicationToolContract(
name: "execute_node_characterization",
): (typeof APPLICATION_TOOL_CONTRACTS)[7];
export function applicationToolContract(
name: "build_reconstruction_obligation_ledger",
): (typeof APPLICATION_TOOL_CONTRACTS)[8];
export function applicationToolContract(
name: "evaluate_reconstruction_readiness",
): (typeof APPLICATION_TOOL_CONTRACTS)[9];
export function applicationToolContract(
name: "commit_reconstruction_coverage",
): (typeof APPLICATION_TOOL_CONTRACTS)[10];
export function applicationToolContract(
name: "query_reconstruction_coverage",
): (typeof APPLICATION_TOOL_CONTRACTS)[11];
export function applicationToolContract(
name: (typeof APPLICATION_TOOL_CONTRACTS)[number]["name"],
): (typeof APPLICATION_TOOL_CONTRACTS)[number] => {
): (typeof APPLICATION_TOOL_CONTRACTS)[number] {
const contract = APPLICATION_TOOL_CONTRACTS.find(
({ name: candidate }) => candidate === name,
);
if (contract === undefined)
throw new Error(`Missing application tool contract: ${name}`);
return contract;
};
}
+123 -132
View File
@@ -12,149 +12,140 @@ const evidenceIdSchema = z
.regex(/^ev_[a-f0-9]{64}$/u)
.describe("Evidence ID returned earlier in this session");
const requireExactlyOne = (
context: z.RefinementCtx,
fields: readonly [string, unknown, string, unknown],
): void => {
const [leftName, left, rightName, right] = fields;
if ((left === undefined) !== (right === undefined)) return;
context.addIssue({
code: "custom",
path: [left === undefined ? leftName : rightName],
message: `Supply exactly one of ${leftName} or ${rightName}`,
});
};
const traceApplicationFeatureFacts = {
native_observations:
traceApplicationFeatureInputSchema.shape.native_observations,
native_observation_evidence_ids: z
.array(evidenceIdSchema)
.max(64)
.default([]),
seed: traceApplicationFeatureInputSchema.shape.seed,
direction: traceApplicationFeatureInputSchema.shape.direction,
limits: traceApplicationFeatureInputSchema.shape.limits,
} as const;
/** MCP/CLI trace request accepting full Evidence or a ledger reference. */
export const traceApplicationFeatureRequestSchema = z
.strictObject({
application: evidenceSchema.optional(),
application_evidence_id: evidenceIdSchema.optional(),
native_observations:
traceApplicationFeatureInputSchema.shape.native_observations,
native_observation_evidence_ids: z
.array(evidenceIdSchema)
.max(64)
.default([]),
seed: traceApplicationFeatureInputSchema.shape.seed,
direction: traceApplicationFeatureInputSchema.shape.direction,
limits: traceApplicationFeatureInputSchema.shape.limits,
})
.superRefine((input, context) => {
requireExactlyOne(context, [
"application",
input.application,
"application_evidence_id",
input.application_evidence_id,
]);
});
export const traceApplicationFeatureRequestSchema = z.union([
z.strictObject({
...traceApplicationFeatureFacts,
application: evidenceSchema,
}),
z.strictObject({
...traceApplicationFeatureFacts,
application_evidence_id: evidenceIdSchema,
}),
]);
/** MCP/CLI semantic trace request accepting full Evidence or a ledger reference. */
export const traceJavaScriptSemanticsRequestSchema = z
.strictObject({
application: evidenceSchema.optional(),
application_evidence_id: evidenceIdSchema.optional(),
export const traceJavaScriptSemanticsRequestSchema = z.union([
z.strictObject({
application: evidenceSchema,
query: javaScriptSemanticQueryInputSchema,
})
.superRefine((input, context) => {
requireExactlyOne(context, [
"application",
input.application,
"application_evidence_id",
input.application_evidence_id,
]);
});
}),
z.strictObject({
application_evidence_id: evidenceIdSchema,
query: javaScriptSemanticQueryInputSchema,
}),
]);
const compareApplicationVersionsFacts = {
left_native_observations:
compareApplicationVersionsInputSchema.shape.left_native_observations,
left_native_observation_evidence_ids: z
.array(evidenceIdSchema)
.max(64)
.default([]),
right_native_observations:
compareApplicationVersionsInputSchema.shape.right_native_observations,
right_native_observation_evidence_ids: z
.array(evidenceIdSchema)
.max(64)
.default([]),
limits: compareApplicationVersionsInputSchema.shape.limits,
unknown_registry_approved:
compareApplicationVersionsInputSchema.shape.unknown_registry_approved,
} as const;
/** MCP/CLI comparison request accepting full Evidence or ledger references. */
export const compareApplicationVersionsRequestSchema = z
.strictObject({
left: evidenceSchema.optional(),
left_evidence_id: evidenceIdSchema.optional(),
right: evidenceSchema.optional(),
right_evidence_id: evidenceIdSchema.optional(),
left_native_observations:
compareApplicationVersionsInputSchema.shape.left_native_observations,
left_native_observation_evidence_ids: z
.array(evidenceIdSchema)
.max(64)
.default([]),
right_native_observations:
compareApplicationVersionsInputSchema.shape.right_native_observations,
right_native_observation_evidence_ids: z
.array(evidenceIdSchema)
.max(64)
.default([]),
limits: compareApplicationVersionsInputSchema.shape.limits,
unknown_registry_approved:
compareApplicationVersionsInputSchema.shape.unknown_registry_approved,
})
.superRefine((input, context) => {
requireExactlyOne(context, [
"left",
input.left,
"left_evidence_id",
input.left_evidence_id,
]);
requireExactlyOne(context, [
"right",
input.right,
"right_evidence_id",
input.right_evidence_id,
]);
});
export const compareApplicationVersionsRequestSchema = z.union([
z.strictObject({
...compareApplicationVersionsFacts,
left: evidenceSchema,
right: evidenceSchema,
}),
z.strictObject({
...compareApplicationVersionsFacts,
left: evidenceSchema,
right_evidence_id: evidenceIdSchema,
}),
z.strictObject({
...compareApplicationVersionsFacts,
left_evidence_id: evidenceIdSchema,
right: evidenceSchema,
}),
z.strictObject({
...compareApplicationVersionsFacts,
left_evidence_id: evidenceIdSchema,
right_evidence_id: evidenceIdSchema,
}),
]);
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. */
export const compareSourceToBundleRequestSchema = z
.strictObject({
reference: compareSourceToBundleInputSchema.shape.reference,
application: evidenceSchema.optional(),
application_evidence_id: evidenceIdSchema.optional(),
limits: compareSourceToBundleInputSchema.shape.limits,
unknown_registry_approved:
compareSourceToBundleInputSchema.shape.unknown_registry_approved,
})
.superRefine((input, context) => {
requireExactlyOne(context, [
"application",
input.application,
"application_evidence_id",
input.application_evidence_id,
]);
});
export const compareSourceToBundleRequestSchema = z.union([
z.strictObject({
...compareSourceToBundleFacts,
application: evidenceSchema,
}),
z.strictObject({
...compareSourceToBundleFacts,
application_evidence_id: evidenceIdSchema,
}),
]);
const compareJavaScriptExportShapesFacts = {
left_module_path:
compareJavaScriptExportShapesInputSchema.shape.left_module_path,
left_export_name:
compareJavaScriptExportShapesInputSchema.shape.left_export_name,
right_module_path:
compareJavaScriptExportShapesInputSchema.shape.right_module_path,
right_export_name:
compareJavaScriptExportShapesInputSchema.shape.right_export_name,
limits: compareJavaScriptExportShapesInputSchema.shape.limits,
unknown_registry_approved:
compareJavaScriptExportShapesInputSchema.shape.unknown_registry_approved,
} as const;
/** MCP/CLI export-shape request accepting full Evidence or ledger references. */
export const compareJavaScriptExportShapesRequestSchema = z
.strictObject({
left: evidenceSchema.optional(),
left_evidence_id: evidenceIdSchema.optional(),
right: evidenceSchema.optional(),
right_evidence_id: evidenceIdSchema.optional(),
left_module_path:
compareJavaScriptExportShapesInputSchema.shape.left_module_path,
left_export_name:
compareJavaScriptExportShapesInputSchema.shape.left_export_name,
right_module_path:
compareJavaScriptExportShapesInputSchema.shape.right_module_path,
right_export_name:
compareJavaScriptExportShapesInputSchema.shape.right_export_name,
limits: compareJavaScriptExportShapesInputSchema.shape.limits,
unknown_registry_approved:
compareJavaScriptExportShapesInputSchema.shape.unknown_registry_approved,
})
.superRefine((input, context) => {
requireExactlyOne(context, [
"left",
input.left,
"left_evidence_id",
input.left_evidence_id,
]);
requireExactlyOne(context, [
"right",
input.right,
"right_evidence_id",
input.right_evidence_id,
]);
});
export const compareJavaScriptExportShapesRequestSchema = z.union([
z.strictObject({
...compareJavaScriptExportShapesFacts,
left: evidenceSchema,
right: evidenceSchema,
}),
z.strictObject({
...compareJavaScriptExportShapesFacts,
left: evidenceSchema,
right_evidence_id: evidenceIdSchema,
}),
z.strictObject({
...compareJavaScriptExportShapesFacts,
left_evidence_id: evidenceIdSchema,
right: evidenceSchema,
}),
z.strictObject({
...compareJavaScriptExportShapesFacts,
left_evidence_id: evidenceIdSchema,
right_evidence_id: evidenceIdSchema,
}),
]);
export type TraceApplicationFeatureRequest = z.output<
typeof traceApplicationFeatureRequestSchema
+41 -47
View File
@@ -5,6 +5,7 @@ import type { ToolContract } from "./toolContracts.js";
import { artifactOutputSchemas } from "./toolOutputSchemas.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { toolContractMetadata } from "./toolEffects.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
import { artifactInspectionLimitsSchema } from "../domain/artifactInspection.js";
const pageInput = {
@@ -35,27 +36,30 @@ const traversalLimitsInput = {
max_path_bytes: z.number().int().min(1).max(65_535).default(4_096),
};
/** Exact caller boundary for deterministic artifact inventory. */
export const artifactInventoryInputSchema = z
.object({
native_mount_approved: z.boolean().default(false),
integrity_policy: z.enum(["fail", "record-and-continue"]).default("fail"),
integrity_continue_approved: z.boolean().default(false),
const integrityInput = {
fail: {
integrity_policy: z.literal("fail").default("fail"),
integrity_continue_approved: z.literal(false).default(false),
max_integrity_mismatches: z.number().int().min(1).max(100).default(10),
...pageInput,
...traversalLimitsInput,
})
.superRefine((input, context) => {
if (
input.integrity_policy === "record-and-continue" &&
input.integrity_continue_approved !== true
)
context.addIssue({
code: "custom",
path: ["integrity_continue_approved"],
message: "record-and-continue requires explicit approval",
});
});
},
continue: {
integrity_policy: z.literal("record-and-continue"),
integrity_continue_approved: z.literal(true),
max_integrity_mismatches: z.number().int().min(1).max(100).default(10),
},
} as const;
const artifactInventoryFacts = {
native_mount_approved: z.boolean().default(false),
...pageInput,
...traversalLimitsInput,
} as const;
/** Exact caller boundary for deterministic artifact inventory. */
export const artifactInventoryInputSchema = z.union([
z.object({ ...artifactInventoryFacts, ...integrityInput.fail }),
z.object({ ...artifactInventoryFacts, ...integrityInput.continue }),
]);
/** Exact caller boundary for approved artifact extraction. */
export const artifactExtractionInputSchema = z.object({
@@ -75,26 +79,15 @@ export const artifactExtractionInputSchema = z.object({
});
/** Bounded provider-neutral inspection using one atomic inventory substep. */
export const artifactInspectionInputSchema = z
.object({
native_mount_approved: z.boolean().default(false),
integrity_policy: z.enum(["fail", "record-and-continue"]).default("fail"),
integrity_continue_approved: z.boolean().default(false),
max_integrity_mismatches: z.number().int().min(1).max(100).default(10),
...artifactInspectionLimitsSchema.shape,
...traversalLimitsInput,
})
.superRefine((input, context) => {
if (
input.integrity_policy === "record-and-continue" &&
input.integrity_continue_approved !== true
)
context.addIssue({
code: "custom",
path: ["integrity_continue_approved"],
message: "record-and-continue requires explicit approval",
});
});
const artifactInspectionFacts = {
native_mount_approved: z.boolean().default(false),
...artifactInspectionLimitsSchema.shape,
...traversalLimitsInput,
} as const;
export const artifactInspectionInputSchema = z.union([
z.object({ ...artifactInspectionFacts, ...integrityInput.fail }),
z.object({ ...artifactInspectionFacts, ...integrityInput.continue }),
]);
const exampleInputSchema = z.record(z.string(), jsonValueSchema);
const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
@@ -107,14 +100,15 @@ const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
},
};
const artifact = <Name extends string>(
const artifact = <
Name extends string,
Schema extends z.ZodType<Readonly<Record<string, unknown>>>,
>(
name: Name,
description: string,
inputSchema: z.ZodObject,
): ToolContract<Name> => {
const outputSchema = artifactOutputSchemas[name];
if (outputSchema === undefined)
throw new Error(`Missing artifact output schema for ${name}`);
inputSchema: Schema,
) => {
const outputSchema = requireOutputSchema(artifactOutputSchemas, name);
return {
name,
...toolContractMetadata(name),
@@ -128,7 +122,7 @@ const artifact = <Name extends string>(
input: exampleInputSchema.parse(examples[name] ?? {}),
},
],
};
} satisfies ToolContract<Name, Schema, typeof outputSchema>;
};
/** Artifact-graph inventory and explicitly approved safe extraction contracts. */
+2 -2
View File
@@ -18,7 +18,7 @@ import {
webMcpDiscoverySchema,
} from "../domain/webMcpDiscovery.js";
import {
browserCaptureComparisonWireSchema,
browserCaptureComparisonInputSchema,
browserCaptureComparisonSchema,
} from "../domain/browserCaptureComparison.js";
import {
@@ -282,7 +282,7 @@ export const BROWSER_TOOL_CONTRACTS = [
description:
"Compare either passive web captures or step-indexed browser scenarios. Scenario comparison aligns exact step IDs, records deterministic literal normalization, and exposes bounded artifact-level changes plus alignment failures. Missing or truncated evidence never proves equality.",
kind: "browser-provider",
inputSchema: browserCaptureComparisonWireSchema,
inputSchema: browserCaptureComparisonInputSchema,
outputSchema: captureDiffOutputSchema,
examples: [
{
+13 -30
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
const traceLiteralInputSchema = z.object({
const traceLiteralInputSchema = z.strictObject({
query: z.string().min(1),
case_sensitive: z.boolean().default(false),
limit: z.number().int().min(1).max(100).default(20),
@@ -13,27 +13,27 @@ const traceLiteralInputSchema = z.object({
/** Input schemas shared by MCP registration and enhanced application dispatch. */
export const enhancedInputSchemas = {
swift_classes: z.object({ pattern: z.string().default("") }),
get_objc_classes: z.object({ pattern: z.string().default("") }),
get_objc_protocols: z.object({}),
batch_decompile: z.object({
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({
addresses: z
.array(z.string().describe("A provider-normalized procedure address"))
.max(20)
.default([]),
}),
get_call_graph: z.object({
get_call_graph: z.strictObject({
address: z.string().describe("A provider-normalized procedure address"),
direction: z.enum(["forward", "backward"]).default("forward"),
depth: z.number().int().min(1).max(5).default(2),
}),
analyze_swift_types: z.object({}),
find_xrefs_to_name: z.object({ name: z.string() }),
binary_overview: z.object({
analyze_swift_types: z.strictObject({}),
find_xrefs_to_name: z.strictObject({ name: z.string() }),
binary_overview: z.strictObject({
detail: z.enum(["concise", "detailed"]).default("concise"),
limit: z.number().int().min(1).max(50).default(10),
}),
analyze_function: z.object({
analyze_function: z.strictObject({
procedure: z.string().describe("A procedure name or address"),
include_assembly: z.boolean().default(false),
limit: z.number().int().min(1).max(500).default(100),
@@ -42,7 +42,7 @@ export const enhancedInputSchemas = {
pseudocode_offset: z.number().int().min(0).default(0),
assembly_offset: z.number().int().min(0).default(0),
collection_offset: z
.object({
.strictObject({
comments: z.number().int().min(0).default(0),
callers: z.number().int().min(0).default(0),
callees: z.number().int().min(0).default(0),
@@ -63,7 +63,7 @@ export const enhancedInputSchemas = {
basic_blocks: 0,
}),
}),
inspect_native_api: z.object({
inspect_native_api: z.strictObject({
procedure: z.string().describe("A procedure name or address"),
max_pseudocode_chars: z.number().int().min(1).max(100_000).default(20_000),
max_instructions: z.number().int().min(1).max(5_000).default(500),
@@ -76,7 +76,7 @@ export const enhancedInputSchemas = {
}),
trace_feature: traceLiteralInputSchema,
find_code_for_string: traceLiteralInputSchema,
trace_call_path: z.object({
trace_call_path: z.strictObject({
start: z.string().describe("A provider-normalized procedure address"),
goal: z
.string()
@@ -94,20 +94,3 @@ export const enhancedInputSchemas = {
} as const;
export type EnhancedToolName = keyof typeof enhancedInputSchemas;
/** Runtime parser for dispatching only the closed enhanced names. */
export const enhancedToolNameSchema = z.enum([
"swift_classes",
"get_objc_classes",
"get_objc_protocols",
"batch_decompile",
"get_call_graph",
"analyze_swift_types",
"find_xrefs_to_name",
"binary_overview",
"analyze_function",
"inspect_native_api",
"trace_feature",
"find_code_for_string",
"trace_call_path",
]);
@@ -4,17 +4,16 @@ import { TOOL_EXAMPLE_OVERRIDES } from "./toolContractExamples.js";
import type { ToolContract } from "./toolContractTypes.js";
import { toolContractMetadata } from "./toolEffects.js";
import { enhancedOutputSchemas } from "./toolOutputSchemas.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
type FunctionWorkflowName = "analyze_function" | "inspect_native_api";
const functionWorkflow = <Name extends FunctionWorkflowName>(
name: Name,
description: string,
): ToolContract<Name> => {
) => {
const inputSchema = enhancedInputSchemas[name];
const outputSchema = enhancedOutputSchemas[name];
if (outputSchema === undefined)
throw new Error(`Missing function workflow output schema for ${name}`);
const outputSchema = requireOutputSchema(enhancedOutputSchemas, name);
return {
name,
...toolContractMetadata(name),
@@ -30,7 +29,7 @@ const functionWorkflow = <Name extends FunctionWorkflowName>(
),
},
],
};
} satisfies ToolContract<Name, typeof inputSchema, typeof outputSchema>;
};
/** Function dossier and native API reconstruction workflow contracts. */
+13 -12
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import type { ToolContract } from "./toolContracts.js";
import { managedOutputSchemas } from "./toolOutputSchemas.js";
import { toolContractMetadata } from "./toolEffects.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
export const managedArtifactInputSchema = z.object({
@@ -110,18 +111,18 @@ export const managedNativeBoundaryInputSchema = z.object({
.default(1_048_576),
});
const outputSchema = managedOutputSchemas.inspect_managed_artifact;
if (outputSchema === undefined)
throw new Error("Missing managed output schema for inspect_managed_artifact");
const memberOutputSchema = managedOutputSchemas.inspect_managed_members;
if (memberOutputSchema === undefined)
throw new Error("Missing managed output schema for inspect_managed_members");
const nativeBoundaryOutputSchema =
managedOutputSchemas.inspect_managed_native_boundaries;
if (nativeBoundaryOutputSchema === undefined)
throw new Error(
"Missing managed output schema for inspect_managed_native_boundaries",
);
const outputSchema = requireOutputSchema(
managedOutputSchemas,
"inspect_managed_artifact",
);
const memberOutputSchema = requireOutputSchema(
managedOutputSchemas,
"inspect_managed_members",
);
const nativeBoundaryOutputSchema = requireOutputSchema(
managedOutputSchemas,
"inspect_managed_native_boundaries",
);
/** Read-only managed artifact contracts. */
export const MANAGED_TOOL_CONTRACTS = [
+12 -9
View File
@@ -57,15 +57,18 @@ const emptyManagedMembers = (
limitations: [],
});
const emptyPage = <Item>(limit: number) => ({
items: [] as Item[],
offset: 0,
limit,
total: 0,
returned: 0,
dropped: 0,
complete: true,
});
const emptyPage = <Item>(limit: number) => {
const items: Item[] = [];
return {
items,
offset: 0,
limit,
total: 0,
returned: 0,
dropped: 0,
complete: true,
};
};
const evidence = (result: ManagedMemberInspection) =>
createEvidence(undefined, MANAGED_STATIC_EXAMPLE_PROVIDER, {
+48 -43
View File
@@ -15,6 +15,7 @@ import {
MANAGED_RUNTIME_CORRELATION_EXAMPLE,
} from "./managedWorkflowExamples.js";
import { toolContractMetadata } from "./toolEffects.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const managedEvidenceIdSchema = evidenceIdSchema.describe(
@@ -96,26 +97,40 @@ export const managedNativeVerificationReferenceInputSchema = z
}
});
/** MCP references for projecting managed Evidence into an application graph. */
const managedApplicationGraphReferenceFacts = {
limits: projectManagedApplicationGraphInputSchema.shape.limits,
} as const;
/** MCP references requiring at least one managed Evidence source. */
export const managedApplicationGraphReferenceInputSchema = z
.strictObject({
managed_artifact_evidence_id: managedArtifactEvidenceIdSchema.optional(),
managed_members_evidence_id: managedEvidenceIdSchema.optional(),
managed_native_boundaries_evidence_id:
managedBoundaryEvidenceIdSchema.optional(),
limits: projectManagedApplicationGraphInputSchema.shape.limits,
})
.union([
z.strictObject({
...managedApplicationGraphReferenceFacts,
managed_artifact_evidence_id: managedArtifactEvidenceIdSchema,
managed_members_evidence_id: managedEvidenceIdSchema.optional(),
managed_native_boundaries_evidence_id:
managedBoundaryEvidenceIdSchema.optional(),
}),
z.strictObject({
...managedApplicationGraphReferenceFacts,
managed_artifact_evidence_id: managedArtifactEvidenceIdSchema.optional(),
managed_members_evidence_id: managedEvidenceIdSchema,
managed_native_boundaries_evidence_id:
managedBoundaryEvidenceIdSchema.optional(),
}),
z.strictObject({
...managedApplicationGraphReferenceFacts,
managed_artifact_evidence_id: managedArtifactEvidenceIdSchema.optional(),
managed_members_evidence_id: managedEvidenceIdSchema.optional(),
managed_native_boundaries_evidence_id: managedBoundaryEvidenceIdSchema,
}),
])
.superRefine((input, context) => {
const ids = [
input.managed_artifact_evidence_id,
input.managed_members_evidence_id,
input.managed_native_boundaries_evidence_id,
].filter((id): id is string => id !== undefined);
if (ids.length === 0)
context.addIssue({
code: "custom",
message: "At least one managed Evidence ID is required",
});
if (new Set(ids).size !== ids.length)
context.addIssue({
code: "custom",
@@ -123,36 +138,26 @@ export const managedApplicationGraphReferenceInputSchema = z
});
});
const comparisonOutputSchema =
managedWorkflowOutputSchemas.compare_managed_members;
if (comparisonOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for compare_managed_members",
);
const runtimeOutputSchema =
managedWorkflowOutputSchemas.plan_managed_runtime_correlation;
if (runtimeOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for plan_managed_runtime_correlation",
);
const reconstructionOutputSchema =
managedWorkflowOutputSchemas.import_managed_reconstruction;
if (reconstructionOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for import_managed_reconstruction",
);
const nativeVerificationOutputSchema =
managedWorkflowOutputSchemas.verify_managed_native_boundaries;
if (nativeVerificationOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for verify_managed_native_boundaries",
);
const managedApplicationGraphOutputSchema =
managedWorkflowOutputSchemas.project_managed_application_graph;
if (managedApplicationGraphOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for project_managed_application_graph",
);
const comparisonOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"compare_managed_members",
);
const runtimeOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"plan_managed_runtime_correlation",
);
const reconstructionOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"import_managed_reconstruction",
);
const nativeVerificationOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"verify_managed_native_boundaries",
);
const managedApplicationGraphOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"project_managed_application_graph",
);
/** Provider-neutral managed-code workflow contracts. */
export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
+6 -7
View File
@@ -4,6 +4,7 @@ import type { ToolContract } from "./toolContracts.js";
import { nativeOutputSchemas } from "./toolOutputSchemas.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { toolContractMetadata } from "./toolEffects.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
inspect_macho: {},
@@ -13,14 +14,12 @@ const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
demangle_swift: { symbols: ["$s4Test3fooyyF"] },
};
const native = <Name extends string>(
const native = <Name extends string, Schema extends z.ZodObject>(
name: Name,
description: string,
inputSchema: z.ZodObject,
): ToolContract<Name> => {
const outputSchema = nativeOutputSchemas[name];
if (outputSchema === undefined)
throw new Error(`Missing native output schema for ${name}`);
inputSchema: Schema,
) => {
const outputSchema = requireOutputSchema(nativeOutputSchemas, name);
return {
name,
...toolContractMetadata(name),
@@ -36,7 +35,7 @@ const native = <Name extends string>(
.parse(examples[name] ?? {}),
},
],
};
} satisfies ToolContract<Name, Schema, typeof outputSchema>;
};
/** Provider-neutral semantic operations backed initially by macOS utilities. */
+11 -3
View File
@@ -35,13 +35,21 @@ export const TOOL_KINDS = [
export type ToolKind = (typeof TOOL_KINDS)[number];
/** Single source of truth for a public MCP tool. */
export interface ToolContract<Name extends string = string> {
export interface ToolContract<
Name extends string = string,
InputSchema extends z.ZodType<Readonly<Record<string, unknown>>> = z.ZodType<
Readonly<Record<string, unknown>>
>,
OutputSchema extends z.ZodType<Readonly<Record<string, unknown>>> = z.ZodType<
Readonly<Record<string, unknown>>
>,
> {
readonly name: Name;
readonly title: string;
readonly description: string;
readonly kind: ToolKind;
readonly inputSchema: z.ZodObject;
readonly outputSchema: z.ZodObject;
readonly inputSchema: InputSchema;
readonly outputSchema: OutputSchema;
readonly effects: ToolEffects;
readonly annotations: ToolAnnotations;
readonly examples: readonly ToolExample[];
+28 -26
View File
@@ -67,11 +67,11 @@ export {
export type { ToolContract, ToolExample } from "./toolContractTypes.js";
const official = <Name extends string>(
const official = <Name extends string, Schema extends z.ZodObject>(
name: Name,
description: string,
inputSchema: z.ZodObject,
): ToolContract<Name> => {
inputSchema: Schema,
) => {
const trackedInputSchema = inputSchema.extend({
unknown_registry_approved: z
.literal(true)
@@ -88,36 +88,38 @@ const official = <Name extends string>(
inputSchema: trackedInputSchema,
outputSchema: requireOutputSchema(officialOutputSchemas, name),
examples: examplesFor(name, trackedInputSchema),
};
} satisfies ToolContract<Name, typeof trackedInputSchema>;
};
const enhanced = <Name extends string>(
const enhanced = <Name extends string, Schema extends z.ZodObject>(
name: Name,
description: string,
inputSchema: z.ZodObject,
): ToolContract<Name> => ({
name,
...toolContractMetadata(name),
description,
kind: "enhanced",
inputSchema,
outputSchema: requireOutputSchema(enhancedOutputSchemas, name),
examples: examplesFor(name, inputSchema),
});
inputSchema: Schema,
) =>
({
name,
...toolContractMetadata(name),
description,
kind: "enhanced",
inputSchema,
outputSchema: requireOutputSchema(enhancedOutputSchemas, name),
examples: examplesFor(name, inputSchema),
}) satisfies ToolContract<Name, Schema>;
const session = <Name extends string>(
const session = <Name extends string, Schema extends z.ZodObject>(
name: Name,
description: string,
inputSchema: z.ZodObject,
): ToolContract<Name> => ({
name,
...toolContractMetadata(name),
description,
kind: "session",
inputSchema,
outputSchema: requireOutputSchema(sessionOutputSchemas, name),
examples: examplesFor(name, inputSchema),
});
inputSchema: Schema,
) =>
({
name,
...toolContractMetadata(name),
description,
kind: "session",
inputSchema,
outputSchema: requireOutputSchema(sessionOutputSchemas, name),
examples: examplesFor(name, inputSchema),
}) satisfies ToolContract<Name, Schema>;
/** Bridge operations exposed without additional application composition. */
export const OFFICIAL_TOOL_CONTRACTS = [
+1
View File
@@ -194,6 +194,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
mutatesSession: true,
writesFilesystem: true,
launchesProcess: true,
accessesNetwork: true,
idempotent: false,
}),
compare_process_captures: sessionEvidence,
+82 -34
View File
@@ -62,11 +62,8 @@ export const targetKindSchema = z.enum([
"artifact",
]);
const providerCapability = z.object({
const providerCapabilityFacts = {
operation: z.string(),
available: z.boolean(),
reason: z.string().nullable(),
availability_code: z.enum(PROVIDER_REJECTION_CODES).nullable(),
input_contract_version: z.number().int().min(1),
output_contract_version: z.number().int().min(1),
pagination: z.enum(["none", "offset", "cursor"]),
@@ -86,7 +83,23 @@ const providerCapability = z.object({
timeout_ms: z.number().int().min(0).nullable(),
}),
limitations: z.array(z.string()),
});
};
export const providerCapability = z.discriminatedUnion("available", [
z.object({
...providerCapabilityFacts,
available: z.literal(true),
reason: z.null(),
availability_code: z.null(),
}),
z.object({
...providerCapabilityFacts,
available: z.literal(false),
reason: z.string().nullable(),
availability_code: z.enum(PROVIDER_REJECTION_CODES).nullable(),
}),
]);
export type ProviderCapability = z.output<typeof providerCapability>;
export const providerIdentity = z.object({
id: z.string(),
@@ -225,32 +238,27 @@ export type ClientFeatureAvailability = z.infer<
typeof clientFeatureAvailabilitySchema
>;
export const toolAvailability = z.object({
const toolAvailabilityMode = z.discriminatedUnion("available", [
z.object({
name: z.string(),
available: z.literal(true),
missing_operations: z.array(z.string()).max(0),
remediation: z.null(),
}),
z.object({
name: z.string(),
available: z.literal(false),
missing_operations: z.array(z.string()).min(1),
remediation: z.string().nullable(),
}),
]);
export type ToolAvailabilityMode = z.output<typeof toolAvailabilityMode>;
const toolAvailabilityFacts = {
name: z.string(),
surface: z.string(),
available: z.boolean(),
reason: z.enum([
"available",
"client_capability_missing",
"target_required",
"provider_missing",
"provider_unavailable",
"target_unsupported",
"unsupported_host",
"policy_disabled",
]),
remediation: z.string().nullable(),
default_mode_available: z.boolean().optional(),
modes: z
.array(
z.object({
name: z.string(),
available: z.boolean(),
missing_operations: z.array(z.string()),
remediation: z.string().nullable(),
}),
)
.optional(),
modes: z.array(toolAvailabilityMode).optional(),
client_requirements: z.object({
required: z.array(clientFeatureNameSchema),
optional: z.array(clientFeatureNameSchema),
@@ -273,7 +281,36 @@ export const toolAvailability = z.object({
idempotent: z.boolean(),
open_world: z.boolean(),
}),
});
};
export const toolUnavailabilityReason = z.enum([
"client_capability_missing",
"target_required",
"provider_missing",
"provider_unavailable",
"target_unsupported",
"unsupported_host",
"policy_disabled",
]);
export const toolAvailability = z.discriminatedUnion("available", [
z.object({
...toolAvailabilityFacts,
available: z.literal(true),
reason: z.literal("available"),
remediation: z.null(),
}),
z.object({
...toolAvailabilityFacts,
available: z.literal(false),
reason: toolUnavailabilityReason,
remediation: z.string().nullable(),
}),
]);
export type ToolAvailability = z.output<typeof toolAvailability>;
export type ToolUnavailabilityReason = z.output<
typeof toolUnavailabilityReason
>;
export const sessionProvider = z.object({
provider: providerIdentity,
@@ -377,14 +414,25 @@ const availableMemoryPermissions = z.object({
source: z.literal("ghidra-memory-block"),
});
export const bounded = (item: z.ZodType) =>
z.object({
export const bounded = (item: z.ZodType) => {
const facts = {
items: z.array(item),
total: z.number().int().min(0).nullable(),
returned: z.number().int().min(0),
truncated: z.boolean(),
next_offset: z.number().int().min(0).nullable(),
});
} as const;
return z.discriminatedUnion("truncated", [
z.object({
...facts,
truncated: z.literal(false),
next_offset: z.null(),
}),
z.object({
...facts,
truncated: z.literal(true),
next_offset: z.number().int().min(0).nullable(),
}),
]);
};
const addressedValue = z.object({
address: z.string(),
-155
View File
@@ -1,155 +0,0 @@
import { READINESS_STAGE_IDS } from "../domain/reconstructionReadinessJourneyFindings.js";
type JsonSchema = Readonly<Record<string, unknown>>;
const conditionResultKey = ["t", "hen"].join("");
const exactlyOne = (left: string, right: string): JsonSchema => ({
oneOf: [{ required: [left] }, { required: [right] }],
});
const exclusivePairs = (
left: [string, string],
right: [string, string],
): JsonSchema => ({
oneOf: [
{
required: left,
not: {
anyOf: right.map((field) => ({ required: [field] })),
},
},
{
required: right,
not: {
anyOf: left.map((field) => ({ required: [field] })),
},
},
],
});
const twoEvidenceSources = (
left: [string, string],
right: [string, string],
): JsonSchema => ({
allOf: [exactlyOne(left[0], left[1]), exactlyOne(right[0], right[1])],
});
const approvalDependency = (flag: string, approval: string): JsonSchema => ({
if: {
required: [flag],
properties: {
[flag]: {
const: true,
description: `Whether ${flag} was requested`,
},
},
},
[conditionResultKey]: {
required: [approval],
properties: {
[approval]: {
const: true,
description: `Approval for ${flag}`,
},
},
},
});
const exactReadinessStages: JsonSchema = {
allOf: [
{
properties: {
stages: {
description: "Complete reconstruction-readiness stage set",
allOf: READINESS_STAGE_IDS.map((stageId) => ({
contains: {
type: "object",
properties: {
stage_id: {
const: stageId,
description: "Readiness stage identifier",
},
},
required: ["stage_id"],
description: "One reconstruction-readiness stage",
},
minContains: 1,
maxContains: 1,
})),
},
},
},
],
};
/** Public JSON-Schema constraints that Standard Schema cannot derive from refinements. */
export const TOOL_INPUT_JSON_SCHEMA_OVERRIDES: Readonly<
Record<string, JsonSchema>
> = {
compare_web_captures: {
...exclusivePairs(
["before", "after"],
["before_scenario", "after_scenario"],
),
},
inspect_web_page: {
allOf: [
approvalDependency("include_console_text", "console_text_approved"),
approvalDependency(
"include_json_body_shapes",
"json_body_schema_approved",
),
approvalDependency(
"include_websocket_shapes",
"websocket_shape_approved",
),
],
},
analyze_web_bundle: {
allOf: [
approvalDependency("include_console_text", "console_text_approved"),
approvalDependency(
"include_json_body_shapes",
"json_body_schema_approved",
),
approvalDependency(
"include_websocket_shapes",
"websocket_shape_approved",
),
approvalDependency("fetch_source_maps", "source_map_fetch_approved"),
],
},
inspect_electron_page: {
allOf: [
approvalDependency("include_script_sources", "source_capture_approved"),
],
},
trace_application_feature: {
...exactlyOne("application", "application_evidence_id"),
},
trace_javascript_semantics: {
...exactlyOne("application", "application_evidence_id"),
},
compare_application_versions: twoEvidenceSources(
["left", "left_evidence_id"],
["right", "right_evidence_id"],
),
compare_javascript_export_shapes: twoEvidenceSources(
["left", "left_evidence_id"],
["right", "right_evidence_id"],
),
compare_source_to_bundle: exactlyOne(
"application",
"application_evidence_id",
),
evaluate_reconstruction_readiness: exactReadinessStages,
};
/** Merge a contract-specific public constraint into generated or advertised input JSON Schema. */
export const applyToolInputJsonSchemaOverride = (
name: string,
schema: JsonSchema,
): JsonSchema => {
const override = TOOL_INPUT_JSON_SCHEMA_OVERRIDES[name];
return override === undefined ? schema : { ...schema, ...override };
};
+156
View File
@@ -0,0 +1,156 @@
import { z } from "zod";
import type { ToolContract } from "./toolContractTypes.js";
const PROPERTY_DESCRIPTIONS: Readonly<Record<string, string>> = {
addresses: "Ordered provider-normalized procedure addresses to analyze.",
approved: "Explicit operator approval to perform this operation.",
after: "The later or right-hand observation to compare.",
before: "The earlier or left-hand observation to compare.",
boundary_id: "Exact reconstruction boundary identifier to evaluate.",
case_sensitive:
"Whether text matching distinguishes uppercase and lowercase.",
cdp_endpoint: "Approved literal loopback Chrome DevTools Protocol endpoint.",
comment: "Exact analyst comment text to write.",
comparisons: "Validated comparison Evidence records to aggregate.",
coverage: "Exact reconstruction-coverage commitment to verify.",
detail: "Requested response detail level.",
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_uri:
"Session resource URI for the recorded Evidence v2 observation.",
executable: "Approved absolute path of the executable to run.",
format: "Declared input artifact format.",
name: "Exact name used by this operation.",
pattern: "Text or bounded pattern used to filter matching results.",
phase: "Current plan or execution phase of the operation.",
plan: "Content-bound execution plan and its approval commitment.",
query: "Non-empty feature or text query to investigate.",
question: "Concrete unresolved question to retain for later investigation.",
result: "Primary structured result returned by this operation.",
left: "Left-hand input used for comparison or differential execution.",
limit: "Maximum number of results to return in this page.",
limits:
"Bounded resource-consumption and result-size limits for this operation.",
mode: "Operation mode that selects the requested behavior.",
offset: "Zero-based index of the first result to return.",
overwrite: "Whether an existing destination may be replaced.",
path: "Local filesystem path used by this operation.",
provider_id:
"Exact deep-analysis provider ID, or automatic selection when omitted.",
right: "Right-hand input used for comparison or differential execution.",
schema_version: "Version of this structured result schema.",
source_evidence:
"Evidence records supporting the prepared source transformation.",
status: "Current lifecycle or verification status.",
summary: "Concise evidence-backed summary of the result.",
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.",
workspace_path:
"Approved local path of the persistent investigation workspace.",
};
/** Attach caller guidance to a canonical schema for the SDK wire projection. */
export const toolInputSchemaWithMetadata = <Contract extends ToolContract>(
contract: Contract,
): Contract["inputSchema"] => {
const schema = contract.inputSchema.meta(
z.globalRegistry.get(contract.inputSchema) ?? {},
);
const standard = schema["~standard"];
const inputJsonSchema = standard.jsonSchema?.input;
if (inputJsonSchema === undefined)
throw new TypeError(
"Tool input schema does not expose Standard JSON Schema",
);
// Zod's input projection drops root metadata when a descendant transforms.
// Preserve the parser and let the SDK own conversion of everything else.
Object.defineProperty(schema, "~standard", {
value: {
...standard,
jsonSchema: {
...standard.jsonSchema,
input: (options: Parameters<typeof inputJsonSchema>[0]) => ({
...describeProperties(inputJsonSchema(options)),
examples: contract.examples.map(({ input }) => input),
}),
},
},
});
return schema;
};
const describeProperties = (
value: Readonly<Record<string, unknown>>,
): Record<string, unknown> =>
Object.fromEntries(
Object.entries(value).map(([key, child]) => {
if (key !== "properties" || !isObject(child))
return [key, describeValue(child)];
return [
key,
Object.fromEntries(
Object.entries(child).map(([property, propertySchema]) => [
property,
isObject(propertySchema) &&
typeof propertySchema.description !== "string"
? {
...describeProperties(propertySchema),
description: fallbackPropertyDescription(property),
}
: describeValue(propertySchema),
]),
),
];
}),
);
const describeValue = (value: unknown): unknown => {
if (Array.isArray(value)) return value.map(describeValue);
return isObject(value) ? describeProperties(value) : value;
};
const fallbackPropertyDescription = (property: string): string => {
const explicit = PROPERTY_DESCRIPTIONS[property];
if (explicit !== undefined) return explicit;
const words = property.replaceAll("_", " ");
if (property.endsWith("_approved"))
return `Explicit operator approval for ${words.slice(0, -9)}.`;
if (property.endsWith("_offset"))
return `Zero-based index of the first ${words.slice(0, -7)} to return.`;
if (property.endsWith("_limit"))
return `Maximum number of ${words.slice(0, -6)} entries to return.`;
if (property.startsWith("max_"))
return `Maximum permitted ${words.slice(4)} for this operation.`;
if (property.startsWith("include_"))
return `Whether to include ${words.slice(8)} in the result.`;
if (property.startsWith("expected_"))
return `Expected ${words.slice(9)} used to reject stale or mismatched input.`;
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.`;
if (property.endsWith("_evidence_ids"))
return `Ordered Evidence v2 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"))
return `Canonical URI for ${words.slice(0, -4)}.`;
if (property.endsWith("_bytes"))
return `Bounded byte count for ${words.slice(0, -6)}.`;
if (property.endsWith("_root") || property.endsWith("_roots"))
return `Approved canonical filesystem ${words}.`;
if (property.startsWith("is_") || property.startsWith("has_"))
return `Whether ${words}.`;
return `Value for ${words}.`;
};
const isObject = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null && !Array.isArray(value);