@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 395 lines 15.7 KB
Raw
1 import * as Domain from "@alchemy.run/domain";
2 import * as DomainAi from "@alchemy.run/domain/Ai";
3 import { InMemory } from "@alchemy.run/domain/InMemory";
4 import { describe, expect, it } from "@alchemy.run/test";
5 import { McpProtocol, McpServer, Tool } from "effect/ai";
6 import * as Cause from "effect/Cause";
7 import * as Context from "effect/Context";
8 import * as Effect from "effect/Effect";
9 import * as Exit from "effect/Exit";
10 import * as Headers from "effect/http/Headers";
11 import * as HttpRouter from "effect/http/HttpRouter";
12 import * as Layer from "effect/Layer";
13 import * as Option from "effect/Option";
14 import type * as Rpc from "effect/rpc/Rpc";
15 import * as RpcMiddleware from "effect/rpc/RpcMiddleware";
16 import * as Schema from "effect/Schema";
17 import * as Stream from "effect/Stream";
18
19 // ---------------------------------------------------------------- a wallet domain
20
21 const WalletId = Schema.String.pipe(Schema.brand("WalletId"));
22
23 class Owner extends Domain.RequestContext<Owner>()("Test/Owner", Schema.String) {}
24 class Unauthenticated extends Domain.Rejection("Unauthenticated") {}
25 class Session extends RpcMiddleware.Service<Session, { provides: Owner }>()("Test/Session", {
26 error: Unauthenticated,
27 }) {}
28 /** The owner is the `x-owner` header; no header, no session. */
29 const SessionLive = Layer.succeed(Session, (effect, { headers }) =>
30 Option.match(Headers.get(headers, "x-owner"), {
31 onNone: () => Effect.fail(new Unauthenticated()),
32 onSome: (owner) => Effect.provideService(effect, Owner, owner),
33 }),
34 );
35
36 class Deposited extends Domain.Event("Deposited", { amount: Schema.Int, balance: Schema.Int }) {}
37 class OverLimit extends Domain.Rejection("OverLimit", { limit: Schema.Int }) {}
38 class NotOwner extends Domain.Rejection("NotOwner") {}
39
40 class Deposit extends Domain.Command("Deposit", {
41 target: WalletId,
42 input: { amount: Schema.Int },
43 middleware: [Session],
44 events: [Deposited],
45 rejects: [OverLimit],
46 reply: { balance: Schema.Int },
47 }) {}
48
49 class Wallet extends Domain.Aggregate("Wallet", {
50 id: WalletId,
51 state: Schema.Struct({ balance: Schema.Int }),
52 initial: { balance: 0 },
53 commands: [Deposit],
54 decide: {
55 Deposit: (s, cmd) =>
56 cmd.amount > 100
57 ? new OverLimit({ limit: 100 })
58 : [new Deposited({ amount: cmd.amount, balance: s.balance + cmd.amount })],
59 },
60 evolve: { Deposited: (_, e) => ({ balance: e.balance }) },
61 reply: { Deposit: (s) => ({ balance: s.balance }) },
62 }) {}
63
64 /** Only the wallet's owner may read its balance. */
65 class Balance extends Domain.View("Balance", {
66 from: [Wallet],
67 key: Wallet,
68 middleware: [Session],
69 rejects: [NotOwner],
70 validate: Effect.fn(function* ({ key }) {
71 if (`${yield* Owner}-wallet` !== key.id) return yield* new NotOwner();
72 }),
73 state: Schema.Struct({ balance: Schema.Int }),
74 initial: { balance: 0 },
75 evolve: { Deposited: (_, e) => ({ balance: e.balance }) },
76 }) {}
77
78 class Wallets extends Domain.Model("Wallets", { aggregates: [Wallet], views: [Balance] }) {}
79
80 class WalletApi extends Domain.Api("WalletApi", { model: Wallets }) {}
81
82 const WalletsLive = Layer.mergeAll(Wallets.layer(Layer.empty), SessionLive).pipe(
83 Layer.provide(InMemory),
84 );
85
86 /** Who the agent acts for, in this test: the owner its calls carry. */
87 const ActingFor = Context.Reference<string | undefined>("Test/ActingFor", {
88 defaultValue: () => undefined,
89 });
90
91 const walletTools = DomainAi.toToolkit(WalletApi, {
92 headers: Effect.map(ActingFor, (owner): Headers.Input => (owner ? { "x-owner": owner } : {})),
93 });
94
95 /** Call a tool as a model would, with JSON, and get its final result. */
96 const call = (name: string, params: unknown, owner?: string) =>
97 Effect.gen(function* () {
98 const toolkit = yield* walletTools.toolkit;
99 const results = yield* toolkit.handle(name, params as never);
100 const last = yield* Stream.runLast(results).pipe(Effect.flatMap(Effect.fromOption));
101 return { isFailure: last.isFailure, encoded: last.encodedResult as unknown };
102 }).pipe(Effect.provideService(ActingFor, owner));
103
104 const ToolsLive = walletTools.layer.pipe(Layer.provideMerge(WalletsLive));
105
106 /** The session's client half, as a server that makes its own calls would hold it. */
107 const ServerCredential = RpcMiddleware.layerClient(Session, ({ request, next }) =>
108 next({ ...request, headers: Headers.set(request.headers, "x-owner", "server") }),
109 );
110
111 // ---------------------------------------------------------------- tests
112
113 describe("Domain Ai: toToolkit", { tags: ["unit", "local"] }, () => {
114 it("has one tool per call that returns once, with the Api's schemas", () => {
115 const { toolkit } = DomainAi.toToolkit(WalletApi);
116 expect(Object.keys(toolkit.tools)).toEqual([
117 "WalletApi_Deposit_send",
118 "WalletApi_Balance_get",
119 "WalletApi_Balance_list",
120 "WalletApi_Balance_snapshot",
121 ]);
122 /** The JSON Schema of the JSON a schema reads and writes on the wire. */
123 const wire = (schema: Schema.Top) => Tool.getJsonSchemaFromSchema(Schema.toCodecJson(schema));
124 const depositRpc = WalletApi.group.requests.get("Deposit") as Rpc.AnyWithProps;
125 const getRpc = WalletApi.group.requests.get("Balance.get") as Rpc.AnyWithProps;
126 const send = toolkit.tools.WalletApi_Deposit_send!;
127 // The tool's parameters are the call's own wire payload.
128 expect(Tool.getJsonSchema(send)).toEqual(wire(depositRpc.payloadSchema));
129 expect(Tool.getJsonSchema(send)).toMatchObject({
130 properties: { target: {}, commandId: {}, input: { properties: { amount: {} } } },
131 });
132 expect(Tool.getJsonSchemaFromSchema(send.successSchema)).toEqual(
133 wire(depositRpc.successSchema),
134 );
135 // Its failure is the command's rejection and its middleware's error.
136 const failure = JSON.stringify(Tool.getJsonSchemaFromSchema(send.failureSchema));
137 for (const tag of ["OverLimit", "Unauthenticated"]) expect(failure).toContain(tag);
138 expect(Tool.getDescription(send)).toBe("Send the Deposit command.");
139 // A read is read-only; a command is a write.
140 const get = toolkit.tools.WalletApi_Balance_get!;
141 expect(Tool.getJsonSchema(get)).toEqual(wire(getRpc.payloadSchema));
142 expect(Context.get(get.annotations, Tool.Readonly)).toBe(true);
143 expect(Context.get(get.annotations, Tool.Destructive)).toBe(false);
144 expect(Context.get(send.annotations, Tool.Readonly)).toBe(false);
145 expect(Context.get(send.annotations, Tool.Destructive)).toBe(true);
146 // `state | null` is not an object, so the tool returns it as `{ value }`.
147 expect(Tool.getJsonSchemaFromSchema(get.successSchema)).toEqual({
148 type: "object",
149 properties: { value: wire(getRpc.successSchema) },
150 required: ["value"],
151 additionalProperties: true,
152 });
153 });
154
155 it.live("a write tool sends the command and returns its receipt", () =>
156 Effect.gen(function* () {
157 const result = yield* call(
158 "WalletApi_Deposit_send",
159 { target: "sam-wallet", input: { amount: 30 } },
160 "sam",
161 );
162 expect(result).toEqual({
163 isFailure: false,
164 encoded: { reply: { balance: 30 }, stream: "Wallet/sam-wallet", version: 1 },
165 });
166 }).pipe(Effect.provide(ToolsLive)),
167 );
168
169 it.live("a rejection comes back as the tool's typed failure", () =>
170 Effect.gen(function* () {
171 const result = yield* call(
172 "WalletApi_Deposit_send",
173 { target: "sam-wallet", input: { amount: 500 } },
174 "sam",
175 );
176 expect(result).toEqual({ isFailure: true, encoded: { _tag: "OverLimit", limit: 100 } });
177 }).pipe(Effect.provide(ToolsLive)),
178 );
179
180 it.live("the call runs the Api's middleware: no session, no command", () =>
181 Effect.gen(function* () {
182 const result = yield* call("WalletApi_Deposit_send", {
183 target: "sam-wallet",
184 input: { amount: 5 },
185 });
186 expect(result).toEqual({ isFailure: true, encoded: { _tag: "Unauthenticated" } });
187 // Nothing was recorded.
188 const balance = yield* call("WalletApi_Balance_get", { key: "sam-wallet" }, "sam");
189 expect(balance.encoded).toEqual({ value: null });
190 }).pipe(Effect.provide(ToolsLive)),
191 );
192
193 it.live("a middleware's client half never signs the agent in as the server", () =>
194 Effect.gen(function* () {
195 const result = yield* call("WalletApi_Deposit_send", {
196 target: "server-wallet",
197 input: { amount: 5 },
198 });
199 expect(result).toEqual({ isFailure: true, encoded: { _tag: "Unauthenticated" } });
200 }).pipe(Effect.provide(ToolsLive.pipe(Layer.provide(ServerCredential)))),
201 );
202
203 it.live("a read tool runs the view's validate, and wraps a value that is not an object", () =>
204 Effect.gen(function* () {
205 const receipt = yield* call(
206 "WalletApi_Deposit_send",
207 { target: "sam-wallet", input: { amount: 7 } },
208 "sam",
209 );
210 const atLeast = { stream: "Wallet/sam-wallet", version: 1 };
211 expect(receipt.isFailure).toBe(false);
212 expect(yield* call("WalletApi_Balance_get", { key: "sam-wallet", atLeast }, "sam")).toEqual({
213 isFailure: false,
214 encoded: { value: { balance: 7 } },
215 });
216 expect(yield* call("WalletApi_Balance_get", { key: "sam-wallet" }, "kim")).toEqual({
217 isFailure: true,
218 encoded: { _tag: "NotOwner" },
219 });
220 }).pipe(Effect.provide(ToolsLive)),
221 );
222
223 it.live("a tool name a model provider would refuse fails the Layer with a DefinitionError", () =>
224 Effect.gen(function* () {
225 class LongApi extends Domain.Api("A".repeat(60), { model: Wallets, views: [] }) {}
226 const exit = yield* Layer.build(DomainAi.toToolkit(LongApi).layer).pipe(
227 Effect.provide(WalletsLive),
228 Effect.scoped,
229 Effect.exit,
230 );
231 expect(Exit.isFailure(exit) && Cause.squash(exit.cause)).toMatchObject({
232 _tag: "DefinitionError",
233 message: `The tool name ${"A".repeat(60)}_Deposit_send is longer than 64 characters`,
234 });
235 }),
236 );
237 });
238
239 // ---------------------------------------------------------------- MCP
240
241 /** An MCP client over the server's web handler, in process. */
242 const mcpClient = (handler: (request: Request) => Promise<Response>) => {
243 let session: string | undefined;
244 let id = 0;
245 const post = Effect.fn(function* (body: object, headers: Record<string, string> = {}) {
246 const response = yield* Effect.promise(() =>
247 handler(
248 new Request("http://localhost/mcp", {
249 method: "POST",
250 headers: {
251 "content-type": "application/json",
252 accept: "application/json, text/event-stream",
253 "mcp-protocol-version": "2025-11-25",
254 ...(session ? { "mcp-session-id": session } : {}),
255 ...headers,
256 },
257 body: JSON.stringify({ jsonrpc: "2.0", ...body }),
258 }),
259 ),
260 );
261 session ??= response.headers.get("mcp-session-id") ?? undefined;
262 const text = yield* Effect.promise(() => response.text());
263 return text === "" ? undefined : (JSON.parse(text) as { result?: any; error?: any });
264 });
265 const request = (method: string, params: object, headers?: Record<string, string>) =>
266 post({ id: ++id, method, params }, headers);
267 const connect = Effect.gen(function* () {
268 yield* request("initialize", {
269 protocolVersion: "2025-11-25",
270 capabilities: {},
271 clientInfo: { name: "test", version: "1.0.0" },
272 });
273 yield* post({ method: "notifications/initialized" });
274 });
275 return { connect, request };
276 };
277
278 describe("Domain Ai: toMcp", { tags: ["unit", "local"] }, () => {
279 it.live("serves the tools over MCP; a call carries the request's headers to the Api", () =>
280 Effect.gen(function* () {
281 const { handler, dispose } = HttpRouter.toWebHandler(
282 DomainAi.toMcp(WalletApi).pipe(
283 Layer.provide(
284 McpServer.layerHttp({
285 name: "wallet",
286 version: "1.0.0",
287 path: "/mcp",
288 protocols: [McpProtocol.v2025_11_25],
289 }),
290 ),
291 Layer.provide(WalletsLive),
292 ),
293 { disableLogger: true },
294 );
295 yield* Effect.addFinalizer(() => Effect.promise(dispose));
296 const mcp = mcpClient(handler);
297 yield* mcp.connect;
298
299 const listed = yield* mcp.request("tools/list", {});
300 const tools = listed!.result.tools as ReadonlyArray<any>;
301 expect(tools.map((tool) => tool.name)).toEqual([
302 "WalletApi_Deposit_send",
303 "WalletApi_Balance_get",
304 "WalletApi_Balance_list",
305 "WalletApi_Balance_snapshot",
306 ]);
307 const [send, get] = tools;
308 expect(send.annotations).toMatchObject({ readOnlyHint: false, destructiveHint: true });
309 expect(get.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false });
310 // Every output is an object, as MCP clients require.
311 expect(tools.every((tool) => tool.outputSchema.type === "object")).toBe(true);
312
313 const deposit = {
314 name: "WalletApi_Deposit_send",
315 arguments: { target: "sam-wallet", input: { amount: 30 } },
316 };
317 const sent = yield* mcp.request("tools/call", deposit, { "x-owner": "sam" });
318 expect(sent!.result.isError).toBe(false);
319 expect(sent!.result.structuredContent).toEqual({
320 reply: { balance: 30 },
321 stream: "Wallet/sam-wallet",
322 version: 1,
323 });
324
325 const anonymous = yield* mcp.request("tools/call", deposit);
326 expect(anonymous!.result.isError).toBe(true);
327 expect(JSON.parse(anonymous!.result.content[0].text)).toMatchObject({
328 _tag: "Unauthenticated",
329 });
330 }).pipe(Effect.scoped),
331 );
332
333 it.live("serves a request-scoped MCP endpoint, as on a Worker", () =>
334 Effect.gen(function* () {
335 const { handler, dispose } = HttpRouter.toWebHandler(
336 DomainAi.toMcp(WalletApi).pipe(
337 Layer.provide(
338 McpServer.layerHttpRequestScoped({
339 name: "wallet",
340 version: "1.0.0",
341 path: "/mcp",
342 protocols: [McpProtocol.v2026_07_28],
343 }),
344 ),
345 Layer.provide(WalletsLive),
346 ),
347 { disableLogger: true },
348 );
349 yield* Effect.addFinalizer(() => Effect.promise(dispose));
350 // A sessionless request carries its protocol and client in `_meta` and headers.
351 const deposit = Effect.fn(function* (headers: Record<string, string>) {
352 const response = yield* Effect.promise(() =>
353 handler(
354 new Request("http://localhost/mcp", {
355 method: "POST",
356 headers: {
357 "content-type": "application/json",
358 accept: "application/json, text/event-stream",
359 "mcp-protocol-version": "2026-07-28",
360 "mcp-method": "tools/call",
361 "mcp-name": "WalletApi_Deposit_send",
362 ...headers,
363 },
364 body: JSON.stringify({
365 jsonrpc: "2.0",
366 id: 1,
367 method: "tools/call",
368 params: {
369 _meta: {
370 "io.modelcontextprotocol/protocolVersion": "2026-07-28",
371 "io.modelcontextprotocol/clientInfo": { name: "test", version: "1.0.0" },
372 "io.modelcontextprotocol/clientCapabilities": {},
373 },
374 name: "WalletApi_Deposit_send",
375 arguments: { target: "sam-wallet", input: { amount: 3 } },
376 },
377 }),
378 }),
379 ),
380 );
381 const body = yield* Effect.promise(() => response.json());
382 return (body as { result: any }).result;
383 });
384 const sent = yield* deposit({ "x-owner": "sam" });
385 expect(sent.structuredContent).toEqual({
386 reply: { balance: 3 },
387 stream: "Wallet/sam-wallet",
388 version: 1,
389 });
390 const anonymous = yield* deposit({});
391 expect(anonymous.isError).toBe(true);
392 expect(JSON.parse(anonymous.content[0].text)).toEqual({ _tag: "Unauthenticated" });
393 }).pipe(Effect.scoped),
394 );
395 });