Add the one schema and its CLI and MCP projections in packages/protocol
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- contracts.ts: the Contracts RpcGroup, with listAsks ({project} to {asks}) and submitAnswer ({ask, base, head} to {main}, failing with NotClaimed | ClaimLapsed | StaleBase | RepoBusy). A subset per contract keeps Match.exhaustive tight. Success schemas are structs because MCP's outputSchema needs an object root. Client is the one port both projections call: an RpcClient for the group, in process or remote. - annotations.ts: Description, read by every surface that lists a contract. - ids.ts: ProjectName. - mcp.ts, ported from rat-stack@fba26d8 to-toolkit.ts: each Rpc becomes a tool (payload, success and error schemas as the tool's). A call goes through the client with the payload alone, so a refusal reaches the agent as the Rpc's encoded error, `_tag`, `next` and `retryable` kept. - cli.ts, ported from rat-stack@fba26d8 to-command.ts: payload fields become flags or positional arguments; string flags check their value with the field's schema, so a malformed value is refused by its flag before any call. `--json` is always offered. A refusal prints protocol/render's text on stderr, or its encoded JSON on stdout with `--json`, and the command fails with it. - The client's transport error is fixed to RpcClientError: TypeScript cannot infer it through RpcClient's mapped type, and `unknown` leaked into the command's error channel. - Tests: MCP over the stateless 2026-07-28 transport, sent as raw JSON-RPC through HttpRouter.toWebHandler (the Worker's fetch shape): the tool list, StaleBase as JSON, listAsks as structured content. CLI by argv: flags to payload, a refusal as render text and as JSON, a malformed sha refused before the call. - tsconfig (user sign-off): packages/protocol/src may use effect/ai, effect/cli and effect/rpc; its tests may also use effect/http. - PROVENANCE.md: the two ports and the borrowed MCP test request shape. - The repo's first four escapes, each with a SAFETY reason: three erasing casts in mcp.ts, one in cli.ts.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+874 added−1 removed
- tests:+407 added−0 removed
- other:+467 added−1 removed
Provenance
- Commit
acf3649- Tree
d5119c2- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
d2fdbdc
13 files changed+874 added−1 removed
added:packages/protocol/src/annotations.ts+6 added
123456import { Context } from "effect";
/** What a contract does, in one sentence, for every surface that lists it. */export const Description = Context.Reference<string>("protocol/Description", { defaultValue: () => "",});added:packages/protocol/src/cli.ts+280 added
1+// Ported from joelhooks/rat-stack@fba26d8 `packages/capability/src/to-command.ts`2+// (MIT, LICENSES/rat-stack.MIT.txt). Changes are listed in PROVENANCE.md.3+import {4+ Console,5+ Context,6+ Effect,7+ Option,8+ Predicate,9+ Schema,10+ SchemaAST,11+} from "effect";12+import { Argument, Command, Flag } from "effect/cli";13+import type { Rpc, RpcClient, RpcClientError } from "effect/rpc";14+15+import { Description } from "./annotations.ts";16+import { Refusal } from "./refusal.ts";17+import { explain } from "./render.ts";18+19+/** How a call can fail on its way to the handler and back. */20+type TransportError = RpcClientError.RpcClientError;21+22+/** A schema that needs no services to decode or encode, as every wire schema is. */23+type Plain = Schema.Top & {24+ readonly DecodingServices: never;25+ readonly EncodingServices: never;26+};27+28+/** An Rpc a command can project: its payload is a struct of plain fields. */29+export type CommandRpc = Rpc.AnyWithProps & {30+ readonly errorSchema: Plain;31+ readonly payloadSchema: Plain &32+ Schema.Struct<Readonly<Record<string, Plain>>>;33+ readonly successSchema: Plain;34+};35+36+export interface ToCommandOptions<Success> {37+ /** The command's name; the Rpc's tag by default. */38+ readonly name?: string;39+ /** Payload fields taken as positional arguments, in order, not flags. */40+ readonly positional?: readonly string[];41+ /** Text for a person; `--json` prints the encoded success instead. */42+ readonly render?: (success: Success) => string;43+}44+45+interface FieldSpec {46+ readonly description: string | undefined;47+ readonly kind: "string" | "number" | "boolean" | "literals" | "json";48+ readonly literals: readonly string[];49+ readonly optional: boolean;50+}51+52+const literalOf = (ast: SchemaAST.AST): string | undefined =>53+ SchemaAST.isLiteral(ast) && Predicate.isString(ast.literal)54+ ? ast.literal55+ : undefined;56+57+const primitiveKinds: Partial<58+ Record<SchemaAST.AST["_tag"], FieldSpec["kind"]>59+> = {60+ Boolean: "boolean",61+ Number: "number",62+ String: "string",63+};64+65+const primitiveKind = (ast: SchemaAST.AST): FieldSpec["kind"] =>66+ primitiveKinds[ast._tag] ?? "json";67+68+const describe = (field: Plain): FieldSpec => {69+ let ast: SchemaAST.AST = field.ast;70+ let optional = ast.context?.isOptional === true;71+72+ const description = SchemaAST.resolveDescription(ast);73+74+ if (SchemaAST.isUnion(ast)) {75+ const members = ast.types.filter(76+ (member) => !SchemaAST.isUndefined(member)77+ );78+79+ if (members.length < ast.types.length) {80+ optional = true;81+ }82+83+ const [only] = members;84+85+ if (members.length === 1 && only !== undefined) {86+ ast = only;87+ } else {88+ const literals = members.map(literalOf);89+90+ if (literals.every((literal) => literal !== undefined)) {91+ return { description, kind: "literals", literals, optional };92+ }93+94+ return { description, kind: "json", literals: [], optional };95+ }96+ }97+98+ const literal = literalOf(ast);99+100+ if (literal !== undefined) {101+ return { description, kind: "literals", literals: [literal], optional };102+ }103+104+ const kind = primitiveKind(ast);105+106+ return { description, kind, literals: [], optional };107+};108+109+const jsonFlag = (name: string, field: Plain) =>110+ Flag.String(name).pipe(111+ Flag.withSchema(Schema.fromJsonString(field)),112+ Flag.withMetavar("JSON")113+ );114+115+const flagBuilders = {116+ boolean: (name) => Flag.Boolean(name).pipe(Flag.withDefault(false)),117+ json: (name, field) => jsonFlag(name, field),118+ literals: (name, _field, spec) => Flag.Literals(name, spec.literals),119+ number: (name) => Flag.Finite(name),120+ // The field's own schema checks the text, so a malformed value is refused121+ // by the parser, naming its flag, before anything is called.122+ string: (name, field) => Flag.String(name).pipe(Flag.withSchema(field)),123+} satisfies Record<124+ FieldSpec["kind"],125+ (name: string, field: Plain, spec: FieldSpec) => Flag.Flag<unknown>126+>;127+128+const flagFor = (name: string, field: Plain): Flag.Flag<unknown> => {129+ const spec = describe(field);130+ const base = flagBuilders[spec.kind](name, field, spec);131+132+ const described =133+ spec.description === undefined134+ ? base135+ : base.pipe(Flag.withDescription(spec.description));136+137+ return spec.optional && spec.kind !== "boolean"138+ ? described.pipe(Flag.optional, Flag.map(Option.getOrUndefined))139+ : described;140+};141+142+const schemaArgument = (name: string, field: Plain, metavar: string) =>143+ Argument.String(name).pipe(144+ Argument.withSchema(Schema.fromJsonString(field)),145+ Argument.withMetavar(metavar)146+ );147+148+const argumentBuilders = {149+ boolean: (name, field) => schemaArgument(name, field, "BOOLEAN"),150+ json: (name, field) => schemaArgument(name, field, "JSON"),151+ literals: (name, _field, spec) => Argument.Literals(name, spec.literals),152+ number: (name) => Argument.Finite(name),153+ string: (name) => Argument.String(name),154+} satisfies Record<155+ FieldSpec["kind"],156+ (name: string, field: Plain, spec: FieldSpec) => Argument.Argument<unknown>157+>;158+159+const argumentFor = (160+ name: string,161+ field: Plain162+): Argument.Argument<unknown> => {163+ const spec = describe(field);164+ const base = argumentBuilders[spec.kind](name, field, spec);165+166+ const described =167+ spec.description === undefined168+ ? base169+ : base.pipe(Argument.withDescription(spec.description));170+171+ return spec.optional172+ ? described.pipe(Argument.optional, Argument.map(Option.getOrUndefined))173+ : described;174+};175+176+const JSON_FLAG = "json";177+178+const isRefusal = Schema.is(Refusal);179+180+const encodeRefusal = Schema.encodeEffect(Refusal);181+182+/**183+ * Says why a call was refused: as JSON on stdout for `--json`, or on stderr in184+ * the same words git's `remote:` lines use.185+ */186+const report = (refusal: Refusal, json: boolean) =>187+ json188+ ? encodeRefusal(refusal).pipe(189+ Effect.flatMap((encoded) =>190+ Console.log(JSON.stringify(encoded, null, 2))191+ ),192+ Effect.orDie193+ )194+ : Console.error(explain([refusal]).join("\n"));195+196+/**197+ * Projects one contract onto a CLI command: payload fields become flags (or198+ * positional arguments), and the command calls the Rpc through `client`.199+ */200+export const toCommand = <R extends CommandRpc, Requirements>(201+ rpc: R,202+ client: Effect.Effect<203+ RpcClient.RpcClient<R, TransportError>,204+ never,205+ Requirements206+ >,207+ options?: ToCommandOptions<Rpc.Success<R>>208+) => {209+ const positional = new Set(options?.positional);210+ const render = options?.render;211+212+ const config: Record<213+ string,214+ Flag.Flag<unknown> | Argument.Argument<unknown>215+ > = {};216+217+ for (const [name, field] of Object.entries(rpc.payloadSchema.fields)) {218+ config[name] = positional.has(name)219+ ? argumentFor(name, field)220+ : flagFor(name, field);221+ }222+223+ config[JSON_FLAG] = Flag.Boolean(JSON_FLAG).pipe(224+ Flag.withDefault(false),225+ Flag.withDescription("Print machine-readable JSON")226+ );227+228+ const decodePayload = Schema.decodeUnknownEffect(rpc.payloadSchema);229+ const encodeSuccess = Schema.encodeUnknownEffect(rpc.successSchema);230+231+ return Command.make(232+ options?.name ?? rpc._tag,233+ config,234+ (235+ parsed236+ ): Effect.Effect<237+ void,238+ Schema.SchemaError | Rpc.Error<R> | TransportError,239+ Requirements240+ > =>241+ Effect.gen(function* () {242+ const { [JSON_FLAG]: json, ...fields } = parsed;243+244+ const provided = Object.fromEntries(245+ Object.entries(fields).filter(([, value]) => value !== undefined)246+ );247+248+ const payload = yield* decodePayload(provided);249+ const calls = yield* client;250+251+ // SAFETY: an RpcClient for a group without prefixes has one method per tag, and `payload` was just decoded with that Rpc's payload schema.252+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the client's mapped type cannot be indexed by a generic tag; see SAFETY.253+ const byTag = calls as Readonly<254+ Record<255+ string,256+ (257+ decoded: typeof payload258+ ) => Effect.Effect<Rpc.Success<R>, Rpc.Error<R> | TransportError>259+ >260+ >;261+262+ const call =263+ byTag[rpc._tag] ??264+ (() => Effect.die(`The client has no method for ${rpc._tag}`));265+266+ const success = yield* call(payload).pipe(267+ Effect.tapError((error) =>268+ isRefusal(error) ? report(error, json === true) : Effect.void269+ )270+ );271+272+ const text =273+ render !== undefined && json !== true274+ ? render(success)275+ : JSON.stringify(yield* encodeSuccess(success), null, 2);276+277+ yield* Console.log(text);278+ }).pipe(Effect.withSpan(`protocol.${rpc._tag}`))279+ ).pipe(Command.withDescription(Context.get(rpc.annotations, Description)));280+};added:packages/protocol/src/contracts.ts+41 added
1234567891011121314151617181920212223242526272829303132333435363738394041import { Context, Schema } from "effect";import { Rpc, RpcGroup } from "effect/rpc";import type { RpcClient, RpcClientError } from "effect/rpc";
import { Description } from "./annotations.ts";import { AskId, CommitSha, ProjectName } from "./ids.ts";import { ClaimLapsed, NotClaimed, RepoBusy, StaleBase } from "./refusal.ts";
/** One open ask, as a list of asks shows it. */export const AskListing = Schema.Struct({ ask: AskId, claimed: Schema.Boolean, territory: Schema.NonEmptyString, want: Schema.NonEmptyString,});
export class ListAsks extends Rpc.make("listAsks", { payload: { project: ProjectName }, success: Schema.Struct({ asks: Schema.Array(AskListing) }),}).annotate(Description, "List a project's open asks.") {}
export class SubmitAnswer extends Rpc.make("submitAnswer", { error: Schema.Union([NotClaimed, ClaimLapsed, StaleBase, RepoBusy]), payload: { ask: AskId, base: CommitSha, head: CommitSha }, success: Schema.Struct({ main: CommitSha }),}).annotate( Description, "Offer the commit `head`, built on `base`, as an answer to an ask; once it lands, `main` is the new tip.") {}
/** The one schema: every surface is a projection of this group. */export class Contracts extends RpcGroup.make(ListAsks, SubmitAnswer) {}
/** A way to call the contracts, in process or over the wire. */export class Client extends Context.Service< Client, RpcClient.RpcClient< RpcGroup.Rpcs<typeof Contracts>, RpcClientError.RpcClientError >>()("protocol/Client") {}modified:packages/protocol/src/ids.ts+11 added
21 unmodified lines22232425262728293031323334353621 unmodified lines/** A path inside a repo, as git prints it. */export const RepoPath = Schema.NonEmptyString.pipe(Schema.brand("RepoPath"));
export type RepoPath = typeof RepoPath.Type;
/** * A project's name. Lowercase letters, digits and dashes, like an ask's, so a * command that names it is safe to paste into a shell. */export const ProjectName = Schema.String.pipe( Schema.check(Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/u)), Schema.brand("ProjectName"));
export type ProjectName = typeof ProjectName.Type;added:packages/protocol/src/mcp.ts+100 added
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.3+import type { Layer } from "effect";4+import { Context, Effect } from "effect";5+import { Tool, Toolkit } from "effect/ai";6+import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";7+8+import { Description } from "./annotations.ts";9+10+/** How a call can fail on its way to the handler and back. */11+type TransportError = RpcClientError.RpcClientError;12+13+/** The tool an Rpc becomes: its payload as parameters, its errors as failures. */14+export type ToolOf<R extends Rpc.Any> =15+ R extends Rpc.Rpc<16+ infer Tag,17+ infer Payload,18+ infer Success,19+ infer Error,20+ infer _Middleware,21+ infer _Requires22+ >23+ ? Tool.Tool<24+ Tag,25+ {26+ readonly failure: Error;27+ readonly failureMode: "error";28+ readonly parameters: Payload;29+ readonly success: Success;30+ }31+ >32+ : never;33+34+export type ToolsOf<Rpcs extends Rpc.Any> = {35+ readonly [R in Rpcs as R["_tag"]]: ToolOf<R>;36+};37+38+export interface ToolkitProjection<Rpcs extends Rpc.AnyWithProps, R> {39+ readonly toolkit: Toolkit.Toolkit<ToolsOf<Rpcs>>;40+ /** Handlers that answer each tool by calling its Rpc through the client. */41+ readonly layer: Layer.Layer<Tool.HandlersFor<ToolsOf<Rpcs>>, never, R>;42+}43+44+const toTool = (rpc: Rpc.AnyWithProps) =>45+ Tool.make(rpc._tag, {46+ description: Context.get(rpc.annotations, Description),47+ failure: rpc.errorSchema,48+ parameters: rpc.payloadSchema,49+ success: rpc.successSchema,50+ });51+52+/**53+ * Projects a group of contracts onto MCP tools. A tool call runs as a call to54+ * its Rpc through `client`, so a refusal reaches the agent as the Rpc's own55+ * encoded error, `_tag` and all.56+ */57+export const toToolkit = <Rpcs extends Rpc.AnyWithProps, R>(58+ group: RpcGroup.RpcGroup<Rpcs>,59+ client: Effect.Effect<RpcClient.RpcClient<Rpcs, TransportError>, never, R>60+): ToolkitProjection<Rpcs, R> => {61+ const rpcs = [...group.requests.values()];62+63+ const made: unknown = Toolkit.make(...rpcs.map(toTool));64+ // SAFETY: `Toolkit.make` is variadic over a tuple of tools; `ToolsOf<Rpcs>` recovers the tuple's type, which `map` over the runtime array cannot carry.65+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the tuple type is out of `map`'s reach; see SAFETY.66+ const toolkit = made as Toolkit.Toolkit<ToolsOf<Rpcs>>;67+68+ const layer = toolkit.toLayer(69+ Effect.map(client, (calls) => {70+ // SAFETY: an RpcClient for a group without prefixes has one method per tag, and the toolkit decodes a tool's parameters with that Rpc's payload schema before calling it.71+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a loop over tags cannot name each Rpc's method; see SAFETY.72+ const byTag = calls as Readonly<73+ Record<74+ string,75+ (76+ payload: Rpc.Payload<Rpcs>77+ ) => Effect.Effect<78+ Rpc.Success<Rpcs>,79+ Rpc.Error<Rpcs> | TransportError80+ >81+ >82+ >;83+84+ // Each handler passes the payload alone: the toolkit's second argument85+ // is its own context, which the client would read as call options.86+ const handlers: unknown = Object.fromEntries(87+ Object.entries(byTag).map(([tag, call]) => [88+ tag,89+ (payload: Rpc.Payload<Rpcs>) => call(payload),90+ ])91+ );92+93+ // SAFETY: the record is keyed by the group's tags, which are exactly the toolkit's tool names, and each value calls that tag's Rpc.94+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `fromEntries` cannot carry the mapped type; see SAFETY.95+ return handlers as Toolkit.HandlersFrom<ToolsOf<Rpcs>>;96+ })97+ );98+99+ return { layer, toolkit };100+};added:packages/protocol/test/cli.test.ts+156 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Effect, Layer, Ref, Result, Schema } from "effect";4+import { CliOutput, Command } from "effect/cli";5+import type { Rpc, RpcGroup } from "effect/rpc";6+import { RpcTest } from "effect/rpc";7+import { TestConsole } from "effect/testing";8+9+import { toCommand } from "../src/cli.ts";10+import { Client, Contracts, ListAsks, SubmitAnswer } from "../src/contracts.ts";11+import { CommitSha } from "../src/ids.ts";12+import { StaleBase } from "../src/refusal.ts";13+import { ask, base, main, path } from "./examples.ts";14+15+const head = CommitSha.make("3333333333333333333333333333333333333333");16+17+/** Handlers that never refuse; `listAsks` echoes its project as the territory. */18+const quiet = Contracts.toLayer({19+ listAsks: ({ project }) =>20+ Effect.succeed({21+ asks: [22+ { ask, claimed: false, territory: project, want: "Parse a comma" },23+ ],24+ }),25+ submitAnswer: () => Effect.succeed({ main }),26+});27+28+/** What was printed, one entry per line however it was written. */29+const lines = (output: Effect.Effect<readonly unknown[]>) =>30+ Effect.map(output, (all) =>31+ all.flatMap((chunk) => String(chunk).split("\n"))32+ );33+34+/**35+ * Runs `command` on `args`, its calls answered by `handlers`, and returns how36+ * it ended with what it printed to stdout and stderr.37+ */38+const run = <Name extends string, Input, E, R, ContextInput>(39+ handlers: Layer.Layer<Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>>,40+ command: Command.Command<Name, Input, ContextInput, E, R>,41+ args: readonly string[]42+) =>43+ Effect.gen(function* () {44+ const result = yield* Effect.result(45+ Command.runWith(command, { version: "0.0.0" })(args)46+ );47+48+ return {49+ err: yield* lines(TestConsole.errorLines),50+ out: yield* lines(TestConsole.logLines),51+ result,52+ };53+ }).pipe(54+ Effect.provide(55+ Layer.mergeAll(56+ TestConsole.layer,57+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),58+ Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(59+ Layer.provide(handlers)60+ )61+ ).pipe(Layer.provideMerge(NodeServices.layer))62+ )63+ );64+65+const Json = Schema.fromJsonString(Schema.Unknown);66+67+const submitAnswer = toCommand(SubmitAnswer, Effect.service(Client));68+69+describe("the contracts as CLI commands", () => {70+ it.effect("takes the payload as flags and prints the success as JSON", () =>71+ Effect.gen(function* () {72+ const { out } = yield* run(73+ quiet,74+ toCommand(ListAsks, Effect.service(Client)),75+ ["--project", "demo"]76+ );77+78+ expect(yield* Schema.decodeEffect(Json)(out.join("\n"))).toStrictEqual({79+ asks: [80+ {81+ ask: "fix-parser",82+ claimed: false,83+ territory: "demo",84+ want: "Parse a comma",85+ },86+ ],87+ });88+ })89+ );90+91+ it.effect("prints a refusal as the renderer's text and fails with it", () =>92+ Effect.gen(function* () {93+ const refusal = new StaleBase({ base, conflicts: [path], main });94+95+ const { err, result } = yield* run(96+ Contracts.toLayer({97+ listAsks: () => Effect.succeed({ asks: [] }),98+ submitAnswer: () => Effect.fail(refusal),99+ }),100+ submitAnswer,101+ ["--ask", ask, "--base", base, "--head", head]102+ );103+104+ expect(result).toStrictEqual(Result.fail(refusal));105+ expect(err).toStrictEqual([106+ "StaleBase: main moved to 2222222, past your base 1111111; conflicts in src/a.ts",107+ " next: git pull --rebase",108+ " retryable: yes",109+ ]);110+ })111+ );112+113+ it.effect("with --json, prints the refusal as JSON that keeps its tag", () =>114+ Effect.gen(function* () {115+ const refusal = new StaleBase({ base, conflicts: [path], main });116+117+ const { err, out, result } = yield* run(118+ Contracts.toLayer({119+ listAsks: () => Effect.succeed({ asks: [] }),120+ submitAnswer: () => Effect.fail(refusal),121+ }),122+ submitAnswer,123+ ["--ask", ask, "--base", base, "--head", head, "--json"]124+ );125+126+ const printed = yield* Schema.decodeEffect(Json)(out.join("\n"));127+128+ expect(result).toStrictEqual(Result.fail(refusal));129+ expect(err).toStrictEqual([]);130+ expect(printed).toHaveProperty("_tag", "StaleBase");131+ expect(132+ yield* Schema.decodeUnknownEffect(StaleBase)(printed)133+ ).toStrictEqual(refusal);134+ })135+ );136+137+ it.effect("refuses a malformed commit id before calling anything", () =>138+ Effect.gen(function* () {139+ const calls = yield* Ref.make(0);140+141+ const { err, result } = yield* run(142+ Contracts.toLayer({143+ listAsks: () => Effect.succeed({ asks: [] }),144+ submitAnswer: () =>145+ Ref.update(calls, (count) => count + 1).pipe(Effect.as({ main })),146+ }),147+ submitAnswer,148+ ["--ask", ask, "--base", "not-a-sha", "--head", head]149+ );150+151+ expect(Result.isFailure(result)).toBeTruthy();152+ expect(yield* Ref.get(calls)).toBe(0);153+ expect(err.join("\n")).toContain("--base");154+ })155+ );156+});added:packages/protocol/test/mcp.test.ts+138 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Context, Effect, Schema } from "effect";3+4+import { Description } from "../src/annotations.ts";5+import { Contracts, ListAsks, SubmitAnswer } from "../src/contracts.ts";6+import { AskId, CommitSha } from "../src/ids.ts";7+import { StaleBase } from "../src/refusal.ts";8+import { ask, base, main, path } from "./examples.ts";9+import { serve } from "./mcp.ts";10+11+const head = CommitSha.make("3333333333333333333333333333333333333333");12+13+/** A tools/call result whose one content block is JSON text. */14+const ToolResult = Schema.Struct({15+ content: Schema.Tuple([16+ Schema.Struct({17+ text: Schema.fromJsonString(Schema.Unknown),18+ type: Schema.Literal("text"),19+ }),20+ ]),21+ isError: Schema.Boolean,22+});23+24+/** Handlers that never refuse, for tests about the tools themselves. */25+const quiet = Contracts.toLayer({26+ listAsks: () => Effect.succeed({ asks: [] }),27+ submitAnswer: () => Effect.succeed({ main }),28+});29+30+const ToolList = Schema.Struct({31+ tools: Schema.Array(32+ Schema.Struct({33+ description: Schema.String,34+ inputSchema: Schema.Struct({ required: Schema.Array(Schema.String) }),35+ name: Schema.String,36+ })37+ ),38+});39+40+describe("the contracts as MCP tools", () => {41+ it.effect("lists each contract as a tool, its payload as the input", () =>42+ Effect.gen(function* () {43+ const mcp = yield* serve(quiet);44+45+ const { tools } = yield* mcp.call("tools/list", {}, ToolList);46+47+ expect(48+ tools.map(({ description, inputSchema, name }) => ({49+ description,50+ name,51+ required: inputSchema.required,52+ }))53+ ).toStrictEqual([54+ {55+ description: Context.get(ListAsks.annotations, Description),56+ name: "listAsks",57+ required: ["project"],58+ },59+ {60+ description: Context.get(SubmitAnswer.annotations, Description),61+ name: "submitAnswer",62+ required: ["ask", "base", "head"],63+ },64+ ]);65+ })66+ );67+68+ it.effect("returns a refusal as JSON that keeps its tag", () =>69+ Effect.gen(function* () {70+ const refusal = new StaleBase({ base, conflicts: [path], main });71+72+ const mcp = yield* serve(73+ Contracts.toLayer({74+ listAsks: () => Effect.succeed({ asks: [] }),75+ submitAnswer: () => Effect.fail(refusal),76+ })77+ );78+79+ const result = yield* mcp.call(80+ "tools/call",81+ { arguments: { ask, base, head }, name: "submitAnswer" },82+ ToolResult83+ );84+85+ const [{ text }] = result.content;86+87+ expect(result.isError).toBeTruthy();88+ expect(text).toHaveProperty("_tag", "StaleBase");89+ expect(yield* Schema.decodeUnknownEffect(StaleBase)(text)).toStrictEqual(90+ refusal91+ );92+ })93+ );94+95+ it.effect("returns a contract's success as structured content", () =>96+ Effect.gen(function* () {97+ const mcp = yield* serve(98+ Contracts.toLayer({99+ listAsks: () =>100+ Effect.succeed({101+ asks: [102+ {103+ ask: AskId.make("fix-parser"),104+ claimed: false,105+ territory: "packages/parser",106+ want: "Parse a trailing comma",107+ },108+ ],109+ }),110+ submitAnswer: () => Effect.succeed({ main }),111+ })112+ );113+114+ const result = yield* mcp.call(115+ "tools/call",116+ { arguments: { project: "demo" }, name: "listAsks" },117+ Schema.Struct({118+ isError: Schema.Boolean,119+ structuredContent: Schema.Unknown,120+ })121+ );122+123+ expect(result).toStrictEqual({124+ isError: false,125+ structuredContent: {126+ asks: [127+ {128+ ask: "fix-parser",129+ claimed: false,130+ territory: "packages/parser",131+ want: "Parse a trailing comma",132+ },133+ ],134+ },135+ });136+ })137+ );138+});added:packages/protocol/test/mcp.ts+113 added
1+import { Effect, Layer, Schema } from "effect";2+import { McpProtocol, McpServer } from "effect/ai";3+import { HttpRouter } from "effect/http";4+import type { Rpc, RpcGroup } from "effect/rpc";5+import { RpcTest } from "effect/rpc";6+7+import { Client, Contracts } from "../src/contracts.ts";8+import { toToolkit } from "../src/mcp.ts";9+10+const endpoint = "http://localhost/mcp";11+12+const protocol = McpProtocol.v2026_07_28;13+14+// The 2026-07-28 protocol is stateless: each request names its version and15+// client in `_meta` and repeats its method and target in headers.16+const meta = {17+ "io.modelcontextprotocol/clientCapabilities": {},18+ "io.modelcontextprotocol/clientInfo": { name: "test", version: "0.0.0" },19+ "io.modelcontextprotocol/protocolVersion": protocol.protocolVersion,20+};21+22+/** The last JSON-RPC message in a reply, which is plain JSON or an event stream. */23+const lastMessage = (response: Response) =>24+ Effect.promise(() => response.text()).pipe(25+ Effect.map((text) =>26+ response.headers.get("content-type")?.includes("text/event-stream") ===27+ true28+ ? (text29+ .split("\n")30+ .findLast((line) => line.startsWith("data: "))31+ ?.slice("data: ".length) ?? "")32+ : text33+ )34+ );35+36+const Reply = Schema.fromJsonString(Schema.Struct({ result: Schema.Unknown }));37+38+/** What a request carries: a tool call names its tool and its arguments. */39+interface Params {40+ readonly arguments?: Readonly<Record<string, string>>;41+ readonly name?: string;42+}43+44+/**45+ * Serves the contracts' tools over MCP's HTTP transport, the way a Worker's46+ * fetch handler would, with `handlers` answering each call.47+ */48+export const serve = Effect.fnUntraced(function* (49+ handlers: Layer.Layer<Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>>50+) {51+ const projection = toToolkit(Contracts, Effect.service(Client));52+53+ const app = McpServer.toolkit(projection.toolkit).pipe(54+ Layer.provideMerge(projection.layer),55+ Layer.provide(Layer.effect(Client)(RpcTest.makeClient(Contracts))),56+ Layer.provide(handlers),57+ Layer.provide(58+ McpServer.layerHttp({59+ name: "test",60+ path: "/mcp",61+ protocols: [protocol],62+ version: "0.0.0",63+ })64+ )65+ );66+67+ const { dispose, handler } = HttpRouter.toWebHandler(app, {68+ disableLogger: true,69+ });70+71+ yield* Effect.addFinalizer(() => Effect.promise(dispose));72+73+ /** Sends one request and decodes its result with `result`. */74+ const call = Effect.fnUntraced(function* <A>(75+ method: string,76+ params: Params,77+ result: Schema.Decoder<A>78+ ) {79+ const headers = new Headers({80+ accept: "application/json, text/event-stream",81+ "content-type": "application/json",82+ "mcp-method": method,83+ "mcp-protocol-version": protocol.protocolVersion,84+ });85+86+ if (params.name !== undefined) {87+ headers.set("mcp-name", params.name);88+ }89+90+ const response = yield* Effect.promise(() =>91+ handler(92+ new Request(endpoint, {93+ body: JSON.stringify({94+ id: 1,95+ jsonrpc: "2.0",96+ method,97+ params: { ...params, _meta: meta },98+ }),99+ headers,100+ method: "POST",101+ })102+ )103+ );104+105+ const reply = yield* Schema.decodeEffect(Reply)(106+ yield* lastMessage(response)107+ );108+109+ return yield* Schema.decodeUnknownEffect(result)(reply.result);110+ });111+112+ return { call };113+});modified:packages/protocol/package.json+5 added
123456789101112135 unmodified lines192021222324252627282 unmodified lines{ "name": "@repo/protocol", "private": true, "type": "module", "exports": { "./cli": "./src/cli.ts", "./contracts": "./src/contracts.ts", "./ids": "./src/ids.ts", "./mcp": "./src/mcp.ts", "./posture": "./src/posture.ts", "./refusal": "./src/refusal.ts", "./render": "./src/render.ts" },5 unmodified lines "@repo/brand": "workspace:*", "effect": "catalog:" }, "devDependencies": { "@cloudflare/workers-types": "5.20261006.1", "@effect/platform-node": "4.0.1", "@effect/vitest": "catalog:", "@repo/config": "workspace:*", "typescript": "catalog:", "vitest": "catalog:"2 unmodified linesmodified:packages/protocol/tsconfig.json+2 added-1 removed
123445678{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true "allowImportingTsExtensions": true, "types": ["@cloudflare/workers-types"] }, "include": ["src/**/*.ts", "test/**/*.ts", "*.config.ts"]}modified:bun.lock+2 added
74 unmodified lines75 "@repo/brand": "workspace:*",76 "effect": "catalog:",77 },78 "devDependencies": {79+ "@cloudflare/workers-types": "5.20261006.1",80+ "@effect/platform-node": "4.0.1",81 "@effect/vitest": "catalog:",82 "@repo/config": "workspace:*",83 "typescript": "catalog:",84 "vitest": "catalog:",766 unmodified linesmodified:PROVENANCE.md+3 added
5 unmodified lines6789101112131415161718195 unmodified lines
| Our file | Origin | Licence | Our changes || --- | --- | --- | --- || `tools/oxlint/anti-slop/` | [dmmulroy/anti-slop](https://github.com/dmmulroy/anti-slop) at `c44ef22` | MIT, `LICENSES/anti-slop.MIT.txt` | None; vendored by its own install script. See `UPSTREAM.md` there. || `packages/protocol/src/cli.ts` | [joelhooks/rat-stack](https://github.com/joelhooks/rat-stack) `packages/capability/src/to-command.ts` l.14–247 at `fba26d8` | MIT, `LICENSES/rat-stack.MIT.txt` | Projects an `Rpc` whose payload is a struct, not a capability, and calls it through an `RpcClient`. `--json` is always offered. A refusal prints `protocol/render`'s text on stderr, or its encoded JSON on stdout with `--json`, and the command fails with it. String flags check their value with the field's schema, so the parser refuses a malformed value by its flag. The description comes from the `Description` annotation. Dropped: `--yes` and approval, the reserved-field guards, and the `as never` casts. || `packages/protocol/src/mcp.ts` | [joelhooks/rat-stack](https://github.com/joelhooks/rat-stack) `packages/capability/src/to-toolkit.ts` l.18–146 at `fba26d8` | MIT, `LICENSES/rat-stack.MIT.txt` | Projects an `RpcGroup`'s Rpcs, not capabilities: the payload, success and error schemas become the tool's. Handlers call each Rpc through an `RpcClient`, passing the payload alone. The description comes from the `Description` annotation. Dropped: the empty-input dynamic tool, approval, the hint annotations and the file-wide diagnostics escape. || `tsconfig.base.json` (compiler options and the Effect diagnostics map) | [joelhooks/rat-stack](https://github.com/joelhooks/rat-stack) `tsconfig.base.json` at `fba26d8` | MIT, `LICENSES/rat-stack.MIT.txt` | `importFromBarrel` dropped (unknown to `@effect/tsgo` 0.48.1); `types` emptied, so each package opts into its host's types; `@effect/platform-bun` added to `namespaceImportPackages`; `outdatedApi`, `unstableApiUsage` and `experimentalApiUsage` raised to `error`; `allowedUnstableApis` emptied and granted per path through `overrides`. |
## Ideas, no code
| Idea | From | Where it lives || --- | --- | --- || The stateless 2026-07-28 MCP request (`_meta` keys plus `Mcp-Method`, `Mcp-Name` and `MCP-Protocol-Version` headers) driven through `HttpRouter.toWebHandler` | Effect's `packages/effect/test/ai/McpServer/v2026_07_28.test.ts` and `TestUtils/McpHttpHarness.ts` | `packages/protocol/test/mcp.ts` || A release-age gate and exact pins on every install | Rat Stack's `pnpm-workspace.yaml` (`minimumReleaseAge`, `minimumReleaseAgeExclude`) | `bunfig.toml` |modified:tsconfig.base.json+17 added
71 unmodified lines72 "allowedUnstableApis": ["effect/process"]73 }74 },75 {76+ "include": ["packages/protocol/src/**/*.ts"],77+ "options": {78+ "allowedUnstableApis": ["effect/ai", "effect/cli", "effect/rpc"]79+ }80+ },81+ {82+ "include": ["packages/protocol/test/**/*.ts"],83+ "options": {84+ "allowedUnstableApis": [85+ "effect/ai",86+ "effect/cli",87+ "effect/http",88+ "effect/rpc"89+ ]90+ }91+ },92+ {93 "include": ["packages/git/test/**/*.ts"],94 "options": {95 "allowedUnstableApis": ["effect/http", "effect/process"]96 }6 unmodified lines