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

main
mdx 145 lines 6.11 KB
Raw
1 ---
2 title: MCP
3 description: Give an agent the commands and reads of an Api as tools, inside the app with Effect AI, or outside it over MCP.
4 ---
5
6 An Api already lists what one kind of client may do. `@alchemy.run/domain/Ai` turns that list into tools for an agent: an Effect AI `Toolkit` for an agent inside your app, and an MCP server for agents outside it. You declare nothing twice. Each tool calls the Api, so its middleware, its `decide` and `validate` checks and its rejections work for an agent as they do for every other client.
7
8 ## Tools from an Api
9
10 `DomainAi.toToolkit` makes one tool for each call of the Api that returns once:
11
12 | Served | Tools | Kind of tool |
13 | --------- | --------------------- | ------------ |
14 | Command | `send` | write |
15 | View | `get`, `list`, `snapshot` | read |
16 | Stream | `peek`, `list` | read |
17 | Aggregate | `get` | read |
18
19 `watch` and `events` are streams, not one result, so they are not tools. Clients that need them use the Api's own client.
20
21 ```typescript
22 import * as DomainAi from "@alchemy.run/domain/Ai";
23
24 const { toolkit, layer } = DomainAi.toToolkit(CustomerApi);
25 Object.keys(toolkit.tools);
26 // ["CustomerApi_DepositMoney_send", "CustomerApi_AccountSummary_get", "CustomerApi_AccountSummary_list", ...]
27 ```
28
29 A tool is named `<api>_<name>_<operation>`, with any character other than a letter, a digit, `_` or `-` turned into `_`, since model providers and MCP clients accept only those:
30
31 ```typescript
32 DomainAi.toolName({ api: "CustomerApi", name: "DepositMoney", operation: "send" });
33 // "CustomerApi_DepositMoney_send"
34 ```
35
36 A name longer than 64 characters, or two calls with one name, fail the toolkit's Layer with a `DefinitionError`.
37
38 A tool's parameters, success and failure are its call's own schemas, the JSON the Api's RPC server reads and writes. MCP requires an object as a tool's output, so a success that is not one, such as a view's `state | null`, comes back as `{ value }`:
39
40 ```json
41 { "value": { "balance": 1000 } }
42 ```
43
44 A read is marked read-only and idempotent, and a command destructive, as an MCP client's `tools/list` shows:
45
46 ```json
47 {
48 "name": "CustomerApi_DepositMoney_send",
49 "description": "Send the DepositMoney command.",
50 "annotations": { "readOnlyHint": false, "destructiveHint": true, "idempotentHint": false }
51 }
52 ```
53
54 `layer` holds the tools' handlers. It needs what the Api needs to serve: the hosted model and the Layers of the middleware of what it serves.
55
56 ## An agent in the app
57
58 Give the toolkit to `LanguageModel`, and provide `layer` with the model:
59
60 ```typescript
61 import * as DomainAi from "@alchemy.run/domain/Ai";
62 import { LanguageModel } from "effect/ai";
63 import * as Effect from "effect/Effect";
64
65 const { toolkit, layer } = DomainAi.toToolkit(CustomerApi, {
66 // Who the agent acts for: the signed-in customer's session.
67 headers: Effect.map(CurrentSession, (session) => ({ authorization: `Bearer ${session.token}` })),
68 });
69
70 const answer = LanguageModel.generateText({
71 prompt: "Move 20 dollars to my savings account",
72 toolkit,
73 }).pipe(Effect.provide(layer));
74 ```
75
76 A rejection (`InsufficientFunds`) or a middleware error (`Unauthenticated`) comes back to the model as the tool's typed failure, so the model can tell the user or try again. Any other error is a defect: the model does not see it.
77
78 ## An MCP server
79
80 `DomainAi.toMcp` registers the tools on Effect's `McpServer`. Provide a transport and the model:
81
82 ```typescript
83 import * as DomainAi from "@alchemy.run/domain/Ai";
84 import { McpProtocol, McpServer } from "effect/ai";
85 import * as HttpRouter from "effect/http/HttpRouter";
86 import * as Layer from "effect/Layer";
87
88 const BankMcp = DomainAi.toMcp(CustomerApi).pipe(
89 Layer.provide(
90 McpServer.layerHttp({
91 name: "bank",
92 version: "1.0.0",
93 path: "/mcp",
94 protocols: [McpProtocol.v2025_11_25],
95 }),
96 ),
97 Layer.provide(BankLive),
98 );
99
100 const { handler } = HttpRouter.toWebHandler(BankMcp);
101 // handler(request) answers MCP requests on /mcp
102 ```
103
104 `McpServer.layerHttp` keeps one server running for all requests. On a host where work must end with the request, such as a Cloudflare Worker, use `McpServer.layerHttpRequestScoped` with the sessionless protocol `McpProtocol.v2026_07_28`.
105
106 ## Who the agent acts for
107
108 Each tool call sends headers to the Api's middleware, as an HTTP client does. Set them with the `headers` option, an Effect that runs for each call. By default, a call sends the headers of the current `HttpServerRequest`, if there is one. So an MCP client signs in to your MCP server with the same header or cookie that your Api's session middleware reads, and an in-app agent that runs inside a request acts for the user who sent it.
109
110 The client half of a middleware never runs for a tool call. A server that provides one for its own calls still can't sign an agent in as itself:
111
112 ```typescript
113 // held by the server for the calls it makes; an agent's call still carries only its own headers
114 const ServerCredential = RpcMiddleware.layerClient(Session, ({ request, next }) =>
115 next({ ...request, headers: Headers.set(request.headers, "authorization", serverToken) }),
116 );
117 ```
118
119 A call with no session fails as it does for any client:
120
121 ```json
122 { "isError": true, "content": [{ "type": "text", "text": "{\"_tag\":\"Unauthenticated\"}" }] }
123 ```
124
125 ## Limits
126
127 `watch` and `events` are not tools; an MCP resource subscription can serve them later.
128
129 `tools/list` shows every tool to every MCP client. The Api still checks each call, so a caller who may not use a tool gets a rejection. Listing only the tools a caller may use needs `McpServer` to filter per request, which Effect does not do yet.
130
131 Nothing asks a person before a dangerous write. `LanguageModel` can ask when a tool sets `needsApproval`, and an MCP server can ask with elicitation, but neither is set from the Api yet.
132
133 Every call the Api serves is a tool, so give agents their own Api with only what they may reach:
134
135 ```typescript
136 export class AgentApi extends Domain.Api("AgentApi", {
137 model: Bank,
138 commands: ["DepositMoney", "RequestTransfer"],
139 views: ["AccountSummary"],
140 streams: [],
141 aggregates: [],
142 }) {}
143
144 const BankMcp = DomainAi.toMcp(AgentApi);
145 ```