Skip to content
Myr

Inline a percent-encoded root as McpServer does, and stop the gen test pinning W1's contracts

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Review fixes for 105, before merge. - mcp.ts toJsonSchema unescaped a root $ref by hand (~1, ~0) and skipped percent-decoding. A root named "Answer receipt" (#/$defs/Answer%20receipt) stayed a $ref while McpServer inlines it, so listTools, mcp-tools.md and commands.json would disagree with tools/list, and cli.md would say the command takes no arguments. It now reads the pointer with JsonPointer.parseUriFragment, the way Effect's own getReferenceKey does. Test: mcp.test.ts "inlines a named root whose pointer is percent-encoded", red by assertion before the fix. - gen.test.ts pinned the exact W1 contract set: 4 tool schemas, a two-element catalog, submitAnswer's exact error and payload lists, and listAsks.error as {not: {}}. 215 changes every one of those, and it does not own this file. Now: - every contract in Contracts has payload, success and error definitions; - a contract whose error is Never gets {not: {}}; - cli.md lists every catalog command, and a row for each positional and flag; - asks and submit are found by name; - the MCP schema count is twice the number of tool sections. Known W1 rows are still asserted, so an empty catalog can't pass. Planted mutations in gen.ts (a dropped flag row, an error schema replaced, a contract left out) each turn the matching test red by assertion. - scripts/lib/gen.ts re-exports Contracts for that test, as it already re-exports Refusal: packages/config takes no @repo/* dependency. - The comments on Destructive now give the real risk: every tool carries our value, default false, so a destructive contract that forgot it would tell an agent it is safe. The old comment said MCP's default would apply, which toTool never lets happen. - The generated docs/reference files are byte-identical; gen:check is clean.

authored by oscabriel · committed by oscabriel · parent e0f9120 · Browse files · 6 files+199 added−91 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+199 added−91 removed

  • tests:+177 added−75 removed
  • other:+22 added−16 removed

6 files+199 added−91 removed

modified:packages/config/test/gen.test.ts+156 added-67 removed
1import { describe, expect, it } from "@effect/vitest";2import { Effect, Predicate, Schema } from "effect";2import { Predicate, Schema, SchemaAST } from "effect";34import { CommandCatalog, generate, Refusal } from "../../../scripts/lib/gen.ts";4import {5 CommandCatalog,6 Contracts,7 generate,8 Refusal,9} from "../../../scripts/lib/gen.ts";1011const NON_FINITE = new Set(["Infinity", "-Infinity", "NaN"]);1213/** A generated JSON file, or a JSON block, decoded where the test reads it. */
73 unmodified lines
8788const content = (path: string) =>89 generate().find((file) => file.path === path)?.content ?? "";9086const decodeCatalog = Schema.decodeUnknownEffect(87 Schema.fromJsonString(CommandCatalog)88);8991/** The JSON blocks in a Markdown page: here, each tool's schemas. */92const jsonBlocks = (markdown: string): readonly Schema.Json[] =>93 [...markdown.matchAll(/```json\n(?<body>[\s\S]*?)\n```/gu)].map((match) =>94 parseJson(match.groups?.body ?? "null")95 );9697/** A Markdown page's `## ` sections, keyed by their heading. */98const sections = (markdown: string): ReadonlyMap<string, string> =>99 new Map(100 [101 ...markdown.matchAll(102 /^## (?<heading>.+)\n(?<body>[\s\S]*?)(?=^## |(?![\s\S]))/gmu103 ),104 ].map((match) => [match.groups?.heading ?? "", match.groups?.body ?? ""])105 );106107/** The definitions in protocol.schema.json, by name. */108const definitions = () =>109 Schema.decodeSync(110 Schema.fromJsonString(111 Schema.Struct({ $defs: Schema.Record(Schema.String, Schema.Json) })112 )113 )(content("docs/reference/protocol.schema.json")).$defs;114115const catalog = () =>116 Schema.decodeSync(Schema.fromJsonString(CommandCatalog))(117 content("docs/reference/commands.json")118 );119120/** The fields a command's payload schema names. */121const payloadFields = Schema.decodeUnknownSync(122 Schema.Struct({ properties: Schema.Record(Schema.String, Schema.Json) })123);124125/** A union of pointers, as a contract's error is written. */126const decodeUnion = Schema.decodeUnknownSync(127 Schema.Struct({ anyOf: Schema.Array(Schema.Struct({ $ref: Schema.String })) })128);129130/** An object schema's required keys. */131const decodeObject = Schema.decodeUnknownSync(132 Schema.Struct({ required: Schema.Array(Schema.String) })133);134135const contracts = [...Contracts.requests.values()];136137describe("generation", () => {138 it("writes exactly the five reference files, sorted by path", () => {139 expect(generate().map((file) => file.path)).toStrictEqual([140 "docs/reference/cli.md",
36 unmodified lines
177 });178});179180describe("the generated JSON Schema", () => {140 it("has a definition for each contract's payload, success and error, and the refusal union", () => {181 it("defines each contract's payload, success and error", () => {182 const defined = new Set(Object.keys(definitions()));183184 const missing = contracts185 .flatMap((rpc) =>186 ["payload", "success", "error"].map((part) => `${rpc._tag}.${part}`)187 )188 .filter((name) => !defined.has(name));189190 expect(contracts).not.toHaveLength(0);191 expect(missing).toStrictEqual([]);192 });193194 it("defines each refusal once, and points the union and a contract's errors at it", () => {195 const document = parseJson(content("docs/reference/protocol.schema.json"));196 const $defs = definitions();197 const { anyOf } = decodeUnion($defs["submitAnswer.error"]);198 const { required } = decodeObject($defs["submitAnswer.payload"]);199200 const pointedAt = new Set(anyOf.map((member) => member.$ref));201 const fields = new Set(required);202203 expect(document).toMatchObject({204 $defs: {205 Refusal: {206 anyOf: Refusal.members.map((member) => ref(member.identifier)),207 },148 // A contract with no refusals of its own can't fail that way.149 "listAsks.error": { not: {} },208 "listAsks.payload": { required: ["project"] },209 "listAsks.success": { required: ["asks"] },152 "submitAnswer.error": {153 anyOf: ["NotClaimed", "ClaimLapsed", "StaleBase", "RepoBusy"].map(154 ref155 ),156 },157 "submitAnswer.payload": { required: ["ask", "base", "head"] },158 "submitAnswer.success": { required: ["main"] },210 },211 $schema: "https://json-schema.org/draft/2020-12/schema",212 });213 // Later contracts may widen submitAnswer; what it has now must stay.214 expect(215 ["NotClaimed", "ClaimLapsed", "StaleBase", "RepoBusy"].flatMap((tag) =>216 pointedAt.has(ref(tag).$ref) ? [] : [tag]217 )218 ).toStrictEqual([]);219 expect(220 ["ask", "base", "head"].flatMap((field) =>221 fields.has(field) ? [] : [field]222 )223 ).toStrictEqual([]);224 });225226 it("says a contract with no refusals of its own can't fail that way", () => {227 const $defs = definitions();228229 const infallible = contracts.flatMap((rpc) =>230 SchemaAST.isNever(rpc.errorSchema.ast) ? [rpc._tag] : []231 );232233 expect(infallible).not.toHaveLength(0);234 expect(infallible.map((tag) => $defs[`${tag}.error`])).toStrictEqual(235 infallible.map(() => ({ not: {} }))236 );237 });238239 it("admits no non-finite number string and no null under an optional key", () => {240 expect(241 leaks(parseJson(content("docs/reference/protocol.schema.json")))242 ).toStrictEqual([]);243 });244245 it("gives every MCP tool's input and output schema, with no leak in either", () => {171 const schemas = jsonBlocks(content("docs/reference/mcp-tools.md"));246 const reference = content("docs/reference/mcp-tools.md");247 const schemas = jsonBlocks(reference);248173 // Two tools, an input and an output each.174 expect(schemas).toHaveLength(4);249 // An input and an output for each tool.250 expect(sections(reference).size).toBeGreaterThan(0);251 expect(schemas).toHaveLength(2 * sections(reference).size);252 expect(schemas.flatMap(leaks)).toStrictEqual([]);253 });254});255256describe("the command catalog", () => {180 it.effect(181 "decodes with its own schema and lists the projected commands",182 () =>183 Effect.gen(function* () {184 const catalog = yield* decodeCatalog(185 content("docs/reference/commands.json")186 );257 it("decodes with its own schema and lists asks and submit", () => {258 const { commands, version } = catalog();259188 expect(catalog.version).toBe(1);189 expect(catalog.commands).toMatchObject([190 {191 contract: "listAsks",192 destructive: false,193 idempotent: true,194 name: "asks",195 needsApproval: false,196 path: ["asks"],197 positional: [],198 readOnly: true,199 source: "projected",200 surfaces: ["rpc", "mcp", "cli", "web"],201 },202 {203 contract: "submitAnswer",204 destructive: false,205 idempotent: true,206 name: "submit",207 needsApproval: false,208 path: ["submit"],209 positional: [],210 readOnly: false,211 source: "projected",212 surfaces: ["rpc", "mcp", "cli", "web"],213 },214 ]);215 expect(216 catalog.commands.flatMap((command) => leaks(command.payloadSchema))217 ).toStrictEqual([]);218 })219 );260 const byName = new Map(commands.map((command) => [command.name, command]));261221 it("is what the CLI reference is rendered from: each command with its flags", () => {222 const reference = content("docs/reference/cli.md");223 const submit = reference.slice(reference.indexOf("submit`"));262 expect(version).toBe(1);263 expect(byName.get("asks")).toMatchObject({264 contract: "listAsks",265 destructive: false,266 idempotent: true,267 needsApproval: false,268 path: ["asks"],269 positional: [],270 readOnly: true,271 source: "projected",272 surfaces: ["rpc", "mcp", "cli", "web"],273 });274 expect(byName.get("submit")).toMatchObject({275 contract: "submitAnswer",276 destructive: false,277 idempotent: true,278 needsApproval: false,279 path: ["submit"],280 readOnly: false,281 source: "projected",282 });283 expect(284 commands.flatMap((command) => leaks(command.payloadSchema))285 ).toStrictEqual([]);286 });287225 expect(reference).toContain("asks`");226 expect(reference.slice(reference.indexOf("asks`"))).toContain(227 "`--project`"288 it("is what the CLI reference is rendered from: every command, with its arguments", () => {289 const { commands } = catalog();290291 // A heading is the command line in backticks: the CLI's name, then the path.292 const byPath = new Map(293 [...sections(content("docs/reference/cli.md"))].map(([heading, body]) => [294 heading.replace(/^`\S+ (?<path>.+)`$/u, "$<path>"),295 body,296 ])297 );298230 for (const flag of ["`--ask`", "`--base`", "`--head`"]) {231 expect(submit).toContain(flag);232 }299 const unrendered = commands.flatMap((command) => {300 const path = command.path.join(" ");301 const body = byPath.get(path) ?? "";302 const positional = new Set(command.positional);303 const { properties } = payloadFields(command.payloadSchema);304305 return [306 ...command.positional.map((field) => `<${field}>`),307 ...Object.keys(properties).flatMap((field) =>308 positional.has(field) ? [] : [`--${field}`]309 ),310 ].flatMap((argument) =>311 body.includes(`| \`${argument}\` |`) ? [] : [`${path} ${argument}`]312 );313 });314315 expect([...byPath.keys()]).toStrictEqual(316 commands.map((command) => command.path.join(" "))317 );318 expect(unrendered).toStrictEqual([]);319 // Known rows, so an empty catalog can't pass.320 expect(byPath.get("asks")).toContain("| `--project` | text | yes |");321 expect(byPath.get("submit")).toContain("| `--head` | text | yes |");322 });323});324325describe("the refusals reference", () => {
14 unmodified lines
modified:packages/protocol/src/annotations.ts+3 added-2 removed
modified:packages/protocol/src/mcp.ts+13 added-11 removed
1// Ported from joelhooks/rat-stack@fba26d8 `packages/capability/src/to-toolkit.ts`2// (MIT, LICENSES/rat-stack.MIT.txt). Changes are listed in PROVENANCE.md.3import type { JsonSchema, Layer } from "effect";4import { Context, Effect, Predicate, Schema } from "effect";4import { Context, Effect, JsonPointer, Predicate, Schema } from "effect";5import { Tool, Toolkit } from "effect/ai";6import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";78import {
46 unmodified lines
55 readonly inputSchema: JsonSchema.JsonSchema;56 readonly outputSchema: JsonSchema.JsonSchema;57}5859/** How a document points at one of its own definitions. */60const DEFINITION = "#/$defs/";59/**60 * The definition a `$ref` names, read as Effect reads it: a URI fragment61 * (percent-encoded, then `~1` and `~0` escaped) of the form `#/$defs/<key>`.62 */63const definitionKey = ($ref: string) => {64 const tokens = JsonPointer.parseUriFragment($ref);6566 return tokens?.length === 2 && tokens[0] === "$defs" ? tokens[1] : undefined;67};6869/**70 * A schema as MCP lists it, derived the way `McpServer` derives a tool's:71 * JSON Schema with an object root (a top-level `$ref` is inlined) and its72 * definitions under `$defs`.73 */74export const toJsonSchema = (schema: Schema.Top): JsonSchema.JsonSchema => {75 const { definitions, schema: root } = Schema.toJsonSchemaDocument(schema);7670 // A JSON Pointer escapes `/` as `~1` and `~` as `~0`.71 const key =72 Predicate.isString(root.$ref) && root.$ref.startsWith(DEFINITION)73 ? root.$ref74 .slice(DEFINITION.length)75 .replaceAll("~1", "/")76 .replaceAll("~0", "~")77 : undefined;77 const key = Predicate.isString(root.$ref)78 ? definitionKey(root.$ref)79 : undefined;8081 const inlined = (key === undefined ? undefined : definitions[key]) ?? root;8283 return Object.keys(definitions).length === 0
102 unmodified lines
modified:packages/protocol/test/annotations.test.ts+2 added-1 removed
modified:packages/protocol/test/mcp.test.ts+19 added-7 removed
66 unmodified lines
67 })68 ),69});7071/** A struct of one commit, as JSON Schema writes it. */72const receipt = {73 additionalProperties: true,74 properties: { main: { pattern: "^[0-9a-f]{40}$", type: "string" } },75 required: ["main"],76 type: "object",77};7879describe("the contracts as MCP tools", () => {80 it.effect("lists each contract as a tool, its payload as the input", () =>81 Effect.gen(function* () {82 const mcp = yield* serve(quiet);
65 unmodified lines
148 })149 );150151 it("inlines a named root schema, since MCP wants an object at the root", () => {144 const receipt = {145 additionalProperties: true,146 properties: { main: { pattern: "^[0-9a-f]{40}$", type: "string" } },147 required: ["main"],148 type: "object",149 };150152 expect(153 toJsonSchema(154 Schema.Struct({ main: CommitSha }).annotate({ identifier: "Receipt" })155 )156 ).toStrictEqual({ ...receipt, $defs: { Receipt: receipt } });157 });158159 // The pointer to "Answer receipt" is `#/$defs/Answer%20receipt`.160 it("inlines a named root whose pointer is percent-encoded", () => {161 expect(162 toJsonSchema(163 Schema.Struct({ main: CommitSha }).annotate({164 identifier: "Answer receipt",165 })166 )167 ).toStrictEqual({ ...receipt, $defs: { "Answer receipt": receipt } });168 });169170 it("tells the agent a person approves a contract that needs approval", () => {171 class Abandon extends Rpc.make("abandon", {172 payload: { project: ProjectName },173 })
84 unmodified lines
modified:scripts/lib/gen.ts+6 added-3 removed
60 unmodified lines
61 SchemaRepresentation,62} from "effect";6364/**65 * The union `refusals.md` is rendered from. Tests in `packages/config` read it66 * here: that package takes no `@repo/*` dependency, since every package67 * dev-depends on it and the edge would be a cycle.65 * The union and the group the reference is rendered from. Tests in66 * `packages/config` read them here: that package takes no `@repo/*`67 * dependency, since every package dev-depends on it and the edge would be a68 * cycle.69 */70export { Refusal } from "@repo/protocol/refusal";7172export { Contracts } from "@repo/protocol/contracts";7374/**75 * `docs/reference/commands.json`: every command the CLI has. `projected`76 * commands come from a contract; W4 merges in the hand-written `local` ones.77 */
522 unmodified lines