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
+3 -4
View File
@@ -6,7 +6,6 @@ import {
type ArtifactNode,
type ArtifactOccurrence,
} from "./artifactGraph.js";
import { evidenceSchema } from "./evidence.js";
import {
parseArtifactInventoryEvidence,
type InventorySet,
@@ -42,9 +41,9 @@ const comparisonDimensionSchema = z.enum([
]);
/** Strict Evidence-backed input for deterministic artifact comparison. */
export const artifactComparisonInputSchema = z.object({
left: z.union([evidenceSchema, z.array(evidenceSchema).min(1).max(100)]),
right: z.union([evidenceSchema, z.array(evidenceSchema).min(1).max(100)]),
export const artifactComparisonInputSchema = z.strictObject({
left_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
right_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(500).default(100),
unknown_registry_approved: z
+3 -4
View File
@@ -3,7 +3,6 @@ import { createHash } from "node:crypto";
import { z } from "zod";
import {
evidenceBundleSchema,
parseEvidenceBundle,
serializeEvidenceBundle,
type EvidenceBundle,
@@ -22,9 +21,9 @@ const classificationSchema = z.enum([
]);
/** Strict bounded input for canonical Evidence bundle comparison. */
export const bundleComparisonInputSchema = z.object({
left: evidenceBundleSchema,
right: evidenceBundleSchema,
export const bundleComparisonInputSchema = z.strictObject({
left_bundle_path: z.string().min(1).max(4_096),
right_bundle_path: z.string().min(1).max(4_096),
record_pairs: z
.array(
z.object({
+49
View File
@@ -69,11 +69,27 @@ export class AnalysisInputError extends AnalysisError {
constructor(
readonly operation: string,
options?: ErrorOptions,
readonly issues: readonly AnalysisInputIssue[] = [],
) {
super(`Invalid analysis input for ${operation}`, options);
}
}
/** Secret-safe correction metadata for one rejected caller argument. */
export interface AnalysisInputIssue {
readonly path: readonly (string | number)[];
readonly reason:
| "unknown_argument"
| "missing_argument"
| "invalid_type"
| "out_of_range"
| "invalid_value"
| "invalid_format";
readonly expected?: JsonValue;
readonly minimum?: number;
readonly maximum?: number;
}
/** Provider output failed provider-neutral application parsing. */
export class AnalysisOutputError extends AnalysisError {
readonly _tag = "AnalysisOutputError";
@@ -307,6 +323,18 @@ export class EvidenceIntegrityError extends AnalysisError {
readonly _tag = "EvidenceIntegrityError";
}
/** A session Evidence reference is missing or has the wrong semantic identity. */
export class EvidenceReferenceError extends EvidenceIntegrityError {
constructor(
readonly evidenceId: string,
readonly reason: "missing" | "wrong_operation" | "wrong_predicate",
readonly expected: string,
readonly actual: string | null,
) {
super(`Evidence reference ${reason}: ${evidenceId}`);
}
}
/** A bounded evidence ledger cannot accept more records or serialized bytes. */
export class EvidenceLimitError extends AnalysisError {
readonly _tag = "EvidenceLimitError";
@@ -681,6 +709,24 @@ const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
const errorDetails = (
error: AnalysisError,
): Readonly<Record<string, JsonValue>> | undefined => {
if (error instanceof AnalysisInputError && error.issues.length > 0)
return {
operation: error.operation,
issues: error.issues.map((issue) => ({
path: [...issue.path],
reason: issue.reason,
...(issue.expected === undefined ? {} : { expected: issue.expected }),
...(issue.minimum === undefined ? {} : { minimum: issue.minimum }),
...(issue.maximum === undefined ? {} : { maximum: issue.maximum }),
})),
};
if (error instanceof EvidenceReferenceError)
return {
evidence_id: error.evidenceId,
reason: error.reason,
expected: error.expected,
actual: error.actual,
};
if (error instanceof ReplayPlanStaleError)
return {
approved_plan_digest: error.approvedDigest,
@@ -793,6 +839,7 @@ const missingScopeDetails = (
});
const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
"invalid_request",
"provider_timeout",
"cancelled",
"revision_conflict",
@@ -800,6 +847,8 @@ const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
]);
const remediationAction = (error: AnalysisError): string => {
if (error instanceof AnalysisInputError)
return "Correct the listed arguments and retry.";
if (error instanceof ReplayPlanStaleError)
return "Review the rebuilt replay plan and explicitly approve its new digest.";
if (error instanceof PermissionRequiredError)
+3 -9
View File
@@ -1,11 +1,5 @@
import { z } from "zod";
import { evidenceSchema } from "./evidence.js";
const evidenceInput = z.union([
evidenceSchema,
z.array(evidenceSchema).min(1).max(100),
]);
const comparisonStatusSchema = z.enum([
"unchanged",
"added",
@@ -28,9 +22,9 @@ const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
/** Strict bounded input for explicit function-to-function comparison. */
export const functionComparisonInputSchema = z.object({
left: evidenceInput,
right: evidenceInput,
export const functionComparisonInputSchema = z.strictObject({
left_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
right_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(100).default(100),
unknown_registry_approved: z.literal(true).optional(),
+83
View File
@@ -0,0 +1,83 @@
import type { z } from "zod";
import type { AnalysisInputIssue } from "./errors.js";
/** Project Zod failures to secret-safe caller correction metadata. */
export const projectInputIssues = (
issues: readonly z.core.$ZodIssue[],
input: unknown,
): readonly AnalysisInputIssue[] =>
issues.flatMap((issue) => projectIssue(issue, input));
const projectIssue = (
issue: z.core.$ZodIssue,
input: unknown,
): readonly AnalysisInputIssue[] => {
const path = issue.path.flatMap((part) =>
typeof part === "string" || typeof part === "number" ? [part] : [],
);
if (issue.code === "unrecognized_keys")
return issue.keys.map((key) => ({
path: [...path, key],
reason: "unknown_argument" as const,
}));
if (issue.code === "invalid_type")
return [
{
path,
reason:
valueAtPath(input, path) === undefined
? "missing_argument"
: "invalid_type",
expected: safeExpected(issue.expected),
},
];
if (issue.code === "too_small")
return [boundedIssue(path, "minimum", numericBound(issue.minimum))];
if (issue.code === "too_big")
return [boundedIssue(path, "maximum", numericBound(issue.maximum))];
if (issue.code === "invalid_format")
return [{ path, reason: "invalid_format", expected: issue.format }];
if (issue.code === "invalid_value")
return [
{
path,
reason: "invalid_value",
expected: issue.values.filter(isSafeExpected),
},
];
return [{ path, reason: "invalid_value" }];
};
const valueAtPath = (
input: unknown,
path: readonly (string | number)[],
): unknown => {
let current = input;
for (const part of path) {
if (typeof current !== "object" || current === null) return undefined;
current = (current as Readonly<Record<string | number, unknown>>)[part];
}
return current;
};
const numericBound = (value: number | bigint): number | undefined =>
typeof value === "number" && Number.isFinite(value) ? value : undefined;
const isSafeExpected = (
value: unknown,
): value is string | number | boolean | null =>
value === null || ["string", "number", "boolean"].includes(typeof value);
const safeExpected = (value: unknown) =>
isSafeExpected(value) ? value : "schema-defined value";
const boundedIssue = (
path: readonly (string | number)[],
key: "minimum" | "maximum",
value: number | undefined,
): AnalysisInputIssue => ({
path,
reason: "out_of_range",
...(value === undefined ? {} : { [key]: value }),
});
@@ -1,7 +1,5 @@
import { z } from "zod";
import { evidenceBundleSchema } from "./evidenceBundle.js";
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const unknownIdSchema = z.string().regex(/^unk_[a-f0-9]{64}$/u);
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
@@ -78,9 +76,8 @@ export const reconstructionSpecificationSchema = z
});
/** Bounded reconstruction-verification input. */
export const reconstructionVerificationInputSchema = z.object({
export const reconstructionVerificationInputSchema = z.strictObject({
specification: reconstructionSpecificationSchema,
evidence_bundle: evidenceBundleSchema,
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(100).default(100),
unknown_registry_approved: z.literal(true).optional(),