agents 0.0.0-e2d7b5c → 0.0.0-e31e26c

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