diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 08cfa1193..4ca8b0e38 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,6 +29,8 @@ Spellchecking is done via `npm run spellcheck`. Run `cargo test` for the Rust tests and `npm run test:json-schema` to check the published JSON Schemas. The latter compiles the root and definitions for both protocol versions, with and without Draft features, and validates complete JSON-RPC examples in the corresponding guides. +Guide requests and notifications also validate their params against the schema for the named method. This matters for v1, whose root schema does not select payloads by method. A method that the schema does not define must be an extension method whose name starts with `_`, so a misspelled method name fails. Response examples have no method and are checked only against the root schema, without correlating them to an earlier request. + The schema tests run Ajv in strict mode. Register new generator annotations or formats explicitly in `scripts/schema-tests/publications.mjs`. `uri` and `date-time` are checked as values. Numeric format names are type hints: use JSON Schema `minimum` and `maximum` for wire limits. JavaScript numbers cannot distinguish adjacent integers outside the safe integer range, so do not rely on Ajv to check exact 64-bit endpoints. Unreleased features will be behind an `unstable` feature flag in the Rust crate. diff --git a/scripts/schema-tests/publications.mjs b/scripts/schema-tests/publications.mjs index 1548f0ae0..4d7426bcb 100644 --- a/scripts/schema-tests/publications.mjs +++ b/scripts/schema-tests/publications.mjs @@ -49,3 +49,64 @@ export function validators(version, file) { }, }; } + +// A v1 root accepts the union of payloads without dispatching on method. Guide +// requests and notifications also need their own method's parameter schema. +// Responses have no method and still need the originating request to do that. +export function guideExampleChecker({ schema, at }) { + const root = at(); + const routes = { request: new Map(), notification: new Map() }; + const collect = (node, kind) => { + if (node.$ref) { + const def = schema.$defs[node.$ref.split("/").at(-1)]; + const method = def["x-method"]; + if (!method) return; // Extension payloads have no fixed method. + assert.ok(!routes[kind].has(method), `Duplicate ${kind}: ${method}`); + routes[kind].set(method, at(node.$ref.slice(1))); + return; + } + for (const key of ["allOf", "anyOf", "oneOf"]) { + for (const child of node[key] ?? []) collect(child, kind); + } + }; + for (const side of ["Agent", "Client", "Proxy"]) { + for (const [suffix, kind] of [ + ["Request", "request"], + ["Notification", "notification"], + ]) { + const envelope = schema.$defs[side + suffix]; + if (envelope) collect(envelope.properties.params, kind); + } + } + const protocol = schema.anyOf.find((node) => node.title === "ProtocolLevel"); + collect(protocol.properties.params, "notification"); + + return (example, location) => { + assert.ok( + root(example), + `Invalid JSON-RPC example in ${location}: ${JSON.stringify(root.errors)}`, + ); + if (!Object.hasOwn(example, "method")) return; + const kind = Object.hasOwn(example, "id") ? "request" : "notification"; + const payload = routes[kind].get(example.method); + if (!payload) { + assert.ok( + !routes.request.has(example.method) && + !routes.notification.has(example.method), + `Invalid ${kind} method in ${location}: ${example.method}`, + ); + // Only extension methods have no payload schema. Anything else is a + // misspelled or removed method that the v1 root accepts as an extension. + assert.ok( + example.method.startsWith("_"), + `Unknown ${kind} method in ${location}: ${example.method}`, + ); + return; + } + const params = Object.hasOwn(example, "params") ? example.params : {}; + assert.ok( + payload(params), + `Invalid ${example.method} params in ${location}: ${JSON.stringify(payload.errors)}`, + ); + }; +} diff --git a/scripts/schema-tests/publications.test.mjs b/scripts/schema-tests/publications.test.mjs index 26250f9bf..78090e613 100644 --- a/scripts/schema-tests/publications.test.mjs +++ b/scripts/schema-tests/publications.test.mjs @@ -1,7 +1,12 @@ import assert from "node:assert/strict"; import { readdirSync, readFileSync } from "node:fs"; import test from "node:test"; -import { createAjv, schemaFiles, validators } from "./publications.mjs"; +import { + createAjv, + guideExampleChecker, + schemaFiles, + validators, +} from "./publications.mjs"; test("new keywords and formats need an explicit registration", () => { for (const version of ["v1", "v2"]) { @@ -20,7 +25,96 @@ test("new keywords and formats need an explicit registration", () => { for (const version of ["v1", "v2"]) { for (const file of schemaFiles) { const label = `${version}/${file}`; - const { at, schema } = validators(version, file); + const publication = validators(version, file); + const { at, schema } = publication; + const checkExample = guideExampleChecker(publication); + + test(`${label}: guide examples use the named method's payload`, () => { + const prompt = { + jsonrpc: "2.0", + id: 1, + method: "session/prompt", + params: { sessionId: "s", prompt: [{ type: "text", text: "Hello" }] }, + }; + checkExample(prompt, "valid prompt"); + checkExample( + { ...prompt, params: { ...prompt.params, futureField: true } }, + "future field", + ); + for (const params of [ + { prompt: prompt.params.prompt }, + { sessionId: "s", prompt: "wrong" }, + null, + ]) { + assert.throws(() => checkExample({ ...prompt, params }, "bad prompt")); + } + const { params, ...withoutParams } = prompt; + assert.throws(() => checkExample(withoutParams, "missing params")); + const { id, ...promptNotification } = prompt; + assert.throws(() => + checkExample(promptNotification, "request without id"), + ); + checkExample( + { + jsonrpc: "2.0", + id: 2, + method: version === "v1" ? "logout" : "auth/logout", + }, + "optional params", + ); + checkExample( + { + jsonrpc: "2.0", + method: "session/cancel", + params: { sessionId: "s" }, + }, + "valid notification", + ); + assert.throws(() => + checkExample( + { jsonrpc: "2.0", method: "session/cancel", params: {} }, + "bad notification", + ), + ); + checkExample({ jsonrpc: "2.0", id: 1, result: {} }, "response"); + checkExample({ jsonrpc: "2.0", method: "_example/ping" }, "extension"); + for (const misspelled of [ + { ...prompt, method: "session/promt" }, + { jsonrpc: "2.0", method: "session/updat", params: {} }, + ]) { + assert.throws( + () => checkExample(misspelled, "misspelled method"), + /method/, + ); + } + checkExample( + { + jsonrpc: "2.0", + method: "$/cancel_request", + params: { requestId: 1 }, + }, + "protocol notification", + ); + assert.throws(() => + checkExample( + { jsonrpc: "2.0", method: "$/cancel_request", params: {} }, + "bad protocol notification", + ), + ); + if (file === "schema.unstable.json") { + for (const fields of [{}, { id: 3 }]) { + checkExample( + { + jsonrpc: "2.0", + method: "proxy/successor", + params: { method: "initialize" }, + ...fields, + }, + "shared request and notification method", + ); + } + } + }); test(`${label}: compile the root and each public definition`, (t) => { at(); @@ -54,7 +148,6 @@ for (const version of ["v1", "v2"]) { test(`${label}: validate complete JSON-RPC examples in its guides`, (t) => { const guide = `docs/protocol/${version}/${file === "schema.unstable.json" ? "draft/" : ""}`; const dir = new URL(`../../${guide}`, import.meta.url); - const validate = at(); let checked = 0; for (const name of readdirSync(dir)) { // The migration guide intentionally shows both versions side by side. @@ -72,10 +165,7 @@ for (const version of ["v1", "v2"]) { throw new Error(`Invalid JSON in ${location}`, { cause }); } if (!example || !Object.hasOwn(example, "jsonrpc")) continue; // Payload fragment. - if (!validate(example)) - assert.fail( - `Invalid JSON-RPC example in ${location}: ${JSON.stringify(validate.errors)}`, - ); + checkExample(example, location); checked++; } }