agents 0.2.13 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2457 @@
1
+ import { MessageType } from "./ai-types-UZlfLOYP.js";
2
+ import { camelCaseToKebabCase } from "./client-DjR-lC16.js";
3
+ import { DisposableStore, MCPClientManager } from "./client-CZBVDDoO.js";
4
+ import { DurableObjectOAuthClientProvider } from "./do-oauth-client-provider-B2jr6UNq.js";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { parseCronExpression } from "cron-schedule";
7
+ import { nanoid } from "nanoid";
8
+ import { EmailMessage } from "cloudflare:email";
9
+ import { Server, getServerByName, routePartykitRequest } from "partyserver";
10
+ import { ElicitRequestSchema as ElicitRequestSchema$1, InitializeRequestSchema, JSONRPCMessageSchema, isInitializeRequest, isJSONRPCError, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResponse } from "@modelcontextprotocol/sdk/types.js";
11
+
12
+ //#region src/observability/index.ts
13
+ /**
14
+ * A generic observability implementation that logs events to the console.
15
+ */
16
+ const genericObservability = { emit(event) {
17
+ if (isLocalMode()) {
18
+ console.log(event.displayMessage);
19
+ return;
20
+ }
21
+ console.log(event);
22
+ } };
23
+ let localMode = false;
24
+ function isLocalMode() {
25
+ if (localMode) return true;
26
+ const { request } = getCurrentAgent();
27
+ if (!request) return false;
28
+ localMode = new URL(request.url).hostname === "localhost";
29
+ return localMode;
30
+ }
31
+
32
+ //#endregion
33
+ //#region src/mcp/utils.ts
34
+ /**
35
+ * Since we use WebSockets to bridge the client to the
36
+ * MCP transport in the Agent, we use this header to signal
37
+ * the method of the original request the user made, while
38
+ * leaving the WS Upgrade request as GET.
39
+ */
40
+ const MCP_HTTP_METHOD_HEADER = "cf-mcp-method";
41
+ /**
42
+ * Since we use WebSockets to bridge the client to the
43
+ * MCP transport in the Agent, we use this header to include
44
+ * the original request body.
45
+ */
46
+ const MCP_MESSAGE_HEADER = "cf-mcp-message";
47
+ const MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
48
+ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
49
+ let pathname = basePath;
50
+ if (basePath === "/") pathname = "/*";
51
+ const basePattern = new URLPattern({ pathname });
52
+ return async (request, ctx) => {
53
+ const url = new URL(request.url);
54
+ if (basePattern.test(url)) {
55
+ if (request.method === "POST") {
56
+ const acceptHeader = request.headers.get("accept");
57
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
58
+ const body$1 = JSON.stringify({
59
+ error: {
60
+ code: -32e3,
61
+ message: "Not Acceptable: Client must accept both application/json and text/event-stream"
62
+ },
63
+ id: null,
64
+ jsonrpc: "2.0"
65
+ });
66
+ return new Response(body$1, { status: 406 });
67
+ }
68
+ const ct = request.headers.get("content-type");
69
+ if (!ct || !ct.includes("application/json")) {
70
+ const body$1 = JSON.stringify({
71
+ error: {
72
+ code: -32e3,
73
+ message: "Unsupported Media Type: Content-Type must be application/json"
74
+ },
75
+ id: null,
76
+ jsonrpc: "2.0"
77
+ });
78
+ return new Response(body$1, { status: 415 });
79
+ }
80
+ if (Number.parseInt(request.headers.get("content-length") ?? "0", 10) > MAXIMUM_MESSAGE_SIZE_BYTES) {
81
+ const body$1 = JSON.stringify({
82
+ error: {
83
+ code: -32e3,
84
+ message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
85
+ },
86
+ id: null,
87
+ jsonrpc: "2.0"
88
+ });
89
+ return new Response(body$1, { status: 413 });
90
+ }
91
+ let sessionId = request.headers.get("mcp-session-id");
92
+ let rawMessage;
93
+ try {
94
+ rawMessage = await request.json();
95
+ } catch (_error) {
96
+ const body$1 = JSON.stringify({
97
+ error: {
98
+ code: -32700,
99
+ message: "Parse error: Invalid JSON"
100
+ },
101
+ id: null,
102
+ jsonrpc: "2.0"
103
+ });
104
+ return new Response(body$1, { status: 400 });
105
+ }
106
+ let arrayMessage;
107
+ if (Array.isArray(rawMessage)) arrayMessage = rawMessage;
108
+ else arrayMessage = [rawMessage];
109
+ let messages = [];
110
+ for (const msg of arrayMessage) if (!JSONRPCMessageSchema.safeParse(msg).success) {
111
+ const body$1 = JSON.stringify({
112
+ error: {
113
+ code: -32700,
114
+ message: "Parse error: Invalid JSON-RPC message"
115
+ },
116
+ id: null,
117
+ jsonrpc: "2.0"
118
+ });
119
+ return new Response(body$1, { status: 400 });
120
+ }
121
+ messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
122
+ const maybeInitializeRequest = messages.find((msg) => InitializeRequestSchema.safeParse(msg).success);
123
+ if (!!maybeInitializeRequest && sessionId) {
124
+ const body$1 = JSON.stringify({
125
+ error: {
126
+ code: -32600,
127
+ message: "Invalid Request: Initialization requests must not include a sessionId"
128
+ },
129
+ id: null,
130
+ jsonrpc: "2.0"
131
+ });
132
+ return new Response(body$1, { status: 400 });
133
+ }
134
+ if (!!maybeInitializeRequest && messages.length > 1) {
135
+ const body$1 = JSON.stringify({
136
+ error: {
137
+ code: -32600,
138
+ message: "Invalid Request: Only one initialization request is allowed"
139
+ },
140
+ id: null,
141
+ jsonrpc: "2.0"
142
+ });
143
+ return new Response(body$1, { status: 400 });
144
+ }
145
+ if (!maybeInitializeRequest && !sessionId) {
146
+ const body$1 = JSON.stringify({
147
+ error: {
148
+ code: -32e3,
149
+ message: "Bad Request: Mcp-Session-Id header is required"
150
+ },
151
+ id: null,
152
+ jsonrpc: "2.0"
153
+ });
154
+ return new Response(body$1, { status: 400 });
155
+ }
156
+ sessionId = sessionId ?? namespace.newUniqueId().toString();
157
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
158
+ const isInitialized = await agent.getInitializeRequest();
159
+ if (maybeInitializeRequest) await agent.setInitializeRequest(maybeInitializeRequest);
160
+ else if (!isInitialized) {
161
+ const body$1 = JSON.stringify({
162
+ error: {
163
+ code: -32001,
164
+ message: "Session not found"
165
+ },
166
+ id: null,
167
+ jsonrpc: "2.0"
168
+ });
169
+ return new Response(body$1, { status: 404 });
170
+ }
171
+ const { readable, writable } = new TransformStream();
172
+ const writer = writable.getWriter();
173
+ const encoder = new TextEncoder();
174
+ const existingHeaders = {};
175
+ request.headers.forEach((value, key) => {
176
+ existingHeaders[key] = value;
177
+ });
178
+ const req = new Request(request.url, { headers: {
179
+ ...existingHeaders,
180
+ [MCP_HTTP_METHOD_HEADER]: "POST",
181
+ [MCP_MESSAGE_HEADER]: Buffer.from(JSON.stringify(messages)).toString("base64"),
182
+ Upgrade: "websocket"
183
+ } });
184
+ if (ctx.props) agent.updateProps(ctx.props);
185
+ const ws = (await agent.fetch(req)).webSocket;
186
+ if (!ws) {
187
+ console.error("Failed to establish WebSocket connection");
188
+ await writer.close();
189
+ const body$1 = JSON.stringify({
190
+ error: {
191
+ code: -32001,
192
+ message: "Failed to establish WebSocket connection"
193
+ },
194
+ id: null,
195
+ jsonrpc: "2.0"
196
+ });
197
+ return new Response(body$1, { status: 500 });
198
+ }
199
+ ws.accept();
200
+ ws.addEventListener("message", (event) => {
201
+ async function onMessage(event$1) {
202
+ try {
203
+ const data = typeof event$1.data === "string" ? event$1.data : new TextDecoder().decode(event$1.data);
204
+ const message = JSON.parse(data);
205
+ if (message.type !== MessageType.CF_MCP_AGENT_EVENT) return;
206
+ await writer.write(encoder.encode(message.event));
207
+ if (message.close) {
208
+ ws?.close();
209
+ await writer.close().catch(() => {});
210
+ }
211
+ } catch (error) {
212
+ console.error("Error forwarding message to SSE:", error);
213
+ }
214
+ }
215
+ onMessage(event).catch(console.error);
216
+ });
217
+ ws.addEventListener("error", (error) => {
218
+ async function onError(_error) {
219
+ await writer.close().catch(() => {});
220
+ }
221
+ onError(error).catch(console.error);
222
+ });
223
+ ws.addEventListener("close", () => {
224
+ async function onClose() {
225
+ await writer.close().catch(() => {});
226
+ }
227
+ onClose().catch(console.error);
228
+ });
229
+ if (messages.every((msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg))) {
230
+ ws.close();
231
+ return new Response(null, {
232
+ headers: corsHeaders(request, corsOptions),
233
+ status: 202
234
+ });
235
+ }
236
+ return new Response(readable, {
237
+ headers: {
238
+ "Cache-Control": "no-cache",
239
+ Connection: "keep-alive",
240
+ "Content-Type": "text/event-stream",
241
+ "mcp-session-id": sessionId,
242
+ ...corsHeaders(request, corsOptions)
243
+ },
244
+ status: 200
245
+ });
246
+ } else if (request.method === "GET") {
247
+ if (!request.headers.get("accept")?.includes("text/event-stream")) {
248
+ const body$1 = JSON.stringify({
249
+ jsonrpc: "2.0",
250
+ error: {
251
+ code: -32e3,
252
+ message: "Not Acceptable: Client must accept text/event-stream"
253
+ },
254
+ id: null
255
+ });
256
+ return new Response(body$1, { status: 406 });
257
+ }
258
+ const sessionId = request.headers.get("mcp-session-id");
259
+ if (!sessionId) return new Response(JSON.stringify({
260
+ error: {
261
+ code: -32e3,
262
+ message: "Bad Request: Mcp-Session-Id header is required"
263
+ },
264
+ id: null,
265
+ jsonrpc: "2.0"
266
+ }), { status: 400 });
267
+ const { readable, writable } = new TransformStream();
268
+ const writer = writable.getWriter();
269
+ const encoder = new TextEncoder();
270
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
271
+ if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
272
+ jsonrpc: "2.0",
273
+ error: {
274
+ code: -32001,
275
+ message: "Session not found"
276
+ },
277
+ id: null
278
+ }), { status: 404 });
279
+ const existingHeaders = {};
280
+ request.headers.forEach((v, k) => {
281
+ existingHeaders[k] = v;
282
+ });
283
+ if (ctx.props) agent.updateProps(ctx.props);
284
+ const ws = (await agent.fetch(new Request(request.url, { headers: {
285
+ ...existingHeaders,
286
+ [MCP_HTTP_METHOD_HEADER]: "GET",
287
+ Upgrade: "websocket"
288
+ } }))).webSocket;
289
+ if (!ws) {
290
+ await writer.close();
291
+ return new Response("Failed to establish WS to DO", { status: 500 });
292
+ }
293
+ ws.accept();
294
+ ws.addEventListener("message", (event) => {
295
+ try {
296
+ async function onMessage(ev) {
297
+ const data = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
298
+ const message = JSON.parse(data);
299
+ if (message.type !== MessageType.CF_MCP_AGENT_EVENT) return;
300
+ await writer.write(encoder.encode(message.event));
301
+ }
302
+ onMessage(event).catch(console.error);
303
+ } catch (e) {
304
+ console.error("Error forwarding message to SSE:", e);
305
+ }
306
+ });
307
+ ws.addEventListener("error", () => {
308
+ writer.close().catch(() => {});
309
+ });
310
+ ws.addEventListener("close", () => {
311
+ writer.close().catch(() => {});
312
+ });
313
+ return new Response(readable, {
314
+ headers: {
315
+ "Cache-Control": "no-cache",
316
+ Connection: "keep-alive",
317
+ "Content-Type": "text/event-stream",
318
+ "mcp-session-id": sessionId,
319
+ ...corsHeaders(request, corsOptions)
320
+ },
321
+ status: 200
322
+ });
323
+ } else if (request.method === "DELETE") {
324
+ const sessionId = request.headers.get("mcp-session-id");
325
+ if (!sessionId) return new Response(JSON.stringify({
326
+ jsonrpc: "2.0",
327
+ error: {
328
+ code: -32e3,
329
+ message: "Bad Request: Mcp-Session-Id header is required"
330
+ },
331
+ id: null
332
+ }), {
333
+ status: 400,
334
+ headers: corsHeaders(request, corsOptions)
335
+ });
336
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`);
337
+ if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
338
+ jsonrpc: "2.0",
339
+ error: {
340
+ code: -32001,
341
+ message: "Session not found"
342
+ },
343
+ id: null
344
+ }), {
345
+ status: 404,
346
+ headers: corsHeaders(request, corsOptions)
347
+ });
348
+ ctx.waitUntil(agent.destroy().catch(() => {}));
349
+ return new Response(null, {
350
+ status: 204,
351
+ headers: corsHeaders(request, corsOptions)
352
+ });
353
+ }
354
+ }
355
+ const body = JSON.stringify({
356
+ error: {
357
+ code: -32e3,
358
+ message: "Not found"
359
+ },
360
+ id: null,
361
+ jsonrpc: "2.0"
362
+ });
363
+ return new Response(body, { status: 404 });
364
+ };
365
+ };
366
+ const createLegacySseHandler = (basePath, namespace, corsOptions) => {
367
+ let pathname = basePath;
368
+ if (basePath === "/") pathname = "/*";
369
+ const basePattern = new URLPattern({ pathname });
370
+ const messagePattern = new URLPattern({ pathname: `${basePath}/message` });
371
+ return async (request, ctx) => {
372
+ const url = new URL(request.url);
373
+ if (request.method === "GET" && basePattern.test(url)) {
374
+ const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
375
+ const { readable, writable } = new TransformStream();
376
+ const writer = writable.getWriter();
377
+ const encoder = new TextEncoder();
378
+ const endpointUrl = new URL(request.url);
379
+ endpointUrl.pathname = encodeURI(`${basePath}/message`);
380
+ endpointUrl.searchParams.set("sessionId", sessionId);
381
+ const endpointMessage = `event: endpoint\ndata: ${endpointUrl.pathname + endpointUrl.search + endpointUrl.hash}\n\n`;
382
+ writer.write(encoder.encode(endpointMessage));
383
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
384
+ const existingHeaders = {};
385
+ request.headers.forEach((value, key) => {
386
+ existingHeaders[key] = value;
387
+ });
388
+ if (ctx.props) agent.updateProps(ctx.props);
389
+ const ws = (await agent.fetch(new Request(request.url, { headers: {
390
+ ...existingHeaders,
391
+ Upgrade: "websocket"
392
+ } }))).webSocket;
393
+ if (!ws) {
394
+ console.error("Failed to establish WebSocket connection");
395
+ await writer.close();
396
+ return new Response("Failed to establish WebSocket connection", { status: 500 });
397
+ }
398
+ ws.accept();
399
+ ws.addEventListener("message", (event) => {
400
+ async function onMessage(event$1) {
401
+ try {
402
+ const message = JSON.parse(event$1.data);
403
+ const result = JSONRPCMessageSchema.safeParse(message);
404
+ if (!result.success) return;
405
+ const messageText = `event: message\ndata: ${JSON.stringify(result.data)}\n\n`;
406
+ await writer.write(encoder.encode(messageText));
407
+ } catch (error) {
408
+ console.error("Error forwarding message to SSE:", error);
409
+ }
410
+ }
411
+ onMessage(event).catch(console.error);
412
+ });
413
+ ws.addEventListener("error", (error) => {
414
+ async function onError(_error) {
415
+ try {
416
+ await writer.close();
417
+ } catch (_e) {}
418
+ }
419
+ onError(error).catch(console.error);
420
+ });
421
+ ws.addEventListener("close", () => {
422
+ async function onClose() {
423
+ try {
424
+ await writer.close();
425
+ } catch (error) {
426
+ console.error("Error closing SSE connection:", error);
427
+ }
428
+ }
429
+ onClose().catch(console.error);
430
+ });
431
+ return new Response(readable, { headers: {
432
+ "Cache-Control": "no-cache",
433
+ Connection: "keep-alive",
434
+ "Content-Type": "text/event-stream",
435
+ ...corsHeaders(request, corsOptions)
436
+ } });
437
+ }
438
+ if (request.method === "POST" && messagePattern.test(url)) {
439
+ const sessionId = url.searchParams.get("sessionId");
440
+ if (!sessionId) return new Response(`Missing sessionId. Expected POST to ${basePath} to initiate new one`, { status: 400 });
441
+ const contentType = request.headers.get("content-type") || "";
442
+ if (!contentType.includes("application/json")) return new Response(`Unsupported content-type: ${contentType}`, { status: 400 });
443
+ const contentLength = Number.parseInt(request.headers.get("content-length") || "0", 10);
444
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) return new Response(`Request body too large: ${contentLength} bytes`, { status: 400 });
445
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
446
+ const messageBody = await request.json();
447
+ const error = await agent.onSSEMcpMessage(sessionId, messageBody);
448
+ if (error) return new Response(error.message, {
449
+ headers: {
450
+ "Cache-Control": "no-cache",
451
+ Connection: "keep-alive",
452
+ "Content-Type": "text/event-stream",
453
+ ...corsHeaders(request, corsOptions)
454
+ },
455
+ status: 400
456
+ });
457
+ return new Response("Accepted", {
458
+ headers: {
459
+ "Cache-Control": "no-cache",
460
+ Connection: "keep-alive",
461
+ "Content-Type": "text/event-stream",
462
+ ...corsHeaders(request, corsOptions)
463
+ },
464
+ status: 202
465
+ });
466
+ }
467
+ return new Response("Not Found", { status: 404 });
468
+ };
469
+ };
470
+ function corsHeaders(_request, corsOptions = {}) {
471
+ const origin = "*";
472
+ return {
473
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, Accept, mcp-session-id, mcp-protocol-version",
474
+ "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, DELETE, OPTIONS",
475
+ "Access-Control-Allow-Origin": corsOptions.origin || origin,
476
+ "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
477
+ "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
478
+ };
479
+ }
480
+ function handleCORS(request, corsOptions) {
481
+ if (request.method === "OPTIONS") return new Response(null, { headers: corsHeaders(request, corsOptions) });
482
+ return null;
483
+ }
484
+ function isDurableObjectNamespace(namespace) {
485
+ return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
486
+ }
487
+
488
+ //#endregion
489
+ //#region src/mcp/transport.ts
490
+ var McpSSETransport = class {
491
+ constructor(getWebSocket) {
492
+ this._started = false;
493
+ this._getWebSocket = getWebSocket;
494
+ }
495
+ async start() {
496
+ if (this._started) throw new Error("Transport already started");
497
+ this._started = true;
498
+ }
499
+ async send(message) {
500
+ if (!this._started) throw new Error("Transport not started");
501
+ const websocket = this._getWebSocket();
502
+ if (!websocket) throw new Error("WebSocket not connected");
503
+ try {
504
+ websocket.send(JSON.stringify(message));
505
+ } catch (error) {
506
+ this.onerror?.(error);
507
+ }
508
+ }
509
+ async close() {
510
+ this.onclose?.();
511
+ }
512
+ };
513
+ /**
514
+ * Adapted from: https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/client/streamableHttp.ts
515
+ * - Validation and initialization are removed as they're handled in `McpAgent.serve()` handler.
516
+ * - Replaces the Node-style `req`/`res` with Worker's `Request`.
517
+ * - Writes events as WS messages that the Worker forwards to the client as SSE events.
518
+ * - Replaces the in-memory maps that track requestID/stream by using `connection.setState()` and `agent.getConnections()`.
519
+ *
520
+ * Besides these points, the implementation is the same and should be updated to match the original as new features are added.
521
+ */
522
+ var StreamableHTTPServerTransport = class {
523
+ constructor(options) {
524
+ this._started = false;
525
+ this._requestResponseMap = /* @__PURE__ */ new Map();
526
+ const { agent } = getCurrentAgent();
527
+ if (!agent) throw new Error("McpAgent was not found in Transport constructor");
528
+ this.sessionId = agent.getSessionId();
529
+ this._eventStore = options.eventStore;
530
+ }
531
+ /**
532
+ * Starts the transport. This is required by the Transport interface but is a no-op
533
+ * for the Streamable HTTP transport as connections are managed per-request.
534
+ */
535
+ async start() {
536
+ if (this._started) throw new Error("Transport already started");
537
+ this._started = true;
538
+ }
539
+ /**
540
+ * Handles GET requests for SSE stream
541
+ */
542
+ async handleGetRequest(req) {
543
+ const { connection } = getCurrentAgent();
544
+ if (!connection) throw new Error("Connection was not found in handleGetRequest");
545
+ if (this._eventStore) {
546
+ const lastEventId = req.headers.get("last-event-id");
547
+ if (lastEventId) {
548
+ await this.replayEvents(lastEventId);
549
+ return;
550
+ }
551
+ }
552
+ connection.setState({ _standaloneSse: true });
553
+ }
554
+ /**
555
+ * Replays events that would have been sent after the specified event ID
556
+ * Only used when resumability is enabled
557
+ */
558
+ async replayEvents(lastEventId) {
559
+ if (!this._eventStore) return;
560
+ const { connection } = getCurrentAgent();
561
+ if (!connection) throw new Error("Connection was not available in replayEvents");
562
+ try {
563
+ await this._eventStore?.replayEventsAfter(lastEventId, { send: async (eventId, message) => {
564
+ try {
565
+ this.writeSSEEvent(connection, message, eventId);
566
+ } catch (error) {
567
+ this.onerror?.(error);
568
+ }
569
+ } });
570
+ } catch (error) {
571
+ this.onerror?.(error);
572
+ }
573
+ }
574
+ /**
575
+ * Writes an event to the SSE stream with proper formatting
576
+ */
577
+ writeSSEEvent(connection, message, eventId, close) {
578
+ let eventData = "event: message\n";
579
+ if (eventId) eventData += `id: ${eventId}\n`;
580
+ eventData += `data: ${JSON.stringify(message)}\n\n`;
581
+ return connection.send(JSON.stringify({
582
+ type: MessageType.CF_MCP_AGENT_EVENT,
583
+ event: eventData,
584
+ close
585
+ }));
586
+ }
587
+ /**
588
+ * Handles POST requests containing JSON-RPC messages
589
+ */
590
+ async handlePostRequest(req, parsedBody) {
591
+ const authInfo = req.auth;
592
+ const requestInfo = { headers: Object.fromEntries(req.headers.entries()) };
593
+ delete requestInfo.headers[MCP_HTTP_METHOD_HEADER];
594
+ delete requestInfo.headers[MCP_MESSAGE_HEADER];
595
+ delete requestInfo.headers.upgrade;
596
+ const rawMessage = parsedBody;
597
+ let messages;
598
+ if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
599
+ else messages = [JSONRPCMessageSchema.parse(rawMessage)];
600
+ const hasRequests = messages.some(isJSONRPCRequest);
601
+ if (!hasRequests) for (const message of messages) this.onmessage?.(message, {
602
+ authInfo,
603
+ requestInfo
604
+ });
605
+ else if (hasRequests) {
606
+ const { connection } = getCurrentAgent();
607
+ if (!connection) throw new Error("Connection was not found in handlePostRequest");
608
+ const requestIds = messages.filter(isJSONRPCRequest).map((message) => message.id);
609
+ connection.setState({ requestIds });
610
+ for (const message of messages) this.onmessage?.(message, {
611
+ authInfo,
612
+ requestInfo
613
+ });
614
+ }
615
+ }
616
+ async close() {
617
+ const { agent } = getCurrentAgent();
618
+ if (!agent) throw new Error("Agent was not found in close");
619
+ for (const conn of agent.getConnections()) conn.close(1e3, "Session closed");
620
+ this.onclose?.();
621
+ }
622
+ async send(message, options) {
623
+ const { agent } = getCurrentAgent();
624
+ if (!agent) throw new Error("Agent was not found in send");
625
+ let requestId = options?.relatedRequestId;
626
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) requestId = message.id;
627
+ if (requestId === void 0) {
628
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
629
+ let standaloneConnection;
630
+ for (const conn of agent.getConnections()) if (conn.state?._standaloneSse) standaloneConnection = conn;
631
+ if (standaloneConnection === void 0) return;
632
+ let eventId$1;
633
+ if (this._eventStore) eventId$1 = await this._eventStore.storeEvent(standaloneConnection.id, message);
634
+ this.writeSSEEvent(standaloneConnection, message, eventId$1);
635
+ return;
636
+ }
637
+ const connection = Array.from(agent.getConnections()).find((conn) => conn.state?.requestIds?.includes(requestId));
638
+ if (!connection) throw new Error(`No connection established for request ID: ${String(requestId)}`);
639
+ let eventId;
640
+ if (this._eventStore) eventId = await this._eventStore.storeEvent(connection.id, message);
641
+ let shouldClose = false;
642
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
643
+ this._requestResponseMap.set(requestId, message);
644
+ const relatedIds = connection.state?.requestIds ?? [];
645
+ shouldClose = relatedIds.every((id) => this._requestResponseMap.has(id));
646
+ if (shouldClose) for (const id of relatedIds) this._requestResponseMap.delete(id);
647
+ }
648
+ this.writeSSEEvent(connection, message, eventId, shouldClose);
649
+ }
650
+ };
651
+
652
+ //#endregion
653
+ //#region src/mcp/worker-transport.ts
654
+ var WorkerTransport = class {
655
+ constructor(options) {
656
+ this.started = false;
657
+ this.initialized = false;
658
+ this.enableJsonResponse = false;
659
+ this.standaloneSseStreamId = "_GET_stream";
660
+ this.streamMapping = /* @__PURE__ */ new Map();
661
+ this.requestToStreamMapping = /* @__PURE__ */ new Map();
662
+ this.requestResponseMap = /* @__PURE__ */ new Map();
663
+ this.sessionIdGenerator = options?.sessionIdGenerator;
664
+ this.enableJsonResponse = options?.enableJsonResponse ?? false;
665
+ this.onsessioninitialized = options?.onsessioninitialized;
666
+ }
667
+ async start() {
668
+ if (this.started) throw new Error("Transport already started");
669
+ this.started = true;
670
+ }
671
+ async handleRequest(request, parsedBody) {
672
+ switch (request.method) {
673
+ case "OPTIONS": return this.handleOptionsRequest(request);
674
+ case "GET": return this.handleGetRequest(request);
675
+ case "POST": return this.handlePostRequest(request, parsedBody);
676
+ case "DELETE": return this.handleDeleteRequest(request);
677
+ default: return this.handleUnsupportedRequest();
678
+ }
679
+ }
680
+ async handleGetRequest(request) {
681
+ if (!request.headers.get("Accept")?.includes("text/event-stream")) return new Response(JSON.stringify({
682
+ jsonrpc: "2.0",
683
+ error: {
684
+ code: -32e3,
685
+ message: "Not Acceptable: Client must accept text/event-stream"
686
+ },
687
+ id: null
688
+ }), {
689
+ status: 406,
690
+ headers: { "Content-Type": "application/json" }
691
+ });
692
+ const sessionValid = this.validateSession(request);
693
+ if (sessionValid !== true) return sessionValid;
694
+ const streamId = this.standaloneSseStreamId;
695
+ if (this.streamMapping.get(streamId) !== void 0) return new Response(JSON.stringify({
696
+ jsonrpc: "2.0",
697
+ error: {
698
+ code: -32e3,
699
+ message: "Conflict: Only one SSE stream is allowed per session"
700
+ },
701
+ id: null
702
+ }), {
703
+ status: 409,
704
+ headers: { "Content-Type": "application/json" }
705
+ });
706
+ const { readable, writable } = new TransformStream();
707
+ const writer = writable.getWriter();
708
+ const encoder = new TextEncoder();
709
+ const headers = new Headers({
710
+ "Content-Type": "text/event-stream",
711
+ "Cache-Control": "no-cache",
712
+ Connection: "keep-alive",
713
+ "Access-Control-Allow-Origin": "*",
714
+ "Access-Control-Expose-Headers": "mcp-session-id"
715
+ });
716
+ if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
717
+ const keepAlive = setInterval(() => {
718
+ try {
719
+ writer.write(encoder.encode("event: ping\ndata: \n\n"));
720
+ } catch {
721
+ clearInterval(keepAlive);
722
+ }
723
+ }, 3e4);
724
+ this.streamMapping.set(streamId, {
725
+ writer,
726
+ encoder,
727
+ cleanup: () => {
728
+ clearInterval(keepAlive);
729
+ this.streamMapping.delete(streamId);
730
+ writer.close().catch(() => {});
731
+ }
732
+ });
733
+ return new Response(readable, { headers });
734
+ }
735
+ async handlePostRequest(request, parsedBody) {
736
+ const acceptHeader = request.headers.get("Accept");
737
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) return new Response(JSON.stringify({
738
+ jsonrpc: "2.0",
739
+ error: {
740
+ code: -32e3,
741
+ message: "Not Acceptable: Client must accept both application/json and text/event-stream"
742
+ },
743
+ id: null
744
+ }), {
745
+ status: 406,
746
+ headers: { "Content-Type": "application/json" }
747
+ });
748
+ if (!request.headers.get("Content-Type")?.includes("application/json")) return new Response(JSON.stringify({
749
+ jsonrpc: "2.0",
750
+ error: {
751
+ code: -32e3,
752
+ message: "Unsupported Media Type: Content-Type must be application/json"
753
+ },
754
+ id: null
755
+ }), {
756
+ status: 415,
757
+ headers: { "Content-Type": "application/json" }
758
+ });
759
+ let rawMessage = parsedBody;
760
+ if (rawMessage === void 0) try {
761
+ rawMessage = await request.json();
762
+ } catch {
763
+ return new Response(JSON.stringify({
764
+ jsonrpc: "2.0",
765
+ error: {
766
+ code: -32700,
767
+ message: "Parse error: Invalid JSON"
768
+ },
769
+ id: null
770
+ }), {
771
+ status: 400,
772
+ headers: { "Content-Type": "application/json" }
773
+ });
774
+ }
775
+ let messages;
776
+ try {
777
+ if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
778
+ else messages = [JSONRPCMessageSchema.parse(rawMessage)];
779
+ } catch {
780
+ return new Response(JSON.stringify({
781
+ jsonrpc: "2.0",
782
+ error: {
783
+ code: -32700,
784
+ message: "Parse error: Invalid JSON-RPC message"
785
+ },
786
+ id: null
787
+ }), {
788
+ status: 400,
789
+ headers: { "Content-Type": "application/json" }
790
+ });
791
+ }
792
+ const isInitializationRequest = messages.some(isInitializeRequest);
793
+ if (isInitializationRequest) {
794
+ if (this.initialized && this.sessionId !== void 0) return new Response(JSON.stringify({
795
+ jsonrpc: "2.0",
796
+ error: {
797
+ code: -32600,
798
+ message: "Invalid Request: Server already initialized"
799
+ },
800
+ id: null
801
+ }), {
802
+ status: 400,
803
+ headers: { "Content-Type": "application/json" }
804
+ });
805
+ if (messages.length > 1) return new Response(JSON.stringify({
806
+ jsonrpc: "2.0",
807
+ error: {
808
+ code: -32600,
809
+ message: "Invalid Request: Only one initialization request is allowed"
810
+ },
811
+ id: null
812
+ }), {
813
+ status: 400,
814
+ headers: { "Content-Type": "application/json" }
815
+ });
816
+ this.sessionId = this.sessionIdGenerator?.();
817
+ this.initialized = true;
818
+ if (this.sessionId && this.onsessioninitialized) this.onsessioninitialized(this.sessionId);
819
+ }
820
+ if (!isInitializationRequest) {
821
+ const sessionValid = this.validateSession(request);
822
+ if (sessionValid !== true) return sessionValid;
823
+ }
824
+ if (!messages.some(isJSONRPCRequest)) {
825
+ for (const message of messages) this.onmessage?.(message);
826
+ return new Response(null, {
827
+ status: 202,
828
+ headers: { "Access-Control-Allow-Origin": "*" }
829
+ });
830
+ }
831
+ const streamId = crypto.randomUUID();
832
+ if (this.enableJsonResponse) return new Promise((resolve) => {
833
+ this.streamMapping.set(streamId, {
834
+ resolveJson: resolve,
835
+ cleanup: () => {
836
+ this.streamMapping.delete(streamId);
837
+ }
838
+ });
839
+ for (const message of messages) if (isJSONRPCRequest(message)) this.requestToStreamMapping.set(message.id, streamId);
840
+ for (const message of messages) this.onmessage?.(message);
841
+ });
842
+ const { readable, writable } = new TransformStream();
843
+ const writer = writable.getWriter();
844
+ const encoder = new TextEncoder();
845
+ const headers = new Headers({
846
+ "Content-Type": "text/event-stream",
847
+ "Cache-Control": "no-cache",
848
+ Connection: "keep-alive",
849
+ "Access-Control-Allow-Origin": "*",
850
+ "Access-Control-Expose-Headers": "mcp-session-id"
851
+ });
852
+ if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
853
+ this.streamMapping.set(streamId, {
854
+ writer,
855
+ encoder,
856
+ cleanup: () => {
857
+ this.streamMapping.delete(streamId);
858
+ writer.close().catch(() => {});
859
+ }
860
+ });
861
+ for (const message of messages) if (isJSONRPCRequest(message)) this.requestToStreamMapping.set(message.id, streamId);
862
+ for (const message of messages) this.onmessage?.(message);
863
+ return new Response(readable, { headers });
864
+ }
865
+ async handleDeleteRequest(request) {
866
+ const sessionValid = this.validateSession(request);
867
+ if (sessionValid !== true) return sessionValid;
868
+ await this.close();
869
+ return new Response(null, {
870
+ status: 200,
871
+ headers: { "Access-Control-Allow-Origin": "*" }
872
+ });
873
+ }
874
+ handleOptionsRequest(_request) {
875
+ const headers = new Headers({
876
+ "Access-Control-Allow-Origin": "*",
877
+ "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
878
+ "Access-Control-Allow-Headers": "Content-Type, Accept, Authorization, mcp-session-id",
879
+ "Access-Control-Max-Age": "86400"
880
+ });
881
+ return new Response(null, {
882
+ status: 204,
883
+ headers
884
+ });
885
+ }
886
+ handleUnsupportedRequest() {
887
+ return new Response(JSON.stringify({
888
+ jsonrpc: "2.0",
889
+ error: {
890
+ code: -32e3,
891
+ message: "Method not allowed."
892
+ },
893
+ id: null
894
+ }), {
895
+ status: 405,
896
+ headers: {
897
+ Allow: "GET, POST, DELETE, OPTIONS",
898
+ "Content-Type": "application/json"
899
+ }
900
+ });
901
+ }
902
+ validateSession(request) {
903
+ if (this.sessionIdGenerator === void 0) return true;
904
+ if (!this.initialized) return new Response(JSON.stringify({
905
+ jsonrpc: "2.0",
906
+ error: {
907
+ code: -32e3,
908
+ message: "Bad Request: Server not initialized"
909
+ },
910
+ id: null
911
+ }), {
912
+ status: 400,
913
+ headers: { "Content-Type": "application/json" }
914
+ });
915
+ const sessionId = request.headers.get("mcp-session-id");
916
+ if (!sessionId) return new Response(JSON.stringify({
917
+ jsonrpc: "2.0",
918
+ error: {
919
+ code: -32e3,
920
+ message: "Bad Request: Mcp-Session-Id header is required"
921
+ },
922
+ id: null
923
+ }), {
924
+ status: 400,
925
+ headers: { "Content-Type": "application/json" }
926
+ });
927
+ if (sessionId !== this.sessionId) return new Response(JSON.stringify({
928
+ jsonrpc: "2.0",
929
+ error: {
930
+ code: -32001,
931
+ message: "Session not found"
932
+ },
933
+ id: null
934
+ }), {
935
+ status: 404,
936
+ headers: { "Content-Type": "application/json" }
937
+ });
938
+ return true;
939
+ }
940
+ async close() {
941
+ for (const { cleanup } of this.streamMapping.values()) cleanup();
942
+ this.streamMapping.clear();
943
+ this.requestResponseMap.clear();
944
+ this.onclose?.();
945
+ }
946
+ async send(message) {
947
+ let requestId;
948
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) requestId = message.id;
949
+ if (requestId === void 0) {
950
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
951
+ const standaloneSse = this.streamMapping.get(this.standaloneSseStreamId);
952
+ if (standaloneSse === void 0) return;
953
+ if (standaloneSse.writer && standaloneSse.encoder) {
954
+ const data = `event: message\ndata: ${JSON.stringify(message)}\n\n`;
955
+ await standaloneSse.writer.write(standaloneSse.encoder.encode(data));
956
+ }
957
+ return;
958
+ }
959
+ const streamId = this.requestToStreamMapping.get(requestId);
960
+ if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`);
961
+ const response = this.streamMapping.get(streamId);
962
+ if (!response) throw new Error(`No connection established for request ID: ${String(requestId)}`);
963
+ if (!this.enableJsonResponse) {
964
+ if (response.writer && response.encoder) {
965
+ const data = `event: message\ndata: ${JSON.stringify(message)}\n\n`;
966
+ await response.writer.write(response.encoder.encode(data));
967
+ }
968
+ }
969
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
970
+ this.requestResponseMap.set(requestId, message);
971
+ const relatedIds = Array.from(this.requestToStreamMapping.entries()).filter(([, sid]) => sid === streamId).map(([id]) => id);
972
+ if (relatedIds.every((id) => this.requestResponseMap.has(id))) {
973
+ if (this.enableJsonResponse && response.resolveJson) {
974
+ const responses = relatedIds.map((id) => this.requestResponseMap.get(id));
975
+ const headers = new Headers({
976
+ "Content-Type": "application/json",
977
+ "Access-Control-Allow-Origin": "*",
978
+ "Access-Control-Expose-Headers": "mcp-session-id"
979
+ });
980
+ if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
981
+ const body = responses.length === 1 ? responses[0] : responses;
982
+ response.resolveJson(new Response(JSON.stringify(body), { headers }));
983
+ } else response.cleanup();
984
+ for (const id of relatedIds) {
985
+ this.requestResponseMap.delete(id);
986
+ this.requestToStreamMapping.delete(id);
987
+ }
988
+ }
989
+ }
990
+ }
991
+ };
992
+
993
+ //#endregion
994
+ //#region src/mcp/auth-context.ts
995
+ const authContextStorage = new AsyncLocalStorage();
996
+ function getMcpAuthContext() {
997
+ return authContextStorage.getStore();
998
+ }
999
+ function runWithAuthContext(context, fn) {
1000
+ return authContextStorage.run(context, fn);
1001
+ }
1002
+
1003
+ //#endregion
1004
+ //#region src/mcp/handler.ts
1005
+ function experimental_createMcpHandler(server, options = {}) {
1006
+ const route = options.route ?? "/mcp";
1007
+ return async (request, _env, ctx) => {
1008
+ const url = new URL(request.url);
1009
+ if (route && url.pathname !== route) return new Response("Not Found", { status: 404 });
1010
+ const oauthCtx = ctx;
1011
+ const authContext = oauthCtx.props ? { props: oauthCtx.props } : void 0;
1012
+ const transport = new WorkerTransport(options);
1013
+ await server.connect(transport);
1014
+ const handleRequest = async () => {
1015
+ return await transport.handleRequest(request);
1016
+ };
1017
+ try {
1018
+ let response;
1019
+ if (authContext) response = await runWithAuthContext(authContext, handleRequest);
1020
+ else response = await handleRequest();
1021
+ return response;
1022
+ } catch (error) {
1023
+ console.error("MCP handler error:", error);
1024
+ return new Response(JSON.stringify({
1025
+ jsonrpc: "2.0",
1026
+ error: {
1027
+ code: -32603,
1028
+ message: error instanceof Error ? error.message : "Internal server error"
1029
+ },
1030
+ id: null
1031
+ }), {
1032
+ status: 500,
1033
+ headers: { "Content-Type": "application/json" }
1034
+ });
1035
+ }
1036
+ };
1037
+ }
1038
+
1039
+ //#endregion
1040
+ //#region src/mcp/index.ts
1041
+ var McpAgent = class McpAgent extends Agent {
1042
+ async setInitializeRequest(initializeRequest) {
1043
+ await this.ctx.storage.put("initializeRequest", initializeRequest);
1044
+ }
1045
+ async getInitializeRequest() {
1046
+ return this.ctx.storage.get("initializeRequest");
1047
+ }
1048
+ /** Read the transport type for this agent.
1049
+ * This relies on the naming scheme being `sse:${sessionId}`
1050
+ * or `streamable-http:${sessionId}`.
1051
+ */
1052
+ getTransportType() {
1053
+ const [t, ..._] = this.name.split(":");
1054
+ switch (t) {
1055
+ case "sse": return "sse";
1056
+ case "streamable-http": return "streamable-http";
1057
+ default: throw new Error("Invalid transport type. McpAgent must be addressed with a valid protocol.");
1058
+ }
1059
+ }
1060
+ /** Read the sessionId for this agent.
1061
+ * This relies on the naming scheme being `sse:${sessionId}`
1062
+ * or `streamable-http:${sessionId}`.
1063
+ */
1064
+ getSessionId() {
1065
+ const [_, sessionId] = this.name.split(":");
1066
+ if (!sessionId) throw new Error("Invalid session id. McpAgent must be addressed with a valid session id.");
1067
+ return sessionId;
1068
+ }
1069
+ /** Get the unique WebSocket. SSE transport only. */
1070
+ getWebSocket() {
1071
+ const websockets = Array.from(this.getConnections());
1072
+ if (websockets.length === 0) return null;
1073
+ return websockets[0];
1074
+ }
1075
+ /** Returns a new transport matching the type of the Agent. */
1076
+ initTransport() {
1077
+ switch (this.getTransportType()) {
1078
+ case "sse": return new McpSSETransport(() => this.getWebSocket());
1079
+ case "streamable-http": return new StreamableHTTPServerTransport({});
1080
+ }
1081
+ }
1082
+ /** Update and store the props */
1083
+ async updateProps(props) {
1084
+ await this.ctx.storage.put("props", props ?? {});
1085
+ this.props = props;
1086
+ }
1087
+ async reinitializeServer() {
1088
+ const initializeRequest = await this.getInitializeRequest();
1089
+ if (initializeRequest) this._transport?.onmessage?.(initializeRequest);
1090
+ }
1091
+ /** Sets up the MCP transport and server every time the Agent is started.*/
1092
+ async onStart(props) {
1093
+ if (props) await this.updateProps(props);
1094
+ this.props = await this.ctx.storage.get("props");
1095
+ await this.init();
1096
+ const server = await this.server;
1097
+ this._transport = this.initTransport();
1098
+ await server.connect(this._transport);
1099
+ await this.reinitializeServer();
1100
+ }
1101
+ /** Validates new WebSocket connections. */
1102
+ async onConnect(conn, { request: req }) {
1103
+ switch (this.getTransportType()) {
1104
+ case "sse":
1105
+ if (Array.from(this.getConnections()).length > 1) {
1106
+ conn.close(1008, "Websocket already connected");
1107
+ return;
1108
+ }
1109
+ break;
1110
+ case "streamable-http": if (this._transport instanceof StreamableHTTPServerTransport) switch (req.headers.get(MCP_HTTP_METHOD_HEADER)) {
1111
+ case "POST": {
1112
+ const payloadHeader = req.headers.get(MCP_MESSAGE_HEADER);
1113
+ let rawPayload;
1114
+ if (!payloadHeader) rawPayload = "{}";
1115
+ else try {
1116
+ rawPayload = Buffer.from(payloadHeader, "base64").toString("utf-8");
1117
+ } catch (_error) {
1118
+ throw new Error("Internal Server Error: Failed to decode MCP message header");
1119
+ }
1120
+ const parsedBody = JSON.parse(rawPayload);
1121
+ this._transport?.handlePostRequest(req, parsedBody);
1122
+ break;
1123
+ }
1124
+ case "GET":
1125
+ this._transport?.handleGetRequest(req);
1126
+ break;
1127
+ }
1128
+ }
1129
+ }
1130
+ /** Handles MCP Messages for the legacy SSE transport. */
1131
+ async onSSEMcpMessage(_sessionId, messageBody) {
1132
+ if (this.getTransportType() !== "sse") return /* @__PURE__ */ new Error("Internal Server Error: Expected SSE transport");
1133
+ try {
1134
+ let parsedMessage;
1135
+ try {
1136
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
1137
+ } catch (error) {
1138
+ this._transport?.onerror?.(error);
1139
+ throw error;
1140
+ }
1141
+ if (await this._handleElicitationResponse(parsedMessage)) return null;
1142
+ this._transport?.onmessage?.(parsedMessage);
1143
+ return null;
1144
+ } catch (error) {
1145
+ console.error("Error forwarding message to SSE:", error);
1146
+ this._transport?.onerror?.(error);
1147
+ return error;
1148
+ }
1149
+ }
1150
+ /** Elicit user input with a message and schema */
1151
+ async elicitInput(params) {
1152
+ const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
1153
+ await this.ctx.storage.put(`elicitation:${requestId}`, {
1154
+ message: params.message,
1155
+ requestedSchema: params.requestedSchema,
1156
+ timestamp: Date.now()
1157
+ });
1158
+ const elicitRequest = {
1159
+ jsonrpc: "2.0",
1160
+ id: requestId,
1161
+ method: "elicitation/create",
1162
+ params: {
1163
+ message: params.message,
1164
+ requestedSchema: params.requestedSchema
1165
+ }
1166
+ };
1167
+ if (this._transport) await this._transport.send(elicitRequest);
1168
+ else {
1169
+ const connections = this.getConnections();
1170
+ if (!connections || Array.from(connections).length === 0) {
1171
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
1172
+ throw new Error("No active connections available for elicitation");
1173
+ }
1174
+ const connectionList = Array.from(connections);
1175
+ for (const connection of connectionList) try {
1176
+ connection.send(JSON.stringify(elicitRequest));
1177
+ } catch (error) {
1178
+ console.error("Failed to send elicitation request:", error);
1179
+ }
1180
+ }
1181
+ return this._waitForElicitationResponse(requestId);
1182
+ }
1183
+ /** Wait for elicitation response through storage polling */
1184
+ async _waitForElicitationResponse(requestId) {
1185
+ const startTime = Date.now();
1186
+ const timeout = 6e4;
1187
+ try {
1188
+ while (Date.now() - startTime < timeout) {
1189
+ const response = await this.ctx.storage.get(`elicitation:response:${requestId}`);
1190
+ if (response) {
1191
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
1192
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
1193
+ return response;
1194
+ }
1195
+ await new Promise((resolve) => setTimeout(resolve, 100));
1196
+ }
1197
+ throw new Error("Elicitation request timed out");
1198
+ } finally {
1199
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
1200
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
1201
+ }
1202
+ }
1203
+ /** Handle elicitation responses */
1204
+ async _handleElicitationResponse(message) {
1205
+ if (isJSONRPCResponse(message) && message.result) {
1206
+ const requestId = message.id?.toString();
1207
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
1208
+ if (!await this.ctx.storage.get(`elicitation:${requestId}`)) return false;
1209
+ await this.ctx.storage.put(`elicitation:response:${requestId}`, message.result);
1210
+ return true;
1211
+ }
1212
+ if (isJSONRPCError(message)) {
1213
+ const requestId = message.id?.toString();
1214
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
1215
+ if (!await this.ctx.storage.get(`elicitation:${requestId}`)) return false;
1216
+ const errorResult = {
1217
+ action: "cancel",
1218
+ content: { error: message.error.message || "Elicitation request failed" }
1219
+ };
1220
+ await this.ctx.storage.put(`elicitation:response:${requestId}`, errorResult);
1221
+ return true;
1222
+ }
1223
+ return false;
1224
+ }
1225
+ /** Return a handler for the given path for this MCP.
1226
+ * Defaults to Streamable HTTP transport.
1227
+ */
1228
+ static serve(path, { binding = "MCP_OBJECT", corsOptions, transport = "streamable-http" } = {}) {
1229
+ return { async fetch(request, env, ctx) {
1230
+ const corsResponse = handleCORS(request, corsOptions);
1231
+ if (corsResponse) return corsResponse;
1232
+ const bindingValue = env[binding];
1233
+ if (bindingValue == null || typeof bindingValue !== "object") throw new Error(`Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`);
1234
+ if (!isDurableObjectNamespace(bindingValue)) throw new Error(`Invalid McpAgent binding for ${binding}. Make sure it's a Durable Object binding.`);
1235
+ const namespace = bindingValue;
1236
+ switch (transport) {
1237
+ case "streamable-http": return createStreamingHttpHandler(path, namespace, corsOptions)(request, ctx);
1238
+ case "sse": return createLegacySseHandler(path, namespace, corsOptions)(request, ctx);
1239
+ default: return new Response("Invalid MCP transport mode. Only `streamable-http` or `sse` are allowed.", { status: 500 });
1240
+ }
1241
+ } };
1242
+ }
1243
+ /**
1244
+ * Legacy api
1245
+ **/
1246
+ static mount(path, opts = {}) {
1247
+ return McpAgent.serveSSE(path, opts);
1248
+ }
1249
+ static serveSSE(path, opts = {}) {
1250
+ return McpAgent.serve(path, {
1251
+ ...opts,
1252
+ transport: "sse"
1253
+ });
1254
+ }
1255
+ };
1256
+
1257
+ //#endregion
1258
+ //#region src/index.ts
1259
+ /**
1260
+ * Type guard for RPC request messages
1261
+ */
1262
+ function isRPCRequest(msg) {
1263
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.RPC && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
1264
+ }
1265
+ /**
1266
+ * Type guard for state update messages
1267
+ */
1268
+ function isStateUpdateMessage(msg) {
1269
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.CF_AGENT_STATE && "state" in msg;
1270
+ }
1271
+ const callableMetadata = /* @__PURE__ */ new Map();
1272
+ /**
1273
+ * Decorator that marks a method as callable by clients
1274
+ * @param metadata Optional metadata about the callable method
1275
+ */
1276
+ function callable(metadata = {}) {
1277
+ return function callableDecorator(target, context) {
1278
+ if (!callableMetadata.has(target)) callableMetadata.set(target, metadata);
1279
+ return target;
1280
+ };
1281
+ }
1282
+ let didWarnAboutUnstableCallable = false;
1283
+ /**
1284
+ * Decorator that marks a method as callable by clients
1285
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
1286
+ * @param metadata Optional metadata about the callable method
1287
+ */
1288
+ const unstable_callable = (metadata = {}) => {
1289
+ if (!didWarnAboutUnstableCallable) {
1290
+ didWarnAboutUnstableCallable = true;
1291
+ console.warn("unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.");
1292
+ }
1293
+ callable(metadata);
1294
+ };
1295
+ function getNextCronTime(cron) {
1296
+ return parseCronExpression(cron).getNextDate();
1297
+ }
1298
+ const STATE_ROW_ID = "cf_state_row_id";
1299
+ const STATE_WAS_CHANGED = "cf_state_was_changed";
1300
+ const DEFAULT_STATE = {};
1301
+ const agentContext = new AsyncLocalStorage();
1302
+ function getCurrentAgent() {
1303
+ const store = agentContext.getStore();
1304
+ if (!store) return {
1305
+ agent: void 0,
1306
+ connection: void 0,
1307
+ request: void 0,
1308
+ email: void 0
1309
+ };
1310
+ return store;
1311
+ }
1312
+ /**
1313
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
1314
+ * @param agent The agent instance
1315
+ * @param method The method to wrap
1316
+ * @returns A wrapped method that runs within the agent context
1317
+ */
1318
+ function withAgentContext(method) {
1319
+ return function(...args) {
1320
+ const { connection, request, email, agent } = getCurrentAgent();
1321
+ if (agent === this) return method.apply(this, args);
1322
+ return agentContext.run({
1323
+ agent: this,
1324
+ connection,
1325
+ request,
1326
+ email
1327
+ }, () => {
1328
+ return method.apply(this, args);
1329
+ });
1330
+ };
1331
+ }
1332
+ /**
1333
+ * Base class for creating Agent implementations
1334
+ * @template Env Environment type containing bindings
1335
+ * @template State State type to store within the Agent
1336
+ */
1337
+ var Agent = class Agent extends Server {
1338
+ /**
1339
+ * Current state of the Agent
1340
+ */
1341
+ get state() {
1342
+ if (this._state !== DEFAULT_STATE) return this._state;
1343
+ const wasChanged = this.sql`
1344
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
1345
+ `;
1346
+ const result = this.sql`
1347
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
1348
+ `;
1349
+ if (wasChanged[0]?.state === "true" || result[0]?.state) {
1350
+ const state = result[0]?.state;
1351
+ this._state = JSON.parse(state);
1352
+ return this._state;
1353
+ }
1354
+ if (this.initialState === DEFAULT_STATE) return;
1355
+ this.setState(this.initialState);
1356
+ return this.initialState;
1357
+ }
1358
+ static {
1359
+ this.options = { hibernate: true };
1360
+ }
1361
+ /**
1362
+ * Execute SQL queries against the Agent's database
1363
+ * @template T Type of the returned rows
1364
+ * @param strings SQL query template strings
1365
+ * @param values Values to be inserted into the query
1366
+ * @returns Array of query results
1367
+ */
1368
+ sql(strings, ...values) {
1369
+ let query = "";
1370
+ try {
1371
+ query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
1372
+ return [...this.ctx.storage.sql.exec(query, ...values)];
1373
+ } catch (e) {
1374
+ console.error(`failed to execute sql query: ${query}`, e);
1375
+ throw this.onError(e);
1376
+ }
1377
+ }
1378
+ constructor(ctx, env) {
1379
+ super(ctx, env);
1380
+ this._state = DEFAULT_STATE;
1381
+ this._disposables = new DisposableStore();
1382
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
1383
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
1384
+ this.initialState = DEFAULT_STATE;
1385
+ this.observability = genericObservability;
1386
+ this._flushingQueue = false;
1387
+ this.alarm = async () => {
1388
+ const now = Math.floor(Date.now() / 1e3);
1389
+ const result = this.sql`
1390
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
1391
+ `;
1392
+ if (result && Array.isArray(result)) for (const row of result) {
1393
+ const callback = this[row.callback];
1394
+ if (!callback) {
1395
+ console.error(`callback ${row.callback} not found`);
1396
+ continue;
1397
+ }
1398
+ await agentContext.run({
1399
+ agent: this,
1400
+ connection: void 0,
1401
+ request: void 0,
1402
+ email: void 0
1403
+ }, async () => {
1404
+ try {
1405
+ this.observability?.emit({
1406
+ displayMessage: `Schedule ${row.id} executed`,
1407
+ id: nanoid(),
1408
+ payload: {
1409
+ callback: row.callback,
1410
+ id: row.id
1411
+ },
1412
+ timestamp: Date.now(),
1413
+ type: "schedule:execute"
1414
+ }, this.ctx);
1415
+ await callback.bind(this)(JSON.parse(row.payload), row);
1416
+ } catch (e) {
1417
+ console.error(`error executing callback "${row.callback}"`, e);
1418
+ }
1419
+ });
1420
+ if (row.type === "cron") {
1421
+ const nextExecutionTime = getNextCronTime(row.cron);
1422
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
1423
+ this.sql`
1424
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
1425
+ `;
1426
+ } else this.sql`
1427
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
1428
+ `;
1429
+ }
1430
+ await this._scheduleNextAlarm();
1431
+ };
1432
+ if (!wrappedClasses.has(this.constructor)) {
1433
+ this._autoWrapCustomMethods();
1434
+ wrappedClasses.add(this.constructor);
1435
+ }
1436
+ this._disposables.add(this.mcp.onConnected(async () => {
1437
+ this.broadcastMcpServers();
1438
+ }));
1439
+ this._disposables.add(this.mcp.onObservabilityEvent((event) => {
1440
+ this.observability?.emit(event);
1441
+ }));
1442
+ this.sql`
1443
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
1444
+ id TEXT PRIMARY KEY NOT NULL,
1445
+ state TEXT
1446
+ )
1447
+ `;
1448
+ this.sql`
1449
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
1450
+ id TEXT PRIMARY KEY NOT NULL,
1451
+ payload TEXT,
1452
+ callback TEXT,
1453
+ created_at INTEGER DEFAULT (unixepoch())
1454
+ )
1455
+ `;
1456
+ this.ctx.blockConcurrencyWhile(async () => {
1457
+ return this._tryCatch(async () => {
1458
+ this.sql`
1459
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
1460
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
1461
+ callback TEXT,
1462
+ payload TEXT,
1463
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
1464
+ time INTEGER,
1465
+ delayInSeconds INTEGER,
1466
+ cron TEXT,
1467
+ created_at INTEGER DEFAULT (unixepoch())
1468
+ )
1469
+ `;
1470
+ await this.alarm();
1471
+ });
1472
+ });
1473
+ this.sql`
1474
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
1475
+ id TEXT PRIMARY KEY NOT NULL,
1476
+ name TEXT NOT NULL,
1477
+ server_url TEXT NOT NULL,
1478
+ callback_url TEXT NOT NULL,
1479
+ client_id TEXT,
1480
+ auth_url TEXT,
1481
+ server_options TEXT
1482
+ )
1483
+ `;
1484
+ const _onRequest = this.onRequest.bind(this);
1485
+ this.onRequest = (request) => {
1486
+ return agentContext.run({
1487
+ agent: this,
1488
+ connection: void 0,
1489
+ request,
1490
+ email: void 0
1491
+ }, async () => {
1492
+ const callbackResult = await this._handlePotentialOAuthCallback(request);
1493
+ if (callbackResult) return callbackResult;
1494
+ return this._tryCatch(() => _onRequest(request));
1495
+ });
1496
+ };
1497
+ const _onMessage = this.onMessage.bind(this);
1498
+ this.onMessage = async (connection, message) => {
1499
+ return agentContext.run({
1500
+ agent: this,
1501
+ connection,
1502
+ request: void 0,
1503
+ email: void 0
1504
+ }, async () => {
1505
+ if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
1506
+ let parsed;
1507
+ try {
1508
+ parsed = JSON.parse(message);
1509
+ } catch (_e) {
1510
+ return this._tryCatch(() => _onMessage(connection, message));
1511
+ }
1512
+ if (isStateUpdateMessage(parsed)) {
1513
+ this._setStateInternal(parsed.state, connection);
1514
+ return;
1515
+ }
1516
+ if (isRPCRequest(parsed)) {
1517
+ try {
1518
+ const { id, method, args } = parsed;
1519
+ const methodFn = this[method];
1520
+ if (typeof methodFn !== "function") throw new Error(`Method ${method} does not exist`);
1521
+ if (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);
1522
+ const metadata = callableMetadata.get(methodFn);
1523
+ if (metadata?.streaming) {
1524
+ const stream = new StreamingResponse(connection, id);
1525
+ await methodFn.apply(this, [stream, ...args]);
1526
+ return;
1527
+ }
1528
+ const result = await methodFn.apply(this, args);
1529
+ this.observability?.emit({
1530
+ displayMessage: `RPC call to ${method}`,
1531
+ id: nanoid(),
1532
+ payload: {
1533
+ method,
1534
+ streaming: metadata?.streaming
1535
+ },
1536
+ timestamp: Date.now(),
1537
+ type: "rpc"
1538
+ }, this.ctx);
1539
+ const response = {
1540
+ done: true,
1541
+ id,
1542
+ result,
1543
+ success: true,
1544
+ type: MessageType.RPC
1545
+ };
1546
+ connection.send(JSON.stringify(response));
1547
+ } catch (e) {
1548
+ const response = {
1549
+ error: e instanceof Error ? e.message : "Unknown error occurred",
1550
+ id: parsed.id,
1551
+ success: false,
1552
+ type: MessageType.RPC
1553
+ };
1554
+ connection.send(JSON.stringify(response));
1555
+ console.error("RPC error:", e);
1556
+ }
1557
+ return;
1558
+ }
1559
+ return this._tryCatch(() => _onMessage(connection, message));
1560
+ });
1561
+ };
1562
+ const _onConnect = this.onConnect.bind(this);
1563
+ this.onConnect = (connection, ctx$1) => {
1564
+ return agentContext.run({
1565
+ agent: this,
1566
+ connection,
1567
+ request: ctx$1.request,
1568
+ email: void 0
1569
+ }, () => {
1570
+ if (this.state) connection.send(JSON.stringify({
1571
+ state: this.state,
1572
+ type: MessageType.CF_AGENT_STATE
1573
+ }));
1574
+ connection.send(JSON.stringify({
1575
+ mcp: this.getMcpServers(),
1576
+ type: MessageType.CF_AGENT_MCP_SERVERS
1577
+ }));
1578
+ this.observability?.emit({
1579
+ displayMessage: "Connection established",
1580
+ id: nanoid(),
1581
+ payload: { connectionId: connection.id },
1582
+ timestamp: Date.now(),
1583
+ type: "connect"
1584
+ }, this.ctx);
1585
+ return this._tryCatch(() => _onConnect(connection, ctx$1));
1586
+ });
1587
+ };
1588
+ const _onStart = this.onStart.bind(this);
1589
+ this.onStart = async (props) => {
1590
+ return agentContext.run({
1591
+ agent: this,
1592
+ connection: void 0,
1593
+ request: void 0,
1594
+ email: void 0
1595
+ }, async () => {
1596
+ await this._tryCatch(() => {
1597
+ const servers = this.sql`
1598
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1599
+ `;
1600
+ this.broadcastMcpServers();
1601
+ if (servers && Array.isArray(servers) && servers.length > 0) {
1602
+ servers.forEach((server) => {
1603
+ if (server.callback_url) this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
1604
+ });
1605
+ servers.forEach((server) => {
1606
+ this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, server.server_options ? JSON.parse(server.server_options) : void 0, {
1607
+ id: server.id,
1608
+ oauthClientId: server.client_id ?? void 0
1609
+ }).then(() => {
1610
+ this.broadcastMcpServers();
1611
+ }).catch((error) => {
1612
+ console.error(`Error connecting to MCP server: ${server.name} (${server.server_url})`, error);
1613
+ this.broadcastMcpServers();
1614
+ });
1615
+ });
1616
+ }
1617
+ return _onStart(props);
1618
+ });
1619
+ });
1620
+ };
1621
+ }
1622
+ _setStateInternal(state, source = "server") {
1623
+ this._state = state;
1624
+ this.sql`
1625
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
1626
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
1627
+ `;
1628
+ this.sql`
1629
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
1630
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
1631
+ `;
1632
+ this.broadcast(JSON.stringify({
1633
+ state,
1634
+ type: MessageType.CF_AGENT_STATE
1635
+ }), source !== "server" ? [source.id] : []);
1636
+ return this._tryCatch(() => {
1637
+ const { connection, request, email } = agentContext.getStore() || {};
1638
+ return agentContext.run({
1639
+ agent: this,
1640
+ connection,
1641
+ request,
1642
+ email
1643
+ }, async () => {
1644
+ this.observability?.emit({
1645
+ displayMessage: "State updated",
1646
+ id: nanoid(),
1647
+ payload: {},
1648
+ timestamp: Date.now(),
1649
+ type: "state:update"
1650
+ }, this.ctx);
1651
+ return this.onStateUpdate(state, source);
1652
+ });
1653
+ });
1654
+ }
1655
+ /**
1656
+ * Update the Agent's state
1657
+ * @param state New state to set
1658
+ */
1659
+ setState(state) {
1660
+ this._setStateInternal(state, "server");
1661
+ }
1662
+ /**
1663
+ * Called when the Agent's state is updated
1664
+ * @param state Updated state
1665
+ * @param source Source of the state update ("server" or a client connection)
1666
+ */
1667
+ onStateUpdate(state, source) {}
1668
+ /**
1669
+ * Called when the Agent receives an email via routeAgentEmail()
1670
+ * Override this method to handle incoming emails
1671
+ * @param email Email message to process
1672
+ */
1673
+ async _onEmail(email) {
1674
+ return agentContext.run({
1675
+ agent: this,
1676
+ connection: void 0,
1677
+ request: void 0,
1678
+ email
1679
+ }, async () => {
1680
+ if ("onEmail" in this && typeof this.onEmail === "function") return this._tryCatch(() => this.onEmail(email));
1681
+ else {
1682
+ console.log("Received email from:", email.from, "to:", email.to);
1683
+ console.log("Subject:", email.headers.get("subject"));
1684
+ console.log("Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails");
1685
+ }
1686
+ });
1687
+ }
1688
+ /**
1689
+ * Reply to an email
1690
+ * @param email The email to reply to
1691
+ * @param options Options for the reply
1692
+ * @returns void
1693
+ */
1694
+ async replyToEmail(email, options) {
1695
+ return this._tryCatch(async () => {
1696
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
1697
+ const agentId = this.name;
1698
+ const { createMimeMessage } = await import("mimetext");
1699
+ const msg = createMimeMessage();
1700
+ msg.setSender({
1701
+ addr: email.to,
1702
+ name: options.fromName
1703
+ });
1704
+ msg.setRecipient(email.from);
1705
+ msg.setSubject(options.subject || `Re: ${email.headers.get("subject")}` || "No subject");
1706
+ msg.addMessage({
1707
+ contentType: options.contentType || "text/plain",
1708
+ data: options.body
1709
+ });
1710
+ const messageId = `<${agentId}@${email.from.split("@")[1]}>`;
1711
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
1712
+ msg.setHeader("Message-ID", messageId);
1713
+ msg.setHeader("X-Agent-Name", agentName);
1714
+ msg.setHeader("X-Agent-ID", agentId);
1715
+ if (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);
1716
+ await email.reply({
1717
+ from: email.to,
1718
+ raw: msg.asRaw(),
1719
+ to: email.from
1720
+ });
1721
+ });
1722
+ }
1723
+ async _tryCatch(fn) {
1724
+ try {
1725
+ return await fn();
1726
+ } catch (e) {
1727
+ throw this.onError(e);
1728
+ }
1729
+ }
1730
+ /**
1731
+ * Automatically wrap custom methods with agent context
1732
+ * This ensures getCurrentAgent() works in all custom methods without decorators
1733
+ */
1734
+ _autoWrapCustomMethods() {
1735
+ const basePrototypes = [Agent.prototype, Server.prototype];
1736
+ const baseMethods = /* @__PURE__ */ new Set();
1737
+ for (const baseProto of basePrototypes) {
1738
+ let proto$1 = baseProto;
1739
+ while (proto$1 && proto$1 !== Object.prototype) {
1740
+ const methodNames = Object.getOwnPropertyNames(proto$1);
1741
+ for (const methodName of methodNames) baseMethods.add(methodName);
1742
+ proto$1 = Object.getPrototypeOf(proto$1);
1743
+ }
1744
+ }
1745
+ let proto = Object.getPrototypeOf(this);
1746
+ let depth = 0;
1747
+ while (proto && proto !== Object.prototype && depth < 10) {
1748
+ const methodNames = Object.getOwnPropertyNames(proto);
1749
+ for (const methodName of methodNames) {
1750
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
1751
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") continue;
1752
+ const wrappedFunction = withAgentContext(this[methodName]);
1753
+ if (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));
1754
+ this.constructor.prototype[methodName] = wrappedFunction;
1755
+ }
1756
+ proto = Object.getPrototypeOf(proto);
1757
+ depth++;
1758
+ }
1759
+ }
1760
+ onError(connectionOrError, error) {
1761
+ let theError;
1762
+ if (connectionOrError && error) {
1763
+ theError = error;
1764
+ console.error("Error on websocket connection:", connectionOrError.id, theError);
1765
+ console.error("Override onError(connection, error) to handle websocket connection errors");
1766
+ } else {
1767
+ theError = connectionOrError;
1768
+ console.error("Error on server:", theError);
1769
+ console.error("Override onError(error) to handle server errors");
1770
+ }
1771
+ throw theError;
1772
+ }
1773
+ /**
1774
+ * Render content (not implemented in base class)
1775
+ */
1776
+ render() {
1777
+ throw new Error("Not implemented");
1778
+ }
1779
+ /**
1780
+ * Queue a task to be executed in the future
1781
+ * @param payload Payload to pass to the callback
1782
+ * @param callback Name of the method to call
1783
+ * @returns The ID of the queued task
1784
+ */
1785
+ async queue(callback, payload) {
1786
+ const id = nanoid(9);
1787
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
1788
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
1789
+ this.sql`
1790
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
1791
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
1792
+ `;
1793
+ this._flushQueue().catch((e) => {
1794
+ console.error("Error flushing queue:", e);
1795
+ });
1796
+ return id;
1797
+ }
1798
+ async _flushQueue() {
1799
+ if (this._flushingQueue) return;
1800
+ this._flushingQueue = true;
1801
+ while (true) {
1802
+ const result = this.sql`
1803
+ SELECT * FROM cf_agents_queues
1804
+ ORDER BY created_at ASC
1805
+ `;
1806
+ if (!result || result.length === 0) break;
1807
+ for (const row of result || []) {
1808
+ const callback = this[row.callback];
1809
+ if (!callback) {
1810
+ console.error(`callback ${row.callback} not found`);
1811
+ continue;
1812
+ }
1813
+ const { connection, request, email } = agentContext.getStore() || {};
1814
+ await agentContext.run({
1815
+ agent: this,
1816
+ connection,
1817
+ request,
1818
+ email
1819
+ }, async () => {
1820
+ await callback.bind(this)(JSON.parse(row.payload), row);
1821
+ await this.dequeue(row.id);
1822
+ });
1823
+ }
1824
+ }
1825
+ this._flushingQueue = false;
1826
+ }
1827
+ /**
1828
+ * Dequeue a task by ID
1829
+ * @param id ID of the task to dequeue
1830
+ */
1831
+ async dequeue(id) {
1832
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
1833
+ }
1834
+ /**
1835
+ * Dequeue all tasks
1836
+ */
1837
+ async dequeueAll() {
1838
+ this.sql`DELETE FROM cf_agents_queues`;
1839
+ }
1840
+ /**
1841
+ * Dequeue all tasks by callback
1842
+ * @param callback Name of the callback to dequeue
1843
+ */
1844
+ async dequeueAllByCallback(callback) {
1845
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1846
+ }
1847
+ /**
1848
+ * Get a queued task by ID
1849
+ * @param id ID of the task to get
1850
+ * @returns The task or undefined if not found
1851
+ */
1852
+ async getQueue(id) {
1853
+ const result = this.sql`
1854
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1855
+ `;
1856
+ return result ? {
1857
+ ...result[0],
1858
+ payload: JSON.parse(result[0].payload)
1859
+ } : void 0;
1860
+ }
1861
+ /**
1862
+ * Get all queues by key and value
1863
+ * @param key Key to filter by
1864
+ * @param value Value to filter by
1865
+ * @returns Array of matching QueueItem objects
1866
+ */
1867
+ async getQueues(key, value) {
1868
+ return this.sql`
1869
+ SELECT * FROM cf_agents_queues
1870
+ `.filter((row) => JSON.parse(row.payload)[key] === value);
1871
+ }
1872
+ /**
1873
+ * Schedule a task to be executed in the future
1874
+ * @template T Type of the payload data
1875
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
1876
+ * @param callback Name of the method to call
1877
+ * @param payload Data to pass to the callback
1878
+ * @returns Schedule object representing the scheduled task
1879
+ */
1880
+ async schedule(when, callback, payload) {
1881
+ const id = nanoid(9);
1882
+ const emitScheduleCreate = (schedule) => this.observability?.emit({
1883
+ displayMessage: `Schedule ${schedule.id} created`,
1884
+ id: nanoid(),
1885
+ payload: {
1886
+ callback,
1887
+ id
1888
+ },
1889
+ timestamp: Date.now(),
1890
+ type: "schedule:create"
1891
+ }, this.ctx);
1892
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
1893
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
1894
+ if (when instanceof Date) {
1895
+ const timestamp = Math.floor(when.getTime() / 1e3);
1896
+ this.sql`
1897
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
1898
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
1899
+ `;
1900
+ await this._scheduleNextAlarm();
1901
+ const schedule = {
1902
+ callback,
1903
+ id,
1904
+ payload,
1905
+ time: timestamp,
1906
+ type: "scheduled"
1907
+ };
1908
+ emitScheduleCreate(schedule);
1909
+ return schedule;
1910
+ }
1911
+ if (typeof when === "number") {
1912
+ const time = new Date(Date.now() + when * 1e3);
1913
+ const timestamp = Math.floor(time.getTime() / 1e3);
1914
+ this.sql`
1915
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
1916
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})
1917
+ `;
1918
+ await this._scheduleNextAlarm();
1919
+ const schedule = {
1920
+ callback,
1921
+ delayInSeconds: when,
1922
+ id,
1923
+ payload,
1924
+ time: timestamp,
1925
+ type: "delayed"
1926
+ };
1927
+ emitScheduleCreate(schedule);
1928
+ return schedule;
1929
+ }
1930
+ if (typeof when === "string") {
1931
+ const nextExecutionTime = getNextCronTime(when);
1932
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
1933
+ this.sql`
1934
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
1935
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})
1936
+ `;
1937
+ await this._scheduleNextAlarm();
1938
+ const schedule = {
1939
+ callback,
1940
+ cron: when,
1941
+ id,
1942
+ payload,
1943
+ time: timestamp,
1944
+ type: "cron"
1945
+ };
1946
+ emitScheduleCreate(schedule);
1947
+ return schedule;
1948
+ }
1949
+ throw new Error("Invalid schedule type");
1950
+ }
1951
+ /**
1952
+ * Get a scheduled task by ID
1953
+ * @template T Type of the payload data
1954
+ * @param id ID of the scheduled task
1955
+ * @returns The Schedule object or undefined if not found
1956
+ */
1957
+ async getSchedule(id) {
1958
+ const result = this.sql`
1959
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
1960
+ `;
1961
+ if (!result) {
1962
+ console.error(`schedule ${id} not found`);
1963
+ return;
1964
+ }
1965
+ return {
1966
+ ...result[0],
1967
+ payload: JSON.parse(result[0].payload)
1968
+ };
1969
+ }
1970
+ /**
1971
+ * Get scheduled tasks matching the given criteria
1972
+ * @template T Type of the payload data
1973
+ * @param criteria Criteria to filter schedules
1974
+ * @returns Array of matching Schedule objects
1975
+ */
1976
+ getSchedules(criteria = {}) {
1977
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
1978
+ const params = [];
1979
+ if (criteria.id) {
1980
+ query += " AND id = ?";
1981
+ params.push(criteria.id);
1982
+ }
1983
+ if (criteria.type) {
1984
+ query += " AND type = ?";
1985
+ params.push(criteria.type);
1986
+ }
1987
+ if (criteria.timeRange) {
1988
+ query += " AND time >= ? AND time <= ?";
1989
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
1990
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
1991
+ params.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));
1992
+ }
1993
+ return this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
1994
+ ...row,
1995
+ payload: JSON.parse(row.payload)
1996
+ }));
1997
+ }
1998
+ /**
1999
+ * Cancel a scheduled task
2000
+ * @param id ID of the task to cancel
2001
+ * @returns true if the task was cancelled, false otherwise
2002
+ */
2003
+ async cancelSchedule(id) {
2004
+ const schedule = await this.getSchedule(id);
2005
+ if (schedule) this.observability?.emit({
2006
+ displayMessage: `Schedule ${id} cancelled`,
2007
+ id: nanoid(),
2008
+ payload: {
2009
+ callback: schedule.callback,
2010
+ id: schedule.id
2011
+ },
2012
+ timestamp: Date.now(),
2013
+ type: "schedule:cancel"
2014
+ }, this.ctx);
2015
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
2016
+ await this._scheduleNextAlarm();
2017
+ return true;
2018
+ }
2019
+ async _scheduleNextAlarm() {
2020
+ const result = this.sql`
2021
+ SELECT time FROM cf_agents_schedules
2022
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
2023
+ ORDER BY time ASC
2024
+ LIMIT 1
2025
+ `;
2026
+ if (!result) return;
2027
+ if (result.length > 0 && "time" in result[0]) {
2028
+ const nextTime = result[0].time * 1e3;
2029
+ await this.ctx.storage.setAlarm(nextTime);
2030
+ }
2031
+ }
2032
+ /**
2033
+ * Destroy the Agent, removing all state and scheduled tasks
2034
+ */
2035
+ async destroy() {
2036
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
2037
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
2038
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
2039
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
2040
+ await this.ctx.storage.deleteAlarm();
2041
+ await this.ctx.storage.deleteAll();
2042
+ this._disposables.dispose();
2043
+ await this.mcp.dispose?.();
2044
+ this.ctx.abort("destroyed");
2045
+ this.observability?.emit({
2046
+ displayMessage: "Agent destroyed",
2047
+ id: nanoid(),
2048
+ payload: {},
2049
+ timestamp: Date.now(),
2050
+ type: "destroy"
2051
+ }, this.ctx);
2052
+ }
2053
+ /**
2054
+ * Get all methods marked as callable on this Agent
2055
+ * @returns A map of method names to their metadata
2056
+ */
2057
+ _isCallable(method) {
2058
+ return callableMetadata.has(this[method]);
2059
+ }
2060
+ /**
2061
+ * Connect to a new MCP Server
2062
+ *
2063
+ * @param serverName Name of the MCP server
2064
+ * @param url MCP Server SSE URL
2065
+ * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
2066
+ * @param agentsPrefix agents routing prefix if not using `agents`
2067
+ * @param options MCP client and transport options
2068
+ * @returns authUrl
2069
+ */
2070
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
2071
+ let resolvedCallbackHost = callbackHost;
2072
+ if (!resolvedCallbackHost) {
2073
+ const { request } = getCurrentAgent();
2074
+ if (!request) throw new Error("callbackHost is required when not called within a request context");
2075
+ const requestUrl = new URL(request.url);
2076
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
2077
+ }
2078
+ const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
2079
+ const serverId = nanoid(8);
2080
+ this.sql`
2081
+ INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
2082
+ VALUES (
2083
+ ${serverId},
2084
+ ${serverName},
2085
+ ${url},
2086
+ ${null},
2087
+ ${null},
2088
+ ${callbackUrl},
2089
+ ${options ? JSON.stringify(options) : null}
2090
+ );
2091
+ `;
2092
+ const result = await this._connectToMcpServerInternal(serverName, url, callbackUrl, options, { id: serverId });
2093
+ if (result.clientId || result.authUrl) this.sql`
2094
+ UPDATE cf_agents_mcp_servers
2095
+ SET client_id = ${result.clientId ?? null}, auth_url = ${result.authUrl ?? null}
2096
+ WHERE id = ${serverId}
2097
+ `;
2098
+ this.broadcastMcpServers();
2099
+ return result;
2100
+ }
2101
+ /**
2102
+ * Handle potential OAuth callback requests after DO hibernation.
2103
+ * Detects OAuth callbacks, restores state from database, and processes the callback.
2104
+ * Returns a Response if this was an OAuth callback, otherwise returns undefined.
2105
+ */
2106
+ async _handlePotentialOAuthCallback(request) {
2107
+ if (request.method !== "GET") return;
2108
+ const url = new URL(request.url);
2109
+ if (!(url.pathname.includes("/callback/") && url.searchParams.has("code"))) return;
2110
+ const pathParts = url.pathname.split("/");
2111
+ const callbackIndex = pathParts.indexOf("callback");
2112
+ const serverId = callbackIndex !== -1 ? pathParts[callbackIndex + 1] : null;
2113
+ if (!serverId) return new Response("Invalid callback URL: missing serverId", { status: 400 });
2114
+ if (this.mcp.isCallbackRequest(request) && this.mcp.mcpConnections[serverId]) return this._processOAuthCallback(request);
2115
+ try {
2116
+ const server = this.sql`
2117
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
2118
+ FROM cf_agents_mcp_servers
2119
+ WHERE id = ${serverId}
2120
+ `.find((s) => s.id === serverId);
2121
+ if (!server) return new Response(`OAuth callback failed: Server ${serverId} not found in database`, { status: 404 });
2122
+ if (!server.callback_url) return new Response(`OAuth callback failed: No callback URL stored for server ${serverId}`, { status: 500 });
2123
+ this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
2124
+ if (!this.mcp.mcpConnections[serverId]) {
2125
+ let parsedOptions;
2126
+ try {
2127
+ parsedOptions = server.server_options ? JSON.parse(server.server_options) : void 0;
2128
+ } catch {
2129
+ return new Response(`OAuth callback failed: Invalid server options in database for ${serverId}`, { status: 500 });
2130
+ }
2131
+ await this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, parsedOptions, {
2132
+ id: server.id,
2133
+ oauthClientId: server.client_id ?? void 0
2134
+ });
2135
+ }
2136
+ return this._processOAuthCallback(request);
2137
+ } catch (error) {
2138
+ const errorMsg = error instanceof Error ? error.message : "Unknown error";
2139
+ console.error(`Failed to restore MCP state for ${serverId}:`, error);
2140
+ return new Response(`OAuth callback failed during state restoration: ${errorMsg}`, { status: 500 });
2141
+ }
2142
+ }
2143
+ /**
2144
+ * Process an OAuth callback request (assumes state is already restored)
2145
+ */
2146
+ async _processOAuthCallback(request) {
2147
+ const result = await this.mcp.handleCallbackRequest(request);
2148
+ this.broadcastMcpServers();
2149
+ if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
2150
+ console.error("Background connection failed:", error);
2151
+ }).finally(() => {
2152
+ this.broadcastMcpServers();
2153
+ });
2154
+ return this.handleOAuthCallbackResponse(result, request);
2155
+ }
2156
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
2157
+ const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
2158
+ if (reconnect) {
2159
+ authProvider.serverId = reconnect.id;
2160
+ if (reconnect.oauthClientId) authProvider.clientId = reconnect.oauthClientId;
2161
+ }
2162
+ const transportType = options?.transport?.type ?? "auto";
2163
+ let headerTransportOpts = {};
2164
+ if (options?.transport?.headers) headerTransportOpts = {
2165
+ eventSourceInit: { fetch: (url$1, init) => fetch(url$1, {
2166
+ ...init,
2167
+ headers: options?.transport?.headers
2168
+ }) },
2169
+ requestInit: { headers: options?.transport?.headers }
2170
+ };
2171
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
2172
+ client: options?.client,
2173
+ reconnect,
2174
+ transport: {
2175
+ ...headerTransportOpts,
2176
+ authProvider,
2177
+ type: transportType
2178
+ }
2179
+ });
2180
+ return {
2181
+ authUrl,
2182
+ clientId,
2183
+ id
2184
+ };
2185
+ }
2186
+ async removeMcpServer(id) {
2187
+ this.mcp.closeConnection(id);
2188
+ this.mcp.unregisterCallbackUrl(id);
2189
+ this.sql`
2190
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
2191
+ `;
2192
+ this.broadcastMcpServers();
2193
+ }
2194
+ getMcpServers() {
2195
+ const mcpState = {
2196
+ prompts: this.mcp.listPrompts(),
2197
+ resources: this.mcp.listResources(),
2198
+ servers: {},
2199
+ tools: this.mcp.listTools()
2200
+ };
2201
+ const servers = this.sql`
2202
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
2203
+ `;
2204
+ if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
2205
+ const serverConn = this.mcp.mcpConnections[server.id];
2206
+ mcpState.servers[server.id] = {
2207
+ auth_url: server.auth_url,
2208
+ capabilities: serverConn?.serverCapabilities ?? null,
2209
+ instructions: serverConn?.instructions ?? null,
2210
+ name: server.name,
2211
+ server_url: server.server_url,
2212
+ state: serverConn?.connectionState ?? "authenticating"
2213
+ };
2214
+ }
2215
+ return mcpState;
2216
+ }
2217
+ broadcastMcpServers() {
2218
+ this.broadcast(JSON.stringify({
2219
+ mcp: this.getMcpServers(),
2220
+ type: MessageType.CF_AGENT_MCP_SERVERS
2221
+ }));
2222
+ }
2223
+ /**
2224
+ * Handle OAuth callback response using MCPClientManager configuration
2225
+ * @param result OAuth callback result
2226
+ * @param request The original request (needed for base URL)
2227
+ * @returns Response for the OAuth callback
2228
+ */
2229
+ handleOAuthCallbackResponse(result, request) {
2230
+ const config = this.mcp.getOAuthCallbackConfig();
2231
+ if (config?.customHandler) return config.customHandler(result);
2232
+ if (config?.successRedirect && result.authSuccess) return Response.redirect(config.successRedirect);
2233
+ if (config?.errorRedirect && !result.authSuccess) return Response.redirect(`${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`);
2234
+ const baseUrl = new URL(request.url).origin;
2235
+ return Response.redirect(baseUrl);
2236
+ }
2237
+ };
2238
+ const wrappedClasses = /* @__PURE__ */ new Set();
2239
+ /**
2240
+ * Route a request to the appropriate Agent
2241
+ * @param request Request to route
2242
+ * @param env Environment containing Agent bindings
2243
+ * @param options Routing options
2244
+ * @returns Response from the Agent or undefined if no route matched
2245
+ */
2246
+ async function routeAgentRequest(request, env, options) {
2247
+ const corsHeaders$1 = options?.cors === true ? {
2248
+ "Access-Control-Allow-Credentials": "true",
2249
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
2250
+ "Access-Control-Allow-Origin": "*",
2251
+ "Access-Control-Max-Age": "86400"
2252
+ } : options?.cors;
2253
+ if (request.method === "OPTIONS") {
2254
+ if (corsHeaders$1) return new Response(null, { headers: corsHeaders$1 });
2255
+ console.warn("Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.");
2256
+ }
2257
+ let response = await routePartykitRequest(request, env, {
2258
+ prefix: "agents",
2259
+ ...options
2260
+ });
2261
+ if (response && corsHeaders$1 && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") response = new Response(response.body, { headers: {
2262
+ ...response.headers,
2263
+ ...corsHeaders$1
2264
+ } });
2265
+ return response;
2266
+ }
2267
+ /**
2268
+ * Create a resolver that uses the message-id header to determine the agent to route the email to
2269
+ * @returns A function that resolves the agent to route the email to
2270
+ */
2271
+ function createHeaderBasedEmailResolver() {
2272
+ return async (email, _env) => {
2273
+ const messageId = email.headers.get("message-id");
2274
+ if (messageId) {
2275
+ const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);
2276
+ if (messageIdMatch) {
2277
+ const [, agentId$1, domain] = messageIdMatch;
2278
+ return {
2279
+ agentName: domain.split(".")[0],
2280
+ agentId: agentId$1
2281
+ };
2282
+ }
2283
+ }
2284
+ const references = email.headers.get("references");
2285
+ if (references) {
2286
+ const referencesMatch = references.match(/<([A-Za-z0-9+/]{43}=)@([^>]+)>/);
2287
+ if (referencesMatch) {
2288
+ const [, base64Id, domain] = referencesMatch;
2289
+ const agentId$1 = Buffer.from(base64Id, "base64").toString("hex");
2290
+ return {
2291
+ agentName: domain.split(".")[0],
2292
+ agentId: agentId$1
2293
+ };
2294
+ }
2295
+ }
2296
+ const agentName = email.headers.get("x-agent-name");
2297
+ const agentId = email.headers.get("x-agent-id");
2298
+ if (agentName && agentId) return {
2299
+ agentName,
2300
+ agentId
2301
+ };
2302
+ return null;
2303
+ };
2304
+ }
2305
+ /**
2306
+ * Create a resolver that uses the email address to determine the agent to route the email to
2307
+ * @param defaultAgentName The default agent name to use if the email address does not contain a sub-address
2308
+ * @returns A function that resolves the agent to route the email to
2309
+ */
2310
+ function createAddressBasedEmailResolver(defaultAgentName) {
2311
+ return async (email, _env) => {
2312
+ const emailMatch = email.to.match(/^([^+@]+)(?:\+([^@]+))?@(.+)$/);
2313
+ if (!emailMatch) return null;
2314
+ const [, localPart, subAddress] = emailMatch;
2315
+ if (subAddress) return {
2316
+ agentName: localPart,
2317
+ agentId: subAddress
2318
+ };
2319
+ return {
2320
+ agentName: defaultAgentName,
2321
+ agentId: localPart
2322
+ };
2323
+ };
2324
+ }
2325
+ /**
2326
+ * Create a resolver that uses the agentName and agentId to determine the agent to route the email to
2327
+ * @param agentName The name of the agent to route the email to
2328
+ * @param agentId The id of the agent to route the email to
2329
+ * @returns A function that resolves the agent to route the email to
2330
+ */
2331
+ function createCatchAllEmailResolver(agentName, agentId) {
2332
+ return async () => ({
2333
+ agentName,
2334
+ agentId
2335
+ });
2336
+ }
2337
+ const agentMapCache = /* @__PURE__ */ new WeakMap();
2338
+ /**
2339
+ * Route an email to the appropriate Agent
2340
+ * @param email The email to route
2341
+ * @param env The environment containing the Agent bindings
2342
+ * @param options The options for routing the email
2343
+ * @returns A promise that resolves when the email has been routed
2344
+ */
2345
+ async function routeAgentEmail(email, env, options) {
2346
+ const routingInfo = await options.resolver(email, env);
2347
+ if (!routingInfo) {
2348
+ console.warn("No routing information found for email, dropping message");
2349
+ return;
2350
+ }
2351
+ if (!agentMapCache.has(env)) {
2352
+ const map = {};
2353
+ for (const [key, value] of Object.entries(env)) if (value && typeof value === "object" && "idFromName" in value && typeof value.idFromName === "function") {
2354
+ map[key] = value;
2355
+ map[camelCaseToKebabCase(key)] = value;
2356
+ }
2357
+ agentMapCache.set(env, map);
2358
+ }
2359
+ const agentMap = agentMapCache.get(env);
2360
+ const namespace = agentMap[routingInfo.agentName];
2361
+ if (!namespace) {
2362
+ const availableAgents = Object.keys(agentMap).filter((key) => !key.includes("-")).join(", ");
2363
+ throw new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);
2364
+ }
2365
+ const agent = await getAgentByName(namespace, routingInfo.agentId);
2366
+ const serialisableEmail = {
2367
+ getRaw: async () => {
2368
+ const reader = email.raw.getReader();
2369
+ const chunks = [];
2370
+ let done = false;
2371
+ while (!done) {
2372
+ const { value, done: readerDone } = await reader.read();
2373
+ done = readerDone;
2374
+ if (value) chunks.push(value);
2375
+ }
2376
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
2377
+ const combined = new Uint8Array(totalLength);
2378
+ let offset = 0;
2379
+ for (const chunk of chunks) {
2380
+ combined.set(chunk, offset);
2381
+ offset += chunk.length;
2382
+ }
2383
+ return combined;
2384
+ },
2385
+ headers: email.headers,
2386
+ rawSize: email.rawSize,
2387
+ setReject: (reason) => {
2388
+ email.setReject(reason);
2389
+ },
2390
+ forward: (rcptTo, headers) => {
2391
+ return email.forward(rcptTo, headers);
2392
+ },
2393
+ reply: (options$1) => {
2394
+ return email.reply(new EmailMessage(options$1.from, options$1.to, options$1.raw));
2395
+ },
2396
+ from: email.from,
2397
+ to: email.to
2398
+ };
2399
+ await agent._onEmail(serialisableEmail);
2400
+ }
2401
+ /**
2402
+ * Get or create an Agent by name
2403
+ * @template Env Environment type containing bindings
2404
+ * @template T Type of the Agent class
2405
+ * @param namespace Agent namespace
2406
+ * @param name Name of the Agent instance
2407
+ * @param options Options for Agent creation
2408
+ * @returns Promise resolving to an Agent instance stub
2409
+ */
2410
+ async function getAgentByName(namespace, name, options) {
2411
+ return getServerByName(namespace, name, options);
2412
+ }
2413
+ /**
2414
+ * A wrapper for streaming responses in callable methods
2415
+ */
2416
+ var StreamingResponse = class {
2417
+ constructor(connection, id) {
2418
+ this._closed = false;
2419
+ this._connection = connection;
2420
+ this._id = id;
2421
+ }
2422
+ /**
2423
+ * Send a chunk of data to the client
2424
+ * @param chunk The data to send
2425
+ */
2426
+ send(chunk) {
2427
+ if (this._closed) throw new Error("StreamingResponse is already closed");
2428
+ const response = {
2429
+ done: false,
2430
+ id: this._id,
2431
+ result: chunk,
2432
+ success: true,
2433
+ type: MessageType.RPC
2434
+ };
2435
+ this._connection.send(JSON.stringify(response));
2436
+ }
2437
+ /**
2438
+ * End the stream and send the final chunk (if any)
2439
+ * @param finalChunk Optional final chunk of data to send
2440
+ */
2441
+ end(finalChunk) {
2442
+ if (this._closed) throw new Error("StreamingResponse is already closed");
2443
+ this._closed = true;
2444
+ const response = {
2445
+ done: true,
2446
+ id: this._id,
2447
+ result: finalChunk,
2448
+ success: true,
2449
+ type: MessageType.RPC
2450
+ };
2451
+ this._connection.send(JSON.stringify(response));
2452
+ }
2453
+ };
2454
+
2455
+ //#endregion
2456
+ export { Agent, ElicitRequestSchema$1 as ElicitRequestSchema, McpAgent, StreamingResponse, WorkerTransport, callable, createAddressBasedEmailResolver, createCatchAllEmailResolver, createHeaderBasedEmailResolver, experimental_createMcpHandler, genericObservability, getAgentByName, getCurrentAgent, getMcpAuthContext, routeAgentEmail, routeAgentRequest, unstable_callable };
2457
+ //# sourceMappingURL=src-tpG9NtHy.js.map