agents 0.0.0-d2e8c0e → 0.0.0-d3e7a68

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 (72) hide show
  1. package/README.md +255 -27
  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 +13 -9
  5. package/dist/ai-chat-agent.js +482 -60
  6. package/dist/ai-chat-agent.js.map +1 -1
  7. package/dist/ai-chat-v5-migration.d.ts +152 -0
  8. package/dist/ai-chat-v5-migration.js +20 -0
  9. package/dist/ai-chat-v5-migration.js.map +1 -0
  10. package/dist/ai-react.d.ts +70 -72
  11. package/dist/ai-react.js +260 -107
  12. package/dist/ai-react.js.map +1 -1
  13. package/dist/ai-types.d.ts +37 -19
  14. package/dist/ai-types.js +7 -0
  15. package/dist/ccip-CMBYN64O.js +15 -0
  16. package/dist/ccip-CMBYN64O.js.map +1 -0
  17. package/dist/chunk-5Y6BEZDY.js +276 -0
  18. package/dist/chunk-5Y6BEZDY.js.map +1 -0
  19. package/dist/chunk-BER7KXUJ.js +18 -0
  20. package/dist/chunk-BER7KXUJ.js.map +1 -0
  21. package/dist/chunk-JJBFIGUC.js +5202 -0
  22. package/dist/chunk-JJBFIGUC.js.map +1 -0
  23. package/dist/chunk-PR4QN5HX.js +43 -0
  24. package/dist/chunk-PR4QN5HX.js.map +1 -0
  25. package/dist/{chunk-Y67CHZBI.js → chunk-QEPGNUG6.js} +231 -45
  26. package/dist/chunk-QEPGNUG6.js.map +1 -0
  27. package/dist/{chunk-QSGN3REV.js → chunk-QEVM4BVL.js} +10 -17
  28. package/dist/chunk-QEVM4BVL.js.map +1 -0
  29. package/dist/chunk-RS5OCNEQ.js +1323 -0
  30. package/dist/chunk-RS5OCNEQ.js.map +1 -0
  31. package/dist/chunk-TYAY6AU6.js +159 -0
  32. package/dist/chunk-TYAY6AU6.js.map +1 -0
  33. package/dist/chunk-UJVEAURM.js +150 -0
  34. package/dist/chunk-UJVEAURM.js.map +1 -0
  35. package/dist/{chunk-BZXOAZUX.js → chunk-XFS5ERG3.js} +27 -6
  36. package/dist/chunk-XFS5ERG3.js.map +1 -0
  37. package/dist/client-DNEb-lf3.d.ts +5041 -0
  38. package/dist/client.d.ts +8 -2
  39. package/dist/client.js +3 -1
  40. package/dist/index.d.ts +186 -26
  41. package/dist/index.js +14 -4
  42. package/dist/mcp/client.d.ts +9 -781
  43. package/dist/mcp/client.js +2 -1
  44. package/dist/mcp/do-oauth-client-provider.d.ts +9 -0
  45. package/dist/mcp/do-oauth-client-provider.js +2 -1
  46. package/dist/mcp/index.d.ts +58 -64
  47. package/dist/mcp/index.js +957 -637
  48. package/dist/mcp/index.js.map +1 -1
  49. package/dist/mcp/x402.d.ts +39 -0
  50. package/dist/mcp/x402.js +3195 -0
  51. package/dist/mcp/x402.js.map +1 -0
  52. package/dist/observability/index.d.ts +46 -0
  53. package/dist/observability/index.js +12 -0
  54. package/dist/observability/index.js.map +1 -0
  55. package/dist/react.d.ts +63 -41
  56. package/dist/react.js +121 -11
  57. package/dist/react.js.map +1 -1
  58. package/dist/schedule.d.ts +81 -7
  59. package/dist/schedule.js +21 -6
  60. package/dist/schedule.js.map +1 -1
  61. package/dist/secp256k1-M22GZP2U.js +2193 -0
  62. package/dist/secp256k1-M22GZP2U.js.map +1 -0
  63. package/dist/serializable.d.ts +32 -0
  64. package/dist/serializable.js +1 -0
  65. package/dist/serializable.js.map +1 -0
  66. package/package.json +91 -71
  67. package/src/index.ts +937 -200
  68. package/dist/chunk-BZXOAZUX.js.map +0 -1
  69. package/dist/chunk-J6T74FUS.js +0 -783
  70. package/dist/chunk-J6T74FUS.js.map +0 -1
  71. package/dist/chunk-QSGN3REV.js.map +0 -1
  72. package/dist/chunk-Y67CHZBI.js.map +0 -1
package/dist/mcp/index.js CHANGED
@@ -1,29 +1,563 @@
1
1
  import {
2
- Agent
3
- } from "../chunk-J6T74FUS.js";
4
- import "../chunk-BZXOAZUX.js";
5
- import "../chunk-QSGN3REV.js";
6
- import "../chunk-Y67CHZBI.js";
2
+ Agent,
3
+ getAgentByName,
4
+ getCurrentAgent
5
+ } from "../chunk-RS5OCNEQ.js";
6
+ import {
7
+ SSEEdgeClientTransport,
8
+ StreamableHTTPEdgeClientTransport
9
+ } from "../chunk-QEPGNUG6.js";
10
+ import "../chunk-XFS5ERG3.js";
11
+ import "../chunk-QEVM4BVL.js";
12
+ import "../chunk-BER7KXUJ.js";
13
+ import "../chunk-PR4QN5HX.js";
7
14
 
8
15
  // src/mcp/index.ts
9
- import { DurableObject } from "cloudflare:workers";
10
16
  import {
17
+ JSONRPCMessageSchema as JSONRPCMessageSchema3,
18
+ isJSONRPCError as isJSONRPCError2,
19
+ isJSONRPCResponse as isJSONRPCResponse3
20
+ } from "@modelcontextprotocol/sdk/types.js";
21
+
22
+ // src/mcp/utils.ts
23
+ import {
24
+ JSONRPCMessageSchema,
11
25
  InitializeRequestSchema,
12
- isJSONRPCError,
13
- isJSONRPCNotification,
14
- isJSONRPCRequest,
15
26
  isJSONRPCResponse,
16
- JSONRPCMessageSchema
27
+ isJSONRPCNotification
17
28
  } from "@modelcontextprotocol/sdk/types.js";
29
+ var MCP_HTTP_METHOD_HEADER = "cf-mcp-method";
30
+ var MCP_MESSAGE_HEADER = "cf-mcp-message";
18
31
  var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
19
- function corsHeaders(request, corsOptions = {}) {
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
+ };
553
+ function corsHeaders(_request, corsOptions = {}) {
20
554
  const origin = "*";
21
555
  return {
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",
22
558
  "Access-Control-Allow-Origin": corsOptions.origin || origin,
23
- "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, OPTIONS",
24
- "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id",
25
- "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString(),
26
- "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id"
559
+ "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
560
+ "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
27
561
  };
28
562
  }
29
563
  function handleCORS(request, corsOptions) {
@@ -32,6 +566,17 @@ function handleCORS(request, corsOptions) {
32
566
  }
33
567
  return null;
34
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";
35
580
  var McpSSETransport = class {
36
581
  constructor(getWebSocket) {
37
582
  this._started = false;
@@ -55,251 +600,332 @@ var McpSSETransport = class {
55
600
  websocket.send(JSON.stringify(message));
56
601
  } catch (error) {
57
602
  this.onerror?.(error);
58
- throw error;
59
603
  }
60
604
  }
61
605
  async close() {
62
606
  this.onclose?.();
63
607
  }
64
608
  };
65
- var McpStreamableHttpTransport = class {
66
- constructor(getWebSocketForMessageID, notifyResponseIdSent) {
609
+ var StreamableHTTPServerTransport = class {
610
+ constructor(options) {
67
611
  this._started = false;
68
- this._getWebSocketForMessageID = getWebSocketForMessageID;
69
- this._notifyResponseIdSent = notifyResponseIdSent;
70
- 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;
71
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
+ */
72
626
  async start() {
73
627
  if (this._started) {
74
628
  throw new Error("Transport already started");
75
629
  }
76
630
  this._started = true;
77
631
  }
78
- async send(message) {
79
- if (!this._started) {
80
- throw new Error("Transport not started");
81
- }
82
- let websocket = null;
83
- if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
84
- websocket = this._getWebSocketForMessageID(message.id.toString());
85
- if (!websocket) {
86
- throw new Error(
87
- `Could not find WebSocket for message id: ${message.id}`
88
- );
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;
89
644
  }
90
- } else if (isJSONRPCRequest(message)) {
91
- websocket = this._getWebSocketForGetRequest();
92
- } else if (isJSONRPCNotification(message)) {
93
- websocket = null;
94
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");
95
661
  try {
96
- websocket?.send(JSON.stringify(message));
97
- if (isJSONRPCResponse(message)) {
98
- this._notifyResponseIdSent(message.id.toString());
99
- }
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
+ });
100
671
  } catch (error) {
101
672
  this.onerror?.(error);
102
- throw error;
103
673
  }
104
674
  }
105
- async close() {
106
- this.onclose?.();
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
+ );
107
694
  }
108
- };
109
- var McpAgent = class _McpAgent extends DurableObject {
110
- constructor(ctx, env) {
111
- var _a;
112
- super(ctx, env);
113
- this._status = "zero";
114
- this._transportType = "unset";
115
- this._requestIdToConnectionId = /* @__PURE__ */ new Map();
116
- this.initRun = false;
117
- const self = this;
118
- this._agent = new (_a = class extends Agent {
119
- onStateUpdate(state, source) {
120
- return self.onStateUpdate(state, source);
695
+ /**
696
+ * Handles POST requests containing JSON-RPC messages
697
+ */
698
+ async handlePostRequest(req, parsedBody) {
699
+ const authInfo = req.auth;
700
+ const requestInfo = {
701
+ headers: Object.fromEntries(req.headers.entries())
702
+ };
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));
710
+ } else {
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 });
121
717
  }
122
- async onMessage(connection, message) {
123
- return self.onMessage(connection, message);
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 });
124
728
  }
125
- }, _a.options = {
126
- hibernate: true
127
- }, _a)(ctx, env);
128
- }
129
- get mcp() {
130
- return this._agent.mcp;
131
- }
132
- get state() {
133
- return this._agent.state;
134
- }
135
- sql(strings, ...values) {
136
- return this._agent.sql(strings, ...values);
137
- }
138
- setState(state) {
139
- return this._agent.setState(state);
729
+ }
140
730
  }
141
- 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?.();
142
738
  }
143
- async onStart() {
144
- var _a;
145
- const self = this;
146
- this._agent = new (_a = class extends Agent {
147
- constructor() {
148
- super(...arguments);
149
- 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
+ );
150
751
  }
151
- onStateUpdate(state, source) {
152
- return self.onStateUpdate(state, source);
752
+ let standaloneConnection;
753
+ for (const conn of agent.getConnections()) {
754
+ if (conn.state?._standaloneSse) standaloneConnection = conn;
153
755
  }
154
- async onMessage(connection, event) {
155
- return self.onMessage(connection, event);
756
+ if (standaloneConnection === void 0) {
757
+ return;
156
758
  }
157
- }, _a.options = {
158
- hibernate: true
159
- }, _a)(this.ctx, this.env);
160
- this.props = await this.ctx.storage.get("props");
161
- this._transportType = await this.ctx.storage.get(
162
- "transportType"
163
- );
164
- await this._init(this.props);
165
- const server = await this.server;
166
- if (this._transportType === "sse") {
167
- this._transport = new McpSSETransport(() => this.getWebSocket());
168
- await server.connect(this._transport);
169
- } else if (this._transportType === "streamable-http") {
170
- this._transport = new McpStreamableHttpTransport(
171
- (id) => this.getWebSocketForResponseID(id),
172
- (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)}`
173
775
  );
174
- await server.connect(this._transport);
175
776
  }
176
- }
177
- async _init(props) {
178
- await this.ctx.storage.put("props", props ?? {});
179
- if (!this.ctx.storage.get("transportType")) {
180
- await this.ctx.storage.put("transportType", "unset");
777
+ let eventId;
778
+ if (this._eventStore) {
779
+ eventId = await this._eventStore.storeEvent(connection.id, message);
181
780
  }
182
- this.props = props;
183
- if (!this.initRun) {
184
- this.initRun = true;
185
- await this.init();
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
+ }
186
791
  }
792
+ this.writeSSEEvent(connection, message, eventId, shouldClose);
187
793
  }
188
- async setInitialized() {
189
- await this.ctx.storage.put("initialized", true);
190
- }
191
- async isInitialized() {
192
- return await this.ctx.storage.get("initialized") === true;
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
803
+ */
804
+ async setInitializeRequest(initializeRequest) {
805
+ await this.ctx.storage.put("initializeRequest", initializeRequest);
193
806
  }
194
- async _initialize() {
195
- await this.ctx.blockConcurrencyWhile(async () => {
196
- this._status = "starting";
197
- await this.onStart();
198
- this._status = "started";
199
- });
807
+ async getInitializeRequest() {
808
+ return this.ctx.storage.get("initializeRequest");
200
809
  }
201
- // Allow the worker to fetch a websocket connection to the agent
202
- async fetch(request) {
203
- if (this._status !== "started") {
204
- await this._initialize();
205
- }
206
- if (request.headers.get("Upgrade") !== "websocket") {
207
- return new Response("Expected WebSocket Upgrade request", {
208
- status: 400
209
- });
210
- }
211
- const url = new URL(request.url);
212
- const path = url.pathname;
213
- const server = await this.server;
214
- switch (path) {
215
- case "/sse": {
216
- const websockets = this.ctx.getWebSockets();
217
- if (websockets.length > 0) {
218
- return new Response("Websocket already connected", { status: 400 });
219
- }
220
- await this.ctx.storage.put("transportType", "sse");
221
- this._transportType = "sse";
222
- if (!this._transport) {
223
- this._transport = new McpSSETransport(() => this.getWebSocket());
224
- await server.connect(this._transport);
225
- }
226
- return this._agent.fetch(request);
227
- }
228
- case "/streamable-http": {
229
- if (!this._transport) {
230
- this._transport = new McpStreamableHttpTransport(
231
- (id) => this.getWebSocketForResponseID(id),
232
- (id) => this._requestIdToConnectionId.delete(id)
233
- );
234
- await server.connect(this._transport);
235
- }
236
- await this.ctx.storage.put("transportType", "streamable-http");
237
- this._transportType = "streamable-http";
238
- return this._agent.fetch(request);
239
- }
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";
240
821
  default:
241
- return new Response(
242
- "Internal Server Error: Expected /sse or /streamable-http path",
243
- {
244
- status: 500
245
- }
822
+ throw new Error(
823
+ "Invalid transport type. McpAgent must be addressed with a valid protocol."
246
824
  );
247
825
  }
248
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
+ );
837
+ }
838
+ return sessionId;
839
+ }
840
+ /** Get the unique WebSocket. SSE transport only. */
249
841
  getWebSocket() {
250
- const websockets = this.ctx.getWebSockets();
842
+ const websockets = Array.from(this.getConnections());
251
843
  if (websockets.length === 0) {
252
844
  return null;
253
845
  }
254
846
  return websockets[0];
255
847
  }
256
- getWebSocketForResponseID(id) {
257
- const connectionId = this._requestIdToConnectionId.get(id);
258
- if (connectionId === void 0) {
259
- return null;
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
+ }
260
857
  }
261
- return this._agent.getConnection(connectionId) ?? null;
262
858
  }
263
- // All messages received here. This is currently never called
264
- async onMessage(connection, event) {
265
- if (this._transportType !== "streamable-http") {
266
- const err = new Error(
267
- "Internal Server Error: Expected streamable-http protocol"
268
- );
269
- this._transport?.onerror?.(err);
270
- return;
271
- }
272
- let message;
273
- try {
274
- const data = typeof event === "string" ? event : new TextDecoder().decode(event);
275
- message = JSONRPCMessageSchema.parse(JSON.parse(data));
276
- } catch (error) {
277
- this._transport?.onerror?.(error);
278
- return;
279
- }
280
- if (isJSONRPCRequest(message)) {
281
- this._requestIdToConnectionId.set(message.id.toString(), connection.id);
859
+ /** Update and store the props */
860
+ async updateProps(props) {
861
+ await this.ctx.storage.put("props", props ?? {});
862
+ this.props = props;
863
+ }
864
+ async reinitializeServer() {
865
+ const initializeRequest = await this.getInitializeRequest();
866
+ if (initializeRequest) {
867
+ this._transport?.onmessage?.(initializeRequest);
282
868
  }
283
- this._transport?.onmessage?.(message);
284
869
  }
285
- // All messages received over SSE after the initial connection has been established
286
- // will be passed here
287
- async onSSEMcpMessage(sessionId, request) {
288
- if (this._status !== "started") {
289
- await this._initialize();
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();
878
+ const server = await this.server;
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;
891
+ }
892
+ break;
893
+ }
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;
906
+ }
907
+ }
290
908
  }
291
- if (this._transportType !== "sse") {
292
- return new Error("Internal Server Error: Expected SSE protocol");
909
+ }
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");
293
917
  }
294
918
  try {
295
- const message = await request.json();
296
919
  let parsedMessage;
297
920
  try {
298
- parsedMessage = JSONRPCMessageSchema.parse(message);
921
+ parsedMessage = JSONRPCMessageSchema3.parse(messageBody);
299
922
  } catch (error) {
300
923
  this._transport?.onerror?.(error);
301
924
  throw error;
302
925
  }
926
+ if (await this._handleElicitationResponse(parsedMessage)) {
927
+ return null;
928
+ }
303
929
  this._transport?.onmessage?.(parsedMessage);
304
930
  return null;
305
931
  } catch (error) {
@@ -308,472 +934,166 @@ var McpAgent = class _McpAgent extends DurableObject {
308
934
  return error;
309
935
  }
310
936
  }
311
- // Delegate all websocket events to the underlying agent
312
- async webSocketMessage(ws, event) {
313
- if (this._status !== "started") {
314
- await this._initialize();
315
- }
316
- return await this._agent.webSocketMessage(ws, event);
317
- }
318
- // WebSocket event handlers for hibernation support
319
- async webSocketError(ws, error) {
320
- if (this._status !== "started") {
321
- await this._initialize();
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
+ }
322
970
  }
323
- return await this._agent.webSocketError(ws, error);
971
+ return this._waitForElicitationResponse(requestId);
324
972
  }
325
- async webSocketClose(ws, code, reason, wasClean) {
326
- if (this._status !== "started") {
327
- await this._initialize();
973
+ /** Wait for elicitation response through storage polling */
974
+ async _waitForElicitationResponse(requestId) {
975
+ const startTime = Date.now();
976
+ const timeout = 6e4;
977
+ try {
978
+ while (Date.now() - startTime < timeout) {
979
+ const response = await this.ctx.storage.get(
980
+ `elicitation:response:${requestId}`
981
+ );
982
+ if (response) {
983
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
984
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
985
+ return response;
986
+ }
987
+ await new Promise((resolve) => setTimeout(resolve, 100));
988
+ }
989
+ throw new Error("Elicitation request timed out");
990
+ } finally {
991
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
992
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
328
993
  }
329
- return await this._agent.webSocketClose(ws, code, reason, wasClean);
330
994
  }
331
- static mount(path, {
332
- binding = "MCP_OBJECT",
333
- corsOptions
334
- } = {}) {
335
- return _McpAgent.serveSSE(path, { binding, corsOptions });
336
- }
337
- static serveSSE(path, {
338
- binding = "MCP_OBJECT",
339
- corsOptions
340
- } = {}) {
341
- let pathname = path;
342
- if (path === "/") {
343
- pathname = "/*";
995
+ /** Handle elicitation responses */
996
+ async _handleElicitationResponse(message) {
997
+ if (isJSONRPCResponse3(message) && message.result) {
998
+ const requestId = message.id?.toString();
999
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
1000
+ const pendingRequest = await this.ctx.storage.get(
1001
+ `elicitation:${requestId}`
1002
+ );
1003
+ if (!pendingRequest) return false;
1004
+ await this.ctx.storage.put(
1005
+ `elicitation:response:${requestId}`,
1006
+ message.result
1007
+ );
1008
+ return true;
344
1009
  }
345
- const basePattern = new URLPattern({ pathname });
346
- const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
347
- return {
348
- async fetch(request, env, ctx) {
349
- const corsResponse = handleCORS(request, corsOptions);
350
- if (corsResponse) return corsResponse;
351
- const url = new URL(request.url);
352
- const bindingValue = env[binding];
353
- if (bindingValue == null || typeof bindingValue !== "object") {
354
- console.error(
355
- `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
356
- );
357
- return new Response("Invalid binding", { status: 500 });
358
- }
359
- if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
360
- return new Response("Invalid binding", { status: 500 });
361
- }
362
- const namespace = bindingValue;
363
- if (request.method === "GET" && basePattern.test(url)) {
364
- const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
365
- const { readable, writable } = new TransformStream();
366
- const writer = writable.getWriter();
367
- const encoder = new TextEncoder();
368
- const endpointUrl = new URL(request.url);
369
- endpointUrl.pathname = encodeURI(`${pathname}/message`);
370
- endpointUrl.searchParams.set("sessionId", sessionId);
371
- const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;
372
- const endpointMessage = `event: endpoint
373
- data: ${relativeUrlWithSession}
374
-
375
- `;
376
- writer.write(encoder.encode(endpointMessage));
377
- const id = namespace.idFromName(`sse:${sessionId}`);
378
- const doStub = namespace.get(id);
379
- await doStub._init(ctx.props);
380
- const upgradeUrl = new URL(request.url);
381
- upgradeUrl.pathname = "/sse";
382
- const response = await doStub.fetch(
383
- new Request(upgradeUrl, {
384
- headers: {
385
- Upgrade: "websocket",
386
- // Required by PartyServer
387
- "x-partykit-room": sessionId
388
- }
389
- })
390
- );
391
- const ws = response.webSocket;
392
- if (!ws) {
393
- console.error("Failed to establish WebSocket connection");
394
- await writer.close();
395
- return new Response("Failed to establish WebSocket connection", {
396
- status: 500
397
- });
398
- }
399
- ws.accept();
400
- ws.addEventListener("message", (event) => {
401
- async function onMessage(event2) {
402
- try {
403
- const message = JSON.parse(event2.data);
404
- const result = JSONRPCMessageSchema.safeParse(message);
405
- if (!result.success) {
406
- return;
407
- }
408
- const messageText = `event: message
409
- data: ${JSON.stringify(result.data)}
410
-
411
- `;
412
- await writer.write(encoder.encode(messageText));
413
- } catch (error) {
414
- console.error("Error forwarding message to SSE:", error);
415
- }
416
- }
417
- onMessage(event).catch(console.error);
418
- });
419
- ws.addEventListener("error", (error) => {
420
- async function onError(error2) {
421
- try {
422
- await writer.close();
423
- } catch (e) {
424
- }
425
- }
426
- onError(error).catch(console.error);
427
- });
428
- ws.addEventListener("close", () => {
429
- async function onClose() {
430
- try {
431
- await writer.close();
432
- } catch (error) {
433
- console.error("Error closing SSE connection:", error);
434
- }
435
- }
436
- onClose().catch(console.error);
437
- });
438
- return new Response(readable, {
439
- headers: {
440
- "Content-Type": "text/event-stream",
441
- "Cache-Control": "no-cache",
442
- Connection: "keep-alive",
443
- ...corsHeaders(request, corsOptions)
444
- }
445
- });
446
- }
447
- if (request.method === "POST" && messagePattern.test(url)) {
448
- const sessionId = url.searchParams.get("sessionId");
449
- if (!sessionId) {
450
- return new Response(
451
- `Missing sessionId. Expected POST to ${pathname} to initiate new one`,
452
- { status: 400 }
453
- );
454
- }
455
- const contentType = request.headers.get("content-type") || "";
456
- if (!contentType.includes("application/json")) {
457
- return new Response(`Unsupported content-type: ${contentType}`, {
458
- status: 400
459
- });
460
- }
461
- const contentLength = Number.parseInt(
462
- request.headers.get("content-length") || "0",
463
- 10
464
- );
465
- if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
466
- return new Response(
467
- `Request body too large: ${contentLength} bytes`,
468
- {
469
- status: 400
470
- }
471
- );
472
- }
473
- const id = namespace.idFromName(`sse:${sessionId}`);
474
- const doStub = namespace.get(id);
475
- const error = await doStub.onSSEMcpMessage(sessionId, request);
476
- if (error) {
477
- return new Response(error.message, {
478
- status: 400,
479
- headers: {
480
- "Content-Type": "text/event-stream",
481
- "Cache-Control": "no-cache",
482
- Connection: "keep-alive",
483
- ...corsHeaders(request, corsOptions)
484
- }
485
- });
486
- }
487
- return new Response("Accepted", {
488
- status: 202,
489
- headers: {
490
- "Content-Type": "text/event-stream",
491
- "Cache-Control": "no-cache",
492
- Connection: "keep-alive",
493
- ...corsHeaders(request, corsOptions)
494
- }
495
- });
1010
+ if (isJSONRPCError2(message)) {
1011
+ const requestId = message.id?.toString();
1012
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
1013
+ const pendingRequest = await this.ctx.storage.get(
1014
+ `elicitation:${requestId}`
1015
+ );
1016
+ if (!pendingRequest) return false;
1017
+ const errorResult = {
1018
+ action: "cancel",
1019
+ content: {
1020
+ error: message.error.message || "Elicitation request failed"
496
1021
  }
497
- return new Response("Not Found", { status: 404 });
498
- }
499
- };
1022
+ };
1023
+ await this.ctx.storage.put(
1024
+ `elicitation:response:${requestId}`,
1025
+ errorResult
1026
+ );
1027
+ return true;
1028
+ }
1029
+ return false;
500
1030
  }
1031
+ /** Return a handler for the given path for this MCP.
1032
+ * Defaults to Streamable HTTP transport.
1033
+ */
501
1034
  static serve(path, {
502
1035
  binding = "MCP_OBJECT",
503
- corsOptions
1036
+ corsOptions,
1037
+ transport = "streamable-http"
504
1038
  } = {}) {
505
- let pathname = path;
506
- if (path === "/") {
507
- pathname = "/*";
508
- }
509
- const basePattern = new URLPattern({ pathname });
510
1039
  return {
511
1040
  async fetch(request, env, ctx) {
512
1041
  const corsResponse = handleCORS(request, corsOptions);
513
1042
  if (corsResponse) {
514
1043
  return corsResponse;
515
1044
  }
516
- const url = new URL(request.url);
517
1045
  const bindingValue = env[binding];
518
1046
  if (bindingValue == null || typeof bindingValue !== "object") {
519
- console.error(
1047
+ throw new Error(
520
1048
  `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
521
1049
  );
522
- return new Response("Invalid binding", { status: 500 });
523
1050
  }
524
- if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
525
- return new Response("Invalid binding", { status: 500 });
1051
+ if (!isDurableObjectNamespace(bindingValue)) {
1052
+ throw new Error(
1053
+ `Invalid McpAgent binding for ${binding}. Make sure it's a Durable Object binding.`
1054
+ );
526
1055
  }
527
1056
  const namespace = bindingValue;
528
- if (request.method === "POST" && basePattern.test(url)) {
529
- const acceptHeader = request.headers.get("accept");
530
- if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
531
- const body2 = JSON.stringify({
532
- jsonrpc: "2.0",
533
- error: {
534
- code: -32e3,
535
- message: "Not Acceptable: Client must accept both application/json and text/event-stream"
536
- },
537
- id: null
538
- });
539
- return new Response(body2, { status: 406 });
540
- }
541
- const ct = request.headers.get("content-type");
542
- if (!ct || !ct.includes("application/json")) {
543
- const body2 = JSON.stringify({
544
- jsonrpc: "2.0",
545
- error: {
546
- code: -32e3,
547
- message: "Unsupported Media Type: Content-Type must be application/json"
548
- },
549
- id: null
550
- });
551
- return new Response(body2, { status: 415 });
552
- }
553
- const contentLength = Number.parseInt(
554
- request.headers.get("content-length") ?? "0",
555
- 10
556
- );
557
- if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
558
- const body2 = JSON.stringify({
559
- jsonrpc: "2.0",
560
- error: {
561
- code: -32e3,
562
- message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
563
- },
564
- id: null
565
- });
566
- return new Response(body2, { status: 413 });
567
- }
568
- let sessionId = request.headers.get("mcp-session-id");
569
- let rawMessage;
570
- try {
571
- rawMessage = await request.json();
572
- } catch (error) {
573
- const body2 = JSON.stringify({
574
- jsonrpc: "2.0",
575
- error: {
576
- code: -32700,
577
- message: "Parse error: Invalid JSON"
578
- },
579
- id: null
580
- });
581
- return new Response(body2, { status: 400 });
582
- }
583
- let arrayMessage;
584
- if (Array.isArray(rawMessage)) {
585
- arrayMessage = rawMessage;
586
- } else {
587
- arrayMessage = [rawMessage];
588
- }
589
- let messages = [];
590
- for (const msg of arrayMessage) {
591
- if (!JSONRPCMessageSchema.safeParse(msg).success) {
592
- const body2 = JSON.stringify({
593
- jsonrpc: "2.0",
594
- error: {
595
- code: -32700,
596
- message: "Parse error: Invalid JSON-RPC message"
597
- },
598
- id: null
599
- });
600
- return new Response(body2, { status: 400 });
601
- }
602
- }
603
- messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
604
- const isInitializationRequest = messages.some(
605
- (msg) => InitializeRequestSchema.safeParse(msg).success
606
- );
607
- if (isInitializationRequest && sessionId) {
608
- const body2 = JSON.stringify({
609
- jsonrpc: "2.0",
610
- error: {
611
- code: -32600,
612
- message: "Invalid Request: Initialization requests must not include a sessionId"
613
- },
614
- id: null
615
- });
616
- return new Response(body2, { status: 400 });
617
- }
618
- if (isInitializationRequest && messages.length > 1) {
619
- const body2 = JSON.stringify({
620
- jsonrpc: "2.0",
621
- error: {
622
- code: -32600,
623
- message: "Invalid Request: Only one initialization request is allowed"
624
- },
625
- id: null
626
- });
627
- return new Response(body2, { status: 400 });
628
- }
629
- if (!isInitializationRequest && !sessionId) {
630
- const body2 = JSON.stringify({
631
- jsonrpc: "2.0",
632
- error: {
633
- code: -32e3,
634
- message: "Bad Request: Mcp-Session-Id header is required"
635
- },
636
- id: null
637
- });
638
- return new Response(body2, { status: 400 });
639
- }
640
- sessionId = sessionId ?? namespace.newUniqueId().toString();
641
- const id = namespace.idFromName(`streamable-http:${sessionId}`);
642
- const doStub = namespace.get(id);
643
- const isInitialized = await doStub.isInitialized();
644
- if (isInitializationRequest) {
645
- await doStub._init(ctx.props);
646
- await doStub.setInitialized();
647
- } else if (!isInitialized) {
648
- const body2 = JSON.stringify({
649
- jsonrpc: "2.0",
650
- error: {
651
- code: -32001,
652
- message: "Session not found"
653
- },
654
- id: null
655
- });
656
- return new Response(body2, { status: 404 });
657
- }
658
- const { readable, writable } = new TransformStream();
659
- const writer = writable.getWriter();
660
- const encoder = new TextEncoder();
661
- const upgradeUrl = new URL(request.url);
662
- upgradeUrl.pathname = "/streamable-http";
663
- const response = await doStub.fetch(
664
- new Request(upgradeUrl, {
665
- headers: {
666
- Upgrade: "websocket",
667
- // Required by PartyServer
668
- "x-partykit-room": sessionId
669
- }
670
- })
671
- );
672
- const ws = response.webSocket;
673
- if (!ws) {
674
- console.error("Failed to establish WebSocket connection");
675
- await writer.close();
676
- const body2 = JSON.stringify({
677
- jsonrpc: "2.0",
678
- error: {
679
- code: -32001,
680
- message: "Failed to establish WebSocket connection"
681
- },
682
- id: null
683
- });
684
- return new Response(body2, { status: 500 });
685
- }
686
- const requestIds = /* @__PURE__ */ new Set();
687
- ws.accept();
688
- ws.addEventListener("message", (event) => {
689
- async function onMessage(event2) {
690
- try {
691
- const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
692
- const message = JSON.parse(data);
693
- const result = JSONRPCMessageSchema.safeParse(message);
694
- if (!result.success) {
695
- return;
696
- }
697
- if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
698
- requestIds.delete(result.data.id);
699
- }
700
- const messageText = `event: message
701
- data: ${JSON.stringify(result.data)}
702
-
703
- `;
704
- await writer.write(encoder.encode(messageText));
705
- if (requestIds.size === 0) {
706
- ws.close();
707
- }
708
- } catch (error) {
709
- console.error("Error forwarding message to SSE:", error);
710
- }
711
- }
712
- onMessage(event).catch(console.error);
713
- });
714
- ws.addEventListener("error", (error) => {
715
- async function onError(error2) {
716
- try {
717
- await writer.close();
718
- } catch (e) {
719
- }
720
- }
721
- onError(error).catch(console.error);
722
- });
723
- ws.addEventListener("close", () => {
724
- async function onClose() {
725
- try {
726
- await writer.close();
727
- } catch (error) {
728
- console.error("Error closing SSE connection:", error);
729
- }
730
- }
731
- onClose().catch(console.error);
732
- });
733
- const hasOnlyNotificationsOrResponses = messages.every(
734
- (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
735
- );
736
- if (hasOnlyNotificationsOrResponses) {
737
- for (const message of messages) {
738
- ws.send(JSON.stringify(message));
739
- }
740
- ws.close();
741
- return new Response(null, {
742
- status: 202,
743
- headers: corsHeaders(request, corsOptions)
744
- });
1057
+ switch (transport) {
1058
+ case "streamable-http": {
1059
+ const handleStreamableHttp = createStreamingHttpHandler(
1060
+ path,
1061
+ namespace,
1062
+ corsOptions
1063
+ );
1064
+ return handleStreamableHttp(request, ctx);
745
1065
  }
746
- for (const message of messages) {
747
- if (isJSONRPCRequest(message)) {
748
- requestIds.add(message.id);
749
- }
750
- ws.send(JSON.stringify(message));
1066
+ case "sse": {
1067
+ const handleLegacySse = createLegacySseHandler(
1068
+ path,
1069
+ namespace,
1070
+ corsOptions
1071
+ );
1072
+ return handleLegacySse(request, ctx);
751
1073
  }
752
- return new Response(readable, {
753
- headers: {
754
- "Content-Type": "text/event-stream",
755
- "Cache-Control": "no-cache",
756
- Connection: "keep-alive",
757
- "mcp-session-id": sessionId,
758
- ...corsHeaders(request, corsOptions)
759
- },
760
- status: 200
761
- });
1074
+ default:
1075
+ return new Response(
1076
+ "Invalid MCP transport mode. Only `streamable-http` or `sse` are allowed.",
1077
+ { status: 500 }
1078
+ );
762
1079
  }
763
- const body = JSON.stringify({
764
- jsonrpc: "2.0",
765
- error: {
766
- code: -32e3,
767
- message: "Method not allowed"
768
- },
769
- id: null
770
- });
771
- return new Response(body, { status: 405 });
772
1080
  }
773
1081
  };
774
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
+ }
775
1092
  };
776
1093
  export {
777
- McpAgent
1094
+ ElicitRequestSchema,
1095
+ McpAgent,
1096
+ SSEEdgeClientTransport,
1097
+ StreamableHTTPEdgeClientTransport
778
1098
  };
779
1099
  //# sourceMappingURL=index.js.map