mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
fix(evidence): bound omitted validation issue locations (#13309)
* fix(evidence): bound omitted validation issue locations * fix(evidence): keep diagnostic locations that fit
This commit is contained in:
1 parent
ac4f655858
commit
4485912fd8
4 files changed
+315
-576
No files matched your search
@@ -13,38 +13,24 @@ import { processScenarioSchema } from "./process/processScenario.js";
|
||||
import { applicationFeatureSeedSchema } from "./javascript/javascriptFeatureTraceSchemas.js";
|
||||
import { updateAnalysisSettingsInputSchema } from "../contracts/analysisSettingsContracts.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "../contracts/applicationToolContracts.js";
|
||||
import { ENHANCED_TOOL_CONTRACTS } from "../contracts/enhancedToolContracts.js";
|
||||
import { searchGuidanceInputSchema } from "../contracts/guidanceContracts.js";
|
||||
import { inspectAnalysisViewInputSchema } from "./analysisView/analysisViewRequest.js";
|
||||
|
||||
const projectFlattenedIssueGroups = (
|
||||
...args: Parameters<typeof projectInputIssueGroupsWithinBudget>
|
||||
) => projectInputIssueGroupsWithinBudget(...args)?.flat();
|
||||
|
||||
const officialContract = (
|
||||
name: (typeof OFFICIAL_TOOL_CONTRACTS)[number]["name"],
|
||||
) => {
|
||||
const contract = OFFICIAL_TOOL_CONTRACTS.find((c) => c.name === name);
|
||||
const guidanceInputSchema = (operation: string): z.ZodType => {
|
||||
if (operation === "search_guidance") return searchGuidanceInputSchema;
|
||||
const family =
|
||||
operation === "trace_feature"
|
||||
? ENHANCED_TOOL_CONTRACTS
|
||||
: OFFICIAL_TOOL_CONTRACTS;
|
||||
const contract = family.find(({ name }) => name === operation);
|
||||
if (contract === undefined)
|
||||
throw new Error(`Missing official contract: ${name}`);
|
||||
return contract;
|
||||
};
|
||||
|
||||
const applicationContract = (
|
||||
name: (typeof APPLICATION_TOOL_CONTRACTS)[number]["name"],
|
||||
) => {
|
||||
const contract = APPLICATION_TOOL_CONTRACTS.find((c) => c.name === name);
|
||||
if (contract === undefined)
|
||||
throw new Error(`Missing application contract: ${name}`);
|
||||
return contract;
|
||||
};
|
||||
|
||||
const enhancedContract = (
|
||||
name: (typeof ENHANCED_TOOL_CONTRACTS)[number]["name"],
|
||||
) => {
|
||||
const contract = ENHANCED_TOOL_CONTRACTS.find((c) => c.name === name);
|
||||
if (contract === undefined)
|
||||
throw new Error(`Missing enhanced contract: ${name}`);
|
||||
return contract;
|
||||
throw new Error(`Missing test contract for ${operation}`);
|
||||
return contract.inputSchema;
|
||||
};
|
||||
|
||||
describe("input issue projection", () => {
|
||||
@@ -188,134 +174,64 @@ describe("input issue projection", () => {
|
||||
});
|
||||
|
||||
describe("input issue argument guidance", () => {
|
||||
it("guides callers from neighboring-tool argument names while keeping unknown keys strict", () => {
|
||||
const input = { address: "0x401000", count: 10 };
|
||||
for (const op of [
|
||||
"read_function_instructions",
|
||||
"procedure_pseudo_code",
|
||||
"procedure_assembly",
|
||||
] as const) {
|
||||
const parsed = officialContract(op).inputSchema.safeParse(input);
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
const error = analysisInputErrorFromIssues(
|
||||
op,
|
||||
parsed.error.issues,
|
||||
input,
|
||||
);
|
||||
expect(error.issues).toEqual([
|
||||
{ path: ["procedure"], reason: "missing_argument", expected: "string" },
|
||||
{
|
||||
path: ["address"],
|
||||
reason: "unknown_argument",
|
||||
expected: "procedure",
|
||||
message: expect.stringMatching(/address.*procedure/i),
|
||||
},
|
||||
{ path: ["count"], reason: "unknown_argument" },
|
||||
]);
|
||||
const action = projectAnalysisError(error).remediation.action;
|
||||
expect(action).toMatch(/procedure.*address/i);
|
||||
expect(action).toContain(op);
|
||||
}
|
||||
|
||||
const searchInput = { query: "flag" };
|
||||
for (const op of ["search_strings", "search_procedures"] as const) {
|
||||
const parsed = officialContract(op).inputSchema.safeParse(searchInput);
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
const searchError = analysisInputErrorFromIssues(
|
||||
op,
|
||||
parsed.error.issues,
|
||||
searchInput,
|
||||
);
|
||||
expect(searchError.issues).toEqual([
|
||||
{ path: ["pattern"], reason: "missing_argument", expected: "string" },
|
||||
{
|
||||
path: ["query"],
|
||||
reason: "unknown_argument",
|
||||
expected: "pattern",
|
||||
message: expect.stringMatching(/query.*pattern/i),
|
||||
},
|
||||
]);
|
||||
const action = projectAnalysisError(searchError).remediation.action;
|
||||
expect(action).toMatch(/pattern.*query/i);
|
||||
expect(action).toContain(op);
|
||||
}
|
||||
});
|
||||
|
||||
it("guides callers for symmetric neighboring-tool argument names", () => {
|
||||
const addressInput = { procedure: "main" };
|
||||
for (const op of ["resolve_containing_procedure", "read_bytes"] as const) {
|
||||
const parsed = officialContract(op).inputSchema.safeParse(addressInput);
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
const error = analysisInputErrorFromIssues(
|
||||
op,
|
||||
parsed.error.issues,
|
||||
addressInput,
|
||||
);
|
||||
expect(error.issues).toEqual([
|
||||
{ path: ["address"], reason: "missing_argument", expected: "string" },
|
||||
{
|
||||
path: ["procedure"],
|
||||
reason: "unknown_argument",
|
||||
expected: "address",
|
||||
message: expect.stringMatching(/procedure.*address/i),
|
||||
},
|
||||
]);
|
||||
const action = projectAnalysisError(error).remediation.action;
|
||||
expect(action).toMatch(/address.*procedure/i);
|
||||
expect(action).toContain(op);
|
||||
}
|
||||
|
||||
const xrefsParsed =
|
||||
officialContract("xrefs").inputSchema.safeParse(addressInput);
|
||||
if (xrefsParsed.success) throw new Error("expected invalid input");
|
||||
const xrefsError = analysisInputErrorFromIssues(
|
||||
"xrefs",
|
||||
xrefsParsed.error.issues,
|
||||
addressInput,
|
||||
);
|
||||
expect(xrefsError.issues).toEqual([
|
||||
it("corrects neighboring-tool keys without accepting unknown arguments", () => {
|
||||
const cases = [
|
||||
{
|
||||
path: ["procedure"],
|
||||
reason: "unknown_argument",
|
||||
expected: "address",
|
||||
message: expect.stringMatching(/procedure.*address/i),
|
||||
},
|
||||
]);
|
||||
const xrefsAction = projectAnalysisError(xrefsError).remediation.action;
|
||||
expect(xrefsAction).toMatch(/address.*procedure/i);
|
||||
expect(xrefsAction).toContain("xrefs");
|
||||
|
||||
const queryInput = { pattern: "flag" };
|
||||
const queryCases = [
|
||||
{
|
||||
op: "search_guidance" as const,
|
||||
contract: applicationContract("search_guidance"),
|
||||
operations: [
|
||||
"read_function_instructions",
|
||||
"procedure_pseudo_code",
|
||||
"procedure_assembly",
|
||||
],
|
||||
from: "address",
|
||||
to: "procedure",
|
||||
input: { address: "0x401000", count: 10 },
|
||||
otherIssues: [{ path: ["count"], reason: "unknown_argument" }],
|
||||
},
|
||||
{
|
||||
op: "trace_feature" as const,
|
||||
contract: enhancedContract("trace_feature"),
|
||||
operations: ["search_strings", "search_procedures"],
|
||||
from: "query",
|
||||
to: "pattern",
|
||||
input: { query: "flag" },
|
||||
},
|
||||
];
|
||||
for (const { op, contract } of queryCases) {
|
||||
const parsed = contract.inputSchema.safeParse(queryInput);
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
const error = analysisInputErrorFromIssues(
|
||||
op,
|
||||
parsed.error.issues,
|
||||
queryInput,
|
||||
);
|
||||
expect(error.issues).toEqual([
|
||||
{ path: ["query"], reason: "missing_argument", expected: "string" },
|
||||
{
|
||||
path: ["pattern"],
|
||||
reason: "unknown_argument",
|
||||
expected: "query",
|
||||
message: expect.stringMatching(/pattern.*query/i),
|
||||
},
|
||||
]);
|
||||
const action = projectAnalysisError(error).remediation.action;
|
||||
expect(action).toMatch(/query.*pattern/i);
|
||||
expect(action).toContain(op);
|
||||
{
|
||||
operations: ["resolve_containing_procedure", "read_bytes", "xrefs"],
|
||||
from: "procedure",
|
||||
to: "address",
|
||||
input: { procedure: "main" },
|
||||
},
|
||||
{
|
||||
operations: ["search_guidance", "trace_feature"],
|
||||
from: "pattern",
|
||||
to: "query",
|
||||
input: { pattern: "flag" },
|
||||
},
|
||||
] as const;
|
||||
for (const { operations, from, to, input, ...extras } of cases) {
|
||||
for (const operation of operations) {
|
||||
const parsed = guidanceInputSchema(operation).safeParse(input);
|
||||
if (parsed.success)
|
||||
throw new Error(`Expected ${operation} to reject ${from}`);
|
||||
const error = analysisInputErrorFromIssues(
|
||||
operation,
|
||||
parsed.error.issues,
|
||||
input,
|
||||
);
|
||||
expect(error.issues, operation).toEqual([
|
||||
...(operation === "xrefs"
|
||||
? []
|
||||
: [{ path: [to], reason: "missing_argument", expected: "string" }]),
|
||||
{
|
||||
path: [from],
|
||||
reason: "unknown_argument",
|
||||
expected: to,
|
||||
message: expect.stringMatching(new RegExp(`${from}.*${to}`, "i")),
|
||||
},
|
||||
...("otherIssues" in extras ? extras.otherIssues : []),
|
||||
]);
|
||||
const action = projectAnalysisError(error).remediation.action;
|
||||
expect(action, operation).toMatch(new RegExp(`${to}.*${from}`, "i"));
|
||||
expect(action, operation).toContain(operation);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -327,9 +243,8 @@ describe("input issue argument guidance suppression", () => {
|
||||
address: "0x401000",
|
||||
comment: "entry comment",
|
||||
};
|
||||
const parsed = officialContract(
|
||||
"annotate_native_function",
|
||||
).inputSchema.safeParse(inputWithBoth);
|
||||
const schema = guidanceInputSchema("annotate_native_function");
|
||||
const parsed = schema.safeParse(inputWithBoth);
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
const error = analysisInputErrorFromIssues(
|
||||
"annotate_native_function",
|
||||
@@ -355,9 +270,7 @@ describe("input issue argument guidance suppression", () => {
|
||||
address: "0x401000",
|
||||
comment: "entry comment",
|
||||
};
|
||||
const parsedMissing = officialContract(
|
||||
"annotate_native_function",
|
||||
).inputSchema.safeParse(inputMissingExpected);
|
||||
const parsedMissing = schema.safeParse(inputMissingExpected);
|
||||
if (parsedMissing.success) throw new Error("expected invalid input");
|
||||
const errorMissing = analysisInputErrorFromIssues(
|
||||
"annotate_native_function",
|
||||
@@ -649,126 +562,38 @@ describe("union branch diagnostic merging", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const testViewUnionSchema = z.union([
|
||||
z.strictObject({
|
||||
kind: z.literal("page"),
|
||||
collection: z.enum(["sections", "symbols", "modules"]),
|
||||
offset: z.number().int().default(0),
|
||||
limit: z.number().int().default(64),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("javascript"),
|
||||
collection: z.literal("modules"),
|
||||
projection: z.literal("references"),
|
||||
offset: z.number().int().default(0),
|
||||
limit: z.number().int().default(64),
|
||||
}),
|
||||
]);
|
||||
it("limits cross-kind view guidance to inspect_analysis_view and keeps its public path", () => {
|
||||
const operation = "inspect_analysis_view";
|
||||
const inputSchema = inspectAnalysisViewInputSchema;
|
||||
const input = {
|
||||
source: { kind: "retained-evidence", evidence_id: `ev_${"a".repeat(64)}` },
|
||||
view: { kind: "javascript", collection: "modules", limit: 40, offset: 0 },
|
||||
};
|
||||
const parsed = inputSchema.safeParse(input);
|
||||
const wrapped = z
|
||||
.strictObject({ operation: z.literal(operation), input: inputSchema })
|
||||
.safeParse({ operation, input });
|
||||
if (parsed.success || wrapped.success)
|
||||
throw new Error("Expected the view to require projection");
|
||||
|
||||
describe("inspect_analysis_view cross-kind sub-selector guidance", () => {
|
||||
it("guides caller toward kind 'page' when javascript kind uses collection 'modules' without projection", () => {
|
||||
const input = {
|
||||
source: {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: `ev_${"a".repeat(64)}`,
|
||||
},
|
||||
view: {
|
||||
kind: "javascript",
|
||||
collection: "modules",
|
||||
limit: 40,
|
||||
offset: 0,
|
||||
},
|
||||
};
|
||||
const schema = z.strictObject({
|
||||
source: z.unknown(),
|
||||
view: testViewUnionSchema,
|
||||
});
|
||||
const parsed = schema.safeParse(input);
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
const projected = projectInputIssues(
|
||||
parsed.error.issues,
|
||||
input,
|
||||
"inspect_analysis_view",
|
||||
);
|
||||
expect(projected).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: ["view", "projection"],
|
||||
reason: "invalid_value",
|
||||
expected: ["references"],
|
||||
message: expect.stringMatching(/page.*modules/i),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("omits guidance message when operation is not inspect_analysis_view", () => {
|
||||
const input = {
|
||||
view: {
|
||||
kind: "javascript",
|
||||
collection: "modules",
|
||||
limit: 40,
|
||||
offset: 0,
|
||||
},
|
||||
};
|
||||
const schema = z.strictObject({ view: testViewUnionSchema });
|
||||
const parsed = schema.safeParse(input);
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
const projected = projectInputIssues(
|
||||
parsed.error.issues,
|
||||
input,
|
||||
"other_operation",
|
||||
);
|
||||
expect(projected).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: ["view", "projection"],
|
||||
reason: "invalid_value",
|
||||
expected: ["references"],
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
projected.find((p) => p.path.join(".") === "view.projection")?.message,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("attaches guidance when wrapped in analysisOperationInputErrorFromIssues", () => {
|
||||
const input = {
|
||||
source: {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: `ev_${"a".repeat(64)}`,
|
||||
},
|
||||
view: {
|
||||
kind: "javascript",
|
||||
collection: "modules",
|
||||
limit: 40,
|
||||
offset: 0,
|
||||
},
|
||||
};
|
||||
const schema = z.strictObject({
|
||||
operation: z.literal("inspect_analysis_view"),
|
||||
input: z.strictObject({
|
||||
source: z.unknown(),
|
||||
view: testViewUnionSchema,
|
||||
}),
|
||||
});
|
||||
const parsed = schema.safeParse({
|
||||
operation: "inspect_analysis_view",
|
||||
input,
|
||||
});
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
const error = analysisOperationInputErrorFromIssues(
|
||||
"inspect_analysis_view",
|
||||
parsed.error.issues,
|
||||
input,
|
||||
parsed.error,
|
||||
);
|
||||
expect(error.issues).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: ["view", "projection"],
|
||||
reason: "invalid_value",
|
||||
expected: ["references"],
|
||||
message: expect.stringMatching(/page.*modules/i),
|
||||
}),
|
||||
);
|
||||
});
|
||||
const field = {
|
||||
path: ["view", "projection"],
|
||||
reason: "invalid_value",
|
||||
expected: ["references"],
|
||||
};
|
||||
const guided = { ...field, message: expect.stringMatching(/page.*modules/i) };
|
||||
const direct = projectInputIssues(parsed.error.issues, input, operation);
|
||||
const enveloped = analysisOperationInputErrorFromIssues(
|
||||
operation,
|
||||
wrapped.error.issues,
|
||||
input,
|
||||
wrapped.error,
|
||||
);
|
||||
expect(direct).toContainEqual(guided);
|
||||
expect(enveloped.issues).toEqual(direct);
|
||||
expect(
|
||||
projectInputIssues(parsed.error.issues, input, "other_operation"),
|
||||
).toContainEqual(field);
|
||||
});
|
||||
|
||||
describe("discriminated union nested alternatives and budget", () => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
knownViewMistakeGuidance,
|
||||
} from "./inputArgumentGuidance.js";
|
||||
import { isRecord } from "../kernel/isRecord.js";
|
||||
import { jsonValueByteLength } from "./jsonValueByteLength.js";
|
||||
|
||||
const isRootArgument = (path: readonly unknown[]): boolean =>
|
||||
path.length === 0 || (path.length === 1 && path[0] === "input");
|
||||
@@ -100,24 +101,39 @@ export const projectInputIssuesBounded = (
|
||||
// least one omitted field diagnostic each.
|
||||
const omittedIssueCount = issues.length - index;
|
||||
if (output.length > 0) return { issues: output, omittedIssueCount };
|
||||
// One compound issue, such as `unrecognized_keys` naming hundreds of keys,
|
||||
// can exceed the allowance on its own. Retain a diagnostic at its path so the
|
||||
// caller keeps the location instead of only an omission notice.
|
||||
// Report the first omitted location without copying a path that alone
|
||||
// exceeds the allowance. Keep exact components of the nearest parent.
|
||||
const first = issues[0];
|
||||
if (first === undefined) return { issues: output, omittedIssueCount };
|
||||
const path = first.path.flatMap((part) =>
|
||||
typeof part === "string" || typeof part === "number" ? [part] : [],
|
||||
);
|
||||
return {
|
||||
issues: [
|
||||
{
|
||||
path,
|
||||
reason: "invalid_value",
|
||||
message: `${String(omittedIssueCount)} field diagnostics at this location were omitted because they do not fit the response budget.`,
|
||||
},
|
||||
],
|
||||
omittedIssueCount,
|
||||
const issue = {
|
||||
path: [] as (string | number)[],
|
||||
reason: "invalid_value" as const,
|
||||
message: `${String(omittedIssueCount)} field diagnostics at this location were omitted because they do not fit the response budget.`,
|
||||
};
|
||||
let remaining = budgetBytes - jsonValueByteLength(issue);
|
||||
for (const part of first.path) {
|
||||
if (typeof part !== "number" && typeof part !== "string") continue;
|
||||
const separator = issue.path.length === 0 ? 0 : 1;
|
||||
const bytes =
|
||||
separator + jsonValueByteLength(part, remaining - separator);
|
||||
if (bytes > remaining) {
|
||||
const explanation =
|
||||
" The diagnostic reports the nearest parent because the full location exceeds the response budget.";
|
||||
const message = issue.message + explanation;
|
||||
remaining -=
|
||||
jsonValueByteLength(message) - jsonValueByteLength(issue.message);
|
||||
while (remaining < 0 && issue.path.length > 0) {
|
||||
const last = issue.path.pop()!;
|
||||
remaining +=
|
||||
jsonValueByteLength(last) + (issue.path.length === 0 ? 0 : 1);
|
||||
}
|
||||
issue.message = message;
|
||||
break;
|
||||
}
|
||||
remaining -= bytes;
|
||||
issue.path.push(part);
|
||||
}
|
||||
return { issues: [issue], omittedIssueCount };
|
||||
}
|
||||
return { issues: output, omittedIssueCount: 0 };
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@ import { expect, it } from "vitest";
|
||||
import { analysisViewCaptureEvidence } from "../../tests/fixtures/analysisView.js";
|
||||
import { createApplicationMcpHarness } from "../../tests/fixtures/applicationMcpHarness.js";
|
||||
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { parseMcpToolError } from "../../tests/fixtures/mcpToolError.js";
|
||||
|
||||
/**
|
||||
* Issue #8453 is about the delivered MCP error, not only the reader's result. On
|
||||
@@ -17,55 +17,62 @@ import type { Evidence } from "../domain/evidence.js";
|
||||
*/
|
||||
it("delivers a bounded file validation error through inspect_analysis_view", async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-bounded-issues-");
|
||||
const evidencePath = join(root, "many.json");
|
||||
const source = structuredClone(analysisViewCaptureEvidence());
|
||||
const document = {
|
||||
const source = analysisViewCaptureEvidence();
|
||||
const { client } = await createApplicationMcpHarness();
|
||||
const inspectFile = async (name: string, document: unknown) => {
|
||||
const path = join(root, name);
|
||||
await writeFile(path, JSON.stringify(document));
|
||||
const result = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: { kind: "evidence-file", path },
|
||||
view: { kind: "summary" },
|
||||
},
|
||||
});
|
||||
const { error } = parseMcpToolError(result);
|
||||
expect(error).toMatchObject({ code: "invalid_request", details: { path } });
|
||||
return error;
|
||||
};
|
||||
|
||||
const many = await inspectFile("many.json", {
|
||||
...source,
|
||||
limitations: Array.from({ length: 125_000 }, (_value, index) => index),
|
||||
} as unknown as Evidence;
|
||||
await writeFile(evidencePath, JSON.stringify(document));
|
||||
|
||||
const { client } = await createApplicationMcpHarness();
|
||||
const result = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: { kind: "evidence-file", path: evidencePath },
|
||||
view: { kind: "summary" },
|
||||
},
|
||||
});
|
||||
const issues = many.details?.content_issues;
|
||||
expect(issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ path: ["limitations", 0], reason: "invalid_type", expected: "string" },
|
||||
expect.objectContaining({
|
||||
path: [],
|
||||
message: expect.stringContaining("validator issues were omitted"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(Buffer.byteLength(JSON.stringify(many), "utf8")).toBeLessThan(1 << 20);
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
const text = (result.content as readonly { type: string; text?: string }[])
|
||||
.flatMap(({ type, text: value }) =>
|
||||
type === "text" && value !== undefined ? [value] : [],
|
||||
)
|
||||
.join("");
|
||||
// The typed file error and the selected path survive the response boundary.
|
||||
const delivered = JSON.parse(text) as {
|
||||
error?: {
|
||||
code?: string;
|
||||
details?: {
|
||||
path?: string;
|
||||
content_issues?: readonly {
|
||||
path?: readonly (string | number)[];
|
||||
reason?: string;
|
||||
message?: string;
|
||||
}[];
|
||||
};
|
||||
};
|
||||
};
|
||||
expect(delivered.error?.code).toBe("invalid_request");
|
||||
expect(delivered.error?.details?.path).toBe(evidencePath);
|
||||
const issues = delivered.error?.details?.content_issues ?? [];
|
||||
// Bounded rather than all 125,000, and explicitly incomplete.
|
||||
expect(issues.length).toBeGreaterThan(0);
|
||||
expect(issues.length).toBeLessThan(1_000);
|
||||
expect(issues).toContainEqual(
|
||||
// Projection may run out of work budget while the exact location still fits.
|
||||
const fittingKey = "a".repeat(65_300);
|
||||
const fitting = await inspectFile("fitting-key.json", {
|
||||
...source,
|
||||
caller_input_paths: { [fittingKey]: false },
|
||||
});
|
||||
expect(fitting.details?.content_issues).toContainEqual(
|
||||
expect.objectContaining({ path: ["caller_input_paths", fittingKey] }),
|
||||
);
|
||||
|
||||
const longKey = await inspectFile("oversized-key.json", {
|
||||
...source,
|
||||
caller_input_paths: { ["argument".repeat(10_000)]: false },
|
||||
});
|
||||
expect(longKey.details?.content_issues).toEqual([
|
||||
{
|
||||
path: ["caller_input_paths"],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining("nearest parent"),
|
||||
},
|
||||
expect.objectContaining({
|
||||
path: [],
|
||||
message: expect.stringContaining("validator issues were omitted"),
|
||||
message: expect.stringContaining("1 of 1 validator issues were omitted"),
|
||||
}),
|
||||
);
|
||||
// The whole delivered response stays well inside the default MCP budget.
|
||||
expect(Buffer.byteLength(text, "utf8")).toBeLessThan(1 << 20);
|
||||
]);
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
@@ -8,32 +7,33 @@ import { createToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
|
||||
import { mcpTest } from "../../support/mcp/mcpFixture.js";
|
||||
|
||||
it("keeps concurrent SDK validation issues attached to their own tool call", async () => {
|
||||
let calls = 0;
|
||||
const server = createServer({
|
||||
kind: "fixed",
|
||||
analysis: {
|
||||
execute: () => {
|
||||
calls += 1;
|
||||
return Promise.resolve(observed(null));
|
||||
const malformedRead = { address: 123, length: 0, document: false };
|
||||
const readIssues = [
|
||||
{ path: ["address"], reason: "invalid_type", expected: "string" },
|
||||
{ path: ["length"], reason: "out_of_range", minimum: 1 },
|
||||
{ path: ["document"], reason: "invalid_type", expected: "string" },
|
||||
];
|
||||
|
||||
mcpTest(
|
||||
"keeps concurrent SDK validation issues attached to their own tool call",
|
||||
async ({ mcp }) => {
|
||||
let calls = 0;
|
||||
const server = createServer({
|
||||
kind: "fixed",
|
||||
analysis: {
|
||||
execute: () => {
|
||||
calls += 1;
|
||||
return Promise.resolve(observed(null));
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const client = new Client(
|
||||
{ name: "input-issue-attribution", version: "1" },
|
||||
{ jsonSchemaValidator: createMcpSchemaValidation() },
|
||||
);
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
});
|
||||
const client = await mcp.connect(server);
|
||||
const [read, search, missing] = await Promise.all([
|
||||
client.callTool({
|
||||
name: "read_bytes",
|
||||
arguments: { address: 123, length: 0, document: false },
|
||||
arguments: malformedRead,
|
||||
}),
|
||||
client.callTool({
|
||||
name: "search_bytes",
|
||||
@@ -45,11 +45,7 @@ it("keeps concurrent SDK validation issues attached to their own tool call", asy
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{ path: ["address"], reason: "invalid_type", expected: "string" },
|
||||
{ path: ["length"], reason: "out_of_range", minimum: 1 },
|
||||
{ path: ["document"], reason: "invalid_type", expected: "string" },
|
||||
],
|
||||
issues: readIssues,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -81,71 +77,43 @@ it("keeps concurrent SDK validation issues attached to their own tool call", asy
|
||||
});
|
||||
expect(calls).toBe(0);
|
||||
await expect(client.ping()).resolves.toBeDefined();
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves field diagnostics over production stdio and keeps serving", async () => {
|
||||
const { call, client } = await connectLocalToolsMcp();
|
||||
const result = await call("read_bytes", {
|
||||
address: 123,
|
||||
length: 0,
|
||||
document: false,
|
||||
});
|
||||
const result = await call("read_bytes", malformedRead);
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
recovery: { kind: "inspect_input_contract", operation: "read_bytes" },
|
||||
details: {
|
||||
issues: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: ["address"],
|
||||
reason: "invalid_type",
|
||||
expected: "string",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path: ["length"],
|
||||
reason: "out_of_range",
|
||||
minimum: 1,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path: ["document"],
|
||||
reason: "invalid_type",
|
||||
expected: "string",
|
||||
}),
|
||||
]),
|
||||
issues: readIssues,
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect(client.ping()).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
it("retains mixed SDK field diagnostics without repeating custom guidance", async () => {
|
||||
const info = { name: "custom-issues", version: "1" };
|
||||
const server = new EvidenceMcpServer(
|
||||
info,
|
||||
{ capabilities: {} },
|
||||
undefined,
|
||||
createToolResultDelivery(4096),
|
||||
);
|
||||
const inputSchema = z.strictObject({
|
||||
first: z.string().regex(/^a$/u, "first correction"),
|
||||
second: z.string().regex(/^b$/u, "second correction"),
|
||||
count: z.number(),
|
||||
});
|
||||
server.registerTool("custom_issues", { inputSchema }, async () => ({
|
||||
content: [{ type: "text", text: "unexpected dispatch" }],
|
||||
}));
|
||||
const client = new Client(info, {
|
||||
jsonSchemaValidator: createMcpSchemaValidation(),
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
mcpTest(
|
||||
"retains mixed SDK field diagnostics without repeating custom guidance",
|
||||
async ({ mcp }) => {
|
||||
const info = { name: "custom-issues", version: "1" };
|
||||
const server = new EvidenceMcpServer(
|
||||
info,
|
||||
{ capabilities: {} },
|
||||
undefined,
|
||||
createToolResultDelivery(4096),
|
||||
);
|
||||
const inputSchema = z.strictObject({
|
||||
first: z.string().regex(/^a$/u, "first correction"),
|
||||
second: z.string().regex(/^b$/u, "second correction"),
|
||||
count: z.number(),
|
||||
});
|
||||
server.registerTool("custom_issues", { inputSchema }, async () => ({
|
||||
content: [{ type: "text", text: "unexpected dispatch" }],
|
||||
}));
|
||||
const client = await mcp.connect(server);
|
||||
const argumentsValue = {
|
||||
first: "wrong",
|
||||
second: "wrong",
|
||||
@@ -193,37 +161,29 @@ it("retains mixed SDK field diagnostics without repeating custom guidance", asyn
|
||||
expect(text.split("first correction")).toHaveLength(2);
|
||||
expect(text.split("second correction")).toHaveLength(2);
|
||||
expect(error.message.split(unknownIssue.message)).toHaveLength(2);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps same-path union and independent issues attributed to their producers", async () => {
|
||||
const info = { name: "issue-producer", version: "1" };
|
||||
const server = new EvidenceMcpServer(
|
||||
info,
|
||||
{ capabilities: {} },
|
||||
undefined,
|
||||
createToolResultDelivery(4096),
|
||||
);
|
||||
const inputSchema = z.intersection(
|
||||
z.object({
|
||||
a: z.union([z.object({ x: z.string() }), z.object({ x: z.number() })]),
|
||||
}),
|
||||
z.object({ a: z.object({ x: z.array(z.string()) }) }),
|
||||
);
|
||||
server.registerTool("overlapping_issues", { inputSchema }, async () => ({
|
||||
content: [{ type: "text", text: "unexpected dispatch" }],
|
||||
}));
|
||||
const client = new Client(info, {
|
||||
jsonSchemaValidator: createMcpSchemaValidation(),
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
mcpTest(
|
||||
"keeps same-path union and independent issues attributed to their producers",
|
||||
async ({ mcp }) => {
|
||||
const info = { name: "issue-producer", version: "1" };
|
||||
const server = new EvidenceMcpServer(
|
||||
info,
|
||||
{ capabilities: {} },
|
||||
undefined,
|
||||
createToolResultDelivery(4096),
|
||||
);
|
||||
const inputSchema = z.intersection(
|
||||
z.object({
|
||||
a: z.union([z.object({ x: z.string() }), z.object({ x: z.number() })]),
|
||||
}),
|
||||
z.object({ a: z.object({ x: z.array(z.string()) }) }),
|
||||
);
|
||||
server.registerTool("overlapping_issues", { inputSchema }, async () => ({
|
||||
content: [{ type: "text", text: "unexpected dispatch" }],
|
||||
}));
|
||||
const client = await mcp.connect(server);
|
||||
const input = { a: { x: false } };
|
||||
const parsed = inputSchema.safeParse(input);
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
@@ -236,108 +196,75 @@ it("keeps same-path union and independent issues attributed to their producers",
|
||||
arguments: input,
|
||||
});
|
||||
const error = parseMcpToolError(result).error;
|
||||
const issues = z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
expected: z.unknown().optional(),
|
||||
message: z.string().optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
)
|
||||
.parse(error.details?.issues);
|
||||
const issues = error.details?.issues;
|
||||
expect(issues).toHaveLength(3);
|
||||
expect(issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
{
|
||||
path: ["a", "x"],
|
||||
reason: "invalid_type",
|
||||
expected: "array",
|
||||
message: rawArrayIssue.message,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path: ["a", "x"],
|
||||
reason: "invalid_type",
|
||||
expected: "string",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path: ["a", "x"],
|
||||
reason: "invalid_type",
|
||||
expected: "number",
|
||||
}),
|
||||
},
|
||||
{ path: ["a", "x"], reason: "invalid_type", expected: "string" },
|
||||
{ path: ["a", "x"], reason: "invalid_type", expected: "number" },
|
||||
]),
|
||||
);
|
||||
const stringIssue = issues.find((issue) => issue.expected === "string");
|
||||
expect(stringIssue?.message).not.toBe(rawArrayIssue.message);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("discloses when bounded projection cannot retain union branch details", async () => {
|
||||
const info = { name: "bounded-issues", version: "1" };
|
||||
const server = new EvidenceMcpServer(
|
||||
info,
|
||||
{ capabilities: {} },
|
||||
undefined,
|
||||
createToolResultDelivery(4096),
|
||||
);
|
||||
const branches = Array.from({ length: 256 }, (_, index) =>
|
||||
z.object({ [`field_${String(index)}`]: z.string() }),
|
||||
);
|
||||
const first = branches[0];
|
||||
const second = branches[1];
|
||||
if (first === undefined || second === undefined)
|
||||
throw new Error("missing branches");
|
||||
const inputSchema = z.object({
|
||||
value: z.union([first, second, ...branches.slice(2)]),
|
||||
});
|
||||
server.registerTool("bounded_issues", { inputSchema }, async () => ({
|
||||
content: [{ type: "text", text: "unexpected dispatch" }],
|
||||
}));
|
||||
const sdkServer = new McpServer(info);
|
||||
sdkServer.registerTool("bounded_issues", { inputSchema }, async () => ({
|
||||
content: [{ type: "text", text: "unexpected dispatch" }],
|
||||
}));
|
||||
const keySchema = z.strictObject({});
|
||||
const unreachable = async () => ({
|
||||
content: [{ type: "text" as const, text: "unexpected dispatch" }],
|
||||
});
|
||||
server.registerTool("long_key", { inputSchema: keySchema }, unreachable);
|
||||
sdkServer.registerTool("long_key", { inputSchema: keySchema }, unreachable);
|
||||
const client = new Client(info, {
|
||||
jsonSchemaValidator: createMcpSchemaValidation(),
|
||||
});
|
||||
const sdkClient = new Client(info, {
|
||||
jsonSchemaValidator: createMcpSchemaValidation(),
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const [sdkClientTransport, sdkServerTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await sdkServer.connect(sdkServerTransport);
|
||||
await sdkClient.connect(sdkClientTransport);
|
||||
const sdkResult = await sdkClient.callTool({
|
||||
name: "bounded_issues",
|
||||
arguments: { value: {} },
|
||||
});
|
||||
const sdkText = sdkResult.content.find(
|
||||
(item) => item.type === "text",
|
||||
)?.text;
|
||||
const prefix =
|
||||
"Input validation error: Invalid arguments for tool bounded_issues: ";
|
||||
expect(sdkText?.startsWith(prefix)).toBe(true);
|
||||
const diagnostic = sdkText?.slice(prefix.length);
|
||||
expect(diagnostic).toBeTruthy();
|
||||
const result = await client.callTool({
|
||||
name: "bounded_issues",
|
||||
arguments: { value: {} },
|
||||
});
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
mcpTest(
|
||||
"discloses when bounded projection cannot retain raw SDK field details",
|
||||
async ({ mcp }) => {
|
||||
const info = { name: "bounded-issues", version: "1" };
|
||||
const server = new EvidenceMcpServer(
|
||||
info,
|
||||
{ capabilities: {} },
|
||||
undefined,
|
||||
createToolResultDelivery(4096),
|
||||
);
|
||||
const sdkServer = new McpServer(info);
|
||||
const branches = Array.from({ length: 256 }, (_, index) =>
|
||||
z.object({ [`field_${String(index)}`]: z.string() }),
|
||||
);
|
||||
const cases = [
|
||||
{
|
||||
name: "bounded_issues",
|
||||
inputSchema: z.object({ value: z.union(branches) }),
|
||||
arguments: { value: {} },
|
||||
},
|
||||
{
|
||||
name: "long_key",
|
||||
inputSchema: z.strictObject({}),
|
||||
arguments: { [`key_${"x".repeat(1600)}`]: true },
|
||||
},
|
||||
];
|
||||
const unexpectedDispatch = () => {
|
||||
throw new Error("Invalid input reached tool execution");
|
||||
};
|
||||
for (const { name, inputSchema } of cases) {
|
||||
server.registerTool(name, { inputSchema }, unexpectedDispatch);
|
||||
sdkServer.registerTool(name, { inputSchema }, unexpectedDispatch);
|
||||
}
|
||||
const client = await mcp.connect(server);
|
||||
const sdkClient = await mcp.connect(sdkServer);
|
||||
|
||||
for (const { name, arguments: input } of cases) {
|
||||
const [result, original] = await Promise.all([
|
||||
client.callTool({ name, arguments: input }),
|
||||
sdkClient.callTool({ name, arguments: input }),
|
||||
]);
|
||||
const sdkText = original.content.find(
|
||||
(item) => item.type === "text",
|
||||
)?.text;
|
||||
const prefix = `Input validation error: Invalid arguments for tool ${name}: `;
|
||||
if (sdkText === undefined || !sdkText.startsWith(prefix))
|
||||
throw new Error(`Expected the SDK's argument diagnostic for ${name}`);
|
||||
const diagnostic = sdkText.slice(prefix.length);
|
||||
expect(diagnostic, name).not.toBe("");
|
||||
|
||||
const { error } = parseMcpToolError(result);
|
||||
expect(error, name).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
@@ -349,45 +276,9 @@ it("discloses when bounded projection cannot retain union branch details", async
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const argumentsWithLongKey = { [`key_${"x".repeat(1600)}`]: true };
|
||||
const sdkLongKey = await sdkClient.callTool({
|
||||
name: "long_key",
|
||||
arguments: argumentsWithLongKey,
|
||||
});
|
||||
const sdkLongText = sdkLongKey.content.find(
|
||||
(item) => item.type === "text",
|
||||
)?.text;
|
||||
const keyPrefix =
|
||||
"Input validation error: Invalid arguments for tool long_key: ";
|
||||
expect(sdkLongText?.startsWith(keyPrefix)).toBe(true);
|
||||
const keyDiagnostic = sdkLongText?.slice(keyPrefix.length);
|
||||
expect(keyDiagnostic).toBeTruthy();
|
||||
const longKey = await client.callTool({
|
||||
name: "long_key",
|
||||
arguments: argumentsWithLongKey,
|
||||
});
|
||||
const longKeyError = parseMcpToolError(longKey).error;
|
||||
expect(longKeyError).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message: keyDiagnostic,
|
||||
observed: { field_details: "omitted" },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(longKeyError.message).not.toContain(keyDiagnostic);
|
||||
});
|
||||
expect(error.message, name).not.toContain(diagnostic);
|
||||
}
|
||||
await expect(client.ping()).resolves.toBeDefined();
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await sdkClient.close();
|
||||
await sdkServer.close();
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
Reference in new issue
Block a user