agents 0.0.0-f5b5854 → 0.0.0-f64700e

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.
Files changed (70) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +56 -11
  3. package/dist/ai-chat-agent.js +532 -160
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-gdyLiTd8.js +155 -0
  6. package/dist/ai-chat-v5-migration-gdyLiTd8.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -72
  10. package/dist/ai-react.js +261 -188
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-BWW4umHY.d.ts +95 -0
  13. package/dist/ai-types-UZlfLOYP.js +20 -0
  14. package/dist/ai-types-UZlfLOYP.js.map +1 -0
  15. package/dist/ai-types.d.ts +6 -69
  16. package/dist/ai-types.js +3 -1
  17. package/dist/client-C-nwz-3N.d.ts +5313 -0
  18. package/dist/client-CZBVDDoO.js +786 -0
  19. package/dist/client-CZBVDDoO.js.map +1 -0
  20. package/dist/client-CmMi85Sj.d.ts +104 -0
  21. package/dist/client-DjR-lC16.js +117 -0
  22. package/dist/client-DjR-lC16.js.map +1 -0
  23. package/dist/client.d.ts +12 -79
  24. package/dist/client.js +3 -130
  25. package/dist/codemode/ai.d.ts +27 -0
  26. package/dist/codemode/ai.js +151 -0
  27. package/dist/codemode/ai.js.map +1 -0
  28. package/dist/do-oauth-client-provider-B2jr6UNq.js +93 -0
  29. package/dist/do-oauth-client-provider-B2jr6UNq.js.map +1 -0
  30. package/dist/do-oauth-client-provider-CCwGwnrA.d.ts +55 -0
  31. package/dist/index-CMEWpbHx.d.ts +568 -0
  32. package/dist/index-W4JUkafc.d.ts +54 -0
  33. package/dist/index.d.ts +63 -295
  34. package/dist/index.js +7 -20
  35. package/dist/mcp/client.d.ts +4 -763
  36. package/dist/mcp/client.js +2 -407
  37. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  38. package/dist/mcp/do-oauth-client-provider.js +2 -106
  39. package/dist/mcp/index.d.ts +73 -59
  40. package/dist/mcp/index.js +838 -769
  41. package/dist/mcp/index.js.map +1 -1
  42. package/dist/mcp/x402.d.ts +34 -0
  43. package/dist/mcp/x402.js +194 -0
  44. package/dist/mcp/x402.js.map +1 -0
  45. package/dist/mcp-BEwaCsxO.d.ts +61 -0
  46. package/dist/observability/index.d.ts +3 -0
  47. package/dist/observability/index.js +7 -0
  48. package/dist/react-jvtffQuA.d.ts +113 -0
  49. package/dist/react.d.ts +10 -39
  50. package/dist/react.js +183 -98
  51. package/dist/react.js.map +1 -1
  52. package/dist/schedule.d.ts +89 -12
  53. package/dist/schedule.js +46 -23
  54. package/dist/schedule.js.map +1 -1
  55. package/dist/serializable-gtr9YMhp.d.ts +34 -0
  56. package/dist/serializable.d.ts +7 -0
  57. package/dist/serializable.js +1 -0
  58. package/dist/src-L3cHuAag.js +1231 -0
  59. package/dist/src-L3cHuAag.js.map +1 -0
  60. package/package.json +110 -64
  61. package/src/index.ts +1407 -152
  62. package/dist/ai-types.js.map +0 -1
  63. package/dist/chunk-HMLY7DHA.js +0 -16
  64. package/dist/chunk-HMLY7DHA.js.map +0 -1
  65. package/dist/chunk-XG52S6YY.js +0 -591
  66. package/dist/chunk-XG52S6YY.js.map +0 -1
  67. package/dist/client.js.map +0 -1
  68. package/dist/index.js.map +0 -1
  69. package/dist/mcp/client.js.map +0 -1
  70. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
package/dist/mcp/index.js CHANGED
@@ -1,778 +1,847 @@
1
- import {
2
- Agent
3
- } from "../chunk-XG52S6YY.js";
4
- import {
5
- __privateAdd,
6
- __privateGet,
7
- __privateMethod,
8
- __privateSet
9
- } from "../chunk-HMLY7DHA.js";
1
+ import { MessageType } from "../ai-types-UZlfLOYP.js";
2
+ import "../client-DjR-lC16.js";
3
+ import { SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport } from "../client-CZBVDDoO.js";
4
+ import "../do-oauth-client-provider-B2jr6UNq.js";
5
+ import { Agent, getAgentByName, getCurrentAgent } from "../src-L3cHuAag.js";
6
+ import { ElicitRequestSchema, InitializeRequestSchema, JSONRPCMessageSchema, isJSONRPCError, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResponse } from "@modelcontextprotocol/sdk/types.js";
10
7
 
11
- // src/mcp/index.ts
12
- import { DurableObject } from "cloudflare:workers";
13
- import {
14
- InitializeRequestSchema,
15
- isJSONRPCError,
16
- isJSONRPCNotification,
17
- isJSONRPCRequest,
18
- isJSONRPCResponse,
19
- JSONRPCMessageSchema
20
- } from "@modelcontextprotocol/sdk/types.js";
21
- var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
8
+ //#region src/mcp/utils.ts
9
+ /**
10
+ * Since we use WebSockets to bridge the client to the
11
+ * MCP transport in the Agent, we use this header to signal
12
+ * the method of the original request the user made, while
13
+ * leaving the WS Upgrade request as GET.
14
+ */
15
+ const MCP_HTTP_METHOD_HEADER = "cf-mcp-method";
16
+ /**
17
+ * Since we use WebSockets to bridge the client to the
18
+ * MCP transport in the Agent, we use this header to include
19
+ * the original request body.
20
+ */
21
+ const MCP_MESSAGE_HEADER = "cf-mcp-message";
22
+ const MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
23
+ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
24
+ let pathname = basePath;
25
+ if (basePath === "/") pathname = "/*";
26
+ const basePattern = new URLPattern({ pathname });
27
+ return async (request, ctx) => {
28
+ const url = new URL(request.url);
29
+ if (basePattern.test(url)) {
30
+ if (request.method === "POST") {
31
+ const acceptHeader = request.headers.get("accept");
32
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
33
+ const body$1 = JSON.stringify({
34
+ error: {
35
+ code: -32e3,
36
+ message: "Not Acceptable: Client must accept both application/json and text/event-stream"
37
+ },
38
+ id: null,
39
+ jsonrpc: "2.0"
40
+ });
41
+ return new Response(body$1, { status: 406 });
42
+ }
43
+ const ct = request.headers.get("content-type");
44
+ if (!ct || !ct.includes("application/json")) {
45
+ const body$1 = JSON.stringify({
46
+ error: {
47
+ code: -32e3,
48
+ message: "Unsupported Media Type: Content-Type must be application/json"
49
+ },
50
+ id: null,
51
+ jsonrpc: "2.0"
52
+ });
53
+ return new Response(body$1, { status: 415 });
54
+ }
55
+ if (Number.parseInt(request.headers.get("content-length") ?? "0", 10) > MAXIMUM_MESSAGE_SIZE_BYTES) {
56
+ const body$1 = JSON.stringify({
57
+ error: {
58
+ code: -32e3,
59
+ message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
60
+ },
61
+ id: null,
62
+ jsonrpc: "2.0"
63
+ });
64
+ return new Response(body$1, { status: 413 });
65
+ }
66
+ let sessionId = request.headers.get("mcp-session-id");
67
+ let rawMessage;
68
+ try {
69
+ rawMessage = await request.json();
70
+ } catch (_error) {
71
+ const body$1 = JSON.stringify({
72
+ error: {
73
+ code: -32700,
74
+ message: "Parse error: Invalid JSON"
75
+ },
76
+ id: null,
77
+ jsonrpc: "2.0"
78
+ });
79
+ return new Response(body$1, { status: 400 });
80
+ }
81
+ let arrayMessage;
82
+ if (Array.isArray(rawMessage)) arrayMessage = rawMessage;
83
+ else arrayMessage = [rawMessage];
84
+ let messages = [];
85
+ for (const msg of arrayMessage) if (!JSONRPCMessageSchema.safeParse(msg).success) {
86
+ const body$1 = JSON.stringify({
87
+ error: {
88
+ code: -32700,
89
+ message: "Parse error: Invalid JSON-RPC message"
90
+ },
91
+ id: null,
92
+ jsonrpc: "2.0"
93
+ });
94
+ return new Response(body$1, { status: 400 });
95
+ }
96
+ messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
97
+ const maybeInitializeRequest = messages.find((msg) => InitializeRequestSchema.safeParse(msg).success);
98
+ if (!!maybeInitializeRequest && sessionId) {
99
+ const body$1 = JSON.stringify({
100
+ error: {
101
+ code: -32600,
102
+ message: "Invalid Request: Initialization requests must not include a sessionId"
103
+ },
104
+ id: null,
105
+ jsonrpc: "2.0"
106
+ });
107
+ return new Response(body$1, { status: 400 });
108
+ }
109
+ if (!!maybeInitializeRequest && messages.length > 1) {
110
+ const body$1 = JSON.stringify({
111
+ error: {
112
+ code: -32600,
113
+ message: "Invalid Request: Only one initialization request is allowed"
114
+ },
115
+ id: null,
116
+ jsonrpc: "2.0"
117
+ });
118
+ return new Response(body$1, { status: 400 });
119
+ }
120
+ if (!maybeInitializeRequest && !sessionId) {
121
+ const body$1 = JSON.stringify({
122
+ error: {
123
+ code: -32e3,
124
+ message: "Bad Request: Mcp-Session-Id header is required"
125
+ },
126
+ id: null,
127
+ jsonrpc: "2.0"
128
+ });
129
+ return new Response(body$1, { status: 400 });
130
+ }
131
+ sessionId = sessionId ?? namespace.newUniqueId().toString();
132
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
133
+ const isInitialized = await agent.getInitializeRequest();
134
+ if (maybeInitializeRequest) await agent.setInitializeRequest(maybeInitializeRequest);
135
+ else if (!isInitialized) {
136
+ const body$1 = JSON.stringify({
137
+ error: {
138
+ code: -32001,
139
+ message: "Session not found"
140
+ },
141
+ id: null,
142
+ jsonrpc: "2.0"
143
+ });
144
+ return new Response(body$1, { status: 404 });
145
+ }
146
+ const { readable, writable } = new TransformStream();
147
+ const writer = writable.getWriter();
148
+ const encoder = new TextEncoder();
149
+ const existingHeaders = {};
150
+ request.headers.forEach((value, key) => {
151
+ existingHeaders[key] = value;
152
+ });
153
+ const req = new Request(request.url, { headers: {
154
+ ...existingHeaders,
155
+ [MCP_HTTP_METHOD_HEADER]: "POST",
156
+ [MCP_MESSAGE_HEADER]: Buffer.from(JSON.stringify(messages)).toString("base64"),
157
+ Upgrade: "websocket"
158
+ } });
159
+ if (ctx.props) agent.updateProps(ctx.props);
160
+ const ws = (await agent.fetch(req)).webSocket;
161
+ if (!ws) {
162
+ console.error("Failed to establish WebSocket connection");
163
+ await writer.close();
164
+ const body$1 = JSON.stringify({
165
+ error: {
166
+ code: -32001,
167
+ message: "Failed to establish WebSocket connection"
168
+ },
169
+ id: null,
170
+ jsonrpc: "2.0"
171
+ });
172
+ return new Response(body$1, { status: 500 });
173
+ }
174
+ ws.accept();
175
+ ws.addEventListener("message", (event) => {
176
+ async function onMessage(event$1) {
177
+ try {
178
+ const data = typeof event$1.data === "string" ? event$1.data : new TextDecoder().decode(event$1.data);
179
+ const message = JSON.parse(data);
180
+ if (message.type !== MessageType.CF_MCP_AGENT_EVENT) return;
181
+ await writer.write(encoder.encode(message.event));
182
+ if (message.close) {
183
+ ws?.close();
184
+ await writer.close().catch(() => {});
185
+ }
186
+ } catch (error) {
187
+ console.error("Error forwarding message to SSE:", error);
188
+ }
189
+ }
190
+ onMessage(event).catch(console.error);
191
+ });
192
+ ws.addEventListener("error", (error) => {
193
+ async function onError(_error) {
194
+ await writer.close().catch(() => {});
195
+ }
196
+ onError(error).catch(console.error);
197
+ });
198
+ ws.addEventListener("close", () => {
199
+ async function onClose() {
200
+ await writer.close().catch(() => {});
201
+ }
202
+ onClose().catch(console.error);
203
+ });
204
+ if (messages.every((msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg))) {
205
+ ws.close();
206
+ return new Response(null, {
207
+ headers: corsHeaders(request, corsOptions),
208
+ status: 202
209
+ });
210
+ }
211
+ return new Response(readable, {
212
+ headers: {
213
+ "Cache-Control": "no-cache",
214
+ Connection: "keep-alive",
215
+ "Content-Type": "text/event-stream",
216
+ "mcp-session-id": sessionId,
217
+ ...corsHeaders(request, corsOptions)
218
+ },
219
+ status: 200
220
+ });
221
+ } else if (request.method === "GET") {
222
+ if (!request.headers.get("accept")?.includes("text/event-stream")) {
223
+ const body$1 = JSON.stringify({
224
+ jsonrpc: "2.0",
225
+ error: {
226
+ code: -32e3,
227
+ message: "Not Acceptable: Client must accept text/event-stream"
228
+ },
229
+ id: null
230
+ });
231
+ return new Response(body$1, { status: 406 });
232
+ }
233
+ const sessionId = request.headers.get("mcp-session-id");
234
+ if (!sessionId) return new Response(JSON.stringify({
235
+ error: {
236
+ code: -32e3,
237
+ message: "Bad Request: Mcp-Session-Id header is required"
238
+ },
239
+ id: null,
240
+ jsonrpc: "2.0"
241
+ }), { status: 400 });
242
+ const { readable, writable } = new TransformStream();
243
+ const writer = writable.getWriter();
244
+ const encoder = new TextEncoder();
245
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
246
+ if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
247
+ jsonrpc: "2.0",
248
+ error: {
249
+ code: -32001,
250
+ message: "Session not found"
251
+ },
252
+ id: null
253
+ }), { status: 404 });
254
+ const existingHeaders = {};
255
+ request.headers.forEach((v, k) => {
256
+ existingHeaders[k] = v;
257
+ });
258
+ if (ctx.props) agent.updateProps(ctx.props);
259
+ const ws = (await agent.fetch(new Request(request.url, { headers: {
260
+ ...existingHeaders,
261
+ [MCP_HTTP_METHOD_HEADER]: "GET",
262
+ Upgrade: "websocket"
263
+ } }))).webSocket;
264
+ if (!ws) {
265
+ await writer.close();
266
+ return new Response("Failed to establish WS to DO", { status: 500 });
267
+ }
268
+ ws.accept();
269
+ ws.addEventListener("message", (event) => {
270
+ try {
271
+ async function onMessage(ev) {
272
+ const data = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
273
+ const message = JSON.parse(data);
274
+ if (message.type !== MessageType.CF_MCP_AGENT_EVENT) return;
275
+ await writer.write(encoder.encode(message.event));
276
+ }
277
+ onMessage(event).catch(console.error);
278
+ } catch (e) {
279
+ console.error("Error forwarding message to SSE:", e);
280
+ }
281
+ });
282
+ ws.addEventListener("error", () => {
283
+ writer.close().catch(() => {});
284
+ });
285
+ ws.addEventListener("close", () => {
286
+ writer.close().catch(() => {});
287
+ });
288
+ return new Response(readable, {
289
+ headers: {
290
+ "Cache-Control": "no-cache",
291
+ Connection: "keep-alive",
292
+ "Content-Type": "text/event-stream",
293
+ "mcp-session-id": sessionId,
294
+ ...corsHeaders(request, corsOptions)
295
+ },
296
+ status: 200
297
+ });
298
+ } else if (request.method === "DELETE") {
299
+ const sessionId = request.headers.get("mcp-session-id");
300
+ if (!sessionId) return new Response(JSON.stringify({
301
+ jsonrpc: "2.0",
302
+ error: {
303
+ code: -32e3,
304
+ message: "Bad Request: Mcp-Session-Id header is required"
305
+ },
306
+ id: null
307
+ }), {
308
+ status: 400,
309
+ headers: corsHeaders(request, corsOptions)
310
+ });
311
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`);
312
+ if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
313
+ jsonrpc: "2.0",
314
+ error: {
315
+ code: -32001,
316
+ message: "Session not found"
317
+ },
318
+ id: null
319
+ }), {
320
+ status: 404,
321
+ headers: corsHeaders(request, corsOptions)
322
+ });
323
+ ctx.waitUntil(agent.destroy().catch(() => {}));
324
+ return new Response(null, {
325
+ status: 204,
326
+ headers: corsHeaders(request, corsOptions)
327
+ });
328
+ }
329
+ }
330
+ const body = JSON.stringify({
331
+ error: {
332
+ code: -32e3,
333
+ message: "Not found"
334
+ },
335
+ id: null,
336
+ jsonrpc: "2.0"
337
+ });
338
+ return new Response(body, { status: 404 });
339
+ };
340
+ };
341
+ const createLegacySseHandler = (basePath, namespace, corsOptions) => {
342
+ let pathname = basePath;
343
+ if (basePath === "/") pathname = "/*";
344
+ const basePattern = new URLPattern({ pathname });
345
+ const messagePattern = new URLPattern({ pathname: `${basePath}/message` });
346
+ return async (request, ctx) => {
347
+ const url = new URL(request.url);
348
+ if (request.method === "GET" && basePattern.test(url)) {
349
+ const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
350
+ const { readable, writable } = new TransformStream();
351
+ const writer = writable.getWriter();
352
+ const encoder = new TextEncoder();
353
+ const endpointUrl = new URL(request.url);
354
+ endpointUrl.pathname = encodeURI(`${basePath}/message`);
355
+ endpointUrl.searchParams.set("sessionId", sessionId);
356
+ const endpointMessage = `event: endpoint\ndata: ${endpointUrl.pathname + endpointUrl.search + endpointUrl.hash}\n\n`;
357
+ writer.write(encoder.encode(endpointMessage));
358
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
359
+ const existingHeaders = {};
360
+ request.headers.forEach((value, key) => {
361
+ existingHeaders[key] = value;
362
+ });
363
+ if (ctx.props) agent.updateProps(ctx.props);
364
+ const ws = (await agent.fetch(new Request(request.url, { headers: {
365
+ ...existingHeaders,
366
+ Upgrade: "websocket"
367
+ } }))).webSocket;
368
+ if (!ws) {
369
+ console.error("Failed to establish WebSocket connection");
370
+ await writer.close();
371
+ return new Response("Failed to establish WebSocket connection", { status: 500 });
372
+ }
373
+ ws.accept();
374
+ ws.addEventListener("message", (event) => {
375
+ async function onMessage(event$1) {
376
+ try {
377
+ const message = JSON.parse(event$1.data);
378
+ const result = JSONRPCMessageSchema.safeParse(message);
379
+ if (!result.success) return;
380
+ const messageText = `event: message\ndata: ${JSON.stringify(result.data)}\n\n`;
381
+ await writer.write(encoder.encode(messageText));
382
+ } catch (error) {
383
+ console.error("Error forwarding message to SSE:", error);
384
+ }
385
+ }
386
+ onMessage(event).catch(console.error);
387
+ });
388
+ ws.addEventListener("error", (error) => {
389
+ async function onError(_error) {
390
+ try {
391
+ await writer.close();
392
+ } catch (_e) {}
393
+ }
394
+ onError(error).catch(console.error);
395
+ });
396
+ ws.addEventListener("close", () => {
397
+ async function onClose() {
398
+ try {
399
+ await writer.close();
400
+ } catch (error) {
401
+ console.error("Error closing SSE connection:", error);
402
+ }
403
+ }
404
+ onClose().catch(console.error);
405
+ });
406
+ return new Response(readable, { headers: {
407
+ "Cache-Control": "no-cache",
408
+ Connection: "keep-alive",
409
+ "Content-Type": "text/event-stream",
410
+ ...corsHeaders(request, corsOptions)
411
+ } });
412
+ }
413
+ if (request.method === "POST" && messagePattern.test(url)) {
414
+ const sessionId = url.searchParams.get("sessionId");
415
+ if (!sessionId) return new Response(`Missing sessionId. Expected POST to ${basePath} to initiate new one`, { status: 400 });
416
+ const contentType = request.headers.get("content-type") || "";
417
+ if (!contentType.includes("application/json")) return new Response(`Unsupported content-type: ${contentType}`, { status: 400 });
418
+ const contentLength = Number.parseInt(request.headers.get("content-length") || "0", 10);
419
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) return new Response(`Request body too large: ${contentLength} bytes`, { status: 400 });
420
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
421
+ const messageBody = await request.json();
422
+ const error = await agent.onSSEMcpMessage(sessionId, messageBody);
423
+ if (error) return new Response(error.message, {
424
+ headers: {
425
+ "Cache-Control": "no-cache",
426
+ Connection: "keep-alive",
427
+ "Content-Type": "text/event-stream",
428
+ ...corsHeaders(request, corsOptions)
429
+ },
430
+ status: 400
431
+ });
432
+ return new Response("Accepted", {
433
+ headers: {
434
+ "Cache-Control": "no-cache",
435
+ Connection: "keep-alive",
436
+ "Content-Type": "text/event-stream",
437
+ ...corsHeaders(request, corsOptions)
438
+ },
439
+ status: 202
440
+ });
441
+ }
442
+ return new Response("Not Found", { status: 404 });
443
+ };
444
+ };
445
+ function corsHeaders(_request, corsOptions = {}) {
446
+ const origin = "*";
447
+ return {
448
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, Accept, mcp-session-id, mcp-protocol-version",
449
+ "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, DELETE, OPTIONS",
450
+ "Access-Control-Allow-Origin": corsOptions.origin || origin,
451
+ "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
452
+ "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
453
+ };
454
+ }
22
455
  function handleCORS(request, corsOptions) {
23
- const origin = request.headers.get("Origin") || "*";
24
- const corsHeaders = {
25
- "Access-Control-Allow-Origin": corsOptions?.origin || origin,
26
- "Access-Control-Allow-Methods": corsOptions?.methods || "GET, POST, OPTIONS",
27
- "Access-Control-Allow-Headers": corsOptions?.headers || "Content-Type",
28
- "Access-Control-Max-Age": (corsOptions?.maxAge || 86400).toString()
29
- };
30
- if (request.method === "OPTIONS") {
31
- return new Response(null, { headers: corsHeaders });
32
- }
33
- return null;
456
+ if (request.method === "OPTIONS") return new Response(null, { headers: corsHeaders(request, corsOptions) });
457
+ return null;
34
458
  }
35
- var _getWebSocket, _started;
459
+ function isDurableObjectNamespace(namespace) {
460
+ return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
461
+ }
462
+
463
+ //#endregion
464
+ //#region src/mcp/transport.ts
36
465
  var McpSSETransport = class {
37
- constructor(getWebSocket) {
38
- __privateAdd(this, _getWebSocket);
39
- __privateAdd(this, _started, false);
40
- __privateSet(this, _getWebSocket, getWebSocket);
41
- }
42
- async start() {
43
- if (__privateGet(this, _started)) {
44
- throw new Error("Transport already started");
45
- }
46
- __privateSet(this, _started, true);
47
- }
48
- async send(message) {
49
- if (!__privateGet(this, _started)) {
50
- throw new Error("Transport not started");
51
- }
52
- const websocket = __privateGet(this, _getWebSocket).call(this);
53
- if (!websocket) {
54
- throw new Error("WebSocket not connected");
55
- }
56
- try {
57
- websocket.send(JSON.stringify(message));
58
- } catch (error) {
59
- this.onerror?.(error);
60
- throw error;
61
- }
62
- }
63
- async close() {
64
- this.onclose?.();
65
- }
466
+ constructor(getWebSocket) {
467
+ this._started = false;
468
+ this._getWebSocket = getWebSocket;
469
+ }
470
+ async start() {
471
+ if (this._started) throw new Error("Transport already started");
472
+ this._started = true;
473
+ }
474
+ async send(message) {
475
+ if (!this._started) throw new Error("Transport not started");
476
+ const websocket = this._getWebSocket();
477
+ if (!websocket) throw new Error("WebSocket not connected");
478
+ try {
479
+ websocket.send(JSON.stringify(message));
480
+ } catch (error) {
481
+ this.onerror?.(error);
482
+ }
483
+ }
484
+ async close() {
485
+ this.onclose?.();
486
+ }
66
487
  };
67
- _getWebSocket = new WeakMap();
68
- _started = new WeakMap();
69
- var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
70
- var McpStreamableHttpTransport = class {
71
- constructor(getWebSocketForMessageID, notifyResponseIdSent) {
72
- // TODO: If there is an open connection to send server-initiated messages
73
- // back, we should use that connection
74
- __privateAdd(this, _getWebSocketForGetRequest);
75
- // Get the appropriate websocket connection for a given message id
76
- __privateAdd(this, _getWebSocketForMessageID);
77
- // Notify the server that a response has been sent for a given message id
78
- // so that it may clean up it's mapping of message ids to connections
79
- // once they are no longer needed
80
- __privateAdd(this, _notifyResponseIdSent);
81
- __privateAdd(this, _started2, false);
82
- __privateSet(this, _getWebSocketForMessageID, getWebSocketForMessageID);
83
- __privateSet(this, _notifyResponseIdSent, notifyResponseIdSent);
84
- __privateSet(this, _getWebSocketForGetRequest, () => null);
85
- }
86
- async start() {
87
- if (__privateGet(this, _started2)) {
88
- throw new Error("Transport already started");
89
- }
90
- __privateSet(this, _started2, true);
91
- }
92
- async send(message) {
93
- if (!__privateGet(this, _started2)) {
94
- throw new Error("Transport not started");
95
- }
96
- let websocket = null;
97
- if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
98
- websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
99
- if (!websocket) {
100
- throw new Error(
101
- `Could not find WebSocket for message id: ${message.id}`
102
- );
103
- }
104
- } else if (isJSONRPCRequest(message)) {
105
- websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
106
- } else if (isJSONRPCNotification(message)) {
107
- websocket = null;
108
- }
109
- try {
110
- websocket?.send(JSON.stringify(message));
111
- if (isJSONRPCResponse(message)) {
112
- __privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
113
- }
114
- } catch (error) {
115
- this.onerror?.(error);
116
- throw error;
117
- }
118
- }
119
- async close() {
120
- this.onclose?.();
121
- }
488
+ /**
489
+ * Adapted from: https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/client/streamableHttp.ts
490
+ * - Validation and initialization are removed as they're handled in `McpAgent.serve()` handler.
491
+ * - Replaces the Node-style `req`/`res` with Worker's `Request`.
492
+ * - Writes events as WS messages that the Worker forwards to the client as SSE events.
493
+ * - Replaces the in-memory maps that track requestID/stream by using `connection.setState()` and `agent.getConnections()`.
494
+ *
495
+ * Besides these points, the implementation is the same and should be updated to match the original as new features are added.
496
+ */
497
+ var StreamableHTTPServerTransport = class {
498
+ constructor(options) {
499
+ this._started = false;
500
+ this._requestResponseMap = /* @__PURE__ */ new Map();
501
+ const { agent } = getCurrentAgent();
502
+ if (!agent) throw new Error("McpAgent was not found in Transport constructor");
503
+ this.sessionId = agent.getSessionId();
504
+ this._eventStore = options.eventStore;
505
+ }
506
+ /**
507
+ * Starts the transport. This is required by the Transport interface but is a no-op
508
+ * for the Streamable HTTP transport as connections are managed per-request.
509
+ */
510
+ async start() {
511
+ if (this._started) throw new Error("Transport already started");
512
+ this._started = true;
513
+ }
514
+ /**
515
+ * Handles GET requests for SSE stream
516
+ */
517
+ async handleGetRequest(req) {
518
+ const { connection } = getCurrentAgent();
519
+ if (!connection) throw new Error("Connection was not found in handleGetRequest");
520
+ if (this._eventStore) {
521
+ const lastEventId = req.headers.get("last-event-id");
522
+ if (lastEventId) {
523
+ await this.replayEvents(lastEventId);
524
+ return;
525
+ }
526
+ }
527
+ connection.setState({ _standaloneSse: true });
528
+ }
529
+ /**
530
+ * Replays events that would have been sent after the specified event ID
531
+ * Only used when resumability is enabled
532
+ */
533
+ async replayEvents(lastEventId) {
534
+ if (!this._eventStore) return;
535
+ const { connection } = getCurrentAgent();
536
+ if (!connection) throw new Error("Connection was not available in replayEvents");
537
+ try {
538
+ await this._eventStore?.replayEventsAfter(lastEventId, { send: async (eventId, message) => {
539
+ try {
540
+ this.writeSSEEvent(connection, message, eventId);
541
+ } catch (error) {
542
+ this.onerror?.(error);
543
+ }
544
+ } });
545
+ } catch (error) {
546
+ this.onerror?.(error);
547
+ }
548
+ }
549
+ /**
550
+ * Writes an event to the SSE stream with proper formatting
551
+ */
552
+ writeSSEEvent(connection, message, eventId, close) {
553
+ let eventData = "event: message\n";
554
+ if (eventId) eventData += `id: ${eventId}\n`;
555
+ eventData += `data: ${JSON.stringify(message)}\n\n`;
556
+ return connection.send(JSON.stringify({
557
+ type: MessageType.CF_MCP_AGENT_EVENT,
558
+ event: eventData,
559
+ close
560
+ }));
561
+ }
562
+ /**
563
+ * Handles POST requests containing JSON-RPC messages
564
+ */
565
+ async handlePostRequest(req, parsedBody) {
566
+ const authInfo = req.auth;
567
+ const requestInfo = { headers: Object.fromEntries(req.headers.entries()) };
568
+ delete requestInfo.headers[MCP_HTTP_METHOD_HEADER];
569
+ delete requestInfo.headers[MCP_MESSAGE_HEADER];
570
+ delete requestInfo.headers.upgrade;
571
+ const rawMessage = parsedBody;
572
+ let messages;
573
+ if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
574
+ else messages = [JSONRPCMessageSchema.parse(rawMessage)];
575
+ const hasRequests = messages.some(isJSONRPCRequest);
576
+ if (!hasRequests) for (const message of messages) this.onmessage?.(message, {
577
+ authInfo,
578
+ requestInfo
579
+ });
580
+ else if (hasRequests) {
581
+ const { connection } = getCurrentAgent();
582
+ if (!connection) throw new Error("Connection was not found in handlePostRequest");
583
+ const requestIds = messages.filter(isJSONRPCRequest).map((message) => message.id);
584
+ connection.setState({ requestIds });
585
+ for (const message of messages) this.onmessage?.(message, {
586
+ authInfo,
587
+ requestInfo
588
+ });
589
+ }
590
+ }
591
+ async close() {
592
+ const { agent } = getCurrentAgent();
593
+ if (!agent) throw new Error("Agent was not found in close");
594
+ for (const conn of agent.getConnections()) conn.close(1e3, "Session closed");
595
+ this.onclose?.();
596
+ }
597
+ async send(message, options) {
598
+ const { agent } = getCurrentAgent();
599
+ if (!agent) throw new Error("Agent was not found in send");
600
+ let requestId = options?.relatedRequestId;
601
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) requestId = message.id;
602
+ if (requestId === void 0) {
603
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
604
+ let standaloneConnection;
605
+ for (const conn of agent.getConnections()) if (conn.state?._standaloneSse) standaloneConnection = conn;
606
+ if (standaloneConnection === void 0) return;
607
+ let eventId$1;
608
+ if (this._eventStore) eventId$1 = await this._eventStore.storeEvent(standaloneConnection.id, message);
609
+ this.writeSSEEvent(standaloneConnection, message, eventId$1);
610
+ return;
611
+ }
612
+ const connection = Array.from(agent.getConnections()).find((conn) => conn.state?.requestIds?.includes(requestId));
613
+ if (!connection) throw new Error(`No connection established for request ID: ${String(requestId)}`);
614
+ let eventId;
615
+ if (this._eventStore) eventId = await this._eventStore.storeEvent(connection.id, message);
616
+ let shouldClose = false;
617
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
618
+ this._requestResponseMap.set(requestId, message);
619
+ const relatedIds = connection.state?.requestIds ?? [];
620
+ shouldClose = relatedIds.every((id) => this._requestResponseMap.has(id));
621
+ if (shouldClose) for (const id of relatedIds) this._requestResponseMap.delete(id);
622
+ }
623
+ this.writeSSEEvent(connection, message, eventId, shouldClose);
624
+ }
122
625
  };
123
- _getWebSocketForGetRequest = new WeakMap();
124
- _getWebSocketForMessageID = new WeakMap();
125
- _notifyResponseIdSent = new WeakMap();
126
- _started2 = new WeakMap();
127
- var _status, _transport, _transportType, _requestIdToConnectionId, _agent, _McpAgent_instances, initialize_fn;
128
- var _McpAgent = class _McpAgent extends DurableObject {
129
- constructor(ctx, env) {
130
- var _a;
131
- super(ctx, env);
132
- __privateAdd(this, _McpAgent_instances);
133
- __privateAdd(this, _status, "zero");
134
- __privateAdd(this, _transport);
135
- __privateAdd(this, _transportType, "unset");
136
- __privateAdd(this, _requestIdToConnectionId, /* @__PURE__ */ new Map());
137
- /**
138
- * Since McpAgent's _aren't_ yet real "Agents", let's only expose a couple of the methods
139
- * to the outer class: initialState/state/setState/onStateUpdate/sql
140
- */
141
- __privateAdd(this, _agent);
142
- this.initRun = false;
143
- const self = this;
144
- __privateSet(this, _agent, new (_a = class extends Agent {
145
- onStateUpdate(state, source) {
146
- return self.onStateUpdate(state, source);
147
- }
148
- async onMessage(connection, message) {
149
- return self.onMessage(connection, message);
150
- }
151
- }, _a.options = {
152
- hibernate: true
153
- }, _a)(ctx, env));
154
- }
155
- get state() {
156
- return __privateGet(this, _agent).state;
157
- }
158
- sql(strings, ...values) {
159
- return __privateGet(this, _agent).sql(strings, ...values);
160
- }
161
- setState(state) {
162
- return __privateGet(this, _agent).setState(state);
163
- }
164
- onStateUpdate(state, source) {
165
- }
166
- async onStart() {
167
- var _a;
168
- const self = this;
169
- __privateSet(this, _agent, new (_a = class extends Agent {
170
- constructor() {
171
- super(...arguments);
172
- this.initialState = self.initialState;
173
- }
174
- onStateUpdate(state, source) {
175
- return self.onStateUpdate(state, source);
176
- }
177
- async onMessage(connection, event) {
178
- return self.onMessage(connection, event);
179
- }
180
- }, _a.options = {
181
- hibernate: true
182
- }, _a)(this.ctx, this.env));
183
- this.props = await this.ctx.storage.get("props");
184
- __privateSet(this, _transportType, await this.ctx.storage.get(
185
- "transportType"
186
- ));
187
- await this._init(this.props);
188
- if (__privateGet(this, _transportType) === "sse") {
189
- __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
190
- await this.server.connect(__privateGet(this, _transport));
191
- } else if (__privateGet(this, _transportType) === "streamable-http") {
192
- __privateSet(this, _transport, new McpStreamableHttpTransport(
193
- (id) => this.getWebSocketForResponseID(id),
194
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
195
- ));
196
- await this.server.connect(__privateGet(this, _transport));
197
- }
198
- }
199
- async _init(props) {
200
- await this.ctx.storage.put("props", props ?? {});
201
- if (!this.ctx.storage.get("transportType")) {
202
- await this.ctx.storage.put("transportType", "unset");
203
- }
204
- this.props = props;
205
- if (!this.initRun) {
206
- this.initRun = true;
207
- await this.init();
208
- }
209
- }
210
- async setInitialized() {
211
- await this.ctx.storage.put("initialized", true);
212
- }
213
- async isInitialized() {
214
- return await this.ctx.storage.get("initialized") === true;
215
- }
216
- // Allow the worker to fetch a websocket connection to the agent
217
- async fetch(request) {
218
- if (__privateGet(this, _status) !== "started") {
219
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
220
- }
221
- if (request.headers.get("Upgrade") !== "websocket") {
222
- return new Response("Expected WebSocket Upgrade request", {
223
- status: 400
224
- });
225
- }
226
- const url = new URL(request.url);
227
- const path = url.pathname;
228
- switch (path) {
229
- case "/sse": {
230
- const websockets = this.ctx.getWebSockets();
231
- if (websockets.length > 0) {
232
- return new Response("Websocket already connected", { status: 400 });
233
- }
234
- await this.ctx.storage.put("transportType", "sse");
235
- __privateSet(this, _transportType, "sse");
236
- if (!__privateGet(this, _transport)) {
237
- __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
238
- await this.server.connect(__privateGet(this, _transport));
239
- }
240
- return __privateGet(this, _agent).fetch(request);
241
- }
242
- case "/streamable-http": {
243
- if (!__privateGet(this, _transport)) {
244
- __privateSet(this, _transport, new McpStreamableHttpTransport(
245
- (id) => this.getWebSocketForResponseID(id),
246
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
247
- ));
248
- await this.server.connect(__privateGet(this, _transport));
249
- }
250
- await this.ctx.storage.put("transportType", "streamable-http");
251
- __privateSet(this, _transportType, "streamable-http");
252
- return __privateGet(this, _agent).fetch(request);
253
- }
254
- default:
255
- return new Response(
256
- "Internal Server Error: Expected /sse or /streamable-http path",
257
- {
258
- status: 500
259
- }
260
- );
261
- }
262
- }
263
- getWebSocket() {
264
- const websockets = this.ctx.getWebSockets();
265
- if (websockets.length === 0) {
266
- return null;
267
- }
268
- return websockets[0];
269
- }
270
- getWebSocketForResponseID(id) {
271
- const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
272
- if (connectionId === void 0) {
273
- return null;
274
- }
275
- return __privateGet(this, _agent).getConnection(connectionId) ?? null;
276
- }
277
- // All messages received here. This is currently never called
278
- async onMessage(connection, event) {
279
- if (__privateGet(this, _transportType) !== "streamable-http") {
280
- const err = new Error(
281
- "Internal Server Error: Expected streamable-http protocol"
282
- );
283
- __privateGet(this, _transport)?.onerror?.(err);
284
- return;
285
- }
286
- let message;
287
- try {
288
- const data = typeof event === "string" ? event : new TextDecoder().decode(event);
289
- message = JSONRPCMessageSchema.parse(JSON.parse(data));
290
- } catch (error) {
291
- __privateGet(this, _transport)?.onerror?.(error);
292
- return;
293
- }
294
- if (isJSONRPCRequest(message)) {
295
- __privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
296
- }
297
- __privateGet(this, _transport)?.onmessage?.(message);
298
- }
299
- // All messages received over SSE after the initial connection has been established
300
- // will be passed here
301
- async onSSEMcpMessage(sessionId, request) {
302
- if (__privateGet(this, _status) !== "started") {
303
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
304
- }
305
- if (__privateGet(this, _transportType) !== "sse") {
306
- return new Error("Internal Server Error: Expected SSE protocol");
307
- }
308
- try {
309
- const message = await request.json();
310
- let parsedMessage;
311
- try {
312
- parsedMessage = JSONRPCMessageSchema.parse(message);
313
- } catch (error) {
314
- __privateGet(this, _transport)?.onerror?.(error);
315
- throw error;
316
- }
317
- __privateGet(this, _transport)?.onmessage?.(parsedMessage);
318
- return null;
319
- } catch (error) {
320
- __privateGet(this, _transport)?.onerror?.(error);
321
- return error;
322
- }
323
- }
324
- // Delegate all websocket events to the underlying agent
325
- async webSocketMessage(ws, event) {
326
- if (__privateGet(this, _status) !== "started") {
327
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
328
- }
329
- return await __privateGet(this, _agent).webSocketMessage(ws, event);
330
- }
331
- // WebSocket event handlers for hibernation support
332
- async webSocketError(ws, error) {
333
- if (__privateGet(this, _status) !== "started") {
334
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
335
- }
336
- return await __privateGet(this, _agent).webSocketError(ws, error);
337
- }
338
- async webSocketClose(ws, code, reason, wasClean) {
339
- if (__privateGet(this, _status) !== "started") {
340
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
341
- }
342
- return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
343
- }
344
- static mount(path, {
345
- binding = "MCP_OBJECT",
346
- corsOptions
347
- } = {}) {
348
- return _McpAgent.serveSSE(path, { binding, corsOptions });
349
- }
350
- static serveSSE(path, {
351
- binding = "MCP_OBJECT",
352
- corsOptions
353
- } = {}) {
354
- let pathname = path;
355
- if (path === "/") {
356
- pathname = "/*";
357
- }
358
- const basePattern = new URLPattern({ pathname });
359
- const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
360
- return {
361
- fetch: async (request, env, ctx) => {
362
- const corsResponse = handleCORS(request, corsOptions);
363
- if (corsResponse) return corsResponse;
364
- const url = new URL(request.url);
365
- const namespace = env[binding];
366
- if (request.method === "GET" && basePattern.test(url)) {
367
- const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
368
- const { readable, writable } = new TransformStream();
369
- const writer = writable.getWriter();
370
- const encoder = new TextEncoder();
371
- const endpointMessage = `event: endpoint
372
- data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
373
626
 
374
- `;
375
- writer.write(encoder.encode(endpointMessage));
376
- const id = namespace.idFromName(`sse:${sessionId}`);
377
- const doStub = namespace.get(id);
378
- await doStub._init(ctx.props);
379
- const upgradeUrl = new URL(request.url);
380
- upgradeUrl.pathname = "/sse";
381
- const response = await doStub.fetch(
382
- new Request(upgradeUrl, {
383
- headers: {
384
- Upgrade: "websocket",
385
- // Required by PartyServer
386
- "x-partykit-room": sessionId
387
- }
388
- })
389
- );
390
- const ws = response.webSocket;
391
- if (!ws) {
392
- console.error("Failed to establish WebSocket connection");
393
- await writer.close();
394
- return new Response("Failed to establish WebSocket connection", {
395
- status: 500
396
- });
397
- }
398
- ws.accept();
399
- ws.addEventListener("message", (event) => {
400
- async function onMessage(event2) {
401
- try {
402
- const message = JSON.parse(event2.data);
403
- const result = JSONRPCMessageSchema.safeParse(message);
404
- if (!result.success) {
405
- return;
406
- }
407
- const messageText = `event: message
408
- data: ${JSON.stringify(result.data)}
409
-
410
- `;
411
- await writer.write(encoder.encode(messageText));
412
- } catch (error) {
413
- console.error("Error forwarding message to SSE:", error);
414
- }
415
- }
416
- onMessage(event).catch(console.error);
417
- });
418
- ws.addEventListener("error", (error) => {
419
- async function onError(error2) {
420
- try {
421
- await writer.close();
422
- } catch (e) {
423
- }
424
- }
425
- onError(error).catch(console.error);
426
- });
427
- ws.addEventListener("close", () => {
428
- async function onClose() {
429
- try {
430
- await writer.close();
431
- } catch (error) {
432
- console.error("Error closing SSE connection:", error);
433
- }
434
- }
435
- onClose().catch(console.error);
436
- });
437
- return new Response(readable, {
438
- headers: {
439
- "Content-Type": "text/event-stream",
440
- "Cache-Control": "no-cache",
441
- Connection: "keep-alive",
442
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
443
- }
444
- });
445
- }
446
- if (request.method === "POST" && messagePattern.test(url)) {
447
- const sessionId = url.searchParams.get("sessionId");
448
- if (!sessionId) {
449
- return new Response(
450
- `Missing sessionId. Expected POST to ${pathname} to initiate new one`,
451
- { status: 400 }
452
- );
453
- }
454
- const contentType = request.headers.get("content-type") || "";
455
- if (!contentType.includes("application/json")) {
456
- return new Response(`Unsupported content-type: ${contentType}`, {
457
- status: 400
458
- });
459
- }
460
- const contentLength = Number.parseInt(
461
- request.headers.get("content-length") || "0",
462
- 10
463
- );
464
- if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
465
- return new Response(
466
- `Request body too large: ${contentLength} bytes`,
467
- {
468
- status: 400
469
- }
470
- );
471
- }
472
- const id = namespace.idFromName(`sse:${sessionId}`);
473
- const doStub = namespace.get(id);
474
- const error = await doStub.onSSEMcpMessage(sessionId, request);
475
- if (error) {
476
- return new Response(error.message, {
477
- status: 400,
478
- headers: {
479
- "Content-Type": "text/event-stream",
480
- "Cache-Control": "no-cache",
481
- Connection: "keep-alive",
482
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
483
- }
484
- });
485
- }
486
- return new Response("Accepted", {
487
- status: 202,
488
- headers: {
489
- "Content-Type": "text/event-stream",
490
- "Cache-Control": "no-cache",
491
- Connection: "keep-alive",
492
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
493
- }
494
- });
495
- }
496
- return new Response("Not Found", { status: 404 });
497
- }
498
- };
499
- }
500
- static serve(path, {
501
- binding = "MCP_OBJECT",
502
- corsOptions
503
- } = {}) {
504
- let pathname = path;
505
- if (path === "/") {
506
- pathname = "/*";
507
- }
508
- const basePattern = new URLPattern({ pathname });
509
- return {
510
- fetch: async (request, env, ctx) => {
511
- const corsResponse = handleCORS(request, corsOptions);
512
- if (corsResponse) {
513
- return corsResponse;
514
- }
515
- const url = new URL(request.url);
516
- const namespace = env[binding];
517
- if (request.method === "POST" && basePattern.test(url)) {
518
- const acceptHeader = request.headers.get("accept");
519
- if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
520
- const body2 = JSON.stringify({
521
- jsonrpc: "2.0",
522
- error: {
523
- code: -32e3,
524
- message: "Not Acceptable: Client must accept both application/json and text/event-stream"
525
- },
526
- id: null
527
- });
528
- return new Response(body2, { status: 406 });
529
- }
530
- const ct = request.headers.get("content-type");
531
- if (!ct || !ct.includes("application/json")) {
532
- const body2 = JSON.stringify({
533
- jsonrpc: "2.0",
534
- error: {
535
- code: -32e3,
536
- message: "Unsupported Media Type: Content-Type must be application/json"
537
- },
538
- id: null
539
- });
540
- return new Response(body2, { status: 415 });
541
- }
542
- const contentLength = Number.parseInt(
543
- request.headers.get("content-length") ?? "0",
544
- 10
545
- );
546
- if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
547
- const body2 = JSON.stringify({
548
- jsonrpc: "2.0",
549
- error: {
550
- code: -32e3,
551
- message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
552
- },
553
- id: null
554
- });
555
- return new Response(body2, { status: 413 });
556
- }
557
- let sessionId = request.headers.get("mcp-session-id");
558
- let rawMessage;
559
- try {
560
- rawMessage = await request.json();
561
- } catch (error) {
562
- const body2 = JSON.stringify({
563
- jsonrpc: "2.0",
564
- error: {
565
- code: -32700,
566
- message: "Parse error: Invalid JSON"
567
- },
568
- id: null
569
- });
570
- return new Response(body2, { status: 400 });
571
- }
572
- let arrayMessage;
573
- if (Array.isArray(rawMessage)) {
574
- arrayMessage = rawMessage;
575
- } else {
576
- arrayMessage = [rawMessage];
577
- }
578
- let messages = [];
579
- for (const msg of arrayMessage) {
580
- if (!JSONRPCMessageSchema.safeParse(msg).success) {
581
- const body2 = JSON.stringify({
582
- jsonrpc: "2.0",
583
- error: {
584
- code: -32700,
585
- message: "Parse error: Invalid JSON-RPC message"
586
- },
587
- id: null
588
- });
589
- return new Response(body2, { status: 400 });
590
- }
591
- }
592
- messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
593
- const isInitializationRequest = messages.some(
594
- (msg) => InitializeRequestSchema.safeParse(msg).success
595
- );
596
- if (isInitializationRequest && sessionId) {
597
- const body2 = JSON.stringify({
598
- jsonrpc: "2.0",
599
- error: {
600
- code: -32600,
601
- message: "Invalid Request: Initialization requests must not include a sessionId"
602
- },
603
- id: null
604
- });
605
- return new Response(body2, { status: 400 });
606
- }
607
- if (isInitializationRequest && messages.length > 1) {
608
- const body2 = JSON.stringify({
609
- jsonrpc: "2.0",
610
- error: {
611
- code: -32600,
612
- message: "Invalid Request: Only one initialization request is allowed"
613
- },
614
- id: null
615
- });
616
- return new Response(body2, { status: 400 });
617
- }
618
- if (!isInitializationRequest && !sessionId) {
619
- const body2 = JSON.stringify({
620
- jsonrpc: "2.0",
621
- error: {
622
- code: -32e3,
623
- message: "Bad Request: Mcp-Session-Id header is required"
624
- },
625
- id: null
626
- });
627
- return new Response(body2, { status: 400 });
628
- }
629
- sessionId = sessionId ?? namespace.newUniqueId().toString();
630
- const id = namespace.idFromName(`streamable-http:${sessionId}`);
631
- const doStub = namespace.get(id);
632
- const isInitialized = await doStub.isInitialized();
633
- if (isInitializationRequest) {
634
- await doStub.setInitialized();
635
- } else if (!isInitialized) {
636
- const body2 = JSON.stringify({
637
- jsonrpc: "2.0",
638
- error: {
639
- code: -32001,
640
- message: "Session not found"
641
- },
642
- id: null
643
- });
644
- return new Response(body2, { status: 404 });
645
- }
646
- const { readable, writable } = new TransformStream();
647
- const writer = writable.getWriter();
648
- const encoder = new TextEncoder();
649
- const upgradeUrl = new URL(request.url);
650
- upgradeUrl.pathname = "/streamable-http";
651
- const response = await doStub.fetch(
652
- new Request(upgradeUrl, {
653
- headers: {
654
- Upgrade: "websocket",
655
- // Required by PartyServer
656
- "x-partykit-room": sessionId
657
- }
658
- })
659
- );
660
- const ws = response.webSocket;
661
- if (!ws) {
662
- console.error("Failed to establish WebSocket connection");
663
- await writer.close();
664
- const body2 = JSON.stringify({
665
- jsonrpc: "2.0",
666
- error: {
667
- code: -32001,
668
- message: "Failed to establish WebSocket connection"
669
- },
670
- id: null
671
- });
672
- return new Response(body2, { status: 500 });
673
- }
674
- const requestIds = /* @__PURE__ */ new Set();
675
- ws.accept();
676
- ws.addEventListener("message", (event) => {
677
- async function onMessage(event2) {
678
- try {
679
- const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
680
- const message = JSON.parse(data);
681
- const result = JSONRPCMessageSchema.safeParse(message);
682
- if (!result.success) {
683
- return;
684
- }
685
- if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
686
- requestIds.delete(result.data.id);
687
- }
688
- const messageText = `event: message
689
- data: ${JSON.stringify(result.data)}
690
-
691
- `;
692
- await writer.write(encoder.encode(messageText));
693
- if (requestIds.size === 0) {
694
- ws.close();
695
- }
696
- } catch (error) {
697
- console.error("Error forwarding message to SSE:", error);
698
- }
699
- }
700
- onMessage(event).catch(console.error);
701
- });
702
- ws.addEventListener("error", (error) => {
703
- async function onError(error2) {
704
- try {
705
- await writer.close();
706
- } catch (e) {
707
- }
708
- }
709
- onError(error).catch(console.error);
710
- });
711
- ws.addEventListener("close", () => {
712
- async function onClose() {
713
- try {
714
- await writer.close();
715
- } catch (error) {
716
- console.error("Error closing SSE connection:", error);
717
- }
718
- }
719
- onClose().catch(console.error);
720
- });
721
- const hasOnlyNotificationsOrResponses = messages.every(
722
- (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
723
- );
724
- if (hasOnlyNotificationsOrResponses) {
725
- for (const message of messages) {
726
- ws.send(JSON.stringify(message));
727
- }
728
- ws.close();
729
- return new Response(null, { status: 202 });
730
- }
731
- for (const message of messages) {
732
- if (isJSONRPCRequest(message)) {
733
- requestIds.add(message.id);
734
- }
735
- ws.send(JSON.stringify(message));
736
- }
737
- return new Response(readable, {
738
- headers: {
739
- "Content-Type": "text/event-stream",
740
- "Cache-Control": "no-cache",
741
- Connection: "keep-alive",
742
- "mcp-session-id": sessionId,
743
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
744
- },
745
- status: 200
746
- });
747
- }
748
- const body = JSON.stringify({
749
- jsonrpc: "2.0",
750
- error: {
751
- code: -32e3,
752
- message: "Method not allowed"
753
- },
754
- id: null
755
- });
756
- return new Response(body, { status: 405 });
757
- }
758
- };
759
- }
760
- };
761
- _status = new WeakMap();
762
- _transport = new WeakMap();
763
- _transportType = new WeakMap();
764
- _requestIdToConnectionId = new WeakMap();
765
- _agent = new WeakMap();
766
- _McpAgent_instances = new WeakSet();
767
- initialize_fn = async function() {
768
- await this.ctx.blockConcurrencyWhile(async () => {
769
- __privateSet(this, _status, "starting");
770
- await this.onStart();
771
- __privateSet(this, _status, "started");
772
- });
773
- };
774
- var McpAgent = _McpAgent;
775
- export {
776
- McpAgent
627
+ //#endregion
628
+ //#region src/mcp/index.ts
629
+ var McpAgent = class McpAgent extends Agent {
630
+ async setInitializeRequest(initializeRequest) {
631
+ await this.ctx.storage.put("initializeRequest", initializeRequest);
632
+ }
633
+ async getInitializeRequest() {
634
+ return this.ctx.storage.get("initializeRequest");
635
+ }
636
+ /** Read the transport type for this agent.
637
+ * This relies on the naming scheme being `sse:${sessionId}`
638
+ * or `streamable-http:${sessionId}`.
639
+ */
640
+ getTransportType() {
641
+ const [t, ..._] = this.name.split(":");
642
+ switch (t) {
643
+ case "sse": return "sse";
644
+ case "streamable-http": return "streamable-http";
645
+ default: throw new Error("Invalid transport type. McpAgent must be addressed with a valid protocol.");
646
+ }
647
+ }
648
+ /** Read the sessionId for this agent.
649
+ * This relies on the naming scheme being `sse:${sessionId}`
650
+ * or `streamable-http:${sessionId}`.
651
+ */
652
+ getSessionId() {
653
+ const [_, sessionId] = this.name.split(":");
654
+ if (!sessionId) throw new Error("Invalid session id. McpAgent must be addressed with a valid session id.");
655
+ return sessionId;
656
+ }
657
+ /** Get the unique WebSocket. SSE transport only. */
658
+ getWebSocket() {
659
+ const websockets = Array.from(this.getConnections());
660
+ if (websockets.length === 0) return null;
661
+ return websockets[0];
662
+ }
663
+ /** Returns a new transport matching the type of the Agent. */
664
+ initTransport() {
665
+ switch (this.getTransportType()) {
666
+ case "sse": return new McpSSETransport(() => this.getWebSocket());
667
+ case "streamable-http": return new StreamableHTTPServerTransport({});
668
+ }
669
+ }
670
+ /** Update and store the props */
671
+ async updateProps(props) {
672
+ await this.ctx.storage.put("props", props ?? {});
673
+ this.props = props;
674
+ }
675
+ async reinitializeServer() {
676
+ const initializeRequest = await this.getInitializeRequest();
677
+ if (initializeRequest) this._transport?.onmessage?.(initializeRequest);
678
+ }
679
+ /** Sets up the MCP transport and server every time the Agent is started.*/
680
+ async onStart(props) {
681
+ if (props) await this.updateProps(props);
682
+ this.props = await this.ctx.storage.get("props");
683
+ await this.init();
684
+ const server = await this.server;
685
+ this._transport = this.initTransport();
686
+ await server.connect(this._transport);
687
+ await this.reinitializeServer();
688
+ }
689
+ /** Validates new WebSocket connections. */
690
+ async onConnect(conn, { request: req }) {
691
+ switch (this.getTransportType()) {
692
+ case "sse":
693
+ if (Array.from(this.getConnections()).length > 1) {
694
+ conn.close(1008, "Websocket already connected");
695
+ return;
696
+ }
697
+ break;
698
+ case "streamable-http": if (this._transport instanceof StreamableHTTPServerTransport) switch (req.headers.get(MCP_HTTP_METHOD_HEADER)) {
699
+ case "POST": {
700
+ const payloadHeader = req.headers.get(MCP_MESSAGE_HEADER);
701
+ let rawPayload;
702
+ if (!payloadHeader) rawPayload = "{}";
703
+ else try {
704
+ rawPayload = Buffer.from(payloadHeader, "base64").toString("utf-8");
705
+ } catch (_error) {
706
+ throw new Error("Internal Server Error: Failed to decode MCP message header");
707
+ }
708
+ const parsedBody = JSON.parse(rawPayload);
709
+ this._transport?.handlePostRequest(req, parsedBody);
710
+ break;
711
+ }
712
+ case "GET":
713
+ this._transport?.handleGetRequest(req);
714
+ break;
715
+ }
716
+ }
717
+ }
718
+ /** Handles MCP Messages for the legacy SSE transport. */
719
+ async onSSEMcpMessage(_sessionId, messageBody) {
720
+ if (this.getTransportType() !== "sse") return /* @__PURE__ */ new Error("Internal Server Error: Expected SSE transport");
721
+ try {
722
+ let parsedMessage;
723
+ try {
724
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
725
+ } catch (error) {
726
+ this._transport?.onerror?.(error);
727
+ throw error;
728
+ }
729
+ if (await this._handleElicitationResponse(parsedMessage)) return null;
730
+ this._transport?.onmessage?.(parsedMessage);
731
+ return null;
732
+ } catch (error) {
733
+ console.error("Error forwarding message to SSE:", error);
734
+ this._transport?.onerror?.(error);
735
+ return error;
736
+ }
737
+ }
738
+ /** Elicit user input with a message and schema */
739
+ async elicitInput(params) {
740
+ const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
741
+ await this.ctx.storage.put(`elicitation:${requestId}`, {
742
+ message: params.message,
743
+ requestedSchema: params.requestedSchema,
744
+ timestamp: Date.now()
745
+ });
746
+ const elicitRequest = {
747
+ jsonrpc: "2.0",
748
+ id: requestId,
749
+ method: "elicitation/create",
750
+ params: {
751
+ message: params.message,
752
+ requestedSchema: params.requestedSchema
753
+ }
754
+ };
755
+ if (this._transport) await this._transport.send(elicitRequest);
756
+ else {
757
+ const connections = this.getConnections();
758
+ if (!connections || Array.from(connections).length === 0) {
759
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
760
+ throw new Error("No active connections available for elicitation");
761
+ }
762
+ const connectionList = Array.from(connections);
763
+ for (const connection of connectionList) try {
764
+ connection.send(JSON.stringify(elicitRequest));
765
+ } catch (error) {
766
+ console.error("Failed to send elicitation request:", error);
767
+ }
768
+ }
769
+ return this._waitForElicitationResponse(requestId);
770
+ }
771
+ /** Wait for elicitation response through storage polling */
772
+ async _waitForElicitationResponse(requestId) {
773
+ const startTime = Date.now();
774
+ const timeout = 6e4;
775
+ try {
776
+ while (Date.now() - startTime < timeout) {
777
+ const response = await this.ctx.storage.get(`elicitation:response:${requestId}`);
778
+ if (response) {
779
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
780
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
781
+ return response;
782
+ }
783
+ await new Promise((resolve) => setTimeout(resolve, 100));
784
+ }
785
+ throw new Error("Elicitation request timed out");
786
+ } finally {
787
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
788
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
789
+ }
790
+ }
791
+ /** Handle elicitation responses */
792
+ async _handleElicitationResponse(message) {
793
+ if (isJSONRPCResponse(message) && message.result) {
794
+ const requestId = message.id?.toString();
795
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
796
+ if (!await this.ctx.storage.get(`elicitation:${requestId}`)) return false;
797
+ await this.ctx.storage.put(`elicitation:response:${requestId}`, message.result);
798
+ return true;
799
+ }
800
+ if (isJSONRPCError(message)) {
801
+ const requestId = message.id?.toString();
802
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
803
+ if (!await this.ctx.storage.get(`elicitation:${requestId}`)) return false;
804
+ const errorResult = {
805
+ action: "cancel",
806
+ content: { error: message.error.message || "Elicitation request failed" }
807
+ };
808
+ await this.ctx.storage.put(`elicitation:response:${requestId}`, errorResult);
809
+ return true;
810
+ }
811
+ return false;
812
+ }
813
+ /** Return a handler for the given path for this MCP.
814
+ * Defaults to Streamable HTTP transport.
815
+ */
816
+ static serve(path, { binding = "MCP_OBJECT", corsOptions, transport = "streamable-http" } = {}) {
817
+ return { async fetch(request, env, ctx) {
818
+ const corsResponse = handleCORS(request, corsOptions);
819
+ if (corsResponse) return corsResponse;
820
+ const bindingValue = env[binding];
821
+ if (bindingValue == null || typeof bindingValue !== "object") throw new Error(`Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`);
822
+ if (!isDurableObjectNamespace(bindingValue)) throw new Error(`Invalid McpAgent binding for ${binding}. Make sure it's a Durable Object binding.`);
823
+ const namespace = bindingValue;
824
+ switch (transport) {
825
+ case "streamable-http": return createStreamingHttpHandler(path, namespace, corsOptions)(request, ctx);
826
+ case "sse": return createLegacySseHandler(path, namespace, corsOptions)(request, ctx);
827
+ default: return new Response("Invalid MCP transport mode. Only `streamable-http` or `sse` are allowed.", { status: 500 });
828
+ }
829
+ } };
830
+ }
831
+ /**
832
+ * Legacy api
833
+ **/
834
+ static mount(path, opts = {}) {
835
+ return McpAgent.serveSSE(path, opts);
836
+ }
837
+ static serveSSE(path, opts = {}) {
838
+ return McpAgent.serve(path, {
839
+ ...opts,
840
+ transport: "sse"
841
+ });
842
+ }
777
843
  };
844
+
845
+ //#endregion
846
+ export { ElicitRequestSchema, McpAgent, SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport };
778
847
  //# sourceMappingURL=index.js.map