agents 0.0.0-ecf8926 → 0.0.0-ed3f94d

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 (64) hide show
  1. package/README.md +126 -4
  2. package/dist/_esm-LV5FJ3HK.js +3922 -0
  3. package/dist/_esm-LV5FJ3HK.js.map +1 -0
  4. package/dist/ai-chat-agent.d.ts +2 -1
  5. package/dist/ai-chat-agent.js +391 -76
  6. package/dist/ai-chat-agent.js.map +1 -1
  7. package/dist/ai-chat-v5-migration.js +1 -0
  8. package/dist/ai-react.d.ts +8 -1
  9. package/dist/ai-react.js +157 -111
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types.d.ts +1 -0
  12. package/dist/ai-types.js +2 -1
  13. package/dist/ccip-CMBYN64O.js +15 -0
  14. package/dist/ccip-CMBYN64O.js.map +1 -0
  15. package/dist/{chunk-EGCWEPQL.js → chunk-254F4GDT.js} +151 -98
  16. package/dist/chunk-254F4GDT.js.map +1 -0
  17. package/dist/{chunk-DS7BJNPH.js → chunk-3OT2NNEW.js} +411 -68
  18. package/dist/chunk-3OT2NNEW.js.map +1 -0
  19. package/dist/chunk-5Y6BEZDY.js +276 -0
  20. package/dist/chunk-5Y6BEZDY.js.map +1 -0
  21. package/dist/{chunk-AVYJQSLW.js → chunk-BER7KXUJ.js} +2 -1
  22. package/dist/chunk-BER7KXUJ.js.map +1 -0
  23. package/dist/chunk-JJBFIGUC.js +5202 -0
  24. package/dist/chunk-JJBFIGUC.js.map +1 -0
  25. package/dist/chunk-PR4QN5HX.js +43 -0
  26. package/dist/chunk-PR4QN5HX.js.map +1 -0
  27. package/dist/chunk-TYAY6AU6.js +159 -0
  28. package/dist/chunk-TYAY6AU6.js.map +1 -0
  29. package/dist/{chunk-PVQZBKN7.js → chunk-Z44WASMA.js} +11 -3
  30. package/dist/chunk-Z44WASMA.js.map +1 -0
  31. package/dist/{client-BAqDHqAV.d.ts → client-DVoPb3-C.d.ts} +549 -30
  32. package/dist/client.js +2 -1
  33. package/dist/codemode/ai.d.ts +25 -0
  34. package/dist/codemode/ai.js +5112 -0
  35. package/dist/codemode/ai.js.map +1 -0
  36. package/dist/index.d.ts +44 -35
  37. package/dist/index.js +7 -4
  38. package/dist/mcp/client.d.ts +2 -1
  39. package/dist/mcp/client.js +2 -1
  40. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  41. package/dist/mcp/do-oauth-client-provider.js +2 -1
  42. package/dist/mcp/index.d.ts +50 -83
  43. package/dist/mcp/index.js +903 -760
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +39 -0
  46. package/dist/mcp/x402.js +3195 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-BH1fJeiU.d.ts +58 -0
  49. package/dist/observability/index.d.ts +12 -24
  50. package/dist/observability/index.js +5 -4
  51. package/dist/react.d.ts +10 -6
  52. package/dist/react.js +101 -3
  53. package/dist/react.js.map +1 -1
  54. package/dist/schedule.d.ts +76 -2
  55. package/dist/schedule.js +17 -2
  56. package/dist/schedule.js.map +1 -1
  57. package/dist/secp256k1-M22GZP2U.js +2193 -0
  58. package/dist/secp256k1-M22GZP2U.js.map +1 -0
  59. package/package.json +22 -7
  60. package/src/index.ts +226 -116
  61. package/dist/chunk-AVYJQSLW.js.map +0 -1
  62. package/dist/chunk-DS7BJNPH.js.map +0 -1
  63. package/dist/chunk-EGCWEPQL.js.map +0 -1
  64. package/dist/chunk-PVQZBKN7.js.map +0 -1
package/dist/mcp/index.js CHANGED
@@ -1,47 +1,582 @@
1
1
  import {
2
- Agent
3
- } from "../chunk-EGCWEPQL.js";
2
+ Agent,
3
+ getAgentByName,
4
+ getCurrentAgent
5
+ } from "../chunk-254F4GDT.js";
4
6
  import {
5
7
  SSEEdgeClientTransport,
6
8
  StreamableHTTPEdgeClientTransport
7
- } from "../chunk-DS7BJNPH.js";
8
- import "../chunk-PVQZBKN7.js";
9
+ } from "../chunk-3OT2NNEW.js";
10
+ import "../chunk-Z44WASMA.js";
9
11
  import "../chunk-QEVM4BVL.js";
10
- import "../chunk-AVYJQSLW.js";
12
+ import "../chunk-BER7KXUJ.js";
13
+ import "../chunk-PR4QN5HX.js";
11
14
 
12
15
  // src/mcp/index.ts
13
- import { DurableObject } from "cloudflare:workers";
14
16
  import {
15
- InitializeRequestSchema,
16
- JSONRPCMessageSchema,
17
- isJSONRPCError,
18
- isJSONRPCNotification,
19
- isJSONRPCRequest,
20
- isJSONRPCResponse
17
+ JSONRPCMessageSchema as JSONRPCMessageSchema3,
18
+ isJSONRPCError as isJSONRPCError2,
19
+ isJSONRPCResponse as isJSONRPCResponse3
21
20
  } from "@modelcontextprotocol/sdk/types.js";
21
+
22
+ // src/mcp/utils.ts
22
23
  import {
23
- ElicitRequestSchema
24
+ JSONRPCMessageSchema,
25
+ InitializeRequestSchema,
26
+ isJSONRPCResponse,
27
+ isJSONRPCNotification
24
28
  } from "@modelcontextprotocol/sdk/types.js";
29
+ var MCP_HTTP_METHOD_HEADER = "cf-mcp-method";
30
+ var MCP_MESSAGE_HEADER = "cf-mcp-message";
25
31
  var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
32
+ var createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
33
+ let pathname = basePath;
34
+ if (basePath === "/") pathname = "/*";
35
+ const basePattern = new URLPattern({ pathname });
36
+ return async (request, ctx) => {
37
+ const url = new URL(request.url);
38
+ if (basePattern.test(url)) {
39
+ if (request.method === "POST") {
40
+ const acceptHeader = request.headers.get("accept");
41
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
42
+ const body2 = JSON.stringify({
43
+ error: {
44
+ code: -32e3,
45
+ message: "Not Acceptable: Client must accept both application/json and text/event-stream"
46
+ },
47
+ id: null,
48
+ jsonrpc: "2.0"
49
+ });
50
+ return new Response(body2, { status: 406 });
51
+ }
52
+ const ct = request.headers.get("content-type");
53
+ if (!ct || !ct.includes("application/json")) {
54
+ const body2 = JSON.stringify({
55
+ error: {
56
+ code: -32e3,
57
+ message: "Unsupported Media Type: Content-Type must be application/json"
58
+ },
59
+ id: null,
60
+ jsonrpc: "2.0"
61
+ });
62
+ return new Response(body2, { status: 415 });
63
+ }
64
+ const contentLength = Number.parseInt(
65
+ request.headers.get("content-length") ?? "0",
66
+ 10
67
+ );
68
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
69
+ const body2 = JSON.stringify({
70
+ error: {
71
+ code: -32e3,
72
+ message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
73
+ },
74
+ id: null,
75
+ jsonrpc: "2.0"
76
+ });
77
+ return new Response(body2, { status: 413 });
78
+ }
79
+ let sessionId = request.headers.get("mcp-session-id");
80
+ let rawMessage;
81
+ try {
82
+ rawMessage = await request.json();
83
+ } catch (_error) {
84
+ const body2 = JSON.stringify({
85
+ error: {
86
+ code: -32700,
87
+ message: "Parse error: Invalid JSON"
88
+ },
89
+ id: null,
90
+ jsonrpc: "2.0"
91
+ });
92
+ return new Response(body2, { status: 400 });
93
+ }
94
+ let arrayMessage;
95
+ if (Array.isArray(rawMessage)) {
96
+ arrayMessage = rawMessage;
97
+ } else {
98
+ arrayMessage = [rawMessage];
99
+ }
100
+ let messages = [];
101
+ for (const msg of arrayMessage) {
102
+ if (!JSONRPCMessageSchema.safeParse(msg).success) {
103
+ const body2 = JSON.stringify({
104
+ error: {
105
+ code: -32700,
106
+ message: "Parse error: Invalid JSON-RPC message"
107
+ },
108
+ id: null,
109
+ jsonrpc: "2.0"
110
+ });
111
+ return new Response(body2, { status: 400 });
112
+ }
113
+ }
114
+ messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
115
+ const maybeInitializeRequest = messages.find(
116
+ (msg) => InitializeRequestSchema.safeParse(msg).success
117
+ );
118
+ if (!!maybeInitializeRequest && sessionId) {
119
+ const body2 = JSON.stringify({
120
+ error: {
121
+ code: -32600,
122
+ message: "Invalid Request: Initialization requests must not include a sessionId"
123
+ },
124
+ id: null,
125
+ jsonrpc: "2.0"
126
+ });
127
+ return new Response(body2, { status: 400 });
128
+ }
129
+ if (!!maybeInitializeRequest && messages.length > 1) {
130
+ const body2 = JSON.stringify({
131
+ error: {
132
+ code: -32600,
133
+ message: "Invalid Request: Only one initialization request is allowed"
134
+ },
135
+ id: null,
136
+ jsonrpc: "2.0"
137
+ });
138
+ return new Response(body2, { status: 400 });
139
+ }
140
+ if (!maybeInitializeRequest && !sessionId) {
141
+ const body2 = JSON.stringify({
142
+ error: {
143
+ code: -32e3,
144
+ message: "Bad Request: Mcp-Session-Id header is required"
145
+ },
146
+ id: null,
147
+ jsonrpc: "2.0"
148
+ });
149
+ return new Response(body2, { status: 400 });
150
+ }
151
+ sessionId = sessionId ?? namespace.newUniqueId().toString();
152
+ const agent = await getAgentByName(
153
+ namespace,
154
+ `streamable-http:${sessionId}`,
155
+ { props: ctx.props }
156
+ );
157
+ const isInitialized = await agent.getInitializeRequest();
158
+ if (maybeInitializeRequest) {
159
+ await agent.setInitializeRequest(maybeInitializeRequest);
160
+ } else if (!isInitialized) {
161
+ const body2 = 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(body2, { 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, {
179
+ headers: {
180
+ ...existingHeaders,
181
+ [MCP_HTTP_METHOD_HEADER]: "POST",
182
+ [MCP_MESSAGE_HEADER]: JSON.stringify(messages),
183
+ Upgrade: "websocket"
184
+ }
185
+ });
186
+ if (ctx.props) agent.updateProps(ctx.props);
187
+ const response = await agent.fetch(req);
188
+ const ws = response.webSocket;
189
+ if (!ws) {
190
+ console.error("Failed to establish WebSocket connection");
191
+ await writer.close();
192
+ const body2 = JSON.stringify({
193
+ error: {
194
+ code: -32001,
195
+ message: "Failed to establish WebSocket connection"
196
+ },
197
+ id: null,
198
+ jsonrpc: "2.0"
199
+ });
200
+ return new Response(body2, { status: 500 });
201
+ }
202
+ ws.accept();
203
+ ws.addEventListener("message", (event) => {
204
+ async function onMessage(event2) {
205
+ try {
206
+ const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
207
+ const message = JSON.parse(data);
208
+ if (message.type !== "cf_mcp_agent_event" /* CF_MCP_AGENT_EVENT */) {
209
+ return;
210
+ }
211
+ await writer.write(encoder.encode(message.event));
212
+ if (message.close) {
213
+ ws?.close();
214
+ await writer.close().catch(() => {
215
+ });
216
+ }
217
+ } catch (error) {
218
+ console.error("Error forwarding message to SSE:", error);
219
+ }
220
+ }
221
+ onMessage(event).catch(console.error);
222
+ });
223
+ ws.addEventListener("error", (error) => {
224
+ async function onError(_error) {
225
+ await writer.close().catch(() => {
226
+ });
227
+ }
228
+ onError(error).catch(console.error);
229
+ });
230
+ ws.addEventListener("close", () => {
231
+ async function onClose() {
232
+ await writer.close().catch(() => {
233
+ });
234
+ }
235
+ onClose().catch(console.error);
236
+ });
237
+ const hasOnlyNotificationsOrResponses = messages.every(
238
+ (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
239
+ );
240
+ if (hasOnlyNotificationsOrResponses) {
241
+ ws.close();
242
+ return new Response(null, {
243
+ headers: corsHeaders(request, corsOptions),
244
+ status: 202
245
+ });
246
+ }
247
+ return new Response(readable, {
248
+ headers: {
249
+ "Cache-Control": "no-cache",
250
+ Connection: "keep-alive",
251
+ "Content-Type": "text/event-stream",
252
+ "mcp-session-id": sessionId,
253
+ ...corsHeaders(request, corsOptions)
254
+ },
255
+ status: 200
256
+ });
257
+ } else if (request.method === "GET") {
258
+ const acceptHeader = request.headers.get("accept");
259
+ if (!acceptHeader?.includes("text/event-stream")) {
260
+ const body2 = JSON.stringify({
261
+ jsonrpc: "2.0",
262
+ error: {
263
+ code: -32e3,
264
+ message: "Not Acceptable: Client must accept text/event-stream"
265
+ },
266
+ id: null
267
+ });
268
+ return new Response(body2, { status: 406 });
269
+ }
270
+ const sessionId = request.headers.get("mcp-session-id");
271
+ if (!sessionId)
272
+ return new Response(
273
+ JSON.stringify({
274
+ error: {
275
+ code: -32e3,
276
+ message: "Bad Request: Mcp-Session-Id header is required"
277
+ },
278
+ id: null,
279
+ jsonrpc: "2.0"
280
+ }),
281
+ { status: 400 }
282
+ );
283
+ const { readable, writable } = new TransformStream();
284
+ const writer = writable.getWriter();
285
+ const encoder = new TextEncoder();
286
+ const agent = await getAgentByName(
287
+ namespace,
288
+ `streamable-http:${sessionId}`,
289
+ { props: ctx.props }
290
+ );
291
+ const isInitialized = await agent.getInitializeRequest();
292
+ if (!isInitialized) {
293
+ return new Response(
294
+ JSON.stringify({
295
+ jsonrpc: "2.0",
296
+ error: { code: -32001, message: "Session not found" },
297
+ id: null
298
+ }),
299
+ { status: 404 }
300
+ );
301
+ }
302
+ const existingHeaders = {};
303
+ request.headers.forEach((v, k) => {
304
+ existingHeaders[k] = v;
305
+ });
306
+ if (ctx.props) agent.updateProps(ctx.props);
307
+ const response = await agent.fetch(
308
+ new Request(request.url, {
309
+ headers: {
310
+ ...existingHeaders,
311
+ [MCP_HTTP_METHOD_HEADER]: "GET",
312
+ Upgrade: "websocket"
313
+ }
314
+ })
315
+ );
316
+ const ws = response.webSocket;
317
+ if (!ws) {
318
+ await writer.close();
319
+ return new Response("Failed to establish WS to DO", {
320
+ status: 500
321
+ });
322
+ }
323
+ ws.accept();
324
+ ws.addEventListener("message", (event) => {
325
+ try {
326
+ async function onMessage(ev) {
327
+ const data = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
328
+ const message = JSON.parse(data);
329
+ if (message.type !== "cf_mcp_agent_event" /* CF_MCP_AGENT_EVENT */) {
330
+ return;
331
+ }
332
+ await writer.write(encoder.encode(message.event));
333
+ }
334
+ onMessage(event).catch(console.error);
335
+ } catch (e) {
336
+ console.error("Error forwarding message to SSE:", e);
337
+ }
338
+ });
339
+ ws.addEventListener("error", () => {
340
+ writer.close().catch(() => {
341
+ });
342
+ });
343
+ ws.addEventListener("close", () => {
344
+ writer.close().catch(() => {
345
+ });
346
+ });
347
+ return new Response(readable, {
348
+ headers: {
349
+ "Cache-Control": "no-cache",
350
+ Connection: "keep-alive",
351
+ "Content-Type": "text/event-stream",
352
+ "mcp-session-id": sessionId,
353
+ ...corsHeaders(request, corsOptions)
354
+ },
355
+ status: 200
356
+ });
357
+ } else if (request.method === "DELETE") {
358
+ const sessionId = request.headers.get("mcp-session-id");
359
+ if (!sessionId) {
360
+ return new Response(
361
+ JSON.stringify({
362
+ jsonrpc: "2.0",
363
+ error: {
364
+ code: -32e3,
365
+ message: "Bad Request: Mcp-Session-Id header is required"
366
+ },
367
+ id: null
368
+ }),
369
+ { status: 400, headers: corsHeaders(request, corsOptions) }
370
+ );
371
+ }
372
+ const agent = await getAgentByName(
373
+ namespace,
374
+ `streamable-http:${sessionId}`
375
+ );
376
+ const isInitialized = await agent.getInitializeRequest();
377
+ if (!isInitialized) {
378
+ return new Response(
379
+ JSON.stringify({
380
+ jsonrpc: "2.0",
381
+ error: { code: -32001, message: "Session not found" },
382
+ id: null
383
+ }),
384
+ { status: 404, headers: corsHeaders(request, corsOptions) }
385
+ );
386
+ }
387
+ ctx.waitUntil(
388
+ agent.destroy().catch(() => {
389
+ })
390
+ );
391
+ return new Response(null, {
392
+ status: 204,
393
+ headers: corsHeaders(request, corsOptions)
394
+ });
395
+ }
396
+ }
397
+ const body = JSON.stringify({
398
+ error: {
399
+ code: -32e3,
400
+ message: "Not found"
401
+ },
402
+ id: null,
403
+ jsonrpc: "2.0"
404
+ });
405
+ return new Response(body, { status: 404 });
406
+ };
407
+ };
408
+ var createLegacySseHandler = (basePath, namespace, corsOptions) => {
409
+ let pathname = basePath;
410
+ if (basePath === "/") pathname = "/*";
411
+ const basePattern = new URLPattern({ pathname });
412
+ const messagePattern = new URLPattern({ pathname: `${basePath}/message` });
413
+ return async (request, ctx) => {
414
+ const url = new URL(request.url);
415
+ if (request.method === "GET" && basePattern.test(url)) {
416
+ const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
417
+ const { readable, writable } = new TransformStream();
418
+ const writer = writable.getWriter();
419
+ const encoder = new TextEncoder();
420
+ const endpointUrl = new URL(request.url);
421
+ endpointUrl.pathname = encodeURI(`${basePath}/message`);
422
+ endpointUrl.searchParams.set("sessionId", sessionId);
423
+ const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;
424
+ const endpointMessage = `event: endpoint
425
+ data: ${relativeUrlWithSession}
426
+
427
+ `;
428
+ writer.write(encoder.encode(endpointMessage));
429
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, {
430
+ props: ctx.props
431
+ });
432
+ const existingHeaders = {};
433
+ request.headers.forEach((value, key) => {
434
+ existingHeaders[key] = value;
435
+ });
436
+ if (ctx.props) agent.updateProps(ctx.props);
437
+ const response = await agent.fetch(
438
+ new Request(request.url, {
439
+ headers: {
440
+ ...existingHeaders,
441
+ Upgrade: "websocket"
442
+ }
443
+ })
444
+ );
445
+ const ws = response.webSocket;
446
+ if (!ws) {
447
+ console.error("Failed to establish WebSocket connection");
448
+ await writer.close();
449
+ return new Response("Failed to establish WebSocket connection", {
450
+ status: 500
451
+ });
452
+ }
453
+ ws.accept();
454
+ ws.addEventListener("message", (event) => {
455
+ async function onMessage(event2) {
456
+ try {
457
+ const message = JSON.parse(event2.data);
458
+ const result = JSONRPCMessageSchema.safeParse(message);
459
+ if (!result.success) {
460
+ return;
461
+ }
462
+ const messageText = `event: message
463
+ data: ${JSON.stringify(result.data)}
464
+
465
+ `;
466
+ await writer.write(encoder.encode(messageText));
467
+ } catch (error) {
468
+ console.error("Error forwarding message to SSE:", error);
469
+ }
470
+ }
471
+ onMessage(event).catch(console.error);
472
+ });
473
+ ws.addEventListener("error", (error) => {
474
+ async function onError(_error) {
475
+ try {
476
+ await writer.close();
477
+ } catch (_e) {
478
+ }
479
+ }
480
+ onError(error).catch(console.error);
481
+ });
482
+ ws.addEventListener("close", () => {
483
+ async function onClose() {
484
+ try {
485
+ await writer.close();
486
+ } catch (error) {
487
+ console.error("Error closing SSE connection:", error);
488
+ }
489
+ }
490
+ onClose().catch(console.error);
491
+ });
492
+ return new Response(readable, {
493
+ headers: {
494
+ "Cache-Control": "no-cache",
495
+ Connection: "keep-alive",
496
+ "Content-Type": "text/event-stream",
497
+ ...corsHeaders(request, corsOptions)
498
+ }
499
+ });
500
+ }
501
+ if (request.method === "POST" && messagePattern.test(url)) {
502
+ const sessionId = url.searchParams.get("sessionId");
503
+ if (!sessionId) {
504
+ return new Response(
505
+ `Missing sessionId. Expected POST to ${basePath} to initiate new one`,
506
+ { status: 400 }
507
+ );
508
+ }
509
+ const contentType = request.headers.get("content-type") || "";
510
+ if (!contentType.includes("application/json")) {
511
+ return new Response(`Unsupported content-type: ${contentType}`, {
512
+ status: 400
513
+ });
514
+ }
515
+ const contentLength = Number.parseInt(
516
+ request.headers.get("content-length") || "0",
517
+ 10
518
+ );
519
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
520
+ return new Response(`Request body too large: ${contentLength} bytes`, {
521
+ status: 400
522
+ });
523
+ }
524
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, {
525
+ props: ctx.props
526
+ });
527
+ const messageBody = await request.json();
528
+ const error = await agent.onSSEMcpMessage(sessionId, messageBody);
529
+ if (error) {
530
+ return new Response(error.message, {
531
+ headers: {
532
+ "Cache-Control": "no-cache",
533
+ Connection: "keep-alive",
534
+ "Content-Type": "text/event-stream",
535
+ ...corsHeaders(request, corsOptions)
536
+ },
537
+ status: 400
538
+ });
539
+ }
540
+ return new Response("Accepted", {
541
+ headers: {
542
+ "Cache-Control": "no-cache",
543
+ Connection: "keep-alive",
544
+ "Content-Type": "text/event-stream",
545
+ ...corsHeaders(request, corsOptions)
546
+ },
547
+ status: 202
548
+ });
549
+ }
550
+ return new Response("Not Found", { status: 404 });
551
+ };
552
+ };
26
553
  function corsHeaders(_request, corsOptions = {}) {
27
554
  const origin = "*";
28
555
  return {
29
- "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id, mcp-protocol-version",
30
- "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, OPTIONS",
556
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, Accept, mcp-session-id, mcp-protocol-version",
557
+ "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, DELETE, OPTIONS",
31
558
  "Access-Control-Allow-Origin": corsOptions.origin || origin,
32
559
  "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
33
560
  "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
34
561
  };
35
562
  }
36
- function isDurableObjectNamespace(namespace) {
37
- return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
38
- }
39
563
  function handleCORS(request, corsOptions) {
40
564
  if (request.method === "OPTIONS") {
41
565
  return new Response(null, { headers: corsHeaders(request, corsOptions) });
42
566
  }
43
567
  return null;
44
568
  }
569
+ function isDurableObjectNamespace(namespace) {
570
+ return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
571
+ }
572
+
573
+ // src/mcp/transport.ts
574
+ import {
575
+ isJSONRPCError,
576
+ isJSONRPCRequest,
577
+ isJSONRPCResponse as isJSONRPCResponse2,
578
+ JSONRPCMessageSchema as JSONRPCMessageSchema2
579
+ } from "@modelcontextprotocol/sdk/types.js";
45
580
  var McpSSETransport = class {
46
581
  constructor(getWebSocket) {
47
582
  this._started = false;
@@ -65,300 +600,377 @@ var McpSSETransport = class {
65
600
  websocket.send(JSON.stringify(message));
66
601
  } catch (error) {
67
602
  this.onerror?.(error);
68
- throw error;
69
603
  }
70
604
  }
71
605
  async close() {
72
606
  this.onclose?.();
73
607
  }
74
608
  };
75
- var McpStreamableHttpTransport = class {
76
- constructor(getWebSocketForMessageID, notifyResponseIdSent) {
609
+ var StreamableHTTPServerTransport = class {
610
+ constructor(options) {
77
611
  this._started = false;
78
- this._getWebSocketForMessageID = getWebSocketForMessageID;
79
- this._notifyResponseIdSent = notifyResponseIdSent;
80
- this._getWebSocketForGetRequest = () => null;
612
+ // This is to keep track whether all messages from a single POST request have been answered.
613
+ // I's fine that we don't persist this since it's only for backwards compatibility as clients
614
+ // should no longer batch requests, per the spec.
615
+ this._requestResponseMap = /* @__PURE__ */ new Map();
616
+ const { agent } = getCurrentAgent();
617
+ if (!agent)
618
+ throw new Error("McpAgent was not found in Transport constructor");
619
+ this.sessionId = agent.getSessionId();
620
+ this._eventStore = options.eventStore;
81
621
  }
622
+ /**
623
+ * Starts the transport. This is required by the Transport interface but is a no-op
624
+ * for the Streamable HTTP transport as connections are managed per-request.
625
+ */
82
626
  async start() {
83
627
  if (this._started) {
84
628
  throw new Error("Transport already started");
85
629
  }
86
630
  this._started = true;
87
631
  }
88
- async send(message) {
89
- if (!this._started) {
90
- throw new Error("Transport not started");
91
- }
92
- let websocket = null;
93
- if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
94
- websocket = this._getWebSocketForMessageID(message.id.toString());
95
- if (!websocket) {
96
- throw new Error(
97
- `Could not find WebSocket for message id: ${message.id}`
98
- );
632
+ /**
633
+ * Handles GET requests for SSE stream
634
+ */
635
+ async handleGetRequest(req) {
636
+ const { connection } = getCurrentAgent();
637
+ if (!connection)
638
+ throw new Error("Connection was not found in handleGetRequest");
639
+ if (this._eventStore) {
640
+ const lastEventId = req.headers.get("last-event-id");
641
+ if (lastEventId) {
642
+ await this.replayEvents(lastEventId);
643
+ return;
99
644
  }
100
- } else if (isJSONRPCRequest(message)) {
101
- websocket = this._getWebSocketForGetRequest();
102
- } else if (isJSONRPCNotification(message)) {
103
- websocket = null;
104
645
  }
646
+ connection.setState({
647
+ _standaloneSse: true
648
+ });
649
+ }
650
+ /**
651
+ * Replays events that would have been sent after the specified event ID
652
+ * Only used when resumability is enabled
653
+ */
654
+ async replayEvents(lastEventId) {
655
+ if (!this._eventStore) {
656
+ return;
657
+ }
658
+ const { connection } = getCurrentAgent();
659
+ if (!connection)
660
+ throw new Error("Connection was not available in replayEvents");
105
661
  try {
106
- websocket?.send(JSON.stringify(message));
107
- if (isJSONRPCResponse(message)) {
108
- this._notifyResponseIdSent(message.id.toString());
109
- }
662
+ await this._eventStore?.replayEventsAfter(lastEventId, {
663
+ send: async (eventId, message) => {
664
+ try {
665
+ this.writeSSEEvent(connection, message, eventId);
666
+ } catch (error) {
667
+ this.onerror?.(error);
668
+ }
669
+ }
670
+ });
110
671
  } catch (error) {
111
672
  this.onerror?.(error);
112
- throw error;
113
673
  }
114
674
  }
115
- async close() {
116
- this.onclose?.();
117
- }
118
- };
119
- var McpAgent = class _McpAgent extends DurableObject {
120
- constructor(ctx, env) {
121
- var _a;
122
- super(ctx, env);
123
- this._status = "zero";
124
- this._transportType = "unset";
125
- this._requestIdToConnectionId = /* @__PURE__ */ new Map();
126
- this.initRun = false;
127
- const self = this;
128
- this._agent = new (_a = class extends Agent {
129
- onStateUpdate(state, source) {
130
- return self.onStateUpdate(state, source);
131
- }
132
- async onMessage(connection, message) {
133
- return self.onMessage(connection, message);
134
- }
135
- }, _a.options = {
136
- hibernate: true
137
- }, _a)(ctx, env);
138
- }
139
- get mcp() {
140
- return this._agent.mcp;
141
- }
142
- get state() {
143
- return this._agent.state;
144
- }
145
- sql(strings, ...values) {
146
- return this._agent.sql(strings, ...values);
147
- }
148
- setState(state) {
149
- return this._agent.setState(state);
675
+ /**
676
+ * Writes an event to the SSE stream with proper formatting
677
+ */
678
+ writeSSEEvent(connection, message, eventId, close) {
679
+ let eventData = "event: message\n";
680
+ if (eventId) {
681
+ eventData += `id: ${eventId}
682
+ `;
683
+ }
684
+ eventData += `data: ${JSON.stringify(message)}
685
+
686
+ `;
687
+ return connection.send(
688
+ JSON.stringify({
689
+ type: "cf_mcp_agent_event" /* CF_MCP_AGENT_EVENT */,
690
+ event: eventData,
691
+ close
692
+ })
693
+ );
150
694
  }
151
695
  /**
152
- * Elicit user input with a message and schema
696
+ * Handles POST requests containing JSON-RPC messages
153
697
  */
154
- async elicitInput(params) {
155
- const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
156
- await this.ctx.storage.put(`elicitation:${requestId}`, {
157
- message: params.message,
158
- requestedSchema: params.requestedSchema,
159
- timestamp: Date.now()
160
- });
161
- const elicitRequest = {
162
- jsonrpc: "2.0",
163
- id: requestId,
164
- method: "elicitation/create",
165
- params: {
166
- message: params.message,
167
- requestedSchema: params.requestedSchema
168
- }
698
+ async handlePostRequest(req, parsedBody) {
699
+ const authInfo = req.auth;
700
+ const requestInfo = {
701
+ headers: Object.fromEntries(req.headers.entries())
169
702
  };
170
- if (this._transport) {
171
- await this._transport.send(elicitRequest);
703
+ delete requestInfo.headers[MCP_HTTP_METHOD_HEADER];
704
+ delete requestInfo.headers[MCP_MESSAGE_HEADER];
705
+ delete requestInfo.headers.upgrade;
706
+ const rawMessage = parsedBody;
707
+ let messages;
708
+ if (Array.isArray(rawMessage)) {
709
+ messages = rawMessage.map((msg) => JSONRPCMessageSchema2.parse(msg));
172
710
  } else {
173
- const connections = this._agent?.getConnections();
174
- if (!connections || Array.from(connections).length === 0) {
175
- await this.ctx.storage.delete(`elicitation:${requestId}`);
176
- throw new Error("No active connections available for elicitation");
711
+ messages = [JSONRPCMessageSchema2.parse(rawMessage)];
712
+ }
713
+ const hasRequests = messages.some(isJSONRPCRequest);
714
+ if (!hasRequests) {
715
+ for (const message of messages) {
716
+ this.onmessage?.(message, { authInfo, requestInfo });
177
717
  }
178
- const connectionList = Array.from(connections);
179
- for (const connection of connectionList) {
180
- try {
181
- connection.send(JSON.stringify(elicitRequest));
182
- } catch (error) {
183
- console.error("Failed to send elicitation request:", error);
184
- }
718
+ } else if (hasRequests) {
719
+ const { connection } = getCurrentAgent();
720
+ if (!connection)
721
+ throw new Error("Connection was not found in handlePostRequest");
722
+ const requestIds = messages.filter(isJSONRPCRequest).map((message) => message.id);
723
+ connection.setState({
724
+ requestIds
725
+ });
726
+ for (const message of messages) {
727
+ this.onmessage?.(message, { authInfo, requestInfo });
185
728
  }
186
729
  }
187
- return this._waitForElicitationResponse(requestId);
188
730
  }
189
- // we leave the variables as unused for autocomplete purposes
190
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
191
- onStateUpdate(state, source) {
731
+ async close() {
732
+ const { agent } = getCurrentAgent();
733
+ if (!agent) throw new Error("Agent was not found in close");
734
+ for (const conn of agent.getConnections()) {
735
+ conn.close(1e3, "Session closed");
736
+ }
737
+ this.onclose?.();
192
738
  }
193
- async onStart() {
194
- var _a;
195
- const self = this;
196
- this._agent = new (_a = class extends Agent {
197
- constructor() {
198
- super(...arguments);
199
- this.initialState = self.initialState;
739
+ async send(message, options) {
740
+ const { agent } = getCurrentAgent();
741
+ if (!agent) throw new Error("Agent was not found in send");
742
+ let requestId = options?.relatedRequestId;
743
+ if (isJSONRPCResponse2(message) || isJSONRPCError(message)) {
744
+ requestId = message.id;
745
+ }
746
+ if (requestId === void 0) {
747
+ if (isJSONRPCResponse2(message) || isJSONRPCError(message)) {
748
+ throw new Error(
749
+ "Cannot send a response on a standalone SSE stream unless resuming a previous client request"
750
+ );
200
751
  }
201
- onStateUpdate(state, source) {
202
- return self.onStateUpdate(state, source);
752
+ let standaloneConnection;
753
+ for (const conn of agent.getConnections()) {
754
+ if (conn.state?._standaloneSse) standaloneConnection = conn;
203
755
  }
204
- async onMessage(connection, event) {
205
- return self.onMessage(connection, event);
756
+ if (standaloneConnection === void 0) {
757
+ return;
206
758
  }
207
- }, _a.options = {
208
- hibernate: true
209
- }, _a)(this.ctx, this.env);
210
- this.props = await this.ctx.storage.get("props");
211
- this._transportType = await this.ctx.storage.get(
212
- "transportType"
213
- );
214
- await this._init(this.props);
215
- const server = await this.server;
216
- if (this._transportType === "sse") {
217
- this._transport = new McpSSETransport(() => this.getWebSocket());
218
- await server.connect(this._transport);
219
- } else if (this._transportType === "streamable-http") {
220
- this._transport = new McpStreamableHttpTransport(
221
- (id) => this.getWebSocketForResponseID(id),
222
- (id) => this._requestIdToConnectionId.delete(id)
759
+ let eventId2;
760
+ if (this._eventStore) {
761
+ eventId2 = await this._eventStore.storeEvent(
762
+ standaloneConnection.id,
763
+ message
764
+ );
765
+ }
766
+ this.writeSSEEvent(standaloneConnection, message, eventId2);
767
+ return;
768
+ }
769
+ const connection = Array.from(
770
+ agent.getConnections()
771
+ ).find((conn) => conn.state?.requestIds?.includes(requestId));
772
+ if (!connection) {
773
+ throw new Error(
774
+ `No connection established for request ID: ${String(requestId)}`
223
775
  );
224
- await server.connect(this._transport);
225
776
  }
777
+ let eventId;
778
+ if (this._eventStore) {
779
+ eventId = await this._eventStore.storeEvent(connection.id, message);
780
+ }
781
+ let shouldClose = false;
782
+ if (isJSONRPCResponse2(message) || isJSONRPCError(message)) {
783
+ this._requestResponseMap.set(requestId, message);
784
+ const relatedIds = connection.state?.requestIds ?? [];
785
+ shouldClose = relatedIds.every((id) => this._requestResponseMap.has(id));
786
+ if (shouldClose) {
787
+ for (const id of relatedIds) {
788
+ this._requestResponseMap.delete(id);
789
+ }
790
+ }
791
+ }
792
+ this.writeSSEEvent(connection, message, eventId, shouldClose);
226
793
  }
227
- /**
228
- * Handle errors that occur during initialization or operation.
229
- * Override this method to provide custom error handling.
230
- * @param error - The error that occurred
231
- * @returns An error response object with status code and message
794
+ };
795
+
796
+ // src/mcp/index.ts
797
+ import {
798
+ ElicitRequestSchema
799
+ } from "@modelcontextprotocol/sdk/types.js";
800
+ var McpAgent = class _McpAgent extends Agent {
801
+ /*
802
+ * Helpers
232
803
  */
233
- onError(error) {
234
- console.error("McpAgent error:", error);
235
- return {
236
- status: 500,
237
- message: error.message || "An unexpected error occurred during initialization"
238
- };
804
+ async setInitializeRequest(initializeRequest) {
805
+ await this.ctx.storage.put("initializeRequest", initializeRequest);
806
+ }
807
+ async getInitializeRequest() {
808
+ return this.ctx.storage.get("initializeRequest");
239
809
  }
240
- async _init(props) {
241
- await this.updateProps(props);
242
- if (!this.ctx.storage.get("transportType")) {
243
- await this.ctx.storage.put("transportType", "unset");
810
+ /** Read the transport type for this agent.
811
+ * This relies on the naming scheme being `sse:${sessionId}`
812
+ * or `streamable-http:${sessionId}`.
813
+ */
814
+ getTransportType() {
815
+ const [t, ..._] = this.name.split(":");
816
+ switch (t) {
817
+ case "sse":
818
+ return "sse";
819
+ case "streamable-http":
820
+ return "streamable-http";
821
+ default:
822
+ throw new Error(
823
+ "Invalid transport type. McpAgent must be addressed with a valid protocol."
824
+ );
244
825
  }
245
- if (!this.initRun) {
246
- this.initRun = true;
247
- try {
248
- await this.init();
249
- } catch (error) {
250
- const errorResponse = this.onError(error);
251
- throw new Error(`Initialization failed: ${errorResponse.message}`);
252
- }
826
+ }
827
+ /** Read the sessionId for this agent.
828
+ * This relies on the naming scheme being `sse:${sessionId}`
829
+ * or `streamable-http:${sessionId}`.
830
+ */
831
+ getSessionId() {
832
+ const [_, sessionId] = this.name.split(":");
833
+ if (!sessionId) {
834
+ throw new Error(
835
+ "Invalid session id. McpAgent must be addressed with a valid session id."
836
+ );
253
837
  }
838
+ return sessionId;
254
839
  }
255
- async setInitialized() {
256
- await this.ctx.storage.put("initialized", true);
840
+ /** Get the unique WebSocket. SSE transport only. */
841
+ getWebSocket() {
842
+ const websockets = Array.from(this.getConnections());
843
+ if (websockets.length === 0) {
844
+ return null;
845
+ }
846
+ return websockets[0];
257
847
  }
258
- async isInitialized() {
259
- return await this.ctx.storage.get("initialized") === true;
848
+ /** Returns a new transport matching the type of the Agent. */
849
+ initTransport() {
850
+ switch (this.getTransportType()) {
851
+ case "sse": {
852
+ return new McpSSETransport(() => this.getWebSocket());
853
+ }
854
+ case "streamable-http": {
855
+ return new StreamableHTTPServerTransport({});
856
+ }
857
+ }
260
858
  }
859
+ /** Update and store the props */
261
860
  async updateProps(props) {
262
861
  await this.ctx.storage.put("props", props ?? {});
263
862
  this.props = props;
264
863
  }
265
- async _initialize() {
266
- await this.ctx.blockConcurrencyWhile(async () => {
267
- this._status = "starting";
268
- await this.onStart();
269
- this._status = "started";
270
- });
271
- }
272
- // Allow the worker to fetch a websocket connection to the agent
273
- async fetch(request) {
274
- if (this._status !== "started") {
275
- await this._initialize();
276
- }
277
- if (request.headers.get("Upgrade") !== "websocket") {
278
- return new Response("Expected WebSocket Upgrade request", {
279
- status: 400
280
- });
864
+ async reinitializeServer() {
865
+ const initializeRequest = await this.getInitializeRequest();
866
+ if (initializeRequest) {
867
+ this._transport?.onmessage?.(initializeRequest);
281
868
  }
282
- const url = new URL(request.url);
283
- const path = url.pathname;
869
+ }
870
+ /*
871
+ * Base Agent / Parykit Server overrides
872
+ */
873
+ /** Sets up the MCP transport and server every time the Agent is started.*/
874
+ async onStart(props) {
875
+ if (props) await this.updateProps(props);
876
+ this.props = await this.ctx.storage.get("props");
877
+ await this.init();
284
878
  const server = await this.server;
285
- switch (path) {
286
- case "/sse": {
287
- const websockets = this.ctx.getWebSockets();
288
- if (websockets.length > 0) {
289
- return new Response("Websocket already connected", { status: 400 });
290
- }
291
- await this.ctx.storage.put("transportType", "sse");
292
- this._transportType = "sse";
293
- if (!this._transport) {
294
- this._transport = new McpSSETransport(() => this.getWebSocket());
295
- await server.connect(this._transport);
296
- }
297
- return this._agent.fetch(request);
298
- }
299
- case "/streamable-http": {
300
- if (!this._transport) {
301
- this._transport = new McpStreamableHttpTransport(
302
- (id) => this.getWebSocketForResponseID(id),
303
- (id) => this._requestIdToConnectionId.delete(id)
304
- );
305
- await server.connect(this._transport);
879
+ this._transport = this.initTransport();
880
+ await server.connect(this._transport);
881
+ await this.reinitializeServer();
882
+ }
883
+ /** Validates new WebSocket connections. */
884
+ async onConnect(conn, { request: req }) {
885
+ switch (this.getTransportType()) {
886
+ case "sse": {
887
+ const websockets = Array.from(this.getConnections());
888
+ if (websockets.length > 1) {
889
+ conn.close(1008, "Websocket already connected");
890
+ return;
306
891
  }
307
- await this.ctx.storage.put("transportType", "streamable-http");
308
- this._transportType = "streamable-http";
309
- return this._agent.fetch(request);
892
+ break;
310
893
  }
311
- default:
312
- return new Response(
313
- "Internal Server Error: Expected /sse or /streamable-http path",
314
- {
315
- status: 500
894
+ case "streamable-http":
895
+ if (this._transport instanceof StreamableHTTPServerTransport) {
896
+ switch (req.headers.get(MCP_HTTP_METHOD_HEADER)) {
897
+ case "POST": {
898
+ const payloadHeader = req.headers.get(MCP_MESSAGE_HEADER);
899
+ const parsedBody = await JSON.parse(payloadHeader ?? "{}");
900
+ this._transport?.handlePostRequest(req, parsedBody);
901
+ break;
902
+ }
903
+ case "GET":
904
+ this._transport?.handleGetRequest(req);
905
+ break;
316
906
  }
317
- );
318
- }
319
- }
320
- getWebSocket() {
321
- const websockets = this.ctx.getWebSockets();
322
- if (websockets.length === 0) {
323
- return null;
324
- }
325
- return websockets[0];
326
- }
327
- getWebSocketForResponseID(id) {
328
- const connectionId = this._requestIdToConnectionId.get(id);
329
- if (connectionId === void 0) {
330
- return null;
907
+ }
331
908
  }
332
- return this._agent.getConnection(connectionId) ?? null;
333
909
  }
334
- // All messages received here. This is currently never called
335
- async onMessage(connection, event) {
336
- if (this._transportType !== "streamable-http") {
337
- const err = new Error(
338
- "Internal Server Error: Expected streamable-http protocol"
339
- );
340
- this._transport?.onerror?.(err);
341
- return;
910
+ /*
911
+ * Transport ingress and routing
912
+ */
913
+ /** Handles MCP Messages for the legacy SSE transport. */
914
+ async onSSEMcpMessage(_sessionId, messageBody) {
915
+ if (this.getTransportType() !== "sse") {
916
+ return new Error("Internal Server Error: Expected SSE transport");
342
917
  }
343
- let message;
344
918
  try {
345
- const data = typeof event === "string" ? event : new TextDecoder().decode(event);
346
- message = JSONRPCMessageSchema.parse(JSON.parse(data));
919
+ let parsedMessage;
920
+ try {
921
+ parsedMessage = JSONRPCMessageSchema3.parse(messageBody);
922
+ } catch (error) {
923
+ this._transport?.onerror?.(error);
924
+ throw error;
925
+ }
926
+ if (await this._handleElicitationResponse(parsedMessage)) {
927
+ return null;
928
+ }
929
+ this._transport?.onmessage?.(parsedMessage);
930
+ return null;
347
931
  } catch (error) {
932
+ console.error("Error forwarding message to SSE:", error);
348
933
  this._transport?.onerror?.(error);
349
- return;
350
- }
351
- if (await this._handleElicitationResponse(message)) {
352
- return;
934
+ return error;
353
935
  }
354
- if (isJSONRPCRequest(message)) {
355
- this._requestIdToConnectionId.set(message.id.toString(), connection.id);
936
+ }
937
+ /** Elicit user input with a message and schema */
938
+ async elicitInput(params) {
939
+ const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
940
+ await this.ctx.storage.put(`elicitation:${requestId}`, {
941
+ message: params.message,
942
+ requestedSchema: params.requestedSchema,
943
+ timestamp: Date.now()
944
+ });
945
+ const elicitRequest = {
946
+ jsonrpc: "2.0",
947
+ id: requestId,
948
+ method: "elicitation/create",
949
+ params: {
950
+ message: params.message,
951
+ requestedSchema: params.requestedSchema
952
+ }
953
+ };
954
+ if (this._transport) {
955
+ await this._transport.send(elicitRequest);
956
+ } else {
957
+ const connections = this.getConnections();
958
+ if (!connections || Array.from(connections).length === 0) {
959
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
960
+ throw new Error("No active connections available for elicitation");
961
+ }
962
+ const connectionList = Array.from(connections);
963
+ for (const connection of connectionList) {
964
+ try {
965
+ connection.send(JSON.stringify(elicitRequest));
966
+ } catch (error) {
967
+ console.error("Failed to send elicitation request:", error);
968
+ }
969
+ }
356
970
  }
357
- this._transport?.onmessage?.(message);
971
+ return this._waitForElicitationResponse(requestId);
358
972
  }
359
- /**
360
- * Wait for elicitation response through storage polling
361
- */
973
+ /** Wait for elicitation response through storage polling */
362
974
  async _waitForElicitationResponse(requestId) {
363
975
  const startTime = Date.now();
364
976
  const timeout = 6e4;
@@ -380,10 +992,9 @@ var McpAgent = class _McpAgent extends DurableObject {
380
992
  await this.ctx.storage.delete(`elicitation:response:${requestId}`);
381
993
  }
382
994
  }
383
- /**
384
- * Handle elicitation responses */
995
+ /** Handle elicitation responses */
385
996
  async _handleElicitationResponse(message) {
386
- if (isJSONRPCResponse(message) && message.result) {
997
+ if (isJSONRPCResponse3(message) && message.result) {
387
998
  const requestId = message.id?.toString();
388
999
  if (!requestId || !requestId.startsWith("elicit_")) return false;
389
1000
  const pendingRequest = await this.ctx.storage.get(
@@ -396,7 +1007,7 @@ var McpAgent = class _McpAgent extends DurableObject {
396
1007
  );
397
1008
  return true;
398
1009
  }
399
- if (isJSONRPCError(message)) {
1010
+ if (isJSONRPCError2(message)) {
400
1011
  const requestId = message.id?.toString();
401
1012
  if (!requestId || !requestId.startsWith("elicit_")) return false;
402
1013
  const pendingRequest = await this.ctx.storage.get(
@@ -417,535 +1028,67 @@ var McpAgent = class _McpAgent extends DurableObject {
417
1028
  }
418
1029
  return false;
419
1030
  }
420
- // All messages received over SSE after the initial connection has been established
421
- // will be passed here
422
- async onSSEMcpMessage(_sessionId, messageBody) {
423
- if (this._status !== "started") {
424
- await this._initialize();
425
- }
426
- if (this._transportType !== "sse") {
427
- return new Error("Internal Server Error: Expected SSE protocol");
428
- }
429
- try {
430
- let parsedMessage;
431
- try {
432
- parsedMessage = JSONRPCMessageSchema.parse(messageBody);
433
- } catch (error) {
434
- this._transport?.onerror?.(error);
435
- throw error;
436
- }
437
- if (await this._handleElicitationResponse(parsedMessage)) {
438
- return null;
439
- }
440
- this._transport?.onmessage?.(parsedMessage);
441
- return null;
442
- } catch (error) {
443
- console.error("Error forwarding message to SSE:", error);
444
- this._transport?.onerror?.(error);
445
- return error;
446
- }
447
- }
448
- // Delegate all websocket events to the underlying agent
449
- async webSocketMessage(ws, event) {
450
- if (this._status !== "started") {
451
- await this._initialize();
452
- }
453
- return await this._agent.webSocketMessage(ws, event);
454
- }
455
- // WebSocket event handlers for hibernation support
456
- async webSocketError(ws, error) {
457
- if (this._status !== "started") {
458
- await this._initialize();
459
- }
460
- return await this._agent.webSocketError(ws, error);
461
- }
462
- async webSocketClose(ws, code, reason, wasClean) {
463
- if (this._status !== "started") {
464
- await this._initialize();
465
- }
466
- return await this._agent.webSocketClose(ws, code, reason, wasClean);
467
- }
468
- static mount(path, {
469
- binding = "MCP_OBJECT",
470
- corsOptions
471
- } = {}) {
472
- return _McpAgent.serveSSE(path, { binding, corsOptions });
473
- }
474
- static serveSSE(path, {
475
- binding = "MCP_OBJECT",
476
- corsOptions
477
- } = {}) {
478
- let pathname = path;
479
- if (path === "/") {
480
- pathname = "/*";
481
- }
482
- const basePattern = new URLPattern({ pathname });
483
- const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
484
- return {
485
- async fetch(request, env, ctx) {
486
- const corsResponse = handleCORS(request, corsOptions);
487
- if (corsResponse) return corsResponse;
488
- const url = new URL(request.url);
489
- const bindingValue = env[binding];
490
- if (bindingValue == null || typeof bindingValue !== "object") {
491
- console.error(
492
- `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
493
- );
494
- return new Response("Invalid binding", { status: 500 });
495
- }
496
- if (!isDurableObjectNamespace(bindingValue)) {
497
- return new Response("Invalid binding", { status: 500 });
498
- }
499
- const namespace = bindingValue;
500
- if (request.method === "GET" && basePattern.test(url)) {
501
- const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
502
- const { readable, writable } = new TransformStream();
503
- const writer = writable.getWriter();
504
- const encoder = new TextEncoder();
505
- const endpointUrl = new URL(request.url);
506
- endpointUrl.pathname = encodeURI(`${pathname}/message`);
507
- endpointUrl.searchParams.set("sessionId", sessionId);
508
- const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;
509
- const endpointMessage = `event: endpoint
510
- data: ${relativeUrlWithSession}
511
-
512
- `;
513
- writer.write(encoder.encode(endpointMessage));
514
- const id = namespace.idFromName(`sse:${sessionId}`);
515
- const doStub = namespace.get(id);
516
- try {
517
- await doStub._init(ctx.props);
518
- } catch (error) {
519
- console.error("Failed to initialize McpAgent:", error);
520
- await writer.close();
521
- const errorMessage = error instanceof Error ? error.message : String(error);
522
- return new Response(`Initialization failed: ${errorMessage}`, {
523
- status: 500
524
- });
525
- }
526
- const upgradeUrl = new URL(request.url);
527
- upgradeUrl.pathname = "/sse";
528
- const existingHeaders = {};
529
- request.headers.forEach((value, key) => {
530
- existingHeaders[key] = value;
531
- });
532
- const response = await doStub.fetch(
533
- new Request(upgradeUrl, {
534
- headers: {
535
- ...existingHeaders,
536
- Upgrade: "websocket",
537
- // Required by PartyServer
538
- "x-partykit-room": sessionId
539
- }
540
- })
541
- );
542
- const ws = response.webSocket;
543
- if (!ws) {
544
- console.error("Failed to establish WebSocket connection");
545
- await writer.close();
546
- return new Response("Failed to establish WebSocket connection", {
547
- status: 500
548
- });
549
- }
550
- ws.accept();
551
- ws.addEventListener("message", (event) => {
552
- async function onMessage(event2) {
553
- try {
554
- const message = JSON.parse(event2.data);
555
- const result = JSONRPCMessageSchema.safeParse(message);
556
- if (!result.success) {
557
- return;
558
- }
559
- const messageText = `event: message
560
- data: ${JSON.stringify(result.data)}
561
-
562
- `;
563
- await writer.write(encoder.encode(messageText));
564
- } catch (error) {
565
- console.error("Error forwarding message to SSE:", error);
566
- }
567
- }
568
- onMessage(event).catch(console.error);
569
- });
570
- ws.addEventListener("error", (error) => {
571
- async function onError(_error) {
572
- try {
573
- await writer.close();
574
- } catch (_e) {
575
- }
576
- }
577
- onError(error).catch(console.error);
578
- });
579
- ws.addEventListener("close", () => {
580
- async function onClose() {
581
- try {
582
- await writer.close();
583
- } catch (error) {
584
- console.error("Error closing SSE connection:", error);
585
- }
586
- }
587
- onClose().catch(console.error);
588
- });
589
- return new Response(readable, {
590
- headers: {
591
- "Cache-Control": "no-cache",
592
- Connection: "keep-alive",
593
- "Content-Type": "text/event-stream",
594
- ...corsHeaders(request, corsOptions)
595
- }
596
- });
597
- }
598
- if (request.method === "POST" && messagePattern.test(url)) {
599
- const sessionId = url.searchParams.get("sessionId");
600
- if (!sessionId) {
601
- return new Response(
602
- `Missing sessionId. Expected POST to ${pathname} to initiate new one`,
603
- { status: 400 }
604
- );
605
- }
606
- const contentType = request.headers.get("content-type") || "";
607
- if (!contentType.includes("application/json")) {
608
- return new Response(`Unsupported content-type: ${contentType}`, {
609
- status: 400
610
- });
611
- }
612
- const contentLength = Number.parseInt(
613
- request.headers.get("content-length") || "0",
614
- 10
615
- );
616
- if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
617
- return new Response(
618
- `Request body too large: ${contentLength} bytes`,
619
- {
620
- status: 400
621
- }
622
- );
623
- }
624
- const id = namespace.idFromName(`sse:${sessionId}`);
625
- const doStub = namespace.get(id);
626
- const messageBody = await request.json();
627
- await doStub.updateProps(ctx.props);
628
- const error = await doStub.onSSEMcpMessage(sessionId, messageBody);
629
- if (error) {
630
- return new Response(error.message, {
631
- headers: {
632
- "Cache-Control": "no-cache",
633
- Connection: "keep-alive",
634
- "Content-Type": "text/event-stream",
635
- ...corsHeaders(request, corsOptions)
636
- },
637
- status: 400
638
- });
639
- }
640
- return new Response("Accepted", {
641
- headers: {
642
- "Cache-Control": "no-cache",
643
- Connection: "keep-alive",
644
- "Content-Type": "text/event-stream",
645
- ...corsHeaders(request, corsOptions)
646
- },
647
- status: 202
648
- });
649
- }
650
- return new Response("Not Found", { status: 404 });
651
- }
652
- };
653
- }
1031
+ /** Return a handler for the given path for this MCP.
1032
+ * Defaults to Streamable HTTP transport.
1033
+ */
654
1034
  static serve(path, {
655
1035
  binding = "MCP_OBJECT",
656
- corsOptions
1036
+ corsOptions,
1037
+ transport = "streamable-http"
657
1038
  } = {}) {
658
- let pathname = path;
659
- if (path === "/") {
660
- pathname = "/*";
661
- }
662
- const basePattern = new URLPattern({ pathname });
663
1039
  return {
664
1040
  async fetch(request, env, ctx) {
665
1041
  const corsResponse = handleCORS(request, corsOptions);
666
1042
  if (corsResponse) {
667
1043
  return corsResponse;
668
1044
  }
669
- const url = new URL(request.url);
670
1045
  const bindingValue = env[binding];
671
1046
  if (bindingValue == null || typeof bindingValue !== "object") {
672
- console.error(
1047
+ throw new Error(
673
1048
  `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
674
1049
  );
675
- return new Response("Invalid binding", { status: 500 });
676
1050
  }
677
1051
  if (!isDurableObjectNamespace(bindingValue)) {
678
- return new Response("Invalid binding", { status: 500 });
1052
+ throw new Error(
1053
+ `Invalid McpAgent binding for ${binding}. Make sure it's a Durable Object binding.`
1054
+ );
679
1055
  }
680
1056
  const namespace = bindingValue;
681
- if (request.method === "POST" && basePattern.test(url)) {
682
- const acceptHeader = request.headers.get("accept");
683
- if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
684
- const body2 = JSON.stringify({
685
- error: {
686
- code: -32e3,
687
- message: "Not Acceptable: Client must accept both application/json and text/event-stream"
688
- },
689
- id: null,
690
- jsonrpc: "2.0"
691
- });
692
- return new Response(body2, { status: 406 });
693
- }
694
- const ct = request.headers.get("content-type");
695
- if (!ct || !ct.includes("application/json")) {
696
- const body2 = JSON.stringify({
697
- error: {
698
- code: -32e3,
699
- message: "Unsupported Media Type: Content-Type must be application/json"
700
- },
701
- id: null,
702
- jsonrpc: "2.0"
703
- });
704
- return new Response(body2, { status: 415 });
705
- }
706
- const contentLength = Number.parseInt(
707
- request.headers.get("content-length") ?? "0",
708
- 10
709
- );
710
- if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
711
- const body2 = JSON.stringify({
712
- error: {
713
- code: -32e3,
714
- message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
715
- },
716
- id: null,
717
- jsonrpc: "2.0"
718
- });
719
- return new Response(body2, { status: 413 });
720
- }
721
- let sessionId = request.headers.get("mcp-session-id");
722
- let rawMessage;
723
- try {
724
- rawMessage = await request.json();
725
- } catch (_error) {
726
- const body2 = JSON.stringify({
727
- error: {
728
- code: -32700,
729
- message: "Parse error: Invalid JSON"
730
- },
731
- id: null,
732
- jsonrpc: "2.0"
733
- });
734
- return new Response(body2, { status: 400 });
735
- }
736
- let arrayMessage;
737
- if (Array.isArray(rawMessage)) {
738
- arrayMessage = rawMessage;
739
- } else {
740
- arrayMessage = [rawMessage];
741
- }
742
- let messages = [];
743
- for (const msg of arrayMessage) {
744
- if (!JSONRPCMessageSchema.safeParse(msg).success) {
745
- const body2 = JSON.stringify({
746
- error: {
747
- code: -32700,
748
- message: "Parse error: Invalid JSON-RPC message"
749
- },
750
- id: null,
751
- jsonrpc: "2.0"
752
- });
753
- return new Response(body2, { status: 400 });
754
- }
755
- }
756
- messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
757
- const isInitializationRequest = messages.some(
758
- (msg) => InitializeRequestSchema.safeParse(msg).success
759
- );
760
- if (isInitializationRequest && sessionId) {
761
- const body2 = JSON.stringify({
762
- error: {
763
- code: -32600,
764
- message: "Invalid Request: Initialization requests must not include a sessionId"
765
- },
766
- id: null,
767
- jsonrpc: "2.0"
768
- });
769
- return new Response(body2, { status: 400 });
770
- }
771
- if (isInitializationRequest && messages.length > 1) {
772
- const body2 = JSON.stringify({
773
- error: {
774
- code: -32600,
775
- message: "Invalid Request: Only one initialization request is allowed"
776
- },
777
- id: null,
778
- jsonrpc: "2.0"
779
- });
780
- return new Response(body2, { status: 400 });
781
- }
782
- if (!isInitializationRequest && !sessionId) {
783
- const body2 = JSON.stringify({
784
- error: {
785
- code: -32e3,
786
- message: "Bad Request: Mcp-Session-Id header is required"
787
- },
788
- id: null,
789
- jsonrpc: "2.0"
790
- });
791
- return new Response(body2, { status: 400 });
792
- }
793
- sessionId = sessionId ?? namespace.newUniqueId().toString();
794
- const id = namespace.idFromName(`streamable-http:${sessionId}`);
795
- const doStub = namespace.get(id);
796
- const isInitialized = await doStub.isInitialized();
797
- if (isInitializationRequest) {
798
- try {
799
- await doStub._init(ctx.props);
800
- await doStub.setInitialized();
801
- } catch (error) {
802
- console.error("Failed to initialize McpAgent:", error);
803
- const errorMessage = error instanceof Error ? error.message : String(error);
804
- const body2 = JSON.stringify({
805
- error: {
806
- code: -32001,
807
- message: `Initialization failed: ${errorMessage}`
808
- },
809
- id: null,
810
- jsonrpc: "2.0"
811
- });
812
- return new Response(body2, { status: 500 });
813
- }
814
- } else if (!isInitialized) {
815
- const body2 = JSON.stringify({
816
- error: {
817
- code: -32001,
818
- message: "Session not found"
819
- },
820
- id: null,
821
- jsonrpc: "2.0"
822
- });
823
- return new Response(body2, { status: 404 });
824
- } else {
825
- await doStub.updateProps(ctx.props);
826
- }
827
- const { readable, writable } = new TransformStream();
828
- const writer = writable.getWriter();
829
- const encoder = new TextEncoder();
830
- const upgradeUrl = new URL(request.url);
831
- upgradeUrl.pathname = "/streamable-http";
832
- const existingHeaders = {};
833
- request.headers.forEach((value, key) => {
834
- existingHeaders[key] = value;
835
- });
836
- const response = await doStub.fetch(
837
- new Request(upgradeUrl, {
838
- headers: {
839
- ...existingHeaders,
840
- Upgrade: "websocket",
841
- // Required by PartyServer
842
- "x-partykit-room": sessionId
843
- }
844
- })
845
- );
846
- const ws = response.webSocket;
847
- if (!ws) {
848
- console.error("Failed to establish WebSocket connection");
849
- await writer.close();
850
- const body2 = JSON.stringify({
851
- error: {
852
- code: -32001,
853
- message: "Failed to establish WebSocket connection"
854
- },
855
- id: null,
856
- jsonrpc: "2.0"
857
- });
858
- return new Response(body2, { status: 500 });
859
- }
860
- const requestIds = /* @__PURE__ */ new Set();
861
- ws.accept();
862
- ws.addEventListener("message", (event) => {
863
- async function onMessage(event2) {
864
- try {
865
- const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
866
- const message = JSON.parse(data);
867
- const result = JSONRPCMessageSchema.safeParse(message);
868
- if (!result.success) {
869
- return;
870
- }
871
- if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
872
- requestIds.delete(result.data.id);
873
- }
874
- const messageText = `event: message
875
- data: ${JSON.stringify(result.data)}
876
-
877
- `;
878
- await writer.write(encoder.encode(messageText));
879
- if (requestIds.size === 0) {
880
- ws.close();
881
- }
882
- } catch (error) {
883
- console.error("Error forwarding message to SSE:", error);
884
- }
885
- }
886
- onMessage(event).catch(console.error);
887
- });
888
- ws.addEventListener("error", (error) => {
889
- async function onError(_error) {
890
- try {
891
- await writer.close();
892
- } catch (_e) {
893
- }
894
- }
895
- onError(error).catch(console.error);
896
- });
897
- ws.addEventListener("close", () => {
898
- async function onClose() {
899
- try {
900
- await writer.close();
901
- } catch (error) {
902
- console.error("Error closing SSE connection:", error);
903
- }
904
- }
905
- onClose().catch(console.error);
906
- });
907
- const hasOnlyNotificationsOrResponses = messages.every(
908
- (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
909
- );
910
- if (hasOnlyNotificationsOrResponses) {
911
- for (const message of messages) {
912
- ws.send(JSON.stringify(message));
913
- }
914
- ws.close();
915
- return new Response(null, {
916
- headers: corsHeaders(request, corsOptions),
917
- status: 202
918
- });
1057
+ switch (transport) {
1058
+ case "streamable-http": {
1059
+ const handleStreamableHttp = createStreamingHttpHandler(
1060
+ path,
1061
+ namespace,
1062
+ corsOptions
1063
+ );
1064
+ return handleStreamableHttp(request, ctx);
919
1065
  }
920
- for (const message of messages) {
921
- if (isJSONRPCRequest(message)) {
922
- requestIds.add(message.id);
923
- }
924
- ws.send(JSON.stringify(message));
1066
+ case "sse": {
1067
+ const handleLegacySse = createLegacySseHandler(
1068
+ path,
1069
+ namespace,
1070
+ corsOptions
1071
+ );
1072
+ return handleLegacySse(request, ctx);
925
1073
  }
926
- return new Response(readable, {
927
- headers: {
928
- "Cache-Control": "no-cache",
929
- Connection: "keep-alive",
930
- "Content-Type": "text/event-stream",
931
- "mcp-session-id": sessionId,
932
- ...corsHeaders(request, corsOptions)
933
- },
934
- status: 200
935
- });
1074
+ default:
1075
+ return new Response(
1076
+ "Invalid MCP transport mode. Only `streamable-http` or `sse` are allowed.",
1077
+ { status: 500 }
1078
+ );
936
1079
  }
937
- const body = JSON.stringify({
938
- error: {
939
- code: -32e3,
940
- message: "Method not allowed"
941
- },
942
- id: null,
943
- jsonrpc: "2.0"
944
- });
945
- return new Response(body, { status: 405 });
946
1080
  }
947
1081
  };
948
1082
  }
1083
+ /**
1084
+ * Legacy api
1085
+ **/
1086
+ static mount(path, opts = {}) {
1087
+ return _McpAgent.serveSSE(path, opts);
1088
+ }
1089
+ static serveSSE(path, opts = {}) {
1090
+ return _McpAgent.serve(path, { ...opts, transport: "sse" });
1091
+ }
949
1092
  };
950
1093
  export {
951
1094
  ElicitRequestSchema,