agents 0.0.0-e4a2352 → 0.0.0-e777fdd

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