agents 0.0.0-2a0b252 → 0.0.0-2d0d2e1

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