agents 0.0.0-7d72faa → 0.0.0-7d9b939

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