agents 0.0.0-5b7f03e → 0.0.0-5ebaeb2

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 +157 -27
  2. package/dist/ai-chat-agent.d.ts +40 -10
  3. package/dist/ai-chat-agent.js +260 -143
  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 +160 -54
  9. package/dist/ai-react.js.map +1 -1
  10. package/dist/ai-types.d.ts +36 -19
  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-IJPBZOSS.js +1296 -0
  15. package/dist/chunk-IJPBZOSS.js.map +1 -0
  16. package/dist/chunk-LL2AFX7V.js +109 -0
  17. package/dist/chunk-LL2AFX7V.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-I4YBFB7W.js → chunk-VYENMKFS.js} +209 -53
  23. package/dist/chunk-VYENMKFS.js.map +1 -0
  24. package/dist/client-CcIORE73.d.ts +4607 -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 +275 -25
  29. package/dist/index.js +13 -3
  30. package/dist/mcp/client.d.ts +9 -775
  31. package/dist/mcp/client.js +1 -2
  32. package/dist/mcp/do-oauth-client-provider.d.ts +4 -3
  33. package/dist/mcp/do-oauth-client-provider.js +3 -103
  34. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  35. package/dist/mcp/index.d.ts +73 -50
  36. package/dist/mcp/index.js +882 -661
  37. package/dist/mcp/index.js.map +1 -1
  38. package/dist/observability/index.d.ts +46 -0
  39. package/dist/observability/index.js +11 -0
  40. package/dist/observability/index.js.map +1 -0
  41. package/dist/react.d.ts +89 -5
  42. package/dist/react.js +23 -9
  43. package/dist/react.js.map +1 -1
  44. package/dist/schedule.d.ts +81 -7
  45. package/dist/schedule.js +19 -8
  46. package/dist/schedule.js.map +1 -1
  47. package/dist/serializable.d.ts +32 -0
  48. package/dist/serializable.js +1 -0
  49. package/dist/serializable.js.map +1 -0
  50. package/package.json +86 -67
  51. package/src/index.ts +1164 -157
  52. package/dist/chunk-HMLY7DHA.js +0 -16
  53. package/dist/chunk-I4YBFB7W.js.map +0 -1
  54. package/dist/chunk-NFBE2RQ4.js +0 -606
  55. package/dist/chunk-NFBE2RQ4.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,56 +1,616 @@
1
1
  import {
2
- Agent
3
- } from "../chunk-NFBE2RQ4.js";
4
- import "../chunk-I4YBFB7W.js";
2
+ Agent,
3
+ getAgentByName
4
+ } from "../chunk-IJPBZOSS.js";
5
5
  import {
6
- __privateAdd,
7
- __privateGet,
8
- __privateMethod,
9
- __privateSet
10
- } from "../chunk-HMLY7DHA.js";
6
+ SSEEdgeClientTransport,
7
+ StreamableHTTPEdgeClientTransport
8
+ } from "../chunk-VYENMKFS.js";
9
+ import "../chunk-LL2AFX7V.js";
10
+ import "../chunk-QEVM4BVL.js";
11
+ import "../chunk-AVYJQSLW.js";
11
12
 
12
13
  // src/mcp/index.ts
13
- import { DurableObject } from "cloudflare:workers";
14
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,
15
25
  InitializeRequestSchema,
26
+ isJSONRPCResponse,
16
27
  isJSONRPCError,
17
28
  isJSONRPCNotification,
18
- isJSONRPCRequest,
19
- isJSONRPCResponse,
20
- JSONRPCMessageSchema
29
+ isJSONRPCRequest
21
30
  } from "@modelcontextprotocol/sdk/types.js";
31
+ var STANDALONE_SSE_MARKER = "standalone-sse";
32
+ var STANDALONE_SSE_METHOD = "cf/standalone_sse/attach";
22
33
  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()
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 isInitializationRequest = messages.some(
118
+ (msg) => InitializeRequestSchema.safeParse(msg).success
119
+ );
120
+ if (isInitializationRequest && 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 (isInitializationRequest && 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 (!isInitializationRequest && !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.isInitialized();
160
+ if (isInitializationRequest) {
161
+ await agent.setInitialized();
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();
224
+ }
225
+ } catch (error) {
226
+ console.error("Error forwarding message to SSE:", error);
227
+ }
228
+ }
229
+ onMessage(event).catch(console.error);
230
+ });
231
+ ws.addEventListener("error", (error) => {
232
+ async function onError(_error) {
233
+ try {
234
+ await writer.close();
235
+ } catch (_e) {
236
+ }
237
+ }
238
+ onError(error).catch(console.error);
239
+ });
240
+ ws.addEventListener("close", () => {
241
+ async function onClose() {
242
+ try {
243
+ await writer.close();
244
+ } catch (error) {
245
+ console.error("Error closing SSE connection:", error);
246
+ }
247
+ }
248
+ onClose().catch(console.error);
249
+ });
250
+ const hasOnlyNotificationsOrResponses = messages.every(
251
+ (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
252
+ );
253
+ if (hasOnlyNotificationsOrResponses) {
254
+ for (const message of messages) {
255
+ ws.send(JSON.stringify(message));
256
+ }
257
+ ws.close();
258
+ return new Response(null, {
259
+ headers: corsHeaders(request, corsOptions),
260
+ status: 202
261
+ });
262
+ }
263
+ for (const message of messages) {
264
+ if (isJSONRPCRequest(message)) {
265
+ requestIds.add(message.id);
266
+ }
267
+ ws.send(JSON.stringify(message));
268
+ }
269
+ return new Response(readable, {
270
+ headers: {
271
+ "Cache-Control": "no-cache",
272
+ Connection: "keep-alive",
273
+ "Content-Type": "text/event-stream",
274
+ "mcp-session-id": sessionId,
275
+ ...corsHeaders(request, corsOptions)
276
+ },
277
+ status: 200
278
+ });
279
+ } else if (request.method === "GET") {
280
+ const acceptHeader = request.headers.get("accept");
281
+ if (!acceptHeader?.includes("text/event-stream")) {
282
+ const body2 = JSON.stringify({
283
+ jsonrpc: "2.0",
284
+ error: {
285
+ code: -32e3,
286
+ message: "Not Acceptable: Client must accept text/event-stream"
287
+ },
288
+ id: null
289
+ });
290
+ return new Response(body2, { status: 406 });
291
+ }
292
+ const sessionId = url.searchParams.get("sessionId");
293
+ if (!sessionId)
294
+ return new Response("Missing sessionId", { status: 400 });
295
+ const { readable, writable } = new TransformStream();
296
+ const writer = writable.getWriter();
297
+ const encoder = new TextEncoder();
298
+ const agent = await getAgentByName(
299
+ namespace,
300
+ `streamable-http:${sessionId}`,
301
+ { props: ctx.props }
302
+ );
303
+ const isInitialized = await agent.isInitialized();
304
+ if (!isInitialized) {
305
+ return new Response(
306
+ JSON.stringify({
307
+ jsonrpc: "2.0",
308
+ error: { code: -32001, message: "Session not found" },
309
+ id: null
310
+ }),
311
+ { status: 404 }
312
+ );
313
+ }
314
+ const existingHeaders = {};
315
+ request.headers.forEach((v, k) => {
316
+ existingHeaders[k] = v;
317
+ });
318
+ if (ctx.props) agent.updateProps(ctx.props);
319
+ const response = await agent.fetch(
320
+ new Request(request.url, {
321
+ headers: {
322
+ ...existingHeaders,
323
+ Upgrade: "websocket"
324
+ }
325
+ })
326
+ );
327
+ const ws = response.webSocket;
328
+ if (!ws) {
329
+ await writer.close();
330
+ return new Response("Failed to establish WS to DO", {
331
+ status: 500
332
+ });
333
+ }
334
+ ws.accept();
335
+ ws.send(
336
+ JSON.stringify({
337
+ jsonrpc: "2.0",
338
+ method: STANDALONE_SSE_METHOD,
339
+ params: {}
340
+ })
341
+ );
342
+ ws.addEventListener("message", (event) => {
343
+ try {
344
+ async function onMessage(ev) {
345
+ const data = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
346
+ const parsed = JSONRPCMessageSchema.safeParse(JSON.parse(data));
347
+ if (!parsed.success) return;
348
+ const frame = `event: message
349
+ data: ${JSON.stringify(parsed.data)}
350
+
351
+ `;
352
+ await writer.write(encoder.encode(frame));
353
+ }
354
+ onMessage(event).catch(console.error);
355
+ } catch (e) {
356
+ console.error("Error forwarding message to SSE:", e);
357
+ }
358
+ });
359
+ ws.addEventListener("error", () => {
360
+ writer.close().catch(() => {
361
+ });
362
+ });
363
+ ws.addEventListener("close", () => {
364
+ writer.close().catch(() => {
365
+ });
366
+ });
367
+ return new Response(readable, {
368
+ headers: {
369
+ "Cache-Control": "no-cache",
370
+ Connection: "keep-alive",
371
+ "Content-Type": "text/event-stream",
372
+ "mcp-session-id": sessionId,
373
+ ...corsHeaders(request, corsOptions)
374
+ },
375
+ status: 200
376
+ });
377
+ } else if (request.method === "DELETE") {
378
+ const sessionId = request.headers.get("mcp-session-id");
379
+ if (!sessionId) {
380
+ return new Response(
381
+ JSON.stringify({
382
+ jsonrpc: "2.0",
383
+ error: {
384
+ code: -32e3,
385
+ message: "Bad Request: Mcp-Session-Id header is required"
386
+ },
387
+ id: null
388
+ }),
389
+ { status: 400, headers: corsHeaders(request, corsOptions) }
390
+ );
391
+ }
392
+ const agent = await getAgentByName(
393
+ namespace,
394
+ `streamable-http:${sessionId}`
395
+ );
396
+ const isInitialized = await agent.isInitialized();
397
+ if (!isInitialized) {
398
+ return new Response(
399
+ JSON.stringify({
400
+ jsonrpc: "2.0",
401
+ error: { code: -32001, message: "Session not found" },
402
+ id: null
403
+ }),
404
+ { status: 404, headers: corsHeaders(request, corsOptions) }
405
+ );
406
+ }
407
+ ctx.waitUntil(
408
+ agent.destroy().catch(() => {
409
+ })
410
+ );
411
+ return new Response(null, {
412
+ status: 204,
413
+ headers: corsHeaders(request, corsOptions)
414
+ });
415
+ }
416
+ }
417
+ const body = JSON.stringify({
418
+ error: {
419
+ code: -32e3,
420
+ message: "Not found"
421
+ },
422
+ id: null,
423
+ jsonrpc: "2.0"
424
+ });
425
+ return new Response(body, { status: 404 });
426
+ };
427
+ };
428
+ var createLegacySseHandler = (basePath, namespace, corsOptions) => {
429
+ let pathname = basePath;
430
+ if (basePath === "/") pathname = "/*";
431
+ const basePattern = new URLPattern({ pathname });
432
+ const messagePattern = new URLPattern({ pathname: `${basePath}/message` });
433
+ return async (request, ctx) => {
434
+ const url = new URL(request.url);
435
+ if (request.method === "GET" && basePattern.test(url)) {
436
+ const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
437
+ const { readable, writable } = new TransformStream();
438
+ const writer = writable.getWriter();
439
+ const encoder = new TextEncoder();
440
+ const endpointUrl = new URL(request.url);
441
+ endpointUrl.pathname = encodeURI(`${basePath}/message`);
442
+ endpointUrl.searchParams.set("sessionId", sessionId);
443
+ const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;
444
+ const endpointMessage = `event: endpoint
445
+ data: ${relativeUrlWithSession}
446
+
447
+ `;
448
+ writer.write(encoder.encode(endpointMessage));
449
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, {
450
+ props: ctx.props
451
+ });
452
+ const existingHeaders = {};
453
+ request.headers.forEach((value, key) => {
454
+ existingHeaders[key] = value;
455
+ });
456
+ if (ctx.props) agent.updateProps(ctx.props);
457
+ const response = await agent.fetch(
458
+ new Request(request.url, {
459
+ headers: {
460
+ ...existingHeaders,
461
+ Upgrade: "websocket"
462
+ }
463
+ })
464
+ );
465
+ const ws = response.webSocket;
466
+ if (!ws) {
467
+ console.error("Failed to establish WebSocket connection");
468
+ await writer.close();
469
+ return new Response("Failed to establish WebSocket connection", {
470
+ status: 500
471
+ });
472
+ }
473
+ ws.accept();
474
+ ws.addEventListener("message", (event) => {
475
+ async function onMessage(event2) {
476
+ try {
477
+ const message = JSON.parse(event2.data);
478
+ const result = JSONRPCMessageSchema.safeParse(message);
479
+ if (!result.success) {
480
+ return;
481
+ }
482
+ const messageText = `event: message
483
+ data: ${JSON.stringify(result.data)}
484
+
485
+ `;
486
+ await writer.write(encoder.encode(messageText));
487
+ } catch (error) {
488
+ console.error("Error forwarding message to SSE:", error);
489
+ }
490
+ }
491
+ onMessage(event).catch(console.error);
492
+ });
493
+ ws.addEventListener("error", (error) => {
494
+ async function onError(_error) {
495
+ try {
496
+ await writer.close();
497
+ } catch (_e) {
498
+ }
499
+ }
500
+ onError(error).catch(console.error);
501
+ });
502
+ ws.addEventListener("close", () => {
503
+ async function onClose() {
504
+ try {
505
+ await writer.close();
506
+ } catch (error) {
507
+ console.error("Error closing SSE connection:", error);
508
+ }
509
+ }
510
+ onClose().catch(console.error);
511
+ });
512
+ return new Response(readable, {
513
+ headers: {
514
+ "Cache-Control": "no-cache",
515
+ Connection: "keep-alive",
516
+ "Content-Type": "text/event-stream",
517
+ ...corsHeaders(request, corsOptions)
518
+ }
519
+ });
520
+ }
521
+ if (request.method === "POST" && messagePattern.test(url)) {
522
+ const sessionId = url.searchParams.get("sessionId");
523
+ if (!sessionId) {
524
+ return new Response(
525
+ `Missing sessionId. Expected POST to ${basePath} to initiate new one`,
526
+ { status: 400 }
527
+ );
528
+ }
529
+ const contentType = request.headers.get("content-type") || "";
530
+ if (!contentType.includes("application/json")) {
531
+ return new Response(`Unsupported content-type: ${contentType}`, {
532
+ status: 400
533
+ });
534
+ }
535
+ const contentLength = Number.parseInt(
536
+ request.headers.get("content-length") || "0",
537
+ 10
538
+ );
539
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
540
+ return new Response(`Request body too large: ${contentLength} bytes`, {
541
+ status: 400
542
+ });
543
+ }
544
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, {
545
+ props: ctx.props
546
+ });
547
+ const messageBody = await request.json();
548
+ const error = await agent.onSSEMcpMessage(sessionId, messageBody);
549
+ if (error) {
550
+ return new Response(error.message, {
551
+ headers: {
552
+ "Cache-Control": "no-cache",
553
+ Connection: "keep-alive",
554
+ "Content-Type": "text/event-stream",
555
+ ...corsHeaders(request, corsOptions)
556
+ },
557
+ status: 400
558
+ });
559
+ }
560
+ return new Response("Accepted", {
561
+ headers: {
562
+ "Cache-Control": "no-cache",
563
+ Connection: "keep-alive",
564
+ "Content-Type": "text/event-stream",
565
+ ...corsHeaders(request, corsOptions)
566
+ },
567
+ status: 202
568
+ });
569
+ }
570
+ return new Response("Not Found", { status: 404 });
571
+ };
572
+ };
573
+ function corsHeaders(_request, corsOptions = {}) {
574
+ const origin = "*";
575
+ return {
576
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, Accept, mcp-session-id, mcp-protocol-version",
577
+ "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, DELETE, OPTIONS",
578
+ "Access-Control-Allow-Origin": corsOptions.origin || origin,
579
+ "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
580
+ "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
30
581
  };
582
+ }
583
+ function handleCORS(request, corsOptions) {
31
584
  if (request.method === "OPTIONS") {
32
- return new Response(null, { headers: corsHeaders });
585
+ return new Response(null, { headers: corsHeaders(request, corsOptions) });
33
586
  }
34
587
  return null;
35
588
  }
36
- var _getWebSocket, _started;
589
+ function isDurableObjectNamespace(namespace) {
590
+ return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
591
+ }
592
+
593
+ // src/mcp/transport.ts
594
+ import {
595
+ isJSONRPCError as isJSONRPCError2,
596
+ isJSONRPCResponse as isJSONRPCResponse2
597
+ } from "@modelcontextprotocol/sdk/types.js";
37
598
  var McpSSETransport = class {
38
599
  constructor(getWebSocket) {
39
- __privateAdd(this, _getWebSocket);
40
- __privateAdd(this, _started, false);
41
- __privateSet(this, _getWebSocket, getWebSocket);
600
+ this._started = false;
601
+ this._getWebSocket = getWebSocket;
42
602
  }
43
603
  async start() {
44
- if (__privateGet(this, _started)) {
604
+ if (this._started) {
45
605
  throw new Error("Transport already started");
46
606
  }
47
- __privateSet(this, _started, true);
607
+ this._started = true;
48
608
  }
49
609
  async send(message) {
50
- if (!__privateGet(this, _started)) {
610
+ if (!this._started) {
51
611
  throw new Error("Transport not started");
52
612
  }
53
- const websocket = __privateGet(this, _getWebSocket).call(this);
613
+ const websocket = this._getWebSocket();
54
614
  if (!websocket) {
55
615
  throw new Error("WebSocket not connected");
56
616
  }
@@ -58,751 +618,412 @@ var McpSSETransport = class {
58
618
  websocket.send(JSON.stringify(message));
59
619
  } catch (error) {
60
620
  this.onerror?.(error);
61
- throw error;
62
621
  }
63
622
  }
64
623
  async close() {
65
624
  this.onclose?.();
66
625
  }
67
626
  };
68
- _getWebSocket = new WeakMap();
69
- _started = new WeakMap();
70
- var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
71
627
  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);
628
+ constructor(getWebSocketForMessageID, notifyResponseIdSent, getWebSocketForStandaloneSse) {
629
+ this._started = false;
630
+ this._getWebSocketForMessageID = getWebSocketForMessageID;
631
+ this._notifyResponseIdSent = notifyResponseIdSent;
632
+ this._getWebSocketForStandaloneSse = getWebSocketForStandaloneSse;
86
633
  }
87
634
  async start() {
88
- if (__privateGet(this, _started2)) {
635
+ if (this._started) {
89
636
  throw new Error("Transport already started");
90
637
  }
91
- __privateSet(this, _started2, true);
638
+ this._started = true;
92
639
  }
93
- async send(message) {
94
- if (!__privateGet(this, _started2)) {
640
+ async send(message, options) {
641
+ if (!this._started) {
95
642
  throw new Error("Transport not started");
96
643
  }
97
- let websocket = null;
98
- if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
99
- websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
100
- if (!websocket) {
644
+ let requestId = options?.relatedRequestId;
645
+ if (isJSONRPCResponse2(message) || isJSONRPCError2(message)) {
646
+ requestId = message.id;
647
+ }
648
+ if (requestId === void 0) {
649
+ if (isJSONRPCResponse2(message) || isJSONRPCError2(message)) {
101
650
  throw new Error(
102
- `Could not find WebSocket for message id: ${message.id}`
651
+ "Cannot send a response on a standalone SSE stream unless resuming a previous client request"
103
652
  );
104
653
  }
105
- } else if (isJSONRPCRequest(message)) {
106
- websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
107
- } else if (isJSONRPCNotification(message)) {
108
- websocket = null;
654
+ const standaloneSseSocket = this._getWebSocketForStandaloneSse();
655
+ if (!standaloneSseSocket) {
656
+ return;
657
+ }
658
+ try {
659
+ standaloneSseSocket?.send(JSON.stringify(message));
660
+ } catch (error) {
661
+ this.onerror?.(error);
662
+ }
663
+ return;
664
+ }
665
+ const websocket = this._getWebSocketForMessageID(requestId.toString());
666
+ if (!websocket) {
667
+ throw new Error(`Could not find WebSocket for message id: ${requestId}`);
109
668
  }
110
669
  try {
111
670
  websocket?.send(JSON.stringify(message));
112
- if (isJSONRPCResponse(message)) {
113
- __privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
671
+ if (isJSONRPCResponse2(message) || isJSONRPCError2(message)) {
672
+ this._notifyResponseIdSent(message.id.toString());
114
673
  }
115
674
  } catch (error) {
116
675
  this.onerror?.(error);
117
- throw error;
118
676
  }
119
677
  }
120
678
  async close() {
121
679
  this.onclose?.();
122
680
  }
123
681
  };
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 {
682
+
683
+ // src/mcp/index.ts
684
+ import {
685
+ ElicitRequestSchema
686
+ } from "@modelcontextprotocol/sdk/types.js";
687
+ var McpAgent = class _McpAgent extends Agent {
130
688
  constructor(ctx, env) {
131
- var _a;
132
689
  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);
148
- }
149
- async onMessage(connection, message) {
150
- return self.onMessage(connection, message);
690
+ this._requestIdToConnectionId = /* @__PURE__ */ new Map();
691
+ for (const connection of this.getConnections()) {
692
+ const meta = connection.state;
693
+ if (meta?.role === STANDALONE_SSE_MARKER) {
694
+ this._standaloneSseConnectionId = connection.id;
695
+ return;
151
696
  }
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);
167
- }
168
- onStateUpdate(state, source) {
169
- }
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;
177
- }
178
- onStateUpdate(state, source) {
179
- return self.onStateUpdate(state, source);
180
- }
181
- async onMessage(connection, event) {
182
- return self.onMessage(connection, event);
183
- }
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));
202
- }
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");
208
- }
209
- this.props = props;
210
- if (!this.initRun) {
211
- this.initRun = true;
212
- await this.init();
213
697
  }
214
698
  }
699
+ /*
700
+ * Helpers
701
+ */
215
702
  async setInitialized() {
216
703
  await this.ctx.storage.put("initialized", true);
217
704
  }
218
705
  async isInitialized() {
219
706
  return await this.ctx.storage.get("initialized") === true;
220
707
  }
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
- }
708
+ /** Read the transport type for this agent.
709
+ * This relies on the naming scheme being `sse:${sessionId}`
710
+ * or `streamable-http:${sessionId}`.
711
+ */
712
+ getTransportType() {
713
+ const [t, ..._] = this.name.split(":");
714
+ switch (t) {
715
+ case "sse":
716
+ return "sse";
717
+ case "streamable-http":
718
+ return "streamable-http";
260
719
  default:
261
- return new Response(
262
- "Internal Server Error: Expected /sse or /streamable-http path",
263
- {
264
- status: 500
265
- }
720
+ throw new Error(
721
+ "Invalid transport type. McpAgent must be addressed with a valid protocol."
266
722
  );
267
723
  }
268
724
  }
725
+ /** Get the WebSocket for the standalone SSE if any. Streamable HTTP only. */
726
+ getWebSocketForStandaloneSse() {
727
+ if (!this._standaloneSseConnectionId) return null;
728
+ return this.getConnection(this._standaloneSseConnectionId) ?? null;
729
+ }
730
+ /** Get the unique WebSocket. SSE transport only. */
269
731
  getWebSocket() {
270
- const websockets = this.ctx.getWebSockets();
732
+ const websockets = Array.from(this.getConnections());
271
733
  if (websockets.length === 0) {
272
734
  return null;
273
735
  }
274
736
  return websockets[0];
275
737
  }
738
+ /** Get the corresponding WebSocket for a responseId. Streamable HTTP only. */
276
739
  getWebSocketForResponseID(id) {
277
- const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
740
+ const connectionId = this._requestIdToConnectionId.get(id);
278
741
  if (connectionId === void 0) {
279
742
  return null;
280
743
  }
281
- return __privateGet(this, _agent).getConnection(connectionId) ?? null;
744
+ return this.getConnection(connectionId) ?? null;
745
+ }
746
+ /** Returns a new transport matching the type of the Agent. */
747
+ initTransport() {
748
+ switch (this.getTransportType()) {
749
+ case "sse": {
750
+ return new McpSSETransport(() => this.getWebSocket());
751
+ }
752
+ case "streamable-http": {
753
+ return new McpStreamableHttpTransport(
754
+ (id) => this.getWebSocketForResponseID(id),
755
+ (id) => this._requestIdToConnectionId.delete(id),
756
+ () => this.getWebSocketForStandaloneSse()
757
+ );
758
+ }
759
+ }
760
+ }
761
+ /** Update and store the props */
762
+ async updateProps(props) {
763
+ await this.ctx.storage.put("props", props ?? {});
764
+ this.props = props;
765
+ }
766
+ /*
767
+ * Base Agent / Parykit Server overrides
768
+ */
769
+ /** Sets up the MCP transport and server every time the Agent is started.*/
770
+ async onStart(props) {
771
+ if (props) await this.updateProps(props);
772
+ this.props = await this.ctx.storage.get("props");
773
+ await this.init();
774
+ const server = await this.server;
775
+ this._transport = this.initTransport();
776
+ await server.connect(this._transport);
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
+ }
282
792
  }
283
- // All messages received here. This is currently never called
793
+ /** Handles MCP Messages for Streamable HTTP. */
284
794
  async onMessage(connection, event) {
285
- if (__privateGet(this, _transportType) !== "streamable-http") {
795
+ if (this.getTransportType() !== "streamable-http") {
286
796
  const err = new Error(
287
797
  "Internal Server Error: Expected streamable-http protocol"
288
798
  );
289
- __privateGet(this, _transport)?.onerror?.(err);
799
+ this._transport?.onerror?.(err);
290
800
  return;
291
801
  }
292
802
  let message;
293
803
  try {
294
804
  const data = typeof event === "string" ? event : new TextDecoder().decode(event);
295
- message = JSONRPCMessageSchema.parse(JSON.parse(data));
805
+ message = JSONRPCMessageSchema2.parse(JSON.parse(data));
296
806
  } catch (error) {
297
- __privateGet(this, _transport)?.onerror?.(error);
807
+ this._transport?.onerror?.(error);
808
+ return;
809
+ }
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)) {
298
824
  return;
299
825
  }
300
- if (isJSONRPCRequest(message)) {
301
- __privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
826
+ if (isJSONRPCRequest2(message)) {
827
+ this._requestIdToConnectionId.set(message.id.toString(), connection.id);
302
828
  }
303
- __privateGet(this, _transport)?.onmessage?.(message);
829
+ this._transport?.onmessage?.(message);
304
830
  }
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);
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);
310
835
  }
311
- if (__privateGet(this, _transportType) !== "sse") {
312
- return new Error("Internal Server Error: Expected SSE protocol");
836
+ if (this._standaloneSseConnectionId === conn.id) {
837
+ this._standaloneSseConnectionId = void 0;
838
+ }
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");
313
847
  }
314
848
  try {
315
- const message = await request.json();
316
849
  let parsedMessage;
317
850
  try {
318
- parsedMessage = JSONRPCMessageSchema.parse(message);
851
+ parsedMessage = JSONRPCMessageSchema2.parse(messageBody);
319
852
  } catch (error) {
320
- __privateGet(this, _transport)?.onerror?.(error);
853
+ this._transport?.onerror?.(error);
321
854
  throw error;
322
855
  }
323
- __privateGet(this, _transport)?.onmessage?.(parsedMessage);
856
+ if (await this._handleElicitationResponse(parsedMessage)) {
857
+ return null;
858
+ }
859
+ this._transport?.onmessage?.(parsedMessage);
324
860
  return null;
325
861
  } catch (error) {
326
- __privateGet(this, _transport)?.onerror?.(error);
862
+ console.error("Error forwarding message to SSE:", error);
863
+ this._transport?.onerror?.(error);
327
864
  return error;
328
865
  }
329
866
  }
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);
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
+ }
341
900
  }
342
- return await __privateGet(this, _agent).webSocketError(ws, error);
901
+ return this._waitForElicitationResponse(requestId);
343
902
  }
344
- async webSocketClose(ws, code, reason, wasClean) {
345
- if (__privateGet(this, _status) !== "started") {
346
- 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}`);
347
923
  }
348
- return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
349
924
  }
350
- static mount(path, {
351
- binding = "MCP_OBJECT",
352
- corsOptions
353
- } = {}) {
354
- return _McpAgent.serveSSE(path, { binding, corsOptions });
355
- }
356
- static serveSSE(path, {
357
- binding = "MCP_OBJECT",
358
- corsOptions
359
- } = {}) {
360
- let pathname = path;
361
- if (path === "/") {
362
- 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;
363
939
  }
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
- });
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"
515
951
  }
516
- return new Response("Not Found", { status: 404 });
517
- }
518
- };
952
+ };
953
+ await this.ctx.storage.put(
954
+ `elicitation:response:${requestId}`,
955
+ errorResult
956
+ );
957
+ return true;
958
+ }
959
+ return false;
519
960
  }
961
+ /** Return a handler for the given path for this MCP.
962
+ * Defaults to Streamable HTTP transport.
963
+ */
520
964
  static serve(path, {
521
965
  binding = "MCP_OBJECT",
522
- corsOptions
966
+ corsOptions,
967
+ transport = "streamable-http"
523
968
  } = {}) {
524
- let pathname = path;
525
- if (path === "/") {
526
- pathname = "/*";
527
- }
528
- const basePattern = new URLPattern({ pathname });
529
969
  return {
530
970
  async fetch(request, env, ctx) {
531
971
  const corsResponse = handleCORS(request, corsOptions);
532
972
  if (corsResponse) {
533
973
  return corsResponse;
534
974
  }
535
- const url = new URL(request.url);
536
975
  const bindingValue = env[binding];
537
976
  if (bindingValue == null || typeof bindingValue !== "object") {
538
- console.error(
977
+ throw new Error(
539
978
  `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
540
979
  );
541
- return new Response("Invalid binding", { status: 500 });
542
980
  }
543
- if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
544
- return new Response("Invalid binding", { status: 500 });
981
+ if (!isDurableObjectNamespace(bindingValue)) {
982
+ throw new Error(
983
+ `Invalid McpAgent binding for ${binding}. Make sure it's a Durable Object binding.`
984
+ );
545
985
  }
546
986
  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 });
987
+ switch (transport) {
988
+ case "streamable-http": {
989
+ const handleStreamableHttp = createStreamingHttpHandler(
990
+ path,
991
+ namespace,
992
+ corsOptions
993
+ );
994
+ return handleStreamableHttp(request, ctx);
760
995
  }
761
- for (const message of messages) {
762
- if (isJSONRPCRequest(message)) {
763
- requestIds.add(message.id);
764
- }
765
- ws.send(JSON.stringify(message));
996
+ case "sse": {
997
+ const handleLegacySse = createLegacySseHandler(
998
+ path,
999
+ namespace,
1000
+ corsOptions
1001
+ );
1002
+ return handleLegacySse(request, ctx);
766
1003
  }
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
- });
1004
+ default:
1005
+ return new Response(
1006
+ "Invalid MCP transport mode. Only `streamable-http` or `sse` are allowed.",
1007
+ { status: 500 }
1008
+ );
777
1009
  }
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
1010
  }
788
1011
  };
789
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
+ }
790
1022
  };
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
1023
  export {
806
- McpAgent
1024
+ ElicitRequestSchema,
1025
+ McpAgent,
1026
+ SSEEdgeClientTransport,
1027
+ StreamableHTTPEdgeClientTransport
807
1028
  };
808
1029
  //# sourceMappingURL=index.js.map