agents 0.0.0-ad0054b → 0.0.0-afd9efd

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