agents 0.0.0-be4b7a3 → 0.0.0-bfc9c75

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