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.
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
Provenance
- Commit
19182a5- Tree
af32dfd- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
acf3649
25 files changed+863 added−22 removed
added:apps/cli/src/surfaces.ts+35 added
1234567891011121314151617181920212223242526272829303132333435import { Brand } from "@repo/brand";import { Client, Contracts } from "@repo/protocol/contracts";import { toToolkit } from "@repo/protocol/mcp";import { Effect, Layer } from "effect";import { McpProtocol, McpServer } from "effect/ai";import { Command } from "effect/cli";
const projection = toToolkit(Contracts, Effect.service(Client));
/** * The contracts as MCP tools over stdio, in every protocol a harness may * speak: the stateless 2026-07-28 one, and the four session-based ones before * it. Calls go through the `Client`. */const server = McpServer.toolkit(projection.toolkit).pipe( Layer.provideMerge(projection.layer), Layer.provide( McpServer.layerStdio({ name: Brand.name, protocols: [ McpProtocol.v2026_07_28, McpProtocol.v2025_11_25, McpProtocol.v2025_06_18, McpProtocol.v2025_03_26, McpProtocol.v2024_11_05, ], version: "0.0.0", }) ));
/** `mcp`: serve the contracts to a harness that spawned this process. */export const mcp = Command.make("mcp", {}, () => Layer.launch(server)).pipe( Command.withDescription("Serve the platform's tools over MCP on stdio."));added:apps/cli/test/stdio.ts+92 added
1+import { NodeServices } from "@effect/platform-node";2+import { Client, Contracts } from "@repo/protocol/contracts";3+import { Handle } from "@repo/protocol/ids";4+import { Authenticated, CurrentPrincipal } from "@repo/protocol/principal";5+import {6+ Effect,7+ Fiber,8+ Layer,9+ Predicate,10+ Queue,11+ Schema,12+ Sink,13+ Stdio,14+ Stream,15+} from "effect";16+import type { Cause } from "effect";17+import { CliOutput, Command } from "effect/cli";18+import type { Rpc, RpcGroup } from "effect/rpc";19+import { RpcTest } from "effect/rpc";20+21+import { mcp } from "../src/surfaces.ts";22+23+/** A server side that takes every call as one person. */24+const asTester = Layer.succeed(Authenticated, (effect) =>25+ Effect.provideService(effect, CurrentPrincipal, {26+ handle: Handle.make("tester"),27+ })28+);29+30+const Message = Schema.fromJsonString(31+ Schema.Struct({32+ id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Int])),33+ result: Schema.optionalKey(Schema.Unknown),34+ })35+);36+37+/**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+ */41+export 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();48+49+ 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+ });57+58+ // 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+ );74+75+ yield* Fiber.await(server);76+77+ const decoder = new TextDecoder();78+79+ const text = (yield* Queue.clear(written))80+ .map((chunk) =>81+ Predicate.isString(chunk) ? chunk : decoder.decode(chunk)82+ )83+ .join("");84+85+ const lines = text.split("\n").filter((line) => line.length > 0);86+87+ const replies = yield* Effect.forEach(lines, (line) =>88+ Schema.decodeEffect(Message)(line)89+ );90+91+ return new Map(replies.map((reply) => [reply.id, reply.result]));92+ });added:apps/cli/test/surfaces.test.ts+120 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Contracts } from "@repo/protocol/contracts";3+import { AskId, CommitSha, RepoPath } from "@repo/protocol/ids";4+import { StaleBase } from "@repo/protocol/refusal";5+import { Effect, Schema } from "effect";6+7+import { session } from "./stdio.ts";8+9+const ask = AskId.make("fix-parser");10+11+const base = CommitSha.make("1111111111111111111111111111111111111111");12+13+const main = CommitSha.make("2222222222222222222222222222222222222222");14+15+const head = CommitSha.make("3333333333333333333333333333333333333333");16+17+const refusal = new StaleBase({18+ base,19+ conflicts: [RepoPath.make("src/a.ts")],20+ main,21+});22+23+/** Contracts whose answers always meet a moved main. */24+const stale = Contracts.toLayer({25+ listAsks: () => Effect.succeed({ asks: [] }),26+ submitAnswer: () => Effect.fail(refusal),27+});28+29+const clientInfo = { name: "test", version: "0.0.0" };30+31+const initialize = (protocolVersion: string) => ({32+ id: 1,33+ jsonrpc: "2.0",34+ method: "initialize",35+ params: { capabilities: {}, clientInfo, protocolVersion },36+});37+38+const Initialized = Schema.Struct({ protocolVersion: Schema.String });39+40+/** A tools/call result whose one content block is JSON text. */41+const 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+});50+51+describe("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"];55+56+ 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+ );64+65+ expect(agreed).toStrictEqual(versions);66+ })67+ );68+69+ 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+ ]);85+86+ const discovered = yield* Schema.decodeUnknownEffect(87+ Schema.Struct({ supportedVersions: Schema.Array(Schema.String) })88+ )(replies.get(1));89+90+ expect(discovered.supportedVersions).toContain("2026-07-28");91+ })92+ );93+94+ 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+ ]);106+107+ const result = yield* Schema.decodeUnknownEffect(ToolResult)(108+ replies.get(2)109+ );110+111+ const [{ text }] = result.content;112+113+ 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
123456789101112131415161718192021{ "name": "@repo/cli", "private": true, "type": "module", "scripts": { "typecheck": "tsc --noEmit -p tsconfig.json", "test": "vitest run" }, "dependencies": { "@repo/brand": "workspace:*", "@repo/protocol": "workspace:*", "effect": "catalog:" }, "devDependencies": { "@effect/platform-node": "4.0.1", "@effect/vitest": "catalog:", "@repo/config": "workspace:*", "typescript": "catalog:", "vitest": "catalog:" }}added:apps/cli/tsconfig.json+7 added
1234567{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true }, "include": ["src/**/*.ts", "test/**/*.ts", "*.config.ts"]}added:apps/cli/vitest.config.ts+1 added
1export { preset as default } from "@repo/config/vitest";added:apps/platform/src/sessions/memory.ts+19 added
12345678910111213141516171819import type { Principal } from "@repo/protocol/principal";import { Effect, Layer, Option } from "effect";
import { Sessions } from "../sessions.ts";
/** Sessions from a fixed table of tokens, for tests and local runs. */export const MemorySessions = { layer: (tokens: Readonly<Record<string, Principal>>) => { const byToken = new Map(Object.entries(tokens));
return Layer.succeed( Sessions, Sessions.of({ verify: (token) => Effect.succeed(Option.fromNullishOr(byToken.get(token))), }) ); },};added:apps/platform/src/sessions.ts+11 added
1234567891011import type { Principal } from "@repo/protocol/principal";import { Context } from "effect";import type { Effect, Option } from "effect";
/** Turns a bearer credential into the person it names, if it names anyone. */export class Sessions extends Context.Service< Sessions, { readonly verify: (token: string) => Effect.Effect<Option.Option<Principal>>; }>()("platform/Sessions") {}added:apps/platform/src/surfaces.ts+154 added
1+import { Brand } from "@repo/brand";2+import { Client, Contracts } from "@repo/protocol/contracts";3+import { toToolkit } from "@repo/protocol/mcp";4+import {5+ Authenticated,6+ CurrentPrincipal,7+ Unauthenticated,8+} from "@repo/protocol/principal";9+import { Effect, Layer, Option } from "effect";10+import { McpProtocol, McpServer } from "effect/ai";11+import {12+ Headers,13+ HttpRouter,14+ HttpServerRequest,15+ HttpServerResponse,16+} from "effect/http";17+import type { Rpc, RpcGroup } from "effect/rpc";18+import {19+ RpcMiddleware,20+ RpcSerialization,21+ RpcServer,22+ RpcTest,23+} from "effect/rpc";24+25+import { Sessions } from "./sessions.ts";26+27+/** What the surfaces need from the platform: the contracts' handlers and sessions. */28+export type Services =29+ | Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>30+ | Sessions;31+32+/** The token in an `Authorization: Bearer <token>` header. */33+const bearer = (authorization: string | undefined) =>34+ /^Bearer (?<token>\S+)$/u.exec(authorization ?? "")?.groups?.token;35+36+/** The person an `Authorization` header names, if any. */37+const principalOf = (sessions: Sessions["Service"], authorization?: string) => {38+ const token = bearer(authorization);39+40+ return token === undefined ? Effect.succeedNone : sessions.verify(token);41+};42+43+/**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+ */47+const requireCredential = HttpRouter.middleware(48+ Effect.gen(function* () {49+ const sessions = yield* Sessions;50+51+ return (httpEffect) =>52+ Effect.gen(function* () {53+ const request = yield* HttpServerRequest.HttpServerRequest;54+55+ const principal = yield* principalOf(56+ sessions,57+ request.headers.authorization58+ );59+60+ if (Option.isNone(principal)) {61+ return HttpServerResponse.empty({62+ headers: { "www-authenticate": "Bearer" },63+ status: 401,64+ });65+ }66+67+ return yield* httpEffect;68+ });69+ }),70+ { global: true }71+);72+73+/** Server side: a call runs as the person its credential names, or not at all. */74+const verifyCredential = Layer.effect(75+ Authenticated,76+ Effect.gen(function* () {77+ const sessions = yield* Sessions;78+79+ return (effect, { headers }) =>80+ Effect.gen(function* () {81+ const principal = yield* principalOf(sessions, headers.authorization);82+83+ if (Option.isNone(principal)) {84+ return yield* new Unauthenticated();85+ }86+87+ return yield* Effect.provideService(88+ effect,89+ CurrentPrincipal,90+ principal.value91+ );92+ });93+ })94+);95+96+/**97+ * Client side, for calls made while serving an HTTP request: the call carries98+ * that request's credential.99+ */100+const forwardCredential = RpcMiddleware.layerClient(101+ Authenticated,102+ ({ next, request }) =>103+ Effect.gen(function* () {104+ const incoming = yield* Effect.serviceOption(105+ HttpServerRequest.HttpServerRequest106+ );107+108+ const authorization = Option.flatMapNullishOr(109+ incoming,110+ ({ headers }) => headers.authorization111+ );112+113+ 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+);124+125+const projection = toToolkit(Contracts, Effect.service(Client));126+127+/** The contracts as MCP tools at `/mcp`, each call made as the caller. */128+const 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+);141+142+/** The contracts over HTTP at `/rpc`, for the CLI and anything else remote. */143+const rpc = RpcServer.layerHttp({144+ group: Contracts,145+ path: "/rpc",146+ protocol: "http",147+}).pipe(Layer.provide([verifyCredential, RpcSerialization.layerJson]));148+149+/** The platform's fetch handler over `services`. */150+export 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
1+import { Contracts } from "@repo/protocol/contracts";2+import { Effect, Layer, Schema } from "effect";3+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";4+import { RpcClient, RpcSerialization } from "effect/rpc";5+6+import { serve } from "../src/surfaces.ts";7+import type { Services } from "../src/surfaces.ts";8+9+const origin = "http://localhost";10+11+// 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.13+const version = "2026-07-28";14+15+const meta = {16+ "io.modelcontextprotocol/clientCapabilities": {},17+ "io.modelcontextprotocol/clientInfo": { name: "test", version: "0.0.0" },18+ "io.modelcontextprotocol/protocolVersion": version,19+};20+21+/** A tools/call over MCP's HTTP transport, as `token`'s bearer if given. */22+export 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+ });34+35+ if (token !== undefined) {36+ headers.set("authorization", `Bearer ${token}`);37+ }38+39+ 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+};50+51+/** A tools/call result whose one content block is JSON text. */52+const 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+});61+62+const Reply = Schema.fromJsonString(Schema.Struct({ result: ToolResult }));63+64+/** The last JSON-RPC message in a reply, which is plain JSON or an event stream. */65+const 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+ );77+78+/** A tool call's outcome: whether it failed, and its JSON. */79+export 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+ );87+88+/**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+ */92+export const served = Effect.fnUntraced(function* (93+ services: Layer.Layer<Services>94+) {95+ const { dispose, handler } = serve(services);96+97+ yield* Effect.addFinalizer(() => Effect.promise(dispose));98+99+ return {100+ fetch: (request: Request) => Effect.promise(() => handler(request)),101+ handler,102+ };103+});104+105+/**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+ */110+export 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));116+117+ 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
1+import { describe, expect, it } from "@effect/vitest";2+import { Contracts } from "@repo/protocol/contracts";3+import { AskId, CommitSha, Handle } from "@repo/protocol/ids";4+import { CurrentPrincipal } from "@repo/protocol/principal";5+import { NotClaimed } from "@repo/protocol/refusal";6+import { Effect, Layer, Ref } from "effect";7+8+import { MemorySessions } from "../src/sessions/memory.ts";9+import { rpcClient, served, toolCall, toolResult } from "./harness.ts";10+11+const ask = AskId.make("fix-parser");12+13+const base = CommitSha.make("1111111111111111111111111111111111111111");14+15+const main = CommitSha.make("2222222222222222222222222222222222222222");16+17+const head = CommitSha.make("3333333333333333333333333333333333333333");18+19+const sessions = MemorySessions.layer({20+ "alice-token": { handle: Handle.make("alice") },21+ "bob-token": { handle: Handle.make("bob") },22+});23+24+/** Contracts where only `holder` holds the ask's claim. */25+const claimHeldBy = (holder: string) =>26+ Contracts.toLayer({27+ listAsks: () => Effect.succeed({ asks: [] }),28+ submitAnswer: (payload) =>29+ Effect.gen(function* () {30+ const { handle } = yield* CurrentPrincipal;31+32+ if (handle !== holder) {33+ return yield* NotClaimed.of(payload.ask);34+ }35+36+ return { main };37+ }),38+ });39+40+describe("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+ );46+47+ const args = { ask, base, head };48+49+ const asAlice = yield* toolResult(50+ yield* fetch(toolCall("submitAnswer", args, "alice-token"))51+ );52+53+ const asBob = yield* toolResult(54+ yield* fetch(toolCall("submitAnswer", args, "bob-token"))55+ );56+57+ expect(asAlice).toStrictEqual({ isError: false, json: { main } });58+ expect(asBob.isError).toBeTruthy();59+ expect(asBob.json).toHaveProperty("_tag", "NotClaimed");60+ })61+ );62+63+ 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);68+69+ 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+ );84+85+ const args = { ask, base, head };86+87+ const responses = [88+ yield* fetch(toolCall("submitAnswer", args)),89+ yield* fetch(toolCall("submitAnswer", args, "mallory-token")),90+ ];91+92+ 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+});105+106+describe("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+ );112+113+ const args = { ask, base, head };114+115+ const alice = yield* rpcClient(handler, "alice-token");116+ const bob = yield* rpcClient(handler, "bob-token");117+118+ 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
123456789101112131415161718192021{ "name": "@repo/platform", "private": true, "type": "module", "scripts": { "typecheck": "tsc --noEmit -p tsconfig.json", "test": "vitest run" }, "dependencies": { "@repo/brand": "workspace:*", "@repo/protocol": "workspace:*", "effect": "catalog:" }, "devDependencies": { "@cloudflare/workers-types": "5.20261006.1", "@effect/vitest": "catalog:", "@repo/config": "workspace:*", "typescript": "catalog:", "vitest": "catalog:" }}added:apps/platform/tsconfig.json+8 added
12345678{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true, "types": ["@cloudflare/workers-types"] }, "include": ["src/**/*.ts", "test/**/*.ts", "*.config.ts"]}added:apps/platform/vitest.config.ts+1 added
1+export { preset as default } from "@repo/config/vitest";modified:packages/protocol/src/cli.ts+6 added-9 removed
11 unmodified lines12 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 type { Unauthenticated } from "./principal.ts";17 import { Refusal } from "./refusal.ts";18 import { explain } from "./render.ts";19 19-/** How a call can fail on its way to the handler and back. */20-type TransportError = RpcClientError.RpcClientError;20+/** How a call can fail before its handler runs: in transit, or unauthenticated. */21+type CallError = RpcClientError.RpcClientError | Unauthenticated;22 23 /** A schema that needs no services to decode or encode, as every wire schema is. */24 type Plain = Schema.Top & {25 readonly DecodingServices: never;173 unmodified lines199 * positional arguments), and the command calls the Rpc through `client`.200 */201 export 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 lines231 (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 lines251 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 >;258 259 const call =18 unmodified linesmodified:packages/protocol/src/contracts.ts+4 added-1 removed
2 unmodified lines3 import type { RpcClient, RpcClientError } from "effect/rpc";4 5 import { Description } from "./annotations.ts";6 import { AskId, CommitSha, ProjectName } from "./ids.ts";7+import { Authenticated } from "./principal.ts";8 import { ClaimLapsed, NotClaimed, RepoBusy, StaleBase } from "./refusal.ts";9 10 /** One open ask, as a list of asks shows it. */11 export const AskListing = Schema.Struct({17 unmodified lines29 "Offer the commit `head`, built on `base`, as an answer to an ask; once it lands, `main` is the new tip."30 ) {}31 32 /** The one schema: every surface is a projection of this group. */32-export class Contracts extends RpcGroup.make(ListAsks, SubmitAnswer) {}33+export class Contracts extends RpcGroup.make(ListAsks, SubmitAnswer).middleware(34+ Authenticated35+) {}36 37 /** A way to call the contracts, in process or over the wire. */38 export class Client extends Context.Service<39 Client,5 unmodified linesmodified:packages/protocol/src/ids.ts+8 added
32 unmodified lines33 Schema.brand("ProjectName")34 );35 36 export type ProjectName = typeof ProjectName.Type;37+38+/** A person's handle on the platform, as their sign-in provider spells it. */39+export const Handle = Schema.String.pipe(40+ Schema.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9-]*$/u)),41+ Schema.brand("Handle")42+);43+44+export type Handle = typeof Handle.Type;modified:packages/protocol/src/mcp.ts+5 added-7 removed
4 unmodified lines5 import { Tool, Toolkit } from "effect/ai";6 import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";7 8 import { Description } from "./annotations.ts";9+import type { Unauthenticated } from "./principal.ts";10 10-/** How a call can fail on its way to the handler and back. */11-type TransportError = RpcClientError.RpcClientError;11+/** How a call can fail before its handler runs: in transit, or unauthenticated. */12+type CallError = RpcClientError.RpcClientError | Unauthenticated;13 14 /** The tool an Rpc becomes: its payload as parameters, its errors as failures. */15 export type ToolOf<R extends Rpc.Any> =16 R extends Rpc.Rpc<39 unmodified lines56 * encoded error, `_tag` and all.57 */58 export 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()];63 64 const made: unknown = Toolkit.make(...rpcs.map(toTool));9 unmodified lines74 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 >;81 82 // Each handler passes the payload alone: the toolkit's second argument16 unmodified linesadded:packages/protocol/src/principal.ts+30 added
1+import { Context, Schema } from "effect";2+import { RpcMiddleware } from "effect/rpc";3+4+import { Handle } from "./ids.ts";5+6+/** Who is calling: the person a verified credential names. */7+export const Principal = Schema.Struct({ handle: Handle });8+9+export type Principal = typeof Principal.Type;10+11+/** The caller of the contract being handled. */12+export class CurrentPrincipal extends Context.Service<13+ CurrentPrincipal,14+ Principal15+>()("protocol/CurrentPrincipal") {}16+17+/** The call carried no credential, or one the platform does not know. */18+export class Unauthenticated extends Schema.TaggedError<Unauthenticated>()(19+ "Unauthenticated",20+ {}21+) {}22+23+/**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+ */27+export 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 lines9 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";13+import { asTester, 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. */37 unmodified lines55 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 linesmodified:packages/protocol/test/examples.ts+10 added-2 removed
1-import { DateTime } from "effect";1+import { DateTime, Effect, Layer } from "effect";2 3-import { AskId, CommitSha, RepoPath } from "../src/ids.ts";3+import { AskId, CommitSha, Handle, RepoPath } from "../src/ids.ts";4+import { Authenticated, CurrentPrincipal } from "../src/principal.ts";5 import {6 AskFull,7 AttemptsExhausted,8 CapReached,27 unmodified lines36 export const main = CommitSha.make("2222222222222222222222222222222222222222");37 38 export const path = RepoPath.make("src/a.ts");39 40+/** A server side that takes every call as one person, for tests about other things. */41+export const asTester = Layer.succeed(Authenticated, (effect) =>42+ Effect.provideService(effect, CurrentPrincipal, {43+ handle: Handle.make("tester"),44+ })45+);46+47 // One of each member, in the union's order.48 export const examples: readonly Refusal[] = [49 NotClaimed.of(ask),50 ClaimLapsed.of(ask),32 unmodified linesmodified:packages/protocol/test/mcp.ts+2 added-1 removed
4 unmodified lines5 import { RpcTest } from "effect/rpc";6 7 import { Client, Contracts } from "../src/contracts.ts";8 import { toToolkit } from "../src/mcp.ts";9+import { asTester } from "./examples.ts";10 11 const endpoint = "http://localhost/mcp";12 13 const protocol = McpProtocol.v2026_07_28;39 unmodified lines53 54 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 linesmodified:packages/protocol/package.json+1 added
6 unmodified lines7 "./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 linesmodified:bun.lock+34 added
18 unmodified lines19 "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 lines360 "@repo/artifacts": ["@repo/artifacts@workspace:packages/artifacts"],361 362 "@repo/brand": ["@repo/brand@workspace:packages/brand"],363 364+ "@repo/cli": ["@repo/cli@workspace:apps/cli"],365+366 "@repo/config": ["@repo/config@workspace:packages/config"],367 368 "@repo/git": ["@repo/git@workspace:packages/git"],369 370+ "@repo/platform": ["@repo/platform@workspace:apps/platform"],371+372 "@repo/protocol": ["@repo/protocol@workspace:packages/protocol"],373 374 "@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 linesmodified:tsconfig.base.json+17 added
71 unmodified lines72 "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