mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 22:11:12 +00:00
* test(mcp): check schema parity against the served tools/list Schema parity tests registered contracts on a bare SDK server, so they checked a schema REA never serves and missed the compact presentation's losses (#15310, #15311). - Add servedToolCatalog, which lists every tools/list page from a session server, and use it for parity checks in toolSchemaValidity and advertisedDialect. - Add a catalog-wide test that derives one violating value per constrained canonical field from each contract example and requires the served schema to reject it or the served description to name the rule. Today's gaps are listed by root cause; an entry that stops matching fails the test. - Remove absoluteLocalPathTools.test.ts; the catalog test covers every absolute-path field it checked. Refs #15328 * 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 * fix(mcp): advertise the absolute-path pattern and dialect-dropped rules absoluteLocalPathStringSchema serialized as two allOf patterns, and the dialect projection kept only the first (NUL-free), so every absolute-path field advertised a schema that accepts relative paths. - absoluteLocalPathStringSchema emits one pattern: the absolute envelope over a NUL-free path. NUL is still refused first with its own message. - mergeAllOf conjoins exactly what it can: bounds keep the tighter value and negated-class patterns become one class. A pattern it cannot conjoin is named in tool guidance instead of dropped silently. - multipleOf, length bounds of 1999 or more and exclusive bounds on non-integers become tool guidance, including on nullable values. - Move the allOf merge into advertisedAllOf.ts. Fixes #15310 Refs #15328 * fix(mcp): keep defaults, scalar rules, examples and field semantics in compact schemas Compact input schemas dropped facts an agent needs for a correct first call: every default, the enums and bounds of reduced root properties, any example for reduced or pruned schemas, and the Frida cross-field rules. Name-keyed fallback descriptions also labelled fields of another type. - Tool guidance names root property defaults in one "Defaults:" sentence. - A reduced schema keeps the enum, const, pattern and bounds of each scalar root property. - A reduced or depth-pruned schema states its smallest canonical example (up to 1,024 bytes), and a pruned schema says nested fields are omitted. - Frida contracts state each cross-field rule once, as the refusal and the root description. - Fallback descriptions apply only to a property of the JSON type they describe; they move to propertyFallbackDescriptions.ts. Refs #15311 Refs #15328 * test(mcp): validate the served schema in three advertisement tests compare_artifacts sources, compare_web_captures inputs and the analyze_javascript_application source selection called a canonical or bare-server schema advertised. They now validate the served listing; canonical rejections stay on the contract parser, and the gaps the reduced form leaves are asserted with a pointer to the parity list. Refs #15328 * test(mcp): check recovery promises on an agent's first wrong calls Calls every served tool with generated wrong arguments on a session with nothing open: an unknown path key, an omitted required field, valid arguments for an active-target tool, a missing file and an unknown id. Every refusal must name only advertised tools, name open_binary for an active-target tool, give no schema remediation to arguments the served schema accepts, and claim retryable only when an identical replay can succeed. A seeded property varies the guessed key and missing path. Known failures are listed by root cause (#15309, #15312, #15323 and the active-target declarations #15350 removes); a new failure or a stale entry fails the sweep. * test(mcp): assert the served schema where tests claimed the advertisement Five tests validated the canonical schema and called it advertised, so they asserted rules the served tools/list does not carry: batch_decompile maxItems, inspect_api_contract format and view, the inspect_dart_aot length and line-terminator rules, extract_artifact uniqueItems, and examples on compare_javascript_export_shapes. Each now validates the served schema and keeps the handler enforcement. A missing rule is pinned as a known gap (in the parity sweep where it can see the field, or beside the test where the contract example leaves it unreachable), so the expectation fails once the rule is served. The parity sweep now also derives maxItems and uniqueItems violations from example arrays; it finds inspect_managed_members type_names uniqueItems. Two value-correct tests are relabelled and check the served schema too. * fix(mcp): fit every advertised input schema under Codex's 5,000-byte compaction threshold Codex compacts any MCP input schema above 5,000 serialized bytes and drops descriptions and nested structure first, so update_analysis_settings reached the model as a list of empty objects with no setting IDs. Lower the advertised input budget from 13 KiB to 5,000 bytes, bound $ref expansion separately so projection and depth pruning are judged on their result, and advertise update_analysis_settings changes as one object whose setting enum lists every ID; the canonical parser still enforces each setting's bounds. Refs #15339 * fix(mcp): address review findings across the served-schema stack Keep the recorded description, or its absence, when the deferred runtime materializes, so discovery and the loaded listing agree. Measure example guidance in UTF-8 bytes once, resolve defaults through each property's own reference scope, keep root names and types when scalar rules alone would overflow the reduced form, and decline joining negated classes that a literal hyphen could turn into a range. Served parity now counts guidance only when one sentence labels the field and states its rule, and counts uniqueItems guidance. That stricter match exposed seven gaps the loose match hid; they join their root causes, and the fixed arrayRules gap is removed. The first-contact sweep keys findings by check, checks a structured next step against the served catalog, and uses the catalog's own MCP settings. * chore(mcp): refresh advertised catalog summaries * fix(paths): keep the NUL path refusal's format reason Moving the NUL check out of the advertised pattern turned its issue into a custom refinement, so tool refusals reported reason invalid_value instead of invalid_format with expected regex. The check now raises the same format issue, and still stops before the absolute-path rule. * fix(mcp): state the optional Frida device choice and match bounds by rule The Frida device rule now says both fields may be omitted for the local device. Served parity matches a numeric bound by its direction, unit and complete value, so another bound on the same field cannot cover it. * test(mcp): stop pinning served-schema omissions in workflow tests Workflow tests asserted that the served schema accepts values runtime refuses, so serving a rule would fail them. They keep the valid-input and runtime-refusal checks; the catalog-wide parity sweep tracks what is served. * test(mcp): count a required field only when guidance requires it A sentence that only mentions a field, or a same-named key under another parent, no longer covers a missing required rule. Guidance must state the requirement about the field's full path, or state a shape listing every required key of the field's parent. * test(mcp): credit a served rejection only to the rule that failed The parity sweep counted any served rejection as coverage, so a probe that also broke another rule (a too-long locale that breaks its pattern) hid a missing bound. Served validation now reports every failing keyword, and a rejection covers a rule only when that rule's served keyword fails.
877 lines
29 KiB
TypeScript
877 lines
29 KiB
TypeScript
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
|
import { McpServer } from "@modelcontextprotocol/server";
|
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
import { describe, expect, it } from "vitest";
|
|
import { z } from "zod";
|
|
|
|
import { advertisedInputExamples } from "../../../src/contracts/advertisedInputExamples.js";
|
|
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
|
import { advertiseTool } from "../../../src/contracts/advertisedTool.js";
|
|
import { emptyArraySchema } from "../../../src/domain/emptyArraySchema.js";
|
|
import {
|
|
arrayItemSchemaError,
|
|
unsupportedInputLiteralSchemaError,
|
|
} from "../../fixtures/mcpClientSchemaConstraints.js";
|
|
import {
|
|
advertisedSchemaErrors,
|
|
localInputReferences,
|
|
recursiveReferences,
|
|
resolveReference,
|
|
} from "../../fixtures/mcpAdvertisedSchemaValidity.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";
|
|
import { servedFrom } from "../../fixtures/environmentStateServing.js";
|
|
import type { TimedCaptureRow } from "../../fixtures/analysisView.js";
|
|
import {
|
|
BOOK_INIT_ROWS,
|
|
BOOK_NOT_FOUND,
|
|
FIRST_BOOK,
|
|
THIRD_BOOK,
|
|
} from "../../fixtures/environmentStateWrites.js";
|
|
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;
|
|
readonly inputSchema: Record<string, unknown>;
|
|
readonly outputSchema?: Record<string, unknown> | undefined;
|
|
readonly annotations?: Record<string, unknown> | undefined;
|
|
}
|
|
|
|
function expectStrictInputSchemaParity(
|
|
tools: readonly ToolSchemas[],
|
|
validators: ReadonlyMap<string, ReturnType<Ajv2020["compile"]>>,
|
|
): void {
|
|
const advertised = new Map(tools.map((tool) => [tool.name, tool]));
|
|
const names = [
|
|
"inspect_managed_artifact",
|
|
"inspect_managed_members",
|
|
"inspect_managed_native_boundaries",
|
|
"list_browser_targets",
|
|
"open_binary",
|
|
"close_binary",
|
|
"binary_session",
|
|
"find_changed_behavior",
|
|
"build_call_path",
|
|
"record_unknown",
|
|
"update_unknown",
|
|
];
|
|
for (const name of names) {
|
|
const contract = TOOL_CONTRACTS.find(
|
|
({ name: toolName }) => toolName === name,
|
|
);
|
|
const tool = advertised.get(name);
|
|
const validate = validators.get(name);
|
|
const example = contract?.examples[0];
|
|
if (
|
|
contract === undefined ||
|
|
tool === undefined ||
|
|
validate === undefined ||
|
|
example === undefined
|
|
)
|
|
throw new Error(`${name} did not have an advertised example`);
|
|
const malformed = { ...example.input, __unexpected_root_key__: true };
|
|
expect(contract.inputSchema.safeParse(malformed).success, name).toBe(false);
|
|
expect(validate(malformed), name).toBe(false);
|
|
}
|
|
}
|
|
|
|
async function listAdvertisedTools(server: McpServer) {
|
|
const client = new Client(
|
|
{ name: "schema-validation", version: "0" },
|
|
{ jsonSchemaValidator: createMcpSchemaValidation() },
|
|
);
|
|
const [clientTransport, serverTransport] =
|
|
InMemoryTransport.createLinkedPair();
|
|
try {
|
|
await server.connect(serverTransport);
|
|
await client.connect(clientTransport);
|
|
return (await client.listTools()).tools;
|
|
} finally {
|
|
await Promise.allSettled([client.close(), server.close()]);
|
|
}
|
|
}
|
|
|
|
function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
|
|
const advertised = new Map(tools.map((tool) => [tool.name, tool]));
|
|
const expected = {
|
|
read_bytes: {
|
|
readOnlyHint: false,
|
|
destructiveHint: false,
|
|
idempotentHint: true,
|
|
openWorldHint: false,
|
|
},
|
|
annotate_native_function: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
idempotentHint: true,
|
|
openWorldHint: true,
|
|
},
|
|
unset_bookmark: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
idempotentHint: true,
|
|
openWorldHint: false,
|
|
},
|
|
open_binary: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
idempotentHint: true,
|
|
openWorldHint: true,
|
|
},
|
|
close_binary: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
idempotentHint: false,
|
|
openWorldHint: true,
|
|
},
|
|
start_gdb_session: {
|
|
readOnlyHint: false,
|
|
destructiveHint: false,
|
|
idempotentHint: false,
|
|
openWorldHint: true,
|
|
},
|
|
export_web_scripts: {
|
|
readOnlyHint: false,
|
|
destructiveHint: false,
|
|
idempotentHint: false,
|
|
openWorldHint: false,
|
|
},
|
|
analyze_javascript_application: {
|
|
readOnlyHint: false,
|
|
destructiveHint: false,
|
|
idempotentHint: true,
|
|
openWorldHint: true,
|
|
},
|
|
capture_process_scenario: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
openWorldHint: true,
|
|
},
|
|
observe_native_calls: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
},
|
|
uninstall_adb_package: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
},
|
|
start_adb_app: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
},
|
|
export_evidence_bundle: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
},
|
|
import_evidence_bundle: {
|
|
readOnlyHint: false,
|
|
destructiveHint: false,
|
|
},
|
|
execute_rizin_command: {
|
|
readOnlyHint: false,
|
|
destructiveHint: true,
|
|
idempotentHint: false,
|
|
openWorldHint: true,
|
|
},
|
|
} as const;
|
|
|
|
for (const [name, annotations] of Object.entries(expected))
|
|
expect(advertised.get(name), name).toMatchObject({ annotations });
|
|
}
|
|
|
|
function expectMeaningfulPropertyDescriptions(
|
|
schema: unknown,
|
|
path: string,
|
|
root: unknown = schema,
|
|
active: ReadonlySet<string> = new Set(),
|
|
): void {
|
|
if (!isRecord(schema)) return;
|
|
if (typeof schema.$ref === "string" && !active.has(schema.$ref))
|
|
expectMeaningfulPropertyDescriptions(
|
|
resolveReference(root, schema.$ref),
|
|
`${path}.${schema.$ref}`,
|
|
root,
|
|
new Set([...active, schema.$ref]),
|
|
);
|
|
if (isRecord(schema.properties)) {
|
|
for (const [property, child] of Object.entries(schema.properties)) {
|
|
// Omit a description rather than restate the property name.
|
|
const description = isRecord(child) ? child.description : undefined;
|
|
if (description !== undefined)
|
|
expect(description, `${path}.${property}`).toEqual(
|
|
expect.not.stringMatching(/^(?:Value for .*)?$/u),
|
|
);
|
|
expectMeaningfulPropertyDescriptions(
|
|
child,
|
|
`${path}.${property}`,
|
|
root,
|
|
active,
|
|
);
|
|
}
|
|
}
|
|
|
|
for (const key of ["items", "additionalProperties"])
|
|
if (schema[key] !== undefined)
|
|
expectMeaningfulPropertyDescriptions(schema[key], path, root, active);
|
|
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
|
|
const children = schema[key];
|
|
if (Array.isArray(children))
|
|
children.forEach((child: unknown, index: number) =>
|
|
expectMeaningfulPropertyDescriptions(
|
|
child,
|
|
`${path}.${key}[${index}]`,
|
|
root,
|
|
active,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
|
|
/** Follow SDK-shared local definitions at each schema path component. */
|
|
function schemaAt(
|
|
root: unknown,
|
|
path: readonly string[],
|
|
node: unknown = root,
|
|
): unknown {
|
|
const resolve = (value: unknown): unknown => {
|
|
while (isRecord(value) && typeof value.$ref === "string")
|
|
value = resolveReference(root, value.$ref);
|
|
return value;
|
|
};
|
|
for (const key of path) {
|
|
node = resolve(node);
|
|
if (!isRecord(node)) return undefined;
|
|
node = node[key];
|
|
}
|
|
return resolve(node);
|
|
}
|
|
|
|
/** Validate retained locals facts through the output schema the SDK actually advertised. */
|
|
function expectManagedLocalSignatureSchema(
|
|
tool: ToolSchemas | undefined,
|
|
): void {
|
|
const managedOutput = tool?.outputSchema;
|
|
if (managedOutput === undefined)
|
|
throw new Error("Missing managed member output schema");
|
|
// A budgeted operation delivers its complete result or a `{summary,
|
|
// delivery}` replacement; the locals facts live in the complete result.
|
|
const deliveredResults = schemaAt(managedOutput, ["anyOf"]);
|
|
if (!Array.isArray(deliveredResults))
|
|
throw new Error("Missing delivered result alternatives");
|
|
const completeResult = deliveredResults.find(
|
|
(alternative: unknown) =>
|
|
schemaAt(
|
|
managedOutput,
|
|
["properties", "normalized_result"],
|
|
alternative,
|
|
) !== undefined,
|
|
);
|
|
const managedAlternatives = schemaAt(
|
|
managedOutput,
|
|
["properties", "normalized_result", "anyOf"],
|
|
completeResult,
|
|
);
|
|
if (!Array.isArray(managedAlternatives))
|
|
throw new Error("Missing managed result alternatives");
|
|
const inventory = managedAlternatives.find(
|
|
(alternative: unknown) =>
|
|
schemaAt(managedOutput, ["properties", "methods"], alternative) !==
|
|
undefined,
|
|
);
|
|
const locals = schemaAt(
|
|
managedOutput,
|
|
[
|
|
"properties",
|
|
"methods",
|
|
"items",
|
|
"properties",
|
|
"body",
|
|
"properties",
|
|
"local_var_signature",
|
|
],
|
|
inventory,
|
|
);
|
|
if (!isRecord(locals))
|
|
throw new Error("Missing advertised local signature facts");
|
|
const validateLocals = new Ajv2020({
|
|
strict: false,
|
|
validateFormats: false,
|
|
}).compile({
|
|
...locals,
|
|
$defs: managedOutput.$defs,
|
|
});
|
|
expect(validateLocals(null)).toBe(true);
|
|
expect(
|
|
validateLocals({
|
|
raw_sha256: "a".repeat(64),
|
|
has_context_dependent_types: false,
|
|
}),
|
|
).toBe(true);
|
|
expect(
|
|
validateLocals({
|
|
raw_sha256: "a".repeat(64),
|
|
has_context_dependent_types: true,
|
|
}),
|
|
).toBe(true);
|
|
expect(
|
|
validateLocals({
|
|
raw_sha256: "a".repeat(64),
|
|
has_context_dependent_types: "false",
|
|
}),
|
|
).toBe(false);
|
|
expect(validateLocals({ has_context_dependent_types: false })).toBe(false);
|
|
}
|
|
|
|
it("finds references only in input schema positions, not literal data", () => {
|
|
const schema = {
|
|
type: "object",
|
|
properties: {
|
|
$ref: { type: "string" },
|
|
default: { type: "array", items: { type: "string" } },
|
|
},
|
|
default: { $ref: "literal data" },
|
|
examples: [{ $defs: { field: { $ref: "literal data" } } }],
|
|
};
|
|
expect(
|
|
localInputReferences([{ name: "literal", inputSchema: schema }]),
|
|
).toEqual([]);
|
|
expect(
|
|
localInputReferences([
|
|
{
|
|
name: "nested",
|
|
inputSchema: {
|
|
type: "object",
|
|
properties: {
|
|
default: { type: "array", items: { $ref: "#/definitions/value" } },
|
|
},
|
|
},
|
|
},
|
|
]),
|
|
).toEqual(["nested.inputSchema.properties.default.items.$ref"]);
|
|
});
|
|
|
|
describe("served environment catalogs", () => {
|
|
it("lists portable schemas for bulk bodies, pinned queries and fixed members", async () => {
|
|
const edition = { format: "HC", featured: 1 };
|
|
const stored = { ...THIRD_BOOK, ...edition };
|
|
const captures: readonly (readonly TimedCaptureRow[])[] = [
|
|
[
|
|
...BOOK_INIT_ROWS,
|
|
["DELETE", "/api/books", [{ id: 2 }], 200, [{ id: 2 }]],
|
|
["GET", "/api/books/2", BOOK_NOT_FOUND, 404],
|
|
["GET", "/api/books", [FIRST_BOOK]],
|
|
],
|
|
[
|
|
["GET", "/api/books", [{ ...FIRST_BOOK, ...edition }]],
|
|
["GET", "/api/books/1", { ...FIRST_BOOK, ...edition }],
|
|
[
|
|
"POST",
|
|
"/api/books?notify=quiet",
|
|
stored,
|
|
201,
|
|
{
|
|
books: [
|
|
{ name: "Third Book", format: "hardcover", featured: true },
|
|
],
|
|
},
|
|
],
|
|
["GET", "/api/books/3", stored],
|
|
],
|
|
];
|
|
const tools: Awaited<ReturnType<Client["listTools"]>>["tools"] = [];
|
|
for (const rows of captures) {
|
|
const served = servedFrom(rows);
|
|
const catalog = servedCatalog(served.source, served.state, "books");
|
|
if (!catalog.ok) throw catalog.error;
|
|
const server = createEnvironmentMcpServer(
|
|
"books",
|
|
catalog.value.tools,
|
|
environmentToolAnswer(served.source, served.store),
|
|
);
|
|
tools.push(...(await listAdvertisedTools(server)));
|
|
}
|
|
const create = tools.find((tool) => tool.name === "post_books");
|
|
expect(create?.inputSchema.properties?.["notify"]).toMatchObject({
|
|
enum: ["quiet"],
|
|
});
|
|
expect(create?.inputSchema).toHaveProperty(
|
|
"properties.body.properties.books.items.properties.format.enum",
|
|
["hardcover"],
|
|
);
|
|
expect(create?.inputSchema).toHaveProperty(
|
|
"properties.body.properties.books.items.properties.featured.description",
|
|
expect.stringMatching(/\btrue\b/u),
|
|
);
|
|
expect(
|
|
tools.find((tool) => tool.name === "delete_books")?.inputSchema
|
|
.properties?.["body"],
|
|
).toMatchObject({
|
|
type: "array",
|
|
items: { type: "object" },
|
|
});
|
|
expect(advertisedSchemaErrors(tools)).toEqual([]);
|
|
for (const { name, inputSchema } of tools)
|
|
expect(
|
|
unsupportedInputLiteralSchemaError(inputSchema, name),
|
|
).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe("MCP JSON Schema validity", () => {
|
|
it("preserves empty-array validation in the advertised representation", () => {
|
|
const schema = z.toJSONSchema(emptyArraySchema);
|
|
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
|
expect(ajv.validateSchema(schema)).toBe(true);
|
|
const validate = ajv.compile(schema);
|
|
expect(validate([])).toBe(true);
|
|
for (const value of [
|
|
[null],
|
|
["candidate"],
|
|
[0],
|
|
[false],
|
|
[{}],
|
|
[[]],
|
|
null,
|
|
{},
|
|
])
|
|
expect(validate(value)).toBe(false);
|
|
});
|
|
|
|
it("advertises valid input and output schemas for every canonical tool", async () => {
|
|
const served = await servedToolCatalog();
|
|
expect(served.map(({ name }) => name).sort()).toEqual(
|
|
TOOL_CONTRACTS.map(({ name }) => name).sort(),
|
|
);
|
|
expect(advertisedSchemaErrors(served)).toEqual([]);
|
|
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([]);
|
|
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"])
|
|
expect(comparison).toHaveProperty(
|
|
["properties", side, "properties", "inspection", "anyOf"],
|
|
[
|
|
expect.objectContaining({
|
|
required: ["kind", "evidence_id"],
|
|
}),
|
|
{
|
|
type: "object",
|
|
description: expect.stringContaining(
|
|
"complete canonical observation",
|
|
),
|
|
},
|
|
],
|
|
);
|
|
for (const contract of TOOL_CONTRACTS) {
|
|
const tool = byName.get(contract.name);
|
|
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,
|
|
);
|
|
for (const example of contract.examples)
|
|
expect(
|
|
contract.inputSchema.safeParse(example.input).success,
|
|
`${contract.name}: ${example.title}`,
|
|
).toBe(true);
|
|
expectMeaningfulPropertyDescriptions(tool?.inputSchema, contract.name);
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("MCP root input schemas", () => {
|
|
it("advertises object roots while enforcing union requirements at runtime", async () => {
|
|
const tools = await servedToolCatalog();
|
|
const advertised = new Map(tools.map((tool) => [tool.name, tool]));
|
|
const ajv = new Ajv2020({
|
|
strict: false,
|
|
validateFormats: false,
|
|
inlineRefs: false,
|
|
code: { optimize: false },
|
|
});
|
|
const compiledValidators = new Map<
|
|
string,
|
|
ReturnType<Ajv2020["compile"]>
|
|
>();
|
|
const graphContract = TOOL_CONTRACTS.find(
|
|
({ name }) => name === "project_managed_application_graph",
|
|
);
|
|
const graphTool = advertised.get("project_managed_application_graph");
|
|
if (graphContract === undefined || graphTool === undefined)
|
|
throw new Error("Managed application graph tool was not advertised");
|
|
expect(graphContract.inputSchema.safeParse({}).success).toBe(false);
|
|
expect(graphTool.inputSchema).toMatchObject({ type: "object" });
|
|
const validateGraph = ajv.compile(graphTool.inputSchema);
|
|
compiledValidators.set("project_managed_application_graph", validateGraph);
|
|
// Clients reject root combinators, so the served schema accepts `{}` and
|
|
// the served description names the input groups instead.
|
|
expect(validateGraph({ unrelated: true })).toBe(false);
|
|
expect(graphTool.description).toContain("Provide a complete input group");
|
|
expect(graphTool.description).not.toContain("exactly one");
|
|
|
|
for (const contract of TOOL_CONTRACTS) {
|
|
const inputSchema = advertised.get(contract.name)!.inputSchema;
|
|
expect(inputSchema.type, contract.name).toBe("object");
|
|
expect(inputSchema.properties, contract.name).toBeDefined();
|
|
// Anthropic tool input schemas reject root combinators.
|
|
for (const combinator of ["anyOf", "oneOf", "allOf"])
|
|
expect(inputSchema, contract.name).not.toHaveProperty(combinator);
|
|
const validate =
|
|
compiledValidators.get(contract.name) ?? ajv.compile(inputSchema);
|
|
compiledValidators.set(contract.name, validate);
|
|
for (const example of contract.examples)
|
|
expect(
|
|
validate(example.input),
|
|
`${contract.name}: ${example.title}`,
|
|
).toBe(true);
|
|
}
|
|
|
|
expectStrictInputSchemaParity(tools, compiledValidators);
|
|
|
|
for (const name of ["inspect_web_page", "analyze_web_bundle"]) {
|
|
const contract = TOOL_CONTRACTS.find((tool) => tool.name === name);
|
|
const tool = advertised.get(name);
|
|
if (contract === undefined || tool === undefined)
|
|
throw new Error(`${name} was not advertised`);
|
|
const validate = ajv.compile(
|
|
advertiseTool(
|
|
{ inputSchema: tool.inputSchema },
|
|
advertisedToolPresentation("off"),
|
|
).inputSchema ?? {},
|
|
);
|
|
const base = {
|
|
cdp_endpoint: "http://127.0.0.1:9222",
|
|
target_id: "target",
|
|
};
|
|
for (const flag of [undefined, false, true, "false", null]) {
|
|
const input =
|
|
flag === undefined ? base : { ...base, include_script_sources: flag };
|
|
const accepted =
|
|
flag === undefined ||
|
|
flag === true ||
|
|
(name === "inspect_web_page" && flag === false);
|
|
const parsed = contract.inputSchema.safeParse(input);
|
|
expect(parsed.success, `${name}: ${String(flag)}`).toBe(accepted);
|
|
// The advertised dialect relaxes Boolean literals; the canonical parser
|
|
// still rejects false when this operation requires script sources.
|
|
expect(validate(input), `${name}: ${String(flag)}`).toBe(
|
|
flag === undefined || typeof flag === "boolean",
|
|
);
|
|
if (parsed.success && flag === undefined)
|
|
expect(parsed.data).toMatchObject({
|
|
include_script_sources: name === "analyze_web_bundle",
|
|
});
|
|
}
|
|
}
|
|
|
|
const nativeObservation = TOOL_CONTRACTS.find(
|
|
({ name }) => name === "observe_native_ui",
|
|
);
|
|
const nativeScenario = TOOL_CONTRACTS.find(
|
|
({ name }) => name === "capture_native_ui_scenario",
|
|
);
|
|
const nativeObservationTool = advertised.get("observe_native_ui");
|
|
const nativeScenarioTool = advertised.get("capture_native_ui_scenario");
|
|
if (
|
|
nativeObservation === undefined ||
|
|
nativeScenario === undefined ||
|
|
nativeObservationTool === undefined ||
|
|
nativeScenarioTool === undefined
|
|
)
|
|
throw new Error("Native UI tools were not registered");
|
|
const target = { pid: 123, window_id: 456 };
|
|
const scenario = {
|
|
...target,
|
|
steps: [{ kind: "wait", milliseconds: 100 }],
|
|
};
|
|
const observationResult = nativeObservation.inputSchema.safeParse(target);
|
|
const scenarioResult = nativeScenario.inputSchema.safeParse(scenario);
|
|
expect(observationResult.success).toBe(true);
|
|
expect(scenarioResult.success).toBe(true);
|
|
expect(compiledValidators.get("observe_native_ui")!(target)).toBe(true);
|
|
expect(
|
|
compiledValidators.get("capture_native_ui_scenario")!(scenario),
|
|
).toBe(true);
|
|
});
|
|
});
|
|
|
|
const advertiseAndEnforceItemSelectorCollectionConstraints =
|
|
async (): Promise<void> => {
|
|
const contract = TOOL_CONTRACTS.find(
|
|
({ name }) => name === "inspect_analysis_view",
|
|
);
|
|
if (contract === undefined)
|
|
throw new Error("inspect_analysis_view contract was not registered");
|
|
|
|
const advertised = (await servedToolCatalog()).find(
|
|
({ name }) => name === contract.name,
|
|
);
|
|
if (advertised === undefined)
|
|
throw new Error("inspect_analysis_view tool was not advertised");
|
|
|
|
const validate = new Ajv2020({
|
|
strict: false,
|
|
validateFormats: false,
|
|
inlineRefs: false,
|
|
code: { optimize: false },
|
|
}).compile(advertised.inputSchema);
|
|
const source = {
|
|
kind: "retained-evidence",
|
|
evidence_id: `ev_${"a".repeat(64)}`,
|
|
};
|
|
const itemInput = (collection: string, selector: unknown) => ({
|
|
source,
|
|
view: { kind: "item", collection, selector },
|
|
});
|
|
const nodeId = `jag_node_${"b".repeat(64)}`;
|
|
// Collection-specific selector constraints are enforced at runtime; the
|
|
// served schema must accept every valid selector.
|
|
const invalid: ReadonlyArray<readonly [string, unknown]> = [
|
|
["modules", { index: 0 }],
|
|
["modules", { name: "entry" }],
|
|
["sections", { path: "/src/entry.js" }],
|
|
["symbols", { node_id: nodeId }],
|
|
];
|
|
const valid: ReadonlyArray<readonly [string, unknown]> = [
|
|
["modules", { path: "/src/entry.js" }],
|
|
["modules", { node_id: nodeId }],
|
|
["sections", { index: 0 }],
|
|
["sections", { name: ".text" }],
|
|
["symbols", { index: 0 }],
|
|
["symbols", { name: "main" }],
|
|
];
|
|
for (const [collection, selector] of invalid) {
|
|
const input = itemInput(collection, selector);
|
|
const label = `${collection}/${Object.keys(selector as object)[0]}`;
|
|
expect(contract.inputSchema.safeParse(input).success, label).toBe(false);
|
|
}
|
|
for (const [collection, selector] of valid) {
|
|
const input = itemInput(collection, selector);
|
|
const label = `${collection}/${Object.keys(selector as object)[0]}`;
|
|
expect(contract.inputSchema.safeParse(input).success, label).toBe(true);
|
|
expect(validate(input), `advertised schema accepts ${label}`).toBe(true);
|
|
}
|
|
};
|
|
|
|
it(
|
|
"advertises and enforces the item selector collection constraints",
|
|
advertiseAndEnforceItemSelectorCollectionConstraints,
|
|
);
|
|
|
|
describe("MCP process input JSON Schema", () => {
|
|
it("advertises process strings without weakening terminal input", async () => {
|
|
const tools = await servedToolCatalog();
|
|
const processContract = TOOL_CONTRACTS.find(
|
|
({ name }) => name === "capture_process_scenario",
|
|
);
|
|
const processTool = tools.find(
|
|
({ name }) => name === "capture_process_scenario",
|
|
);
|
|
if (processContract === undefined || processTool === undefined)
|
|
throw new Error("Process scenario tool was not advertised");
|
|
const validate = new Ajv2020({
|
|
strict: false,
|
|
validateFormats: false,
|
|
}).compile(processTool.inputSchema);
|
|
const base = { executable: "/usr/bin/true" };
|
|
for (const input of [
|
|
{ ...base, executable: "/usr/bin/true\0" },
|
|
{ ...base, arguments: ["\0"] },
|
|
{ ...base, working_directory: "/tmp\0" },
|
|
{ ...base, filesystem_observation_paths: ["/tmp\0"] },
|
|
]) {
|
|
expect(processContract.inputSchema.safeParse(input).success).toBe(false);
|
|
expect(validate(input)).toBe(false);
|
|
}
|
|
// Runtime refuses a NUL environment value whether or not the served
|
|
// schema states the rule; the catalog sweep tracks what is served.
|
|
const nulEnvironmentValue = { ...base, environment: { KEY: "value\0" } };
|
|
expect(
|
|
processContract.inputSchema.safeParse(nulEnvironmentValue).success,
|
|
).toBe(false);
|
|
const terminalInput = {
|
|
...base,
|
|
events: [{ type: "input", at_ms: 0, data: "\0" }],
|
|
};
|
|
expect(processContract.inputSchema.safeParse(terminalInput).success).toBe(
|
|
true,
|
|
);
|
|
expect(validate(terminalInput)).toBe(true);
|
|
});
|
|
});
|
|
|
|
it("compiles every output schema independently when IDs repeat, including uncalled tools", () => {
|
|
const outputSchema = { $id: "urn:rea:test:shared-output", type: "string" };
|
|
const errors = advertisedSchemaErrors([
|
|
{ name: "first", inputSchema: { type: "object" }, outputSchema },
|
|
{
|
|
name: "second",
|
|
inputSchema: { type: "object" },
|
|
outputSchema: { ...outputSchema },
|
|
},
|
|
{
|
|
name: "broken",
|
|
inputSchema: { type: "object" },
|
|
outputSchema: { $id: outputSchema.$id, $ref: "#/$defs/missing" },
|
|
},
|
|
]);
|
|
expect(errors).toHaveLength(1);
|
|
expect(errors[0]).toContain("broken.outputSchema");
|
|
expect(errors[0]).toContain("missing");
|
|
});
|
|
|
|
it("checks client array constraints in schema positions while preserving literal metadata", () => {
|
|
const schema = {
|
|
type: "object",
|
|
properties: { examples: { type: "array", items: { type: "string" } } },
|
|
examples: [{ type: "array" }],
|
|
default: { type: "array" },
|
|
const: { type: "array" },
|
|
enum: [{ type: "array" }],
|
|
};
|
|
expect(arrayItemSchemaError(schema, "literal")).toBeUndefined();
|
|
expect(
|
|
arrayItemSchemaError(
|
|
{ ...schema, properties: { examples: { type: "array" } } },
|
|
"broken",
|
|
),
|
|
).toBe(
|
|
"broken.properties.examples: tool parameters array type must have items",
|
|
);
|
|
const booleanMetadata = {
|
|
type: "object",
|
|
properties: { default: { type: "boolean", const: false } },
|
|
default: { const: true },
|
|
examples: [{ enum: [false] }],
|
|
};
|
|
expect(
|
|
unsupportedInputLiteralSchemaError(
|
|
{ ...booleanMetadata, properties: {} },
|
|
"literal",
|
|
),
|
|
).toBeUndefined();
|
|
expect(unsupportedInputLiteralSchemaError(booleanMetadata, "literal")).toBe(
|
|
"literal.properties.default.const is boolean",
|
|
);
|
|
for (const [literal, reason] of [
|
|
[{ const: "" }, "const is an empty string"],
|
|
[{ enum: ["named", ""] }, "enum contains an empty string"],
|
|
] as const) {
|
|
expect(
|
|
unsupportedInputLiteralSchemaError(
|
|
{
|
|
type: "object",
|
|
properties: { value: literal },
|
|
default: { const: "" },
|
|
examples: [{ enum: [""] }],
|
|
},
|
|
"literal",
|
|
),
|
|
).toBe(`literal.properties.value.${reason}`);
|
|
expect(
|
|
unsupportedInputLiteralSchemaError(
|
|
{
|
|
type: "array",
|
|
items: [{ type: "string" }, literal],
|
|
},
|
|
"tuple",
|
|
),
|
|
).toBe(`tuple.items[1].${reason}`);
|
|
expect(
|
|
unsupportedInputLiteralSchemaError(
|
|
{
|
|
type: "string",
|
|
contentSchema: literal,
|
|
},
|
|
"encoded",
|
|
),
|
|
).toBe(`encoded.contentSchema.${reason}`);
|
|
}
|
|
});
|
|
|
|
it.each([false, true])(
|
|
"rejects references to another tool's nested IDs (earlier compilation fails: %s)",
|
|
(invalidPrevious) => {
|
|
const nestedId = "urn:rea:test:nested-output";
|
|
const errors = advertisedSchemaErrors([
|
|
{
|
|
name: "first",
|
|
inputSchema: { type: "object" },
|
|
outputSchema: {
|
|
$defs: { shared: { $id: nestedId, type: "string" } },
|
|
...(invalidPrevious ? { pattern: "[" } : {}),
|
|
},
|
|
},
|
|
{
|
|
name: "broken",
|
|
inputSchema: { type: "object" },
|
|
outputSchema: {
|
|
$ref: nestedId,
|
|
$defs: { shared: { type: "number" } },
|
|
},
|
|
},
|
|
]);
|
|
expect(errors).toHaveLength(invalidPrevious ? 2 : 1);
|
|
const brokenErrors = errors.filter((error) =>
|
|
error.startsWith("broken.outputSchema:"),
|
|
);
|
|
expect(brokenErrors).toHaveLength(1);
|
|
expect(brokenErrors[0]).toContain(nestedId);
|
|
},
|
|
);
|
|
|
|
it("finds recursion through schema-valued keywords and ignores literal metadata", () => {
|
|
const diamond = {
|
|
type: "object",
|
|
properties: {
|
|
left: { $ref: "#/$defs/shared" },
|
|
right: { $ref: "#/$defs/shared" },
|
|
},
|
|
$defs: { shared: { type: "string" } },
|
|
default: { $ref: "#" },
|
|
"x-fixture": { $ref: "#" },
|
|
};
|
|
const escaped = {
|
|
$ref: "#/$defs/a%20~1b",
|
|
$defs: { "a /b": { $ref: "#/$defs/a%20~1b" } },
|
|
};
|
|
expect(
|
|
recursiveReferences([
|
|
{ name: "diamond", inputSchema: diamond },
|
|
{ name: "root", inputSchema: { $ref: "#" } },
|
|
{ name: "escaped", inputSchema: escaped },
|
|
{
|
|
name: "property",
|
|
inputSchema: { properties: { default: { $ref: "#" } } },
|
|
},
|
|
]),
|
|
).toEqual([
|
|
"root.inputSchema: #",
|
|
"escaped.inputSchema: #/$defs/a%20~1b",
|
|
"property.inputSchema: #",
|
|
]);
|
|
});
|