agents 0.0.0-b5aee9f → 0.0.0-b6af48a

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