agents 0.0.0-86dfe61 → 0.0.0-8a1eb98

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,6 +1,7 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-XG52S6YY.js";
3
+ } from "../chunk-AV3OMRR4.js";
4
+ import "../chunk-YZNSS675.js";
4
5
  import {
5
6
  __privateAdd,
6
7
  __privateGet,
@@ -10,8 +11,15 @@ import {
10
11
 
11
12
  // src/mcp/index.ts
12
13
  import { DurableObject } from "cloudflare:workers";
13
- import { JSONRPCMessageSchema } from "@modelcontextprotocol/sdk/types.js";
14
- var MAXIMUM_MESSAGE_SIZE = 4 * 1024 * 1024;
14
+ import {
15
+ InitializeRequestSchema,
16
+ isJSONRPCError,
17
+ isJSONRPCNotification,
18
+ isJSONRPCRequest,
19
+ isJSONRPCResponse,
20
+ JSONRPCMessageSchema
21
+ } from "@modelcontextprotocol/sdk/types.js";
22
+ var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
15
23
  function handleCORS(request, corsOptions) {
16
24
  const origin = request.headers.get("Origin") || "*";
17
25
  const corsHeaders = {
@@ -26,7 +34,7 @@ function handleCORS(request, corsOptions) {
26
34
  return null;
27
35
  }
28
36
  var _getWebSocket, _started;
29
- var McpTransport = class {
37
+ var McpSSETransport = class {
30
38
  constructor(getWebSocket) {
31
39
  __privateAdd(this, _getWebSocket);
32
40
  __privateAdd(this, _started, false);
@@ -59,18 +67,76 @@ var McpTransport = class {
59
67
  };
60
68
  _getWebSocket = new WeakMap();
61
69
  _started = new WeakMap();
62
- var _status, _transport, _connected, _agent, _McpAgent_instances, initialize_fn;
63
- var McpAgent = class extends DurableObject {
70
+ var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
71
+ var McpStreamableHttpTransport = class {
72
+ constructor(getWebSocketForMessageID, notifyResponseIdSent) {
73
+ // TODO: If there is an open connection to send server-initiated messages
74
+ // back, we should use that connection
75
+ __privateAdd(this, _getWebSocketForGetRequest);
76
+ // Get the appropriate websocket connection for a given message id
77
+ __privateAdd(this, _getWebSocketForMessageID);
78
+ // Notify the server that a response has been sent for a given message id
79
+ // so that it may clean up it's mapping of message ids to connections
80
+ // once they are no longer needed
81
+ __privateAdd(this, _notifyResponseIdSent);
82
+ __privateAdd(this, _started2, false);
83
+ __privateSet(this, _getWebSocketForMessageID, getWebSocketForMessageID);
84
+ __privateSet(this, _notifyResponseIdSent, notifyResponseIdSent);
85
+ __privateSet(this, _getWebSocketForGetRequest, () => null);
86
+ }
87
+ async start() {
88
+ if (__privateGet(this, _started2)) {
89
+ throw new Error("Transport already started");
90
+ }
91
+ __privateSet(this, _started2, true);
92
+ }
93
+ async send(message) {
94
+ if (!__privateGet(this, _started2)) {
95
+ throw new Error("Transport not started");
96
+ }
97
+ let websocket = null;
98
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
99
+ websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
100
+ if (!websocket) {
101
+ throw new Error(
102
+ `Could not find WebSocket for message id: ${message.id}`
103
+ );
104
+ }
105
+ } else if (isJSONRPCRequest(message)) {
106
+ websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
107
+ } else if (isJSONRPCNotification(message)) {
108
+ websocket = null;
109
+ }
110
+ try {
111
+ websocket?.send(JSON.stringify(message));
112
+ if (isJSONRPCResponse(message)) {
113
+ __privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
114
+ }
115
+ } catch (error) {
116
+ this.onerror?.(error);
117
+ throw error;
118
+ }
119
+ }
120
+ async close() {
121
+ this.onclose?.();
122
+ }
123
+ };
124
+ _getWebSocketForGetRequest = new WeakMap();
125
+ _getWebSocketForMessageID = new WeakMap();
126
+ _notifyResponseIdSent = new WeakMap();
127
+ _started2 = new WeakMap();
128
+ var _status, _transport, _transportType, _requestIdToConnectionId, _agent, _McpAgent_instances, initialize_fn;
129
+ var _McpAgent = class _McpAgent extends DurableObject {
64
130
  constructor(ctx, env) {
65
131
  var _a;
66
132
  super(ctx, env);
67
133
  __privateAdd(this, _McpAgent_instances);
68
134
  __privateAdd(this, _status, "zero");
69
135
  __privateAdd(this, _transport);
70
- __privateAdd(this, _connected, false);
136
+ __privateAdd(this, _transportType, "unset");
137
+ __privateAdd(this, _requestIdToConnectionId, /* @__PURE__ */ new Map());
71
138
  /**
72
- * Since McpAgent's _aren't_ yet real "Agents" (they route differently, don't support
73
- * websockets, don't support hibernation), let's only expose a couple of the methods
139
+ * Since McpAgent's _aren't_ yet real "Agents", let's only expose a couple of the methods
74
140
  * to the outer class: initialState/state/setState/onStateUpdate/sql
75
141
  */
76
142
  __privateAdd(this, _agent);
@@ -80,10 +146,16 @@ var McpAgent = class extends DurableObject {
80
146
  onStateUpdate(state, source) {
81
147
  return self.onStateUpdate(state, source);
82
148
  }
149
+ async onMessage(connection, message) {
150
+ return self.onMessage(connection, message);
151
+ }
83
152
  }, _a.options = {
84
153
  hibernate: true
85
154
  }, _a)(ctx, env));
86
155
  }
156
+ get mcp() {
157
+ return __privateGet(this, _agent).mcp;
158
+ }
87
159
  get state() {
88
160
  return __privateGet(this, _agent).state;
89
161
  }
@@ -106,22 +178,45 @@ var McpAgent = class extends DurableObject {
106
178
  onStateUpdate(state, source) {
107
179
  return self.onStateUpdate(state, source);
108
180
  }
181
+ async onMessage(connection, event) {
182
+ return self.onMessage(connection, event);
183
+ }
109
184
  }, _a.options = {
110
185
  hibernate: true
111
186
  }, _a)(this.ctx, this.env));
112
187
  this.props = await this.ctx.storage.get("props");
113
- this.init?.();
114
- __privateSet(this, _transport, new McpTransport(() => this.getWebSocket()));
115
- await this.server.connect(__privateGet(this, _transport));
188
+ __privateSet(this, _transportType, await this.ctx.storage.get(
189
+ "transportType"
190
+ ));
191
+ await this._init(this.props);
192
+ if (__privateGet(this, _transportType) === "sse") {
193
+ __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
194
+ await this.server.connect(__privateGet(this, _transport));
195
+ } else if (__privateGet(this, _transportType) === "streamable-http") {
196
+ __privateSet(this, _transport, new McpStreamableHttpTransport(
197
+ (id) => this.getWebSocketForResponseID(id),
198
+ (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
199
+ ));
200
+ await this.server.connect(__privateGet(this, _transport));
201
+ }
116
202
  }
117
203
  async _init(props) {
118
- await this.ctx.storage.put("props", props);
204
+ await this.ctx.storage.put("props", props ?? {});
205
+ if (!this.ctx.storage.get("transportType")) {
206
+ await this.ctx.storage.put("transportType", "unset");
207
+ }
119
208
  this.props = props;
120
209
  if (!this.initRun) {
121
210
  this.initRun = true;
122
211
  await this.init();
123
212
  }
124
213
  }
214
+ async setInitialized() {
215
+ await this.ctx.storage.put("initialized", true);
216
+ }
217
+ async isInitialized() {
218
+ return await this.ctx.storage.get("initialized") === true;
219
+ }
125
220
  // Allow the worker to fetch a websocket connection to the agent
126
221
  async fetch(request) {
127
222
  if (__privateGet(this, _status) !== "started") {
@@ -133,18 +228,41 @@ var McpAgent = class extends DurableObject {
133
228
  });
134
229
  }
135
230
  const url = new URL(request.url);
136
- const sessionId = url.searchParams.get("sessionId");
137
- if (!sessionId) {
138
- return new Response("Missing sessionId", { status: 400 });
139
- }
140
- if (__privateGet(this, _connected)) {
141
- return new Response("WebSocket already connected", { status: 400 });
231
+ const path = url.pathname;
232
+ switch (path) {
233
+ case "/sse": {
234
+ const websockets = this.ctx.getWebSockets();
235
+ if (websockets.length > 0) {
236
+ return new Response("Websocket already connected", { status: 400 });
237
+ }
238
+ await this.ctx.storage.put("transportType", "sse");
239
+ __privateSet(this, _transportType, "sse");
240
+ if (!__privateGet(this, _transport)) {
241
+ __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
242
+ await this.server.connect(__privateGet(this, _transport));
243
+ }
244
+ return __privateGet(this, _agent).fetch(request);
245
+ }
246
+ case "/streamable-http": {
247
+ if (!__privateGet(this, _transport)) {
248
+ __privateSet(this, _transport, new McpStreamableHttpTransport(
249
+ (id) => this.getWebSocketForResponseID(id),
250
+ (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
251
+ ));
252
+ await this.server.connect(__privateGet(this, _transport));
253
+ }
254
+ await this.ctx.storage.put("transportType", "streamable-http");
255
+ __privateSet(this, _transportType, "streamable-http");
256
+ return __privateGet(this, _agent).fetch(request);
257
+ }
258
+ default:
259
+ return new Response(
260
+ "Internal Server Error: Expected /sse or /streamable-http path",
261
+ {
262
+ status: 500
263
+ }
264
+ );
142
265
  }
143
- const response = await __privateGet(this, _agent).fetch(request);
144
- __privateSet(this, _connected, true);
145
- __privateSet(this, _transport, new McpTransport(() => this.getWebSocket()));
146
- await this.server.connect(__privateGet(this, _transport));
147
- return response;
148
266
  }
149
267
  getWebSocket() {
150
268
  const websockets = this.ctx.getWebSockets();
@@ -153,26 +271,45 @@ var McpAgent = class extends DurableObject {
153
271
  }
154
272
  return websockets[0];
155
273
  }
156
- async onMCPMessage(sessionId, request) {
274
+ getWebSocketForResponseID(id) {
275
+ const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
276
+ if (connectionId === void 0) {
277
+ return null;
278
+ }
279
+ return __privateGet(this, _agent).getConnection(connectionId) ?? null;
280
+ }
281
+ // All messages received here. This is currently never called
282
+ async onMessage(connection, event) {
283
+ if (__privateGet(this, _transportType) !== "streamable-http") {
284
+ const err = new Error(
285
+ "Internal Server Error: Expected streamable-http protocol"
286
+ );
287
+ __privateGet(this, _transport)?.onerror?.(err);
288
+ return;
289
+ }
290
+ let message;
291
+ try {
292
+ const data = typeof event === "string" ? event : new TextDecoder().decode(event);
293
+ message = JSONRPCMessageSchema.parse(JSON.parse(data));
294
+ } catch (error) {
295
+ __privateGet(this, _transport)?.onerror?.(error);
296
+ return;
297
+ }
298
+ if (isJSONRPCRequest(message)) {
299
+ __privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
300
+ }
301
+ __privateGet(this, _transport)?.onmessage?.(message);
302
+ }
303
+ // All messages received over SSE after the initial connection has been established
304
+ // will be passed here
305
+ async onSSEMcpMessage(sessionId, request) {
157
306
  if (__privateGet(this, _status) !== "started") {
158
307
  await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
159
308
  }
309
+ if (__privateGet(this, _transportType) !== "sse") {
310
+ return new Error("Internal Server Error: Expected SSE protocol");
311
+ }
160
312
  try {
161
- const contentType = request.headers.get("content-type") || "";
162
- if (!contentType.includes("application/json")) {
163
- return new Response(`Unsupported content-type: ${contentType}`, {
164
- status: 400
165
- });
166
- }
167
- const contentLength = Number.parseInt(
168
- request.headers.get("content-length") || "0",
169
- 10
170
- );
171
- if (contentLength > MAXIMUM_MESSAGE_SIZE) {
172
- return new Response(`Request body too large: ${contentLength} bytes`, {
173
- status: 400
174
- });
175
- }
176
313
  const message = await request.json();
177
314
  let parsedMessage;
178
315
  try {
@@ -182,44 +319,41 @@ var McpAgent = class extends DurableObject {
182
319
  throw error;
183
320
  }
184
321
  __privateGet(this, _transport)?.onmessage?.(parsedMessage);
185
- return new Response("Accepted", { status: 202 });
322
+ return null;
186
323
  } catch (error) {
187
324
  __privateGet(this, _transport)?.onerror?.(error);
188
- return new Response(String(error), { status: 400 });
325
+ return error;
189
326
  }
190
327
  }
191
- // This is unused since there are no incoming websocket messages
328
+ // Delegate all websocket events to the underlying agent
192
329
  async webSocketMessage(ws, event) {
193
- let message;
194
- try {
195
- const data = typeof event === "string" ? event : new TextDecoder().decode(event);
196
- message = JSONRPCMessageSchema.parse(JSON.parse(data));
197
- } catch (error) {
198
- __privateGet(this, _transport)?.onerror?.(error);
199
- return;
200
- }
201
330
  if (__privateGet(this, _status) !== "started") {
202
331
  await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
203
332
  }
204
- __privateGet(this, _transport)?.onmessage?.(message);
333
+ return await __privateGet(this, _agent).webSocketMessage(ws, event);
205
334
  }
206
335
  // WebSocket event handlers for hibernation support
207
336
  async webSocketError(ws, error) {
208
337
  if (__privateGet(this, _status) !== "started") {
209
338
  await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
210
339
  }
211
- __privateGet(this, _transport)?.onerror?.(error);
340
+ return await __privateGet(this, _agent).webSocketError(ws, error);
212
341
  }
213
342
  async webSocketClose(ws, code, reason, wasClean) {
214
343
  if (__privateGet(this, _status) !== "started") {
215
344
  await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
216
345
  }
217
- __privateGet(this, _transport)?.onclose?.();
218
- __privateSet(this, _connected, false);
346
+ return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
219
347
  }
220
348
  static mount(path, {
221
349
  binding = "MCP_OBJECT",
222
350
  corsOptions
351
+ } = {}) {
352
+ return _McpAgent.serveSSE(path, { binding, corsOptions });
353
+ }
354
+ static serveSSE(path, {
355
+ binding = "MCP_OBJECT",
356
+ corsOptions
223
357
  } = {}) {
224
358
  let pathname = path;
225
359
  if (path === "/") {
@@ -228,26 +362,40 @@ var McpAgent = class extends DurableObject {
228
362
  const basePattern = new URLPattern({ pathname });
229
363
  const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
230
364
  return {
231
- fetch: async (request, env, ctx) => {
365
+ async fetch(request, env, ctx) {
232
366
  const corsResponse = handleCORS(request, corsOptions);
233
367
  if (corsResponse) return corsResponse;
234
368
  const url = new URL(request.url);
235
- const namespace = env[binding];
369
+ const bindingValue = env[binding];
370
+ if (bindingValue == null || typeof bindingValue !== "object") {
371
+ console.error(
372
+ `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
373
+ );
374
+ return new Response("Invalid binding", { status: 500 });
375
+ }
376
+ if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
377
+ return new Response("Invalid binding", { status: 500 });
378
+ }
379
+ const namespace = bindingValue;
236
380
  if (request.method === "GET" && basePattern.test(url)) {
237
381
  const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
238
382
  const { readable, writable } = new TransformStream();
239
383
  const writer = writable.getWriter();
240
384
  const encoder = new TextEncoder();
385
+ const endpointUrl = new URL(request.url);
386
+ endpointUrl.pathname = encodeURI(`${pathname}/message`);
387
+ endpointUrl.searchParams.set("sessionId", sessionId);
388
+ const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;
241
389
  const endpointMessage = `event: endpoint
242
- data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
390
+ data: ${relativeUrlWithSession}
243
391
 
244
392
  `;
245
393
  writer.write(encoder.encode(endpointMessage));
246
- const id = namespace.idFromString(sessionId);
394
+ const id = namespace.idFromName(`sse:${sessionId}`);
247
395
  const doStub = namespace.get(id);
248
396
  await doStub._init(ctx.props);
249
397
  const upgradeUrl = new URL(request.url);
250
- upgradeUrl.searchParams.set("sessionId", sessionId);
398
+ upgradeUrl.pathname = "/sse";
251
399
  const response = await doStub.fetch(
252
400
  new Request(upgradeUrl, {
253
401
  headers: {
@@ -261,37 +409,48 @@ data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
261
409
  if (!ws) {
262
410
  console.error("Failed to establish WebSocket connection");
263
411
  await writer.close();
264
- return;
412
+ return new Response("Failed to establish WebSocket connection", {
413
+ status: 500
414
+ });
265
415
  }
266
416
  ws.accept();
267
- ws.addEventListener("message", async (event) => {
268
- try {
269
- const message = JSON.parse(event.data);
270
- const result = JSONRPCMessageSchema.safeParse(message);
271
- if (!result.success) {
272
- return;
273
- }
274
- const messageText = `event: message
417
+ ws.addEventListener("message", (event) => {
418
+ async function onMessage(event2) {
419
+ try {
420
+ const message = JSON.parse(event2.data);
421
+ const result = JSONRPCMessageSchema.safeParse(message);
422
+ if (!result.success) {
423
+ return;
424
+ }
425
+ const messageText = `event: message
275
426
  data: ${JSON.stringify(result.data)}
276
427
 
277
428
  `;
278
- await writer.write(encoder.encode(messageText));
279
- } catch (error) {
280
- console.error("Error forwarding message to SSE:", error);
429
+ await writer.write(encoder.encode(messageText));
430
+ } catch (error) {
431
+ console.error("Error forwarding message to SSE:", error);
432
+ }
281
433
  }
434
+ onMessage(event).catch(console.error);
282
435
  });
283
- ws.addEventListener("error", async (error) => {
284
- try {
285
- await writer.close();
286
- } catch (e) {
436
+ ws.addEventListener("error", (error) => {
437
+ async function onError(error2) {
438
+ try {
439
+ await writer.close();
440
+ } catch (e) {
441
+ }
287
442
  }
443
+ onError(error).catch(console.error);
288
444
  });
289
- ws.addEventListener("close", async () => {
290
- try {
291
- await writer.close();
292
- } catch (error) {
293
- console.error("Error closing SSE connection:", error);
445
+ ws.addEventListener("close", () => {
446
+ async function onClose() {
447
+ try {
448
+ await writer.close();
449
+ } catch (error) {
450
+ console.error("Error closing SSE connection:", error);
451
+ }
294
452
  }
453
+ onClose().catch(console.error);
295
454
  });
296
455
  return new Response(readable, {
297
456
  headers: {
@@ -310,30 +469,327 @@ data: ${JSON.stringify(result.data)}
310
469
  { status: 400 }
311
470
  );
312
471
  }
313
- const object = namespace.get(namespace.idFromString(sessionId));
314
- const response = await object.onMCPMessage(sessionId, request);
315
- const headers = new Headers();
316
- response.headers.forEach?.((value, key) => {
317
- headers.set(key, value);
318
- });
319
- headers.set(
320
- "Access-Control-Allow-Origin",
321
- corsOptions?.origin || "*"
472
+ const contentType = request.headers.get("content-type") || "";
473
+ if (!contentType.includes("application/json")) {
474
+ return new Response(`Unsupported content-type: ${contentType}`, {
475
+ status: 400
476
+ });
477
+ }
478
+ const contentLength = Number.parseInt(
479
+ request.headers.get("content-length") || "0",
480
+ 10
322
481
  );
323
- return new Response(response.body, {
324
- status: response.status,
325
- statusText: response.statusText,
326
- headers
482
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
483
+ return new Response(
484
+ `Request body too large: ${contentLength} bytes`,
485
+ {
486
+ status: 400
487
+ }
488
+ );
489
+ }
490
+ const id = namespace.idFromName(`sse:${sessionId}`);
491
+ const doStub = namespace.get(id);
492
+ const error = await doStub.onSSEMcpMessage(sessionId, request);
493
+ if (error) {
494
+ return new Response(error.message, {
495
+ status: 400,
496
+ headers: {
497
+ "Content-Type": "text/event-stream",
498
+ "Cache-Control": "no-cache",
499
+ Connection: "keep-alive",
500
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
501
+ }
502
+ });
503
+ }
504
+ return new Response("Accepted", {
505
+ status: 202,
506
+ headers: {
507
+ "Content-Type": "text/event-stream",
508
+ "Cache-Control": "no-cache",
509
+ Connection: "keep-alive",
510
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
511
+ }
327
512
  });
328
513
  }
329
514
  return new Response("Not Found", { status: 404 });
330
515
  }
331
516
  };
332
517
  }
518
+ static serve(path, {
519
+ binding = "MCP_OBJECT",
520
+ corsOptions
521
+ } = {}) {
522
+ let pathname = path;
523
+ if (path === "/") {
524
+ pathname = "/*";
525
+ }
526
+ const basePattern = new URLPattern({ pathname });
527
+ return {
528
+ async fetch(request, env, ctx) {
529
+ const corsResponse = handleCORS(request, corsOptions);
530
+ if (corsResponse) {
531
+ return corsResponse;
532
+ }
533
+ const url = new URL(request.url);
534
+ const bindingValue = env[binding];
535
+ if (bindingValue == null || typeof bindingValue !== "object") {
536
+ console.error(
537
+ `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
538
+ );
539
+ return new Response("Invalid binding", { status: 500 });
540
+ }
541
+ if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
542
+ return new Response("Invalid binding", { status: 500 });
543
+ }
544
+ const namespace = bindingValue;
545
+ if (request.method === "POST" && basePattern.test(url)) {
546
+ const acceptHeader = request.headers.get("accept");
547
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
548
+ const body2 = JSON.stringify({
549
+ jsonrpc: "2.0",
550
+ error: {
551
+ code: -32e3,
552
+ message: "Not Acceptable: Client must accept both application/json and text/event-stream"
553
+ },
554
+ id: null
555
+ });
556
+ return new Response(body2, { status: 406 });
557
+ }
558
+ const ct = request.headers.get("content-type");
559
+ if (!ct || !ct.includes("application/json")) {
560
+ const body2 = JSON.stringify({
561
+ jsonrpc: "2.0",
562
+ error: {
563
+ code: -32e3,
564
+ message: "Unsupported Media Type: Content-Type must be application/json"
565
+ },
566
+ id: null
567
+ });
568
+ return new Response(body2, { status: 415 });
569
+ }
570
+ const contentLength = Number.parseInt(
571
+ request.headers.get("content-length") ?? "0",
572
+ 10
573
+ );
574
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
575
+ const body2 = JSON.stringify({
576
+ jsonrpc: "2.0",
577
+ error: {
578
+ code: -32e3,
579
+ message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
580
+ },
581
+ id: null
582
+ });
583
+ return new Response(body2, { status: 413 });
584
+ }
585
+ let sessionId = request.headers.get("mcp-session-id");
586
+ let rawMessage;
587
+ try {
588
+ rawMessage = await request.json();
589
+ } catch (error) {
590
+ const body2 = JSON.stringify({
591
+ jsonrpc: "2.0",
592
+ error: {
593
+ code: -32700,
594
+ message: "Parse error: Invalid JSON"
595
+ },
596
+ id: null
597
+ });
598
+ return new Response(body2, { status: 400 });
599
+ }
600
+ let arrayMessage;
601
+ if (Array.isArray(rawMessage)) {
602
+ arrayMessage = rawMessage;
603
+ } else {
604
+ arrayMessage = [rawMessage];
605
+ }
606
+ let messages = [];
607
+ for (const msg of arrayMessage) {
608
+ if (!JSONRPCMessageSchema.safeParse(msg).success) {
609
+ const body2 = JSON.stringify({
610
+ jsonrpc: "2.0",
611
+ error: {
612
+ code: -32700,
613
+ message: "Parse error: Invalid JSON-RPC message"
614
+ },
615
+ id: null
616
+ });
617
+ return new Response(body2, { status: 400 });
618
+ }
619
+ }
620
+ messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
621
+ const isInitializationRequest = messages.some(
622
+ (msg) => InitializeRequestSchema.safeParse(msg).success
623
+ );
624
+ if (isInitializationRequest && sessionId) {
625
+ const body2 = JSON.stringify({
626
+ jsonrpc: "2.0",
627
+ error: {
628
+ code: -32600,
629
+ message: "Invalid Request: Initialization requests must not include a sessionId"
630
+ },
631
+ id: null
632
+ });
633
+ return new Response(body2, { status: 400 });
634
+ }
635
+ if (isInitializationRequest && messages.length > 1) {
636
+ const body2 = JSON.stringify({
637
+ jsonrpc: "2.0",
638
+ error: {
639
+ code: -32600,
640
+ message: "Invalid Request: Only one initialization request is allowed"
641
+ },
642
+ id: null
643
+ });
644
+ return new Response(body2, { status: 400 });
645
+ }
646
+ if (!isInitializationRequest && !sessionId) {
647
+ const body2 = JSON.stringify({
648
+ jsonrpc: "2.0",
649
+ error: {
650
+ code: -32e3,
651
+ message: "Bad Request: Mcp-Session-Id header is required"
652
+ },
653
+ id: null
654
+ });
655
+ return new Response(body2, { status: 400 });
656
+ }
657
+ sessionId = sessionId ?? namespace.newUniqueId().toString();
658
+ const id = namespace.idFromName(`streamable-http:${sessionId}`);
659
+ const doStub = namespace.get(id);
660
+ const isInitialized = await doStub.isInitialized();
661
+ if (isInitializationRequest) {
662
+ await doStub.setInitialized();
663
+ } else if (!isInitialized) {
664
+ const body2 = JSON.stringify({
665
+ jsonrpc: "2.0",
666
+ error: {
667
+ code: -32001,
668
+ message: "Session not found"
669
+ },
670
+ id: null
671
+ });
672
+ return new Response(body2, { status: 404 });
673
+ }
674
+ const { readable, writable } = new TransformStream();
675
+ const writer = writable.getWriter();
676
+ const encoder = new TextEncoder();
677
+ const upgradeUrl = new URL(request.url);
678
+ upgradeUrl.pathname = "/streamable-http";
679
+ const response = await doStub.fetch(
680
+ new Request(upgradeUrl, {
681
+ headers: {
682
+ Upgrade: "websocket",
683
+ // Required by PartyServer
684
+ "x-partykit-room": sessionId
685
+ }
686
+ })
687
+ );
688
+ const ws = response.webSocket;
689
+ if (!ws) {
690
+ console.error("Failed to establish WebSocket connection");
691
+ await writer.close();
692
+ const body2 = JSON.stringify({
693
+ jsonrpc: "2.0",
694
+ error: {
695
+ code: -32001,
696
+ message: "Failed to establish WebSocket connection"
697
+ },
698
+ id: null
699
+ });
700
+ return new Response(body2, { status: 500 });
701
+ }
702
+ const requestIds = /* @__PURE__ */ new Set();
703
+ ws.accept();
704
+ ws.addEventListener("message", (event) => {
705
+ async function onMessage(event2) {
706
+ try {
707
+ const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
708
+ const message = JSON.parse(data);
709
+ const result = JSONRPCMessageSchema.safeParse(message);
710
+ if (!result.success) {
711
+ return;
712
+ }
713
+ if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
714
+ requestIds.delete(result.data.id);
715
+ }
716
+ const messageText = `event: message
717
+ data: ${JSON.stringify(result.data)}
718
+
719
+ `;
720
+ await writer.write(encoder.encode(messageText));
721
+ if (requestIds.size === 0) {
722
+ ws.close();
723
+ }
724
+ } catch (error) {
725
+ console.error("Error forwarding message to SSE:", error);
726
+ }
727
+ }
728
+ onMessage(event).catch(console.error);
729
+ });
730
+ ws.addEventListener("error", (error) => {
731
+ async function onError(error2) {
732
+ try {
733
+ await writer.close();
734
+ } catch (e) {
735
+ }
736
+ }
737
+ onError(error).catch(console.error);
738
+ });
739
+ ws.addEventListener("close", () => {
740
+ async function onClose() {
741
+ try {
742
+ await writer.close();
743
+ } catch (error) {
744
+ console.error("Error closing SSE connection:", error);
745
+ }
746
+ }
747
+ onClose().catch(console.error);
748
+ });
749
+ const hasOnlyNotificationsOrResponses = messages.every(
750
+ (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
751
+ );
752
+ if (hasOnlyNotificationsOrResponses) {
753
+ for (const message of messages) {
754
+ ws.send(JSON.stringify(message));
755
+ }
756
+ ws.close();
757
+ return new Response(null, { status: 202 });
758
+ }
759
+ for (const message of messages) {
760
+ if (isJSONRPCRequest(message)) {
761
+ requestIds.add(message.id);
762
+ }
763
+ ws.send(JSON.stringify(message));
764
+ }
765
+ return new Response(readable, {
766
+ headers: {
767
+ "Content-Type": "text/event-stream",
768
+ "Cache-Control": "no-cache",
769
+ Connection: "keep-alive",
770
+ "mcp-session-id": sessionId,
771
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
772
+ },
773
+ status: 200
774
+ });
775
+ }
776
+ const body = JSON.stringify({
777
+ jsonrpc: "2.0",
778
+ error: {
779
+ code: -32e3,
780
+ message: "Method not allowed"
781
+ },
782
+ id: null
783
+ });
784
+ return new Response(body, { status: 405 });
785
+ }
786
+ };
787
+ }
333
788
  };
334
789
  _status = new WeakMap();
335
790
  _transport = new WeakMap();
336
- _connected = new WeakMap();
791
+ _transportType = new WeakMap();
792
+ _requestIdToConnectionId = new WeakMap();
337
793
  _agent = new WeakMap();
338
794
  _McpAgent_instances = new WeakSet();
339
795
  initialize_fn = async function() {
@@ -343,6 +799,7 @@ initialize_fn = async function() {
343
799
  __privateSet(this, _status, "started");
344
800
  });
345
801
  };
802
+ var McpAgent = _McpAgent;
346
803
  export {
347
804
  McpAgent
348
805
  };