Skip to content
Myr

Serve the contracts over MCP and RPC as the caller, and over stdio from the CLI

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

- protocol/principal.ts: Principal (a Handle), CurrentPrincipal, Unauthenticated, and the Authenticated RpcMiddleware, which Contracts now carry. Every contract runs as someone: a host's server side turns the call's credential into CurrentPrincipal. The projections' call error is RpcClientError | Unauthenticated. - apps/platform: the Sessions port (bearer token to Principal) with a /memory adapter, until S8 gives identity a home. surfaces.ts serves /mcp (stateless 2026-07-28) and /rpc behind a global gate that answers 401 with `WWW-Authenticate: Bearer` before any surface runs. Authenticated's server side checks the call's `authorization` header; for MCP, a client middleware copies the HTTP request's header into the in-process Rpc call, since the tool handler's fiber still holds the request. The RPC HTTP client carries Rpc headers in the body, so a remote client sends its token as a plain HTTP header, which the RPC server merges into every call's headers. - apps/cli: surfaces.ts has the `mcp` command, the toolkit over stdio in all five protocols (2026-07-28 and the four session-based ones). - Tests: the platform's fetch handler, driven with web Requests: a tool call as Alice lands and as Bob is NotClaimed; no or unknown token gets a 401 and runs nothing; an RpcClient over HTTP calls as its bearer. The CLI's mcp over a test Stdio: each session-based version agrees the version asked for, 2026-07-28 answers server/discover, and StaleBase comes back as JSON. - tsconfig (user sign-off): apps/platform may use effect/ai, effect/http and effect/rpc; apps/cli also effect/cli. - Live (wanted-explainer ONE-SCHEMA-RESULTS.md): pi 1.0.4 lists both tools over 2025-11-25; Claude Code 2.1.292 speaks 2026-07-28 over stdio, gets StaleBase as JSON and names `git pull --rebase` as next.

authored by oscabriel · committed by oscabriel · parent acf3649 · Browse files · 25 files+863 added−22 removed
This commit

State

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

Diff stats

25 files+863 added−22 removed

  • tests:+480 added−5 removed
  • other:+383 added−17 removed

25 files+863 added−22 removed

added:apps/cli/src/surfaces.ts+35 added
added:apps/cli/test/stdio.ts+92 added
1import { NodeServices } from "@effect/platform-node";2import { Client, Contracts } from "@repo/protocol/contracts";3import { Handle } from "@repo/protocol/ids";4import { Authenticated, CurrentPrincipal } from "@repo/protocol/principal";5import {6 Effect,7 Fiber,8 Layer,9 Predicate,10 Queue,11 Schema,12 Sink,13 Stdio,14 Stream,15} from "effect";16import type { Cause } from "effect";17import { CliOutput, Command } from "effect/cli";18import type { Rpc, RpcGroup } from "effect/rpc";19import { RpcTest } from "effect/rpc";2021import { mcp } from "../src/surfaces.ts";2223/** A server side that takes every call as one person. */24const asTester = Layer.succeed(Authenticated, (effect) =>25 Effect.provideService(effect, CurrentPrincipal, {26 handle: Handle.make("tester"),27 })28);2930const Message = Schema.fromJsonString(31 Schema.Struct({32 id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Int])),33 result: Schema.optionalKey(Schema.Unknown),34 })35);3637/**38 * Runs `mcp` as a harness would spawn it: `messages` go in on stdin, one JSON39 * line each, then stdin ends. Returns every result it wrote back, by id.40 */41export const session = (42 handlers: Layer.Layer<Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>>,43 messages: readonly object[]44) =>45 Effect.gen(function* () {46 const written = yield* Queue.unbounded<string | Uint8Array, Cause.Done>();47 const encoder = new TextEncoder();4849 const stdio = Stdio.layerTest({50 stdin: Stream.fromIterable(51 messages.map((message) =>52 encoder.encode(`${JSON.stringify(message)}\n`)53 )54 ),55 stdout: () => Sink.fromQueue(written),56 });5758 // The stdio server interrupts the fiber that started it once stdin ends,59 // as a process would exit, so it runs in a fiber of its own. The test60 // stdio comes last, so it stands in for the real one.61 const server = yield* Command.runWith(mcp, { version: "0.0.0" })([]).pipe(62 Effect.provide(63 Layer.mergeAll(64 NodeServices.layer,65 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),66 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(67 Layer.provide([handlers, asTester])68 ),69 stdio70 )71 ),72 Effect.forkChild73 );7475 yield* Fiber.await(server);7677 const decoder = new TextDecoder();7879 const text = (yield* Queue.clear(written))80 .map((chunk) =>81 Predicate.isString(chunk) ? chunk : decoder.decode(chunk)82 )83 .join("");8485 const lines = text.split("\n").filter((line) => line.length > 0);8687 const replies = yield* Effect.forEach(lines, (line) =>88 Schema.decodeEffect(Message)(line)89 );9091 return new Map(replies.map((reply) => [reply.id, reply.result]));92 });
added:apps/cli/test/surfaces.test.ts+120 added
1import { describe, expect, it } from "@effect/vitest";2import { Contracts } from "@repo/protocol/contracts";3import { AskId, CommitSha, RepoPath } from "@repo/protocol/ids";4import { StaleBase } from "@repo/protocol/refusal";5import { Effect, Schema } from "effect";67import { session } from "./stdio.ts";89const ask = AskId.make("fix-parser");1011const base = CommitSha.make("1111111111111111111111111111111111111111");1213const main = CommitSha.make("2222222222222222222222222222222222222222");1415const head = CommitSha.make("3333333333333333333333333333333333333333");1617const refusal = new StaleBase({18 base,19 conflicts: [RepoPath.make("src/a.ts")],20 main,21});2223/** Contracts whose answers always meet a moved main. */24const stale = Contracts.toLayer({25 listAsks: () => Effect.succeed({ asks: [] }),26 submitAnswer: () => Effect.fail(refusal),27});2829const clientInfo = { name: "test", version: "0.0.0" };3031const initialize = (protocolVersion: string) => ({32 id: 1,33 jsonrpc: "2.0",34 method: "initialize",35 params: { capabilities: {}, clientInfo, protocolVersion },36});3738const Initialized = Schema.Struct({ protocolVersion: Schema.String });3940/** A tools/call result whose one content block is JSON text. */41const ToolResult = Schema.Struct({42 content: Schema.Tuple([43 Schema.Struct({44 text: Schema.fromJsonString(Schema.Unknown),45 type: Schema.Literal("text"),46 }),47 ]),48 isError: Schema.Boolean,49});5051describe("the CLI's MCP server over stdio", () => {52 it.effect("agrees each session-based protocol a client asks for", () =>53 Effect.gen(function* () {54 const versions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];5556 const agreed = yield* Effect.forEach(versions, (version) =>57 session(stale, [initialize(version)]).pipe(58 Effect.flatMap((replies) =>59 Schema.decodeUnknownEffect(Initialized)(replies.get(1))60 ),61 Effect.map((result) => result.protocolVersion)62 )63 );6465 expect(agreed).toStrictEqual(versions);66 })67 );6869 it.effect("answers discovery in the stateless 2026-07-28 protocol", () =>70 Effect.gen(function* () {71 const replies = yield* session(stale, [72 {73 id: 1,74 jsonrpc: "2.0",75 method: "server/discover",76 params: {77 _meta: {78 "io.modelcontextprotocol/clientCapabilities": {},79 "io.modelcontextprotocol/clientInfo": clientInfo,80 "io.modelcontextprotocol/protocolVersion": "2026-07-28",81 },82 },83 },84 ]);8586 const discovered = yield* Schema.decodeUnknownEffect(87 Schema.Struct({ supportedVersions: Schema.Array(Schema.String) })88 )(replies.get(1));8990 expect(discovered.supportedVersions).toContain("2026-07-28");91 })92 );9394 it.effect("returns a refusal as JSON that keeps its tag", () =>95 Effect.gen(function* () {96 const replies = yield* session(stale, [97 initialize("2025-11-25"),98 { jsonrpc: "2.0", method: "notifications/initialized" },99 {100 id: 2,101 jsonrpc: "2.0",102 method: "tools/call",103 params: { arguments: { ask, base, head }, name: "submitAnswer" },104 },105 ]);106107 const result = yield* Schema.decodeUnknownEffect(ToolResult)(108 replies.get(2)109 );110111 const [{ text }] = result.content;112113 expect(result.isError).toBeTruthy();114 expect(text).toHaveProperty("_tag", "StaleBase");115 expect(yield* Schema.decodeUnknownEffect(StaleBase)(text)).toStrictEqual(116 refusal117 );118 })119 );120});
added:apps/cli/package.json+21 added
added:apps/cli/tsconfig.json+7 added
added:apps/cli/vitest.config.ts+1 added
added:apps/platform/src/sessions/memory.ts+19 added
added:apps/platform/src/sessions.ts+11 added
added:apps/platform/src/surfaces.ts+154 added
1import { Brand } from "@repo/brand";2import { Client, Contracts } from "@repo/protocol/contracts";3import { toToolkit } from "@repo/protocol/mcp";4import {5 Authenticated,6 CurrentPrincipal,7 Unauthenticated,8} from "@repo/protocol/principal";9import { Effect, Layer, Option } from "effect";10import { McpProtocol, McpServer } from "effect/ai";11import {12 Headers,13 HttpRouter,14 HttpServerRequest,15 HttpServerResponse,16} from "effect/http";17import type { Rpc, RpcGroup } from "effect/rpc";18import {19 RpcMiddleware,20 RpcSerialization,21 RpcServer,22 RpcTest,23} from "effect/rpc";2425import { Sessions } from "./sessions.ts";2627/** What the surfaces need from the platform: the contracts' handlers and sessions. */28export type Services =29 | Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>30 | Sessions;3132/** The token in an `Authorization: Bearer <token>` header. */33const bearer = (authorization: string | undefined) =>34 /^Bearer (?<token>\S+)$/u.exec(authorization ?? "")?.groups?.token;3536/** The person an `Authorization` header names, if any. */37const principalOf = (sessions: Sessions["Service"], authorization?: string) => {38 const token = bearer(authorization);3940 return token === undefined ? Effect.succeedNone : sessions.verify(token);41};4243/**44 * Every request needs a credential the platform knows; anything else gets a45 * 401 that asks for a bearer token, before any surface sees it.46 */47const requireCredential = HttpRouter.middleware(48 Effect.gen(function* () {49 const sessions = yield* Sessions;5051 return (httpEffect) =>52 Effect.gen(function* () {53 const request = yield* HttpServerRequest.HttpServerRequest;5455 const principal = yield* principalOf(56 sessions,57 request.headers.authorization58 );5960 if (Option.isNone(principal)) {61 return HttpServerResponse.empty({62 headers: { "www-authenticate": "Bearer" },63 status: 401,64 });65 }6667 return yield* httpEffect;68 });69 }),70 { global: true }71);7273/** Server side: a call runs as the person its credential names, or not at all. */74const verifyCredential = Layer.effect(75 Authenticated,76 Effect.gen(function* () {77 const sessions = yield* Sessions;7879 return (effect, { headers }) =>80 Effect.gen(function* () {81 const principal = yield* principalOf(sessions, headers.authorization);8283 if (Option.isNone(principal)) {84 return yield* new Unauthenticated();85 }8687 return yield* Effect.provideService(88 effect,89 CurrentPrincipal,90 principal.value91 );92 });93 })94);9596/**97 * Client side, for calls made while serving an HTTP request: the call carries98 * that request's credential.99 */100const forwardCredential = RpcMiddleware.layerClient(101 Authenticated,102 ({ next, request }) =>103 Effect.gen(function* () {104 const incoming = yield* Effect.serviceOption(105 HttpServerRequest.HttpServerRequest106 );107108 const authorization = Option.flatMapNullishOr(109 incoming,110 ({ headers }) => headers.authorization111 );112113 return yield* next(114 Option.match(authorization, {115 onNone: () => request,116 onSome: (value) => ({117 ...request,118 headers: Headers.set(request.headers, "authorization", value),119 }),120 })121 );122 })123);124125const projection = toToolkit(Contracts, Effect.service(Client));126127/** The contracts as MCP tools at `/mcp`, each call made as the caller. */128const mcp = McpServer.toolkit(projection.toolkit).pipe(129 Layer.provideMerge(projection.layer),130 Layer.provide(Layer.effect(Client, RpcTest.makeClient(Contracts))),131 Layer.provide([verifyCredential, forwardCredential]),132 Layer.provide(133 McpServer.layerHttp({134 name: Brand.name,135 path: "/mcp",136 protocols: [McpProtocol.v2026_07_28],137 version: "0.0.0",138 })139 )140);141142/** The contracts over HTTP at `/rpc`, for the CLI and anything else remote. */143const rpc = RpcServer.layerHttp({144 group: Contracts,145 path: "/rpc",146 protocol: "http",147}).pipe(Layer.provide([verifyCredential, RpcSerialization.layerJson]));148149/** The platform's fetch handler over `services`. */150export const serve = (services: Layer.Layer<Services>) =>151 HttpRouter.toWebHandler(152 Layer.mergeAll(mcp, rpc, requireCredential).pipe(Layer.provide(services)),153 { disableLogger: true }154 );
added:apps/platform/test/harness.ts+130 added
1import { Contracts } from "@repo/protocol/contracts";2import { Effect, Layer, Schema } from "effect";3import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";4import { RpcClient, RpcSerialization } from "effect/rpc";56import { serve } from "../src/surfaces.ts";7import type { Services } from "../src/surfaces.ts";89const origin = "http://localhost";1011// MCP's 2026-07-28 protocol is stateless: each request names its version and12// client in `_meta` and repeats its method and target in headers.13const version = "2026-07-28";1415const meta = {16 "io.modelcontextprotocol/clientCapabilities": {},17 "io.modelcontextprotocol/clientInfo": { name: "test", version: "0.0.0" },18 "io.modelcontextprotocol/protocolVersion": version,19};2021/** A tools/call over MCP's HTTP transport, as `token`'s bearer if given. */22export const toolCall = (23 name: string,24 args: Readonly<Record<string, string>>,25 token?: string26) => {27 const headers = new Headers({28 accept: "application/json, text/event-stream",29 "content-type": "application/json",30 "mcp-method": "tools/call",31 "mcp-name": name,32 "mcp-protocol-version": version,33 });3435 if (token !== undefined) {36 headers.set("authorization", `Bearer ${token}`);37 }3839 return new Request(`${origin}/mcp`, {40 body: JSON.stringify({41 id: 1,42 jsonrpc: "2.0",43 method: "tools/call",44 params: { _meta: meta, arguments: args, name },45 }),46 headers,47 method: "POST",48 });49};5051/** A tools/call result whose one content block is JSON text. */52const ToolResult = Schema.Struct({53 content: Schema.Tuple([54 Schema.Struct({55 text: Schema.fromJsonString(Schema.Unknown),56 type: Schema.Literal("text"),57 }),58 ]),59 isError: Schema.Boolean,60});6162const Reply = Schema.fromJsonString(Schema.Struct({ result: ToolResult }));6364/** The last JSON-RPC message in a reply, which is plain JSON or an event stream. */65const lastMessage = (response: Response) =>66 Effect.promise(() => response.text()).pipe(67 Effect.map((text) =>68 response.headers.get("content-type")?.includes("text/event-stream") ===69 true70 ? (text71 .split("\n")72 .findLast((line) => line.startsWith("data: "))73 ?.slice("data: ".length) ?? "")74 : text75 )76 );7778/** A tool call's outcome: whether it failed, and its JSON. */79export const toolResult = (response: Response) =>80 lastMessage(response).pipe(81 Effect.flatMap(Schema.decodeEffect(Reply)),82 Effect.map(({ result }) => ({83 isError: result.isError,84 json: result.content[0].text,85 }))86 );8788/**89 * The platform's fetch handler over `services`, disposed with the scope: as90 * an Effect, and as the plain function a fetch client calls.91 */92export const served = Effect.fnUntraced(function* (93 services: Layer.Layer<Services>94) {95 const { dispose, handler } = serve(services);9697 yield* Effect.addFinalizer(() => Effect.promise(dispose));9899 return {100 fetch: (request: Request) => Effect.promise(() => handler(request)),101 handler,102 };103});104105/**106 * A client of the contracts over HTTP at `/rpc`, as the CLI makes one: its107 * requests go to `handler`, each with `token` as its HTTP bearer, which the108 * RPC server reads into every call's headers.109 */110export const rpcClient = (111 handler: (request: Request) => Promise<Response>,112 token: string113) => {114 const fetch: typeof globalThis.fetch = (input, init) =>115 handler(new Request(input, init));116117 return RpcClient.make(Contracts).pipe(118 Effect.provide(119 RpcClient.layerProtocolHttp({120 transformClient: HttpClient.mapRequest(121 HttpClientRequest.bearerToken(token)122 ),123 url: `${origin}/rpc`,124 }).pipe(125 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),126 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))127 )128 )129 );130};
added:apps/platform/test/surfaces.test.ts+124 added
1import { describe, expect, it } from "@effect/vitest";2import { Contracts } from "@repo/protocol/contracts";3import { AskId, CommitSha, Handle } from "@repo/protocol/ids";4import { CurrentPrincipal } from "@repo/protocol/principal";5import { NotClaimed } from "@repo/protocol/refusal";6import { Effect, Layer, Ref } from "effect";78import { MemorySessions } from "../src/sessions/memory.ts";9import { rpcClient, served, toolCall, toolResult } from "./harness.ts";1011const ask = AskId.make("fix-parser");1213const base = CommitSha.make("1111111111111111111111111111111111111111");1415const main = CommitSha.make("2222222222222222222222222222222222222222");1617const head = CommitSha.make("3333333333333333333333333333333333333333");1819const sessions = MemorySessions.layer({20 "alice-token": { handle: Handle.make("alice") },21 "bob-token": { handle: Handle.make("bob") },22});2324/** Contracts where only `holder` holds the ask's claim. */25const claimHeldBy = (holder: string) =>26 Contracts.toLayer({27 listAsks: () => Effect.succeed({ asks: [] }),28 submitAnswer: (payload) =>29 Effect.gen(function* () {30 const { handle } = yield* CurrentPrincipal;3132 if (handle !== holder) {33 return yield* NotClaimed.of(payload.ask);34 }3536 return { main };37 }),38 });3940describe("the platform's MCP surface", () => {41 it.effect("calls a tool as the principal its bearer token names", () =>42 Effect.gen(function* () {43 const { fetch } = yield* served(44 Layer.mergeAll(claimHeldBy("alice"), sessions)45 );4647 const args = { ask, base, head };4849 const asAlice = yield* toolResult(50 yield* fetch(toolCall("submitAnswer", args, "alice-token"))51 );5253 const asBob = yield* toolResult(54 yield* fetch(toolCall("submitAnswer", args, "bob-token"))55 );5657 expect(asAlice).toStrictEqual({ isError: false, json: { main } });58 expect(asBob.isError).toBeTruthy();59 expect(asBob.json).toHaveProperty("_tag", "NotClaimed");60 })61 );6263 it.effect(64 "turns away a call with no credential, or one it does not know",65 () =>66 Effect.gen(function* () {67 const calls = yield* Ref.make(0);6869 const { fetch } = yield* served(70 Layer.mergeAll(71 Contracts.toLayer({72 listAsks: () =>73 Ref.update(calls, (count) => count + 1).pipe(74 Effect.as({ asks: [] })75 ),76 submitAnswer: () =>77 Ref.update(calls, (count) => count + 1).pipe(78 Effect.as({ main })79 ),80 }),81 sessions82 )83 );8485 const args = { ask, base, head };8687 const responses = [88 yield* fetch(toolCall("submitAnswer", args)),89 yield* fetch(toolCall("submitAnswer", args, "mallory-token")),90 ];9192 expect(93 responses.map((response) => ({94 challenge: response.headers.get("www-authenticate"),95 status: response.status,96 }))97 ).toStrictEqual([98 { challenge: "Bearer", status: 401 },99 { challenge: "Bearer", status: 401 },100 ]);101 expect(yield* Ref.get(calls)).toBe(0);102 })103 );104});105106describe("the platform's RPC surface", () => {107 it.effect("calls a contract as the principal its bearer token names", () =>108 Effect.gen(function* () {109 const { handler } = yield* served(110 Layer.mergeAll(claimHeldBy("alice"), sessions)111 );112113 const args = { ask, base, head };114115 const alice = yield* rpcClient(handler, "alice-token");116 const bob = yield* rpcClient(handler, "bob-token");117118 expect(yield* alice.submitAnswer(args)).toStrictEqual({ main });119 expect(yield* Effect.flip(bob.submitAnswer(args))).toStrictEqual(120 NotClaimed.of(ask)121 );122 })123 );124});
added:apps/platform/package.json+21 added
added:apps/platform/tsconfig.json+8 added
added:apps/platform/vitest.config.ts+1 added
1export { preset as default } from "@repo/config/vitest";
modified:packages/protocol/src/cli.ts+6 added-9 removed
11 unmodified lines
12import { Argument, Command, Flag } from "effect/cli";13import type { Rpc, RpcClient, RpcClientError } from "effect/rpc";1415import { Description } from "./annotations.ts";16import type { Unauthenticated } from "./principal.ts";17import { Refusal } from "./refusal.ts";18import { explain } from "./render.ts";1919/** How a call can fail on its way to the handler and back. */20type TransportError = RpcClientError.RpcClientError;20/** How a call can fail before its handler runs: in transit, or unauthenticated. */21type CallError = RpcClientError.RpcClientError | Unauthenticated;2223/** A schema that needs no services to decode or encode, as every wire schema is. */24type Plain = Schema.Top & {25 readonly DecodingServices: never;
173 unmodified lines
199 * positional arguments), and the command calls the Rpc through `client`.200 */201export const toCommand = <R extends CommandRpc, Requirements>(202 rpc: R,202 client: Effect.Effect<203 RpcClient.RpcClient<R, TransportError>,204 never,205 Requirements206 >,203 client: Effect.Effect<RpcClient.RpcClient<R, CallError>, never, Requirements>,204 options?: ToCommandOptions<Rpc.Success<R>>205) => {206 const positional = new Set(options?.positional);207 const render = options?.render;
23 unmodified lines
231 (232 parsed233 ): Effect.Effect<234 void,238 Schema.SchemaError | Rpc.Error<R> | TransportError,235 Schema.SchemaError | Rpc.Error<R> | CallError,236 Requirements237 > =>238 Effect.gen(function* () {239 const { [JSON_FLAG]: json, ...fields } = parsed;
11 unmodified lines
251 Record<252 string,253 (254 decoded: typeof payload258 ) => Effect.Effect<Rpc.Success<R>, Rpc.Error<R> | TransportError>255 ) => Effect.Effect<Rpc.Success<R>, Rpc.Error<R> | CallError>256 >257 >;258259 const call =
18 unmodified lines
modified:packages/protocol/src/contracts.ts+4 added-1 removed
2 unmodified lines
3import type { RpcClient, RpcClientError } from "effect/rpc";45import { Description } from "./annotations.ts";6import { AskId, CommitSha, ProjectName } from "./ids.ts";7import { Authenticated } from "./principal.ts";8import { ClaimLapsed, NotClaimed, RepoBusy, StaleBase } from "./refusal.ts";910/** One open ask, as a list of asks shows it. */11export const AskListing = Schema.Struct({
17 unmodified lines
29 "Offer the commit `head`, built on `base`, as an answer to an ask; once it lands, `main` is the new tip."30) {}3132/** The one schema: every surface is a projection of this group. */32export class Contracts extends RpcGroup.make(ListAsks, SubmitAnswer) {}33export class Contracts extends RpcGroup.make(ListAsks, SubmitAnswer).middleware(34 Authenticated35) {}3637/** A way to call the contracts, in process or over the wire. */38export class Client extends Context.Service<39 Client,
5 unmodified lines
modified:packages/protocol/src/ids.ts+8 added
32 unmodified lines
33 Schema.brand("ProjectName")34);3536export type ProjectName = typeof ProjectName.Type;3738/** A person's handle on the platform, as their sign-in provider spells it. */39export const Handle = Schema.String.pipe(40 Schema.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9-]*$/u)),41 Schema.brand("Handle")42);4344export type Handle = typeof Handle.Type;
modified:packages/protocol/src/mcp.ts+5 added-7 removed
4 unmodified lines
5import { Tool, Toolkit } from "effect/ai";6import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";78import { Description } from "./annotations.ts";9import type { Unauthenticated } from "./principal.ts";1010/** How a call can fail on its way to the handler and back. */11type TransportError = RpcClientError.RpcClientError;11/** How a call can fail before its handler runs: in transit, or unauthenticated. */12type CallError = RpcClientError.RpcClientError | Unauthenticated;1314/** The tool an Rpc becomes: its payload as parameters, its errors as failures. */15export type ToolOf<R extends Rpc.Any> =16 R extends Rpc.Rpc<
39 unmodified lines
56 * encoded error, `_tag` and all.57 */58export const toToolkit = <Rpcs extends Rpc.AnyWithProps, R>(59 group: RpcGroup.RpcGroup<Rpcs>,59 client: Effect.Effect<RpcClient.RpcClient<Rpcs, TransportError>, never, R>60 client: Effect.Effect<RpcClient.RpcClient<Rpcs, CallError>, never, R>61): ToolkitProjection<Rpcs, R> => {62 const rpcs = [...group.requests.values()];6364 const made: unknown = Toolkit.make(...rpcs.map(toTool));
9 unmodified lines
74 Record<75 string,76 (77 payload: Rpc.Payload<Rpcs>77 ) => Effect.Effect<78 Rpc.Success<Rpcs>,79 Rpc.Error<Rpcs> | TransportError80 >78 ) => Effect.Effect<Rpc.Success<Rpcs>, Rpc.Error<Rpcs> | CallError>79 >80 >;8182 // Each handler passes the payload alone: the toolkit's second argument
16 unmodified lines
added:packages/protocol/src/principal.ts+30 added
1import { Context, Schema } from "effect";2import { RpcMiddleware } from "effect/rpc";34import { Handle } from "./ids.ts";56/** Who is calling: the person a verified credential names. */7export const Principal = Schema.Struct({ handle: Handle });89export type Principal = typeof Principal.Type;1011/** The caller of the contract being handled. */12export class CurrentPrincipal extends Context.Service<13 CurrentPrincipal,14 Principal15>()("protocol/CurrentPrincipal") {}1617/** The call carried no credential, or one the platform does not know. */18export class Unauthenticated extends Schema.TaggedError<Unauthenticated>()(19 "Unauthenticated",20 {}21) {}2223/**24 * Every contract runs as someone. A host's server side turns the call's25 * credential into the `CurrentPrincipal`; a client side attaches it.26 */27export class Authenticated extends RpcMiddleware.Service<28 Authenticated,29 { provides: CurrentPrincipal }30>()("protocol/Authenticated", { error: Unauthenticated }) {}
modified:packages/protocol/test/cli.test.ts+2 added-2 removed
8 unmodified lines
9import { 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";13import { asTester, ask, base, main, path } from "./examples.ts";1415const head = CommitSha.make("3333333333333333333333333333333333333333");1617/** Handlers that never refuse; `listAsks` echoes its project as the territory. */
37 unmodified lines
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)59 Layer.provide([handlers, asTester])60 )61 ).pipe(Layer.provideMerge(NodeServices.layer))62 )63 );
93 unmodified lines
modified:packages/protocol/test/examples.ts+10 added-2 removed
1import { DateTime } from "effect";1import { DateTime, Effect, Layer } from "effect";23import { AskId, CommitSha, RepoPath } from "../src/ids.ts";3import { AskId, CommitSha, Handle, RepoPath } from "../src/ids.ts";4import { Authenticated, CurrentPrincipal } from "../src/principal.ts";5import {6 AskFull,7 AttemptsExhausted,8 CapReached,
27 unmodified lines
36export const main = CommitSha.make("2222222222222222222222222222222222222222");3738export const path = RepoPath.make("src/a.ts");3940/** A server side that takes every call as one person, for tests about other things. */41export const asTester = Layer.succeed(Authenticated, (effect) =>42 Effect.provideService(effect, CurrentPrincipal, {43 handle: Handle.make("tester"),44 })45);4647// One of each member, in the union's order.48export const examples: readonly Refusal[] = [49 NotClaimed.of(ask),50 ClaimLapsed.of(ask),
32 unmodified lines
modified:packages/protocol/test/mcp.ts+2 added-1 removed
4 unmodified lines
5import { RpcTest } from "effect/rpc";67import { Client, Contracts } from "../src/contracts.ts";8import { toToolkit } from "../src/mcp.ts";9import { asTester } from "./examples.ts";1011const endpoint = "http://localhost/mcp";1213const protocol = McpProtocol.v2026_07_28;
39 unmodified lines
5354 const app = McpServer.toolkit(projection.toolkit).pipe(55 Layer.provideMerge(projection.layer),56 Layer.provide(Layer.effect(Client)(RpcTest.makeClient(Contracts))),56 Layer.provide(handlers),57 Layer.provide([handlers, asTester]),58 Layer.provide(59 McpServer.layerHttp({60 name: "test",61 path: "/mcp",
53 unmodified lines
modified:packages/protocol/package.json+1 added
6 unmodified lines
7 "./contracts": "./src/contracts.ts",8 "./ids": "./src/ids.ts",9 "./mcp": "./src/mcp.ts",10 "./posture": "./src/posture.ts",11 "./principal": "./src/principal.ts",12 "./refusal": "./src/refusal.ts",13 "./render": "./src/render.ts"14 },15 "scripts": {
16 unmodified lines
modified:bun.lock+34 added
18 unmodified lines
19 "ultracite": "7.12.4",20 "varlock": "1.21.1",21 },22 },23 "apps/cli": {24 "name": "@repo/cli",25 "dependencies": {26 "@repo/brand": "workspace:*",27 "@repo/protocol": "workspace:*",28 "effect": "catalog:",29 },30 "devDependencies": {31 "@effect/platform-node": "4.0.1",32 "@effect/vitest": "catalog:",33 "@repo/config": "workspace:*",34 "typescript": "catalog:",35 "vitest": "catalog:",36 },37 },38 "apps/platform": {39 "name": "@repo/platform",40 "dependencies": {41 "@repo/brand": "workspace:*",42 "@repo/protocol": "workspace:*",43 "effect": "catalog:",44 },45 "devDependencies": {46 "@cloudflare/workers-types": "5.20261006.1",47 "@effect/vitest": "catalog:",48 "@repo/config": "workspace:*",49 "typescript": "catalog:",50 "vitest": "catalog:",51 },52 },53 "packages/artifacts": {54 "name": "@repo/artifacts",55 "dependencies": {56 "@repo/protocol": "workspace:*",
303 unmodified lines
360 "@repo/artifacts": ["@repo/artifacts@workspace:packages/artifacts"],361362 "@repo/brand": ["@repo/brand@workspace:packages/brand"],363364 "@repo/cli": ["@repo/cli@workspace:apps/cli"],365366 "@repo/config": ["@repo/config@workspace:packages/config"],367368 "@repo/git": ["@repo/git@workspace:packages/git"],369370 "@repo/platform": ["@repo/platform@workspace:apps/platform"],371372 "@repo/protocol": ["@repo/protocol@workspace:packages/protocol"],373374 "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.12", "", { "os": "android", "cpu": "arm" }, "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A=="],375
509 unmodified lines
modified:tsconfig.base.json+17 added
71 unmodified lines
72 "allowedUnstableApis": ["effect/process"]73 }74 },75 {76 "include": ["apps/platform/**/*.ts"],77 "options": {78 "allowedUnstableApis": ["effect/ai", "effect/http", "effect/rpc"]79 }80 },81 {82 "include": ["apps/cli/**/*.ts"],83 "options": {84 "allowedUnstableApis": [85 "effect/ai",86 "effect/cli",87 "effect/http",88 "effect/rpc"89 ]90 }91 },92 {93 "include": ["packages/protocol/src/**/*.ts"],94 "options": {95 "allowedUnstableApis": ["effect/ai", "effect/cli", "effect/rpc"]96 }
23 unmodified lines