Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent d2fdbdc · Browse files · 13 files+874 added−1 removed
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

13 files+874 added−1 removed

added:packages/protocol/src/annotations.ts+6 added
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.3import {4 Console,5 Context,6 Effect,7 Option,8 Predicate,9 Schema,10 SchemaAST,11} from "effect";12import { Argument, Command, Flag } from "effect/cli";13import type { Rpc, RpcClient, RpcClientError } from "effect/rpc";1415import { Description } from "./annotations.ts";16import { Refusal } from "./refusal.ts";17import { explain } from "./render.ts";1819/** How a call can fail on its way to the handler and back. */20type TransportError = RpcClientError.RpcClientError;2122/** A schema that needs no services to decode or encode, as every wire schema is. */23type Plain = Schema.Top & {24 readonly DecodingServices: never;25 readonly EncodingServices: never;26};2728/** An Rpc a command can project: its payload is a struct of plain fields. */29export type CommandRpc = Rpc.AnyWithProps & {30 readonly errorSchema: Plain;31 readonly payloadSchema: Plain &32 Schema.Struct<Readonly<Record<string, Plain>>>;33 readonly successSchema: Plain;34};3536export 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}4445interface FieldSpec {46 readonly description: string | undefined;47 readonly kind: "string" | "number" | "boolean" | "literals" | "json";48 readonly literals: readonly string[];49 readonly optional: boolean;50}5152const literalOf = (ast: SchemaAST.AST): string | undefined =>53 SchemaAST.isLiteral(ast) && Predicate.isString(ast.literal)54 ? ast.literal55 : undefined;5657const primitiveKinds: Partial<58 Record<SchemaAST.AST["_tag"], FieldSpec["kind"]>59> = {60 Boolean: "boolean",61 Number: "number",62 String: "string",63};6465const primitiveKind = (ast: SchemaAST.AST): FieldSpec["kind"] =>66 primitiveKinds[ast._tag] ?? "json";6768const describe = (field: Plain): FieldSpec => {69 let ast: SchemaAST.AST = field.ast;70 let optional = ast.context?.isOptional === true;7172 const description = SchemaAST.resolveDescription(ast);7374 if (SchemaAST.isUnion(ast)) {75 const members = ast.types.filter(76 (member) => !SchemaAST.isUndefined(member)77 );7879 if (members.length < ast.types.length) {80 optional = true;81 }8283 const [only] = members;8485 if (members.length === 1 && only !== undefined) {86 ast = only;87 } else {88 const literals = members.map(literalOf);8990 if (literals.every((literal) => literal !== undefined)) {91 return { description, kind: "literals", literals, optional };92 }9394 return { description, kind: "json", literals: [], optional };95 }96 }9798 const literal = literalOf(ast);99100 if (literal !== undefined) {101 return { description, kind: "literals", literals: [literal], optional };102 }103104 const kind = primitiveKind(ast);105106 return { description, kind, literals: [], optional };107};108109const jsonFlag = (name: string, field: Plain) =>110 Flag.String(name).pipe(111 Flag.withSchema(Schema.fromJsonString(field)),112 Flag.withMetavar("JSON")113 );114115const 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>;127128const flagFor = (name: string, field: Plain): Flag.Flag<unknown> => {129 const spec = describe(field);130 const base = flagBuilders[spec.kind](name, field, spec);131132 const described =133 spec.description === undefined134 ? base135 : base.pipe(Flag.withDescription(spec.description));136137 return spec.optional && spec.kind !== "boolean"138 ? described.pipe(Flag.optional, Flag.map(Option.getOrUndefined))139 : described;140};141142const schemaArgument = (name: string, field: Plain, metavar: string) =>143 Argument.String(name).pipe(144 Argument.withSchema(Schema.fromJsonString(field)),145 Argument.withMetavar(metavar)146 );147148const 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>;158159const argumentFor = (160 name: string,161 field: Plain162): Argument.Argument<unknown> => {163 const spec = describe(field);164 const base = argumentBuilders[spec.kind](name, field, spec);165166 const described =167 spec.description === undefined168 ? base169 : base.pipe(Argument.withDescription(spec.description));170171 return spec.optional172 ? described.pipe(Argument.optional, Argument.map(Option.getOrUndefined))173 : described;174};175176const JSON_FLAG = "json";177178const isRefusal = Schema.is(Refusal);179180const encodeRefusal = Schema.encodeEffect(Refusal);181182/**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 */186const 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"));195196/**197 * Projects one contract onto a CLI command: payload fields become flags (or198 * positional arguments), and the command calls the Rpc through `client`.199 */200export 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;211212 const config: Record<213 string,214 Flag.Flag<unknown> | Argument.Argument<unknown>215 > = {};216217 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 }222223 config[JSON_FLAG] = Flag.Boolean(JSON_FLAG).pipe(224 Flag.withDefault(false),225 Flag.withDescription("Print machine-readable JSON")226 );227228 const decodePayload = Schema.decodeUnknownEffect(rpc.payloadSchema);229 const encodeSuccess = Schema.encodeUnknownEffect(rpc.successSchema);230231 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;243244 const provided = Object.fromEntries(245 Object.entries(fields).filter(([, value]) => value !== undefined)246 );247248 const payload = yield* decodePayload(provided);249 const calls = yield* client;250251 // 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 >;261262 const call =263 byTag[rpc._tag] ??264 (() => Effect.die(`The client has no method for ${rpc._tag}`));265266 const success = yield* call(payload).pipe(267 Effect.tapError((error) =>268 isRefusal(error) ? report(error, json === true) : Effect.void269 )270 );271272 const text =273 render !== undefined && json !== true274 ? render(success)275 : JSON.stringify(yield* encodeSuccess(success), null, 2);276277 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
modified:packages/protocol/src/ids.ts+11 added
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.3import type { Layer } from "effect";4import { Context, Effect } from "effect";5import { Tool, Toolkit } from "effect/ai";6import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";78import { Description } from "./annotations.ts";910/** How a call can fail on its way to the handler and back. */11type TransportError = RpcClientError.RpcClientError;1213/** The tool an Rpc becomes: its payload as parameters, its errors as failures. */14export 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;3334export type ToolsOf<Rpcs extends Rpc.Any> = {35 readonly [R in Rpcs as R["_tag"]]: ToolOf<R>;36};3738export 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}4344const 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 });5152/**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 */57export 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()];6263 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>>;6768 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 >;8384 // 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 );9293 // 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 );9899 return { layer, toolkit };100};
added:packages/protocol/test/cli.test.ts+156 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Effect, Layer, Ref, Result, Schema } from "effect";4import { CliOutput, Command } from "effect/cli";5import type { Rpc, RpcGroup } from "effect/rpc";6import { RpcTest } from "effect/rpc";7import { TestConsole } from "effect/testing";89import { toCommand } from "../src/cli.ts";10import { Client, Contracts, ListAsks, SubmitAnswer } from "../src/contracts.ts";11import { CommitSha } from "../src/ids.ts";12import { StaleBase } from "../src/refusal.ts";13import { ask, base, main, path } from "./examples.ts";1415const head = CommitSha.make("3333333333333333333333333333333333333333");1617/** Handlers that never refuse; `listAsks` echoes its project as the territory. */18const 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});2728/** What was printed, one entry per line however it was written. */29const lines = (output: Effect.Effect<readonly unknown[]>) =>30 Effect.map(output, (all) =>31 all.flatMap((chunk) => String(chunk).split("\n"))32 );3334/**35 * Runs `command` on `args`, its calls answered by `handlers`, and returns how36 * it ended with what it printed to stdout and stderr.37 */38const 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 );4748 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 );6465const Json = Schema.fromJsonString(Schema.Unknown);6667const submitAnswer = toCommand(SubmitAnswer, Effect.service(Client));6869describe("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 );7778 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 );9091 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 });9495 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 );103104 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 );112113 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 });116117 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 );125126 const printed = yield* Schema.decodeEffect(Json)(out.join("\n"));127128 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 );136137 it.effect("refuses a malformed commit id before calling anything", () =>138 Effect.gen(function* () {139 const calls = yield* Ref.make(0);140141 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 );150151 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
1import { describe, expect, it } from "@effect/vitest";2import { Context, Effect, Schema } from "effect";34import { Description } from "../src/annotations.ts";5import { Contracts, ListAsks, SubmitAnswer } from "../src/contracts.ts";6import { AskId, CommitSha } from "../src/ids.ts";7import { StaleBase } from "../src/refusal.ts";8import { ask, base, main, path } from "./examples.ts";9import { serve } from "./mcp.ts";1011const head = CommitSha.make("3333333333333333333333333333333333333333");1213/** A tools/call result whose one content block is JSON text. */14const 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});2324/** Handlers that never refuse, for tests about the tools themselves. */25const quiet = Contracts.toLayer({26 listAsks: () => Effect.succeed({ asks: [] }),27 submitAnswer: () => Effect.succeed({ main }),28});2930const 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});3940describe("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);4445 const { tools } = yield* mcp.call("tools/list", {}, ToolList);4647 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 );6768 it.effect("returns a refusal as JSON that keeps its tag", () =>69 Effect.gen(function* () {70 const refusal = new StaleBase({ base, conflicts: [path], main });7172 const mcp = yield* serve(73 Contracts.toLayer({74 listAsks: () => Effect.succeed({ asks: [] }),75 submitAnswer: () => Effect.fail(refusal),76 })77 );7879 const result = yield* mcp.call(80 "tools/call",81 { arguments: { ask, base, head }, name: "submitAnswer" },82 ToolResult83 );8485 const [{ text }] = result.content;8687 expect(result.isError).toBeTruthy();88 expect(text).toHaveProperty("_tag", "StaleBase");89 expect(yield* Schema.decodeUnknownEffect(StaleBase)(text)).toStrictEqual(90 refusal91 );92 })93 );9495 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 );113114 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 );122123 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
1import { Effect, Layer, Schema } from "effect";2import { McpProtocol, McpServer } from "effect/ai";3import { HttpRouter } from "effect/http";4import type { Rpc, RpcGroup } from "effect/rpc";5import { RpcTest } from "effect/rpc";67import { Client, Contracts } from "../src/contracts.ts";8import { toToolkit } from "../src/mcp.ts";910const endpoint = "http://localhost/mcp";1112const protocol = McpProtocol.v2026_07_28;1314// The 2026-07-28 protocol is stateless: each request names its version and15// client in `_meta` and repeats its method and target in headers.16const meta = {17 "io.modelcontextprotocol/clientCapabilities": {},18 "io.modelcontextprotocol/clientInfo": { name: "test", version: "0.0.0" },19 "io.modelcontextprotocol/protocolVersion": protocol.protocolVersion,20};2122/** The last JSON-RPC message in a reply, which is plain JSON or an event stream. */23const 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 );3536const Reply = Schema.fromJsonString(Schema.Struct({ result: Schema.Unknown }));3738/** What a request carries: a tool call names its tool and its arguments. */39interface Params {40 readonly arguments?: Readonly<Record<string, string>>;41 readonly name?: string;42}4344/**45 * Serves the contracts' tools over MCP's HTTP transport, the way a Worker's46 * fetch handler would, with `handlers` answering each call.47 */48export const serve = Effect.fnUntraced(function* (49 handlers: Layer.Layer<Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>>50) {51 const projection = toToolkit(Contracts, Effect.service(Client));5253 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 );6667 const { dispose, handler } = HttpRouter.toWebHandler(app, {68 disableLogger: true,69 });7071 yield* Effect.addFinalizer(() => Effect.promise(dispose));7273 /** 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 });8586 if (params.name !== undefined) {87 headers.set("mcp-name", params.name);88 }8990 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 );104105 const reply = yield* Schema.decodeEffect(Reply)(106 yield* lastMessage(response)107 );108109 return yield* Schema.decodeUnknownEffect(result)(reply.result);110 });111112 return { call };113});
modified:packages/protocol/package.json+5 added
modified:packages/protocol/tsconfig.json+2 added-1 removed
modified:bun.lock+2 added
74 unmodified lines
75 "@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 lines
modified:PROVENANCE.md+3 added
modified:tsconfig.base.json+17 added
71 unmodified lines
72 "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