From 659f64f20e20b10d8bfccf8f1e5dd43d18fa2d60 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:44:31 -0500 Subject: [PATCH] test(mcp): add a seeded property and visited fields to served parity - Generate string values for every constrained string field with a fixed fast-check seed; the refinement gaps it found (rules in .refine() with no served keyword or guidance) are listed with a violating value each. - Assert the sweep derives violations for root, nested and array absolute-path fields. - Check canonical schema validity against the contract schemas directly instead of a bare SDK server, and drop the served-listing test that validated canonicalInputSchema. - Move the reserved environment key check into the compact handler test, which now requires the served description to name the rule. - testing.md: assert parity against the served tools/list. Refs #15328 --- docs/development/testing.md | 12 +- .../mcp/absoluteLocalPathSchema.test.ts | 68 ----- .../mcp/compactInputSchemaMcp.test.ts | 11 + tests/boundary/mcp/servedSchemaParity.test.ts | 285 +++++++++++++++--- tests/boundary/mcp/toolSchemaValidity.test.ts | 86 +----- 5 files changed, 277 insertions(+), 185 deletions(-) diff --git a/docs/development/testing.md b/docs/development/testing.md index 9549243b891..04d0e0a07c7 100644 --- a/docs/development/testing.md +++ b/docs/development/testing.md @@ -335,9 +335,15 @@ points as `u` does; Python's `$` also matches before a final newline, which only widens. A client compiling without `u` may still reject one astral character where a wildcard, shorthand or negated class must match it (for example `^[\S]$`); `PortablePatternProjection` documents this accepted -limitation. Keep canonical rejection checks separate from the -intentionally reduced compact advertisement, and probe actual client renderers -when changing schema representations. +limitation. Canonical rejection checks stay on the canonical parser, but +parity between the advertisement and runtime is asserted against the served +`tools/list` (`tests/fixtures/servedToolCatalog.ts`), never a contract +registered on a bare SDK server. `servedSchemaParity.test.ts` derives a +violating value for every constrained field of every contract example, plus a +seeded property over generated strings, and requires the served schema to +reject it or the served description to name the rule. Its known gaps are listed +by root cause, and an entry that stops matching fails the test. Probe actual +client renderers when changing schema representations. The grammar rules are not evidence that an engine accepts a pattern. `npm run verify:advertised-schemas` lists tools from the built package's stdio diff --git a/tests/boundary/mcp/absoluteLocalPathSchema.test.ts b/tests/boundary/mcp/absoluteLocalPathSchema.test.ts index 2550fe466cf..0940b47a7fd 100644 --- a/tests/boundary/mcp/absoluteLocalPathSchema.test.ts +++ b/tests/boundary/mcp/absoluteLocalPathSchema.test.ts @@ -1,6 +1,4 @@ -import { canonicalInputSchema } from "../../fixtures/canonicalOutputSchema.js"; import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; -import { Ajv2020 } from "ajv/dist/2020.js"; import { resolve } from "node:path"; import { expect, it } from "vitest"; @@ -247,72 +245,6 @@ const inputCases = ( ]; }; -it("advertises portable absolute-path constraints after SDK schema conversion", async () => { - const firmwareCalls: string[] = []; - const { client, close } = await createMcp(firmwareCalls, "compact"); - try { - const listed = await client.listTools(); - const ajv = new Ajv2020({ strict: false, validateFormats: false }); - const absolute = resolve("rea-absolute-input"); - const relative = "relative-input"; - const schemaCases = [ - ...inputCases(absolute, relative), - { - name: "inspect_go_binary", - field: "path NUL", - valid: { path: absolute }, - invalid: { path: `${absolute}\0` }, - }, - { - name: "import_evidence_bundle", - field: "path NUL", - valid: { path: absolute }, - invalid: { path: `${absolute}\0` }, - }, - { - name: "compare_bundles", - field: "left_bundle_path empty", - valid: { left_bundle_path: absolute, right_bundle_path: absolute }, - invalid: { left_bundle_path: "", right_bundle_path: absolute }, - }, - { - name: "compare_bundles", - field: "left_bundle_path NUL", - valid: { left_bundle_path: absolute, right_bundle_path: absolute }, - invalid: { - left_bundle_path: `${absolute}\0`, - right_bundle_path: absolute, - }, - }, - ]; - const checked: string[] = []; - for (const { name, field, valid, invalid } of schemaCases) { - if (!listed.tools.some((tool) => tool.name === name)) - throw new Error(`Missing advertised tool ${name}`); - // The canonical projection keeps portable constraints; handlers enforce - // the executing host's stricter path rules. - const validate = ajv.compile(canonicalInputSchema(name)); - expect(validate(invalid), `${name}.${field}`).toBe(false); - expect( - validate(valid), - `${name}.${field}: ${JSON.stringify(validate.errors)}`, - ).toBe(true); - checked.push(`${name}.${field}`); - } - expect(checked).toEqual( - expect.arrayContaining([ - "open_binary.path", - "extract_firmware.output_directory", - "inspect_go_binary.path NUL", - "compare_bundles.left_bundle_path empty", - ]), - ); - expect(firmwareCalls).toEqual([]); - } finally { - await close(); - } -}); - const relativeInspectionPaths = [ ["inspect_dwarf_units", "program"], ["inspect_elf_dependencies", "program"], diff --git a/tests/boundary/mcp/compactInputSchemaMcp.test.ts b/tests/boundary/mcp/compactInputSchemaMcp.test.ts index b4123c04e3f..1a26f99050e 100644 --- a/tests/boundary/mcp/compactInputSchemaMcp.test.ts +++ b/tests/boundary/mcp/compactInputSchemaMcp.test.ts @@ -360,9 +360,20 @@ describe("MCP compact input schema canonical enforcement", () => { executable: "node", environment: { REA_PROCESS_RUN_ID: "caller-value" }, }; + const reservedWithTrailingNewline = { + executable: "node", + environment: { "REA_PROCESS_RUN_ID\n": "caller-value" }, + }; expect(validate(valid)).toBe(true); expect(processScenarioSchema.safeParse(valid).success).toBe(true); + // The portable dialect has no property-name rules, so the served + // description names the reserved key and the handler enforces it. + expect(advertised.description).toContain("REA_PROCESS_RUN_ID is reserved"); expect(processScenarioSchema.safeParse(reserved).success).toBe(false); + expect(validate(reservedWithTrailingNewline)).toBe(true); + expect( + processScenarioSchema.safeParse(reservedWithTrailingNewline).success, + ).toBe(true); const result = await client.callTool({ name: contract.name, arguments: reserved, diff --git a/tests/boundary/mcp/servedSchemaParity.test.ts b/tests/boundary/mcp/servedSchemaParity.test.ts index a54246f871d..ff55e086da5 100644 --- a/tests/boundary/mcp/servedSchemaParity.test.ts +++ b/tests/boundary/mcp/servedSchemaParity.test.ts @@ -1,4 +1,5 @@ import { Ajv2020 } from "ajv/dist/2020.js"; +import { fc } from "@fast-check/vitest"; import { expect, it } from "vitest"; import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js"; @@ -38,7 +39,11 @@ const CONSTRAINT_KEYWORDS = [ "multipleOf", "minItems", ] as const; -type ConstraintKeyword = (typeof CONSTRAINT_KEYWORDS)[number] | "required"; +// `generated` marks a property-generated value, whose broken rule is unknown. +type ConstraintKeyword = + | (typeof CONSTRAINT_KEYWORDS)[number] + | "required" + | "generated"; // Ordered so that a length-valid candidate comes first; the first candidate // the pattern rejects is used. @@ -277,52 +282,101 @@ const guidanceNamesRule = ( ); }; +/** One constrained field of one contract example, and its served tool. */ +interface ParitySite { + readonly tool: string; + readonly canonical: { safeParse(input: unknown): { success: boolean } }; + readonly description: string; + readonly validate: (input: unknown) => boolean; + readonly example: unknown; + readonly mutation: Mutation; +} + +let cachedSites: Promise | undefined; + +/** Every constrained field reachable from every contract example. */ +const paritySites = (): Promise => + (cachedSites ??= (async () => { + const served = new Map( + (await servedToolCatalog()).map((tool) => [tool.name, tool]), + ); + const ajv = new Ajv2020({ + strict: false, + validateFormats: false, + inlineRefs: false, + code: { optimize: false }, + }); + const sites: ParitySite[] = []; + for (const contract of TOOL_CONTRACTS) { + const tool = served.get(contract.name); + if (tool === undefined) throw new Error(`${contract.name} is not served`); + const compiled = ajv.compile(tool.inputSchema); + const validate = (input: unknown): boolean => compiled(input); + const canonical = canonicalInputSchema(contract.name); + for (const example of contract.examples) { + const collector = new MutationCollector(canonical); + collector.visit(canonical, { + value: example.input, + present: true, + path: [], + }); + for (const mutation of collector.mutations) + if (mutation.path.length > 0) + sites.push({ + tool: contract.name, + canonical: contract.inputSchema, + description: tool.description ?? "", + validate, + example: example.input, + mutation, + }); + } + } + return sites; + })()); + +/** + * Judge the site's derived violation, or a generated value at its field: + * false when the canonical parser accepts the input, true when the served + * schema rejects it or the description names the rule, otherwise the finding. + * Guidance never covers a generated value, whose broken rule is unknown. + */ +const judge = ( + site: ParitySite, + generated?: { readonly value: unknown }, +): Finding | boolean => { + const mutation: Mutation = + generated === undefined + ? site.mutation + : { + path: site.mutation.path, + schema: site.mutation.schema, + keyword: "generated", + value: generated.value, + }; + const input = applyMutation(site.example, mutation); + if (site.canonical.safeParse(input).success) return false; + if (!site.validate(input) || guidanceNamesRule(site.description, mutation)) + return true; + return { + tool: site.tool, + path: describePath(mutation.path), + keyword: mutation.keyword, + }; +}; + +/** The exhaustive deterministic sweep: one violating value per site. */ const servedParityFindings = async (): Promise<{ readonly findings: readonly Finding[]; readonly checked: number; }> => { - const served = new Map( - (await servedToolCatalog()).map((tool) => [tool.name, tool]), - ); - const ajv = new Ajv2020({ - strict: false, - validateFormats: false, - inlineRefs: false, - code: { optimize: false }, - }); const findings = new Map(); let checked = 0; - for (const contract of TOOL_CONTRACTS) { - const tool = served.get(contract.name); - if (tool === undefined) throw new Error(`${contract.name} is not served`); - const validate = ajv.compile(tool.inputSchema); - const canonical = canonicalInputSchema(contract.name); - for (const example of contract.examples) { - const collector = new MutationCollector(canonical); - collector.visit(canonical, { - value: example.input, - present: true, - path: [], - }); - for (const mutation of collector.mutations) { - if (mutation.path.length === 0) continue; - const input = applyMutation(example.input, mutation); - // Only a value the canonical parser refuses is a violation. - if (contract.inputSchema.safeParse(input).success) continue; - checked += 1; - if ( - !validate(input) || - guidanceNamesRule(tool.description ?? "", mutation) - ) - continue; - const finding = { - tool: contract.name, - path: describePath(mutation.path), - keyword: mutation.keyword, - }; - findings.set(findingKey(finding), finding); - } - } + for (const site of await paritySites()) { + const verdict = judge(site); + if (verdict === false) continue; + checked += 1; + if (verdict !== true) findings.set(findingKey(verdict), verdict); } return { findings: [...findings.values()], checked }; }; @@ -590,23 +644,166 @@ const KNOWN_GAPS: Readonly> = { }, }; +const knownGapEntries = Object.values(KNOWN_GAPS).flatMap( + ({ findings }) => findings, +); + it("serves every canonical input constraint as a schema rule or guidance", async () => { const { findings, checked } = await servedParityFindings(); // Every constrained field of every contract example was exercised. expect(checked).toBeGreaterThan(10_000); - const entries = Object.values(KNOWN_GAPS).flatMap(({ findings }) => findings); expect( findings .filter( - (finding) => !entries.some((entry) => matchesKnownGap(entry, finding)), + (finding) => + !knownGapEntries.some((entry) => matchesKnownGap(entry, finding)), ) .map(findingKey), "served schemas accept these canonical violations without guidance", ).toEqual([]); expect( - entries.filter( + knownGapEntries.filter( (entry) => !findings.some((finding) => matchesKnownGap(entry, finding)), ), "these known gaps are fixed; remove them", ).toEqual([]); }); + +// Absolute-path fields at the root, nested in objects and inside arrays. The +// sweep must derive a violating value for each one from a contract example. +const ABSOLUTE_PATH_FIELDS = [ + "analyze_javascript_application input_path", + "binary_session expected_server_path", + "capture_browser_scenario browser.executable_path", + "capture_electron_scenario application_path", + "capture_electron_scenario application_root", + "capture_electron_scenario executable_path", + "close_binary snapshot_path", + "compare_bundles left_bundle_path", + "compare_bundles right_bundle_path", + "decompile_all output_directory", + "export_evidence_bundle path", + "export_web_scripts capture_path", + "export_web_scripts output_directory", + "extract_artifact output_root", + "extract_firmware output_directory", + "extract_firmware path", + "import_evidence_bundle path", + "inspect_analysis_view source.path", + "inspect_api_contract operations_path", + "inspect_api_contract path", + "inspect_apple_ips path", + "inspect_byte_entropy path", + "inspect_deb_package path", + "inspect_devicetree path", + "inspect_elf_debug_link candidate_path", + "inspect_elf_debug_link path", + "inspect_elf_notes path", + "inspect_elf_unwind_ranges path", + "inspect_firmware_regions path", + "inspect_go_binary path", + "inspect_kernel_module path", + "inspect_macho_function_starts path", + "inspect_managed_artifact path", + "inspect_maven_gradle_metadata path", + "inspect_nuget_nupkg path", + "inspect_oci_image_layout path", + "inspect_playwright_trace path", + "inspect_python_pyc path", + "inspect_v8_code_cache path", + "inspect_vsix_package path", + "inspect_yara_matches path", + "inspect_yara_matches rule_paths.[]", + "open_binary path", + "open_binary snapshot_path", + "recover_javascript_sources additional_paths.[]", + "recover_javascript_sources output_directory", + "recover_javascript_sources path", +] as const; + +it("derives violations for root, nested and array path fields", async () => { + const visited = new Set( + (await paritySites()) + .filter(({ mutation }) => mutation.keyword === "pattern") + .map(({ tool, mutation }) => `${tool} ${describePath(mutation.path)}`), + ); + expect(ABSOLUTE_PATH_FIELDS.filter((field) => !visited.has(field))).toEqual( + [], + ); +}); + +/** + * Fields whose canonical rule lives in a `.refine()` or transform, so the + * served schema has no keyword for it and no guidance names it. The generated + * property found each; the value is one input runtime rejects and the served + * schema accepts. Endpoint fields are #15319; the UEFI paths and Frida + * programs check absoluteness in a refinement instead of the shared pattern. + */ +const REFINEMENT_GAPS: Readonly> = { + "capture_web_screenshot cdp_endpoint": "a", + "extract_uefi_firmware output_directory": "a", + "extract_uefi_firmware path": "a", + "guided_workflows workflow_id": "a", + "inspect_electron_page cdp_endpoint": "a", + "inspect_native_data_type address": "jpc^!", + "inspect_uefi_firmware path": "a", + "inspect_uefi_nvram path": "a", + "inspect_web_event_listeners cdp_endpoint": "a", + "inspect_web_page cdp_endpoint": "a", + "inspect_with_objdump path": "a", + "inspect_with_objdump symbol": ".", + "instrument_with_frida program": "a", + "list_browser_targets cdp_endpoint": "a", + "list_electron_targets cdp_endpoint": "a", + "list_javascript_runtime_targets inspector_endpoint": "a", + "observe_javascript_runtime inspector_endpoint": "a", + "observe_web_execution cdp_endpoint": "a", + "observe_web_session cdp_endpoint": "a", + "record_unknown domain": " ", + "start_frida_session program": "a", +}; + +it("keeps the refinement gaps current", async () => { + const sites = await paritySites(); + // A gap remains while some example still lets the value through. + const fixed = Object.entries(REFINEMENT_GAPS).filter( + ([field, value]) => + !sites.some( + (site) => + `${site.tool} ${describePath(site.mutation.path)}` === field && + typeof judge(site, { value }) !== "boolean", + ), + ); + expect(fixed, "these refinement gaps are fixed; remove them").toEqual([]); +}); + +// Relative paths, separators, NUL, whitespace and arbitrary short text. +const stringViolation = fc.oneof( + fc.stringMatching(/^[a-z][a-z0-9_-]{0,12}(?:\/[a-z0-9_.-]{1,8}){0,2}$/u), + fc.constantFrom("", ".", "..", "a", "\u0000", " ", "C:", "\\\\"), + fc.string({ maxLength: 24 }), +); + +it("serves string constraints for generated values", async () => { + const sites = (await paritySites()).filter( + ({ mutation }) => + mutation.keyword !== "required" && + (mutation.schema.type === "string" || mutation.keyword === "pattern"), + ); + // The property checks the rule a generated value breaks, not the keyword + // that selected its site, so a known gap covers the whole field. + const known = (finding: Finding): boolean => + Object.hasOwn(REFINEMENT_GAPS, `${finding.tool} ${finding.path}`) || + knownGapEntries.some( + (entry) => + matchesKnownGap(entry, finding) || + entry.startsWith(`${finding.tool} ${finding.path} `), + ); + fc.assert( + fc.property(fc.constantFrom(...sites), stringViolation, (site, value) => { + const verdict = judge(site, { value }); + return typeof verdict === "boolean" || known(verdict); + }), + { seed: 15_328, numRuns: 200 }, + ); +}); diff --git a/tests/boundary/mcp/toolSchemaValidity.test.ts b/tests/boundary/mcp/toolSchemaValidity.test.ts index 58f0110d3a0..e7ab74b2d28 100644 --- a/tests/boundary/mcp/toolSchemaValidity.test.ts +++ b/tests/boundary/mcp/toolSchemaValidity.test.ts @@ -18,7 +18,6 @@ import { recursiveReferences, resolveReference, } from "../../fixtures/mcpAdvertisedSchemaValidity.js"; -import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js"; import { servedCatalog } from "../../../src/application/environment/environmentState.js"; import { environmentToolAnswer } from "../../../src/application/environment/environmentToolAnswer.js"; import { createEnvironmentMcpServer } from "../../../src/server/environment/serveEnvironment.js"; @@ -33,6 +32,10 @@ import { import { advertisedToolPresentation } from "../../../src/contracts/mcpSchemaPresentation.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; import { servedToolCatalog } from "../../fixtures/servedToolCatalog.js"; +import { + canonicalInputSchema, + canonicalOutputSchema, +} from "../../fixtures/canonicalOutputSchema.js"; interface ToolSchemas { readonly name: string; @@ -79,29 +82,6 @@ function expectStrictInputSchemaParity( } } -let cachedContractSchemas: - | Promise>["tools"]> - | undefined; - -/** - * Canonical contract schemas after SDK conversion, registered on a bare SDK - * server. This is not what `tools/list` serves: schema parity checks read - * `servedToolCatalog`, which includes the compact presentation. - */ -function listCanonicalContractSchemas() { - cachedContractSchemas ??= (async () => { - const server = new McpServer({ name: "schema-validation", version: "0" }); - for (const contract of TOOL_CONTRACTS) - server.registerTool( - contract.name, - toolRegistrationOptions(contract), - async () => ({ content: [] }), - ); - return listAdvertisedTools(server); - })(); - return cachedContractSchemas; -} - async function listAdvertisedTools(server: McpServer) { const client = new Client( { name: "schema-validation", version: "0" }, @@ -367,43 +347,6 @@ it("finds references only in input schema positions, not literal data", () => { ).toEqual(["nested.inputSchema.properties.default.items.$ref"]); }); -const advertiseAndEnforceProcessEnvironmentKeyConstraint = - async (): Promise => { - const contract = TOOL_CONTRACTS.find( - ({ name }) => name === "capture_process_scenario", - ); - const advertised = (await servedToolCatalog()).find( - ({ name }) => name === "capture_process_scenario", - ); - if (contract === undefined || advertised === undefined) - throw new Error("Process capture tool was not advertised"); - - const validate = new Ajv2020({ - strict: false, - validateFormats: false, - }).compile(advertised.inputSchema); - const valid = { executable: "node", environment: { APP_MODE: "test" } }; - const reserved = { - executable: "node", - environment: { REA_PROCESS_RUN_ID: "caller-value" }, - }; - const reservedWithTrailingNewline = { - executable: "node", - environment: { "REA_PROCESS_RUN_ID\n": "caller-value" }, - }; - expect(validate(valid)).toBe(true); - expect(contract.inputSchema.safeParse(valid).success).toBe(true); - // The portable dialect has no property-name rules, so the served - // description names the reserved key; runtime rejects it - // (compactInputSchemaMcp.test.ts calls the tool). - expect(contract.inputSchema.safeParse(reserved).success).toBe(false); - expect(advertised.description).toContain("REA_PROCESS_RUN_ID is reserved"); - expect(validate(reservedWithTrailingNewline)).toBe(true); - expect( - contract.inputSchema.safeParse(reservedWithTrailingNewline).success, - ).toBe(true); - }; - describe("served environment catalogs", () => { it("lists portable schemas for bulk bodies, pinned queries and fixed members", async () => { const edition = { format: "HC", featured: 1 }; @@ -497,12 +440,19 @@ describe("MCP JSON Schema validity", () => { TOOL_CONTRACTS.map(({ name }) => name).sort(), ); expect(advertisedSchemaErrors(served)).toEqual([]); - const tools = await listCanonicalContractSchemas(); + expectKnownAuthorityHints(served); + // The canonical contract schemas, which validating clients bind for + // output and the compact presentation projects for input. + const tools = TOOL_CONTRACTS.map(({ name }) => ({ + name, + inputSchema: canonicalInputSchema(name), + outputSchema: canonicalOutputSchema(name), + })); expect(advertisedSchemaErrors(tools)).toEqual([]); expect(localInputReferences(tools)).toEqual([]); expect(recursiveReferences(tools)).toEqual([]); - expectKnownAuthorityHints(tools); const byName = new Map(tools.map((tool) => [tool.name, tool])); + const servedByName = new Map(served.map((tool) => [tool.name, tool])); expectManagedLocalSignatureSchema(byName.get("inspect_managed_members")); const comparison = byName.get("compare_web_captures")?.inputSchema; for (const side of ["before", "after"]) @@ -522,8 +472,9 @@ describe("MCP JSON Schema validity", () => { ); for (const contract of TOOL_CONTRACTS) { const tool = byName.get(contract.name); - expect(tool?.title?.trim(), contract.name).toBeTruthy(); - expect(tool?.description?.trim(), contract.name).toBeTruthy(); + const listed = servedByName.get(contract.name); + expect(listed?.title?.trim(), contract.name).toBeTruthy(); + expect(listed?.description?.trim(), contract.name).toBeTruthy(); const examples = advertisedInputExamples(contract); expect(tool?.inputSchema.examples, contract.name).toEqual( examples.length === 0 ? undefined : examples, @@ -654,11 +605,6 @@ describe("MCP root input schemas", () => { }); }); -it( - "advertises and enforces the process-owned environment key constraint", - advertiseAndEnforceProcessEnvironmentKeyConstraint, -); - const advertiseAndEnforceItemSelectorCollectionConstraints = async (): Promise => { const contract = TOOL_CONTRACTS.find(