The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; |
| 2 | import { Agent, callable, routeAgentRequest } from "agents"; |
| 3 | import { McpAgent } from "agents/mcp"; |
| 4 | import { z } from "zod"; |
| 5 | |
| 6 | interface Env { |
| 7 | Counter: DurableObjectNamespace<Counter>; |
| 8 | MCP_OBJECT: DurableObjectNamespace<Calculator>; |
| 9 | } |
| 10 | |
| 11 | export interface CounterState { |
| 12 | count: number; |
| 13 | reminders: number; |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * A stateful agent: its state syncs to every connected client, `@callable()` |
| 18 | * methods run over the agent's WebSocket, and `schedule()` calls back later. |
| 19 | */ |
| 20 | export class Counter extends Agent<Env, CounterState> { |
| 21 | initialState: CounterState = { count: 0, reminders: 0 }; |
| 22 | |
| 23 | @callable() |
| 24 | increment(by: number) { |
| 25 | this.setState({ ...this.state, count: this.state.count + by }); |
| 26 | return this.state.count; |
| 27 | } |
| 28 | |
| 29 | @callable() |
| 30 | async remindInOneSecond() { |
| 31 | await this.schedule(1, "remind"); |
| 32 | } |
| 33 | |
| 34 | remind() { |
| 35 | this.setState({ ...this.state, reminders: this.state.reminders + 1 }); |
| 36 | } |
| 37 | |
| 38 | // `GET /agents/counter/:name` outside a WebSocket. |
| 39 | onRequest() { |
| 40 | return Response.json(this.state); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | /** An MCP server agent with one tool, served at `/mcp`. */ |
| 45 | export class Calculator extends McpAgent<Env> { |
| 46 | server = new McpServer({ name: "calculator", version: "1.0.0" }); |
| 47 | |
| 48 | async init() { |
| 49 | this.server.registerTool( |
| 50 | "add", |
| 51 | { description: "Add two numbers", inputSchema: { a: z.number(), b: z.number() } }, |
| 52 | async ({ a, b }) => ({ content: [{ type: "text", text: String(a + b) }] }), |
| 53 | ); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | const mcp = Calculator.serve("/mcp"); |
| 58 | |
| 59 | export default { |
| 60 | async fetch(request, env, ctx) { |
| 61 | if (new URL(request.url).pathname.startsWith("/mcp")) { |
| 62 | return mcp.fetch(request, env, ctx); |
| 63 | } |
| 64 | return (await routeAgentRequest(request, env)) ?? new Response("Not found", { status: 404 }); |
| 65 | }, |
| 66 | } satisfies ExportedHandler<Env>; |