agents 0.0.0-88ea3a1 → 0.0.0-8d8216c

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-YMUU7QHV.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,12 +146,17 @@ 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
- if (this.initialState) __privateGet(this, _agent).initialState = this.initialState;
89
160
  return __privateGet(this, _agent).state;
90
161
  }
91
162
  sql(strings, ...values) {
@@ -97,19 +168,55 @@ var McpAgent = class extends DurableObject {
97
168
  onStateUpdate(state, source) {
98
169
  }
99
170
  async onStart() {
171
+ var _a;
172
+ const self = this;
173
+ __privateSet(this, _agent, new (_a = class extends Agent {
174
+ constructor() {
175
+ super(...arguments);
176
+ this.initialState = self.initialState;
177
+ }
178
+ onStateUpdate(state, source) {
179
+ return self.onStateUpdate(state, source);
180
+ }
181
+ async onMessage(connection, event) {
182
+ return self.onMessage(connection, event);
183
+ }
184
+ }, _a.options = {
185
+ hibernate: true
186
+ }, _a)(this.ctx, this.env));
100
187
  this.props = await this.ctx.storage.get("props");
101
- this.init?.();
102
- __privateSet(this, _transport, new McpTransport(() => this.getWebSocket()));
103
- 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
+ }
104
202
  }
105
203
  async _init(props) {
106
- 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
+ }
107
208
  this.props = props;
108
209
  if (!this.initRun) {
109
210
  this.initRun = true;
110
211
  await this.init();
111
212
  }
112
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
+ }
113
220
  // Allow the worker to fetch a websocket connection to the agent
114
221
  async fetch(request) {
115
222
  if (__privateGet(this, _status) !== "started") {
@@ -121,23 +228,41 @@ var McpAgent = class extends DurableObject {
121
228
  });
122
229
  }
123
230
  const url = new URL(request.url);
124
- const sessionId = url.searchParams.get("sessionId");
125
- if (!sessionId) {
126
- return new Response("Missing sessionId", { status: 400 });
127
- }
128
- const webSocketPair = new WebSocketPair();
129
- const [client, server] = Object.values(webSocketPair);
130
- if (__privateGet(this, _connected)) {
131
- 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
+ );
132
265
  }
133
- this.ctx.acceptWebSocket(server);
134
- __privateSet(this, _connected, true);
135
- __privateSet(this, _transport, new McpTransport(() => this.getWebSocket()));
136
- await this.server.connect(__privateGet(this, _transport));
137
- return new Response(null, {
138
- status: 101,
139
- webSocket: client
140
- });
141
266
  }
142
267
  getWebSocket() {
143
268
  const websockets = this.ctx.getWebSockets();
@@ -146,26 +271,45 @@ var McpAgent = class extends DurableObject {
146
271
  }
147
272
  return websockets[0];
148
273
  }
149
- 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) {
150
306
  if (__privateGet(this, _status) !== "started") {
151
307
  await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
152
308
  }
309
+ if (__privateGet(this, _transportType) !== "sse") {
310
+ return new Error("Internal Server Error: Expected SSE protocol");
311
+ }
153
312
  try {
154
- const contentType = request.headers.get("content-type") || "";
155
- if (!contentType.includes("application/json")) {
156
- return new Response(`Unsupported content-type: ${contentType}`, {
157
- status: 400
158
- });
159
- }
160
- const contentLength = Number.parseInt(
161
- request.headers.get("content-length") || "0",
162
- 10
163
- );
164
- if (contentLength > MAXIMUM_MESSAGE_SIZE) {
165
- return new Response(`Request body too large: ${contentLength} bytes`, {
166
- status: 400
167
- });
168
- }
169
313
  const message = await request.json();
170
314
  let parsedMessage;
171
315
  try {
@@ -175,47 +319,48 @@ var McpAgent = class extends DurableObject {
175
319
  throw error;
176
320
  }
177
321
  __privateGet(this, _transport)?.onmessage?.(parsedMessage);
178
- return new Response("Accepted", { status: 202 });
322
+ return null;
179
323
  } catch (error) {
180
324
  __privateGet(this, _transport)?.onerror?.(error);
181
- return new Response(String(error), { status: 400 });
325
+ return error;
182
326
  }
183
327
  }
184
- // This is unused since there are no incoming websocket messages
328
+ // Delegate all websocket events to the underlying agent
185
329
  async webSocketMessage(ws, event) {
186
- let message;
187
- try {
188
- const data = typeof event === "string" ? event : new TextDecoder().decode(event);
189
- message = JSONRPCMessageSchema.parse(JSON.parse(data));
190
- } catch (error) {
191
- __privateGet(this, _transport)?.onerror?.(error);
192
- return;
193
- }
194
330
  if (__privateGet(this, _status) !== "started") {
195
331
  await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
196
332
  }
197
- __privateGet(this, _transport)?.onmessage?.(message);
333
+ return await __privateGet(this, _agent).webSocketMessage(ws, event);
198
334
  }
199
335
  // WebSocket event handlers for hibernation support
200
336
  async webSocketError(ws, error) {
201
337
  if (__privateGet(this, _status) !== "started") {
202
338
  await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
203
339
  }
204
- __privateGet(this, _transport)?.onerror?.(error);
340
+ return await __privateGet(this, _agent).webSocketError(ws, error);
205
341
  }
206
342
  async webSocketClose(ws, code, reason, wasClean) {
207
343
  if (__privateGet(this, _status) !== "started") {
208
344
  await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
209
345
  }
210
- __privateGet(this, _transport)?.onclose?.();
211
- __privateSet(this, _connected, false);
346
+ return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
212
347
  }
213
348
  static mount(path, {
214
349
  binding = "MCP_OBJECT",
215
350
  corsOptions
216
351
  } = {}) {
217
- const basePattern = new URLPattern({ pathname: path });
218
- const messagePattern = new URLPattern({ pathname: `${path}/message` });
352
+ return _McpAgent.serveSSE(path, { binding, corsOptions });
353
+ }
354
+ static serveSSE(path, {
355
+ binding = "MCP_OBJECT",
356
+ corsOptions
357
+ } = {}) {
358
+ let pathname = path;
359
+ if (path === "/") {
360
+ pathname = "/*";
361
+ }
362
+ const basePattern = new URLPattern({ pathname });
363
+ const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
219
364
  return {
220
365
  fetch: async (request, env, ctx) => {
221
366
  const corsResponse = handleCORS(request, corsOptions);
@@ -227,20 +372,26 @@ var McpAgent = class extends DurableObject {
227
372
  const { readable, writable } = new TransformStream();
228
373
  const writer = writable.getWriter();
229
374
  const encoder = new TextEncoder();
375
+ const endpointUrl = new URL(request.url);
376
+ endpointUrl.pathname = encodeURI(`${pathname}/message`);
377
+ endpointUrl.searchParams.set("sessionId", sessionId);
378
+ const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;
230
379
  const endpointMessage = `event: endpoint
231
- data: ${encodeURI(`${path}/message`)}?sessionId=${sessionId}
380
+ data: ${relativeUrlWithSession}
232
381
 
233
382
  `;
234
383
  writer.write(encoder.encode(endpointMessage));
235
- const id = namespace.idFromString(sessionId);
384
+ const id = namespace.idFromName(`sse:${sessionId}`);
236
385
  const doStub = namespace.get(id);
237
386
  await doStub._init(ctx.props);
238
387
  const upgradeUrl = new URL(request.url);
239
- upgradeUrl.searchParams.set("sessionId", sessionId);
388
+ upgradeUrl.pathname = "/sse";
240
389
  const response = await doStub.fetch(
241
390
  new Request(upgradeUrl, {
242
391
  headers: {
243
- Upgrade: "websocket"
392
+ Upgrade: "websocket",
393
+ // Required by PartyServer
394
+ "x-partykit-room": sessionId
244
395
  }
245
396
  })
246
397
  );
@@ -248,44 +399,48 @@ data: ${encodeURI(`${path}/message`)}?sessionId=${sessionId}
248
399
  if (!ws) {
249
400
  console.error("Failed to establish WebSocket connection");
250
401
  await writer.close();
251
- return;
402
+ return new Response("Failed to establish WebSocket connection", {
403
+ status: 500
404
+ });
252
405
  }
253
406
  ws.accept();
254
- ws.addEventListener("message", async (event) => {
255
- try {
256
- const message = JSON.parse(event.data);
257
- if (!(typeof message.id === "number" || message.id === null)) {
258
- throw new Error("Invalid jsonrpc message id");
259
- }
260
- if (message.jsonrpc !== "2.0") {
261
- throw new Error("Invalid jsonrpc version");
262
- }
263
- if (!Object.hasOwn(message, "result") && !Object.hasOwn(message, "error")) {
264
- throw new Error(
265
- "Invalid jsonrpc message. Must have either result or error field"
266
- );
267
- }
268
- const messageText = `event: message
269
- data: ${event.data}
407
+ ws.addEventListener("message", (event) => {
408
+ async function onMessage(event2) {
409
+ try {
410
+ const message = JSON.parse(event2.data);
411
+ const result = JSONRPCMessageSchema.safeParse(message);
412
+ if (!result.success) {
413
+ return;
414
+ }
415
+ const messageText = `event: message
416
+ data: ${JSON.stringify(result.data)}
270
417
 
271
418
  `;
272
- await writer.write(encoder.encode(messageText));
273
- } catch (error) {
274
- console.error("Error forwarding message to SSE:", error);
419
+ await writer.write(encoder.encode(messageText));
420
+ } catch (error) {
421
+ console.error("Error forwarding message to SSE:", error);
422
+ }
275
423
  }
424
+ onMessage(event).catch(console.error);
276
425
  });
277
- ws.addEventListener("error", async (error) => {
278
- try {
279
- await writer.close();
280
- } catch (e) {
426
+ ws.addEventListener("error", (error) => {
427
+ async function onError(error2) {
428
+ try {
429
+ await writer.close();
430
+ } catch (e) {
431
+ }
281
432
  }
433
+ onError(error).catch(console.error);
282
434
  });
283
- ws.addEventListener("close", async () => {
284
- try {
285
- await writer.close();
286
- } catch (error) {
287
- console.error("Error closing SSE connection:", error);
435
+ ws.addEventListener("close", () => {
436
+ async function onClose() {
437
+ try {
438
+ await writer.close();
439
+ } catch (error) {
440
+ console.error("Error closing SSE connection:", error);
441
+ }
288
442
  }
443
+ onClose().catch(console.error);
289
444
  });
290
445
  return new Response(readable, {
291
446
  headers: {
@@ -300,34 +455,321 @@ data: ${event.data}
300
455
  const sessionId = url.searchParams.get("sessionId");
301
456
  if (!sessionId) {
302
457
  return new Response(
303
- `Missing sessionId. Expected POST to ${path} to initiate new one`,
458
+ `Missing sessionId. Expected POST to ${pathname} to initiate new one`,
304
459
  { status: 400 }
305
460
  );
306
461
  }
307
- const object = namespace.get(namespace.idFromString(sessionId));
308
- const response = await object.onMCPMessage(sessionId, request);
309
- const headers = new Headers();
310
- response.headers.forEach?.((value, key) => {
311
- headers.set(key, value);
312
- });
313
- headers.set(
314
- "Access-Control-Allow-Origin",
315
- corsOptions?.origin || "*"
462
+ const contentType = request.headers.get("content-type") || "";
463
+ if (!contentType.includes("application/json")) {
464
+ return new Response(`Unsupported content-type: ${contentType}`, {
465
+ status: 400
466
+ });
467
+ }
468
+ const contentLength = Number.parseInt(
469
+ request.headers.get("content-length") || "0",
470
+ 10
316
471
  );
317
- return new Response(response.body, {
318
- status: response.status,
319
- statusText: response.statusText,
320
- headers
472
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
473
+ return new Response(
474
+ `Request body too large: ${contentLength} bytes`,
475
+ {
476
+ status: 400
477
+ }
478
+ );
479
+ }
480
+ const id = namespace.idFromName(`sse:${sessionId}`);
481
+ const doStub = namespace.get(id);
482
+ const error = await doStub.onSSEMcpMessage(sessionId, request);
483
+ if (error) {
484
+ return new Response(error.message, {
485
+ status: 400,
486
+ headers: {
487
+ "Content-Type": "text/event-stream",
488
+ "Cache-Control": "no-cache",
489
+ Connection: "keep-alive",
490
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
491
+ }
492
+ });
493
+ }
494
+ return new Response("Accepted", {
495
+ status: 202,
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
+ }
321
502
  });
322
503
  }
323
504
  return new Response("Not Found", { status: 404 });
324
505
  }
325
506
  };
326
507
  }
508
+ static serve(path, {
509
+ binding = "MCP_OBJECT",
510
+ corsOptions
511
+ } = {}) {
512
+ let pathname = path;
513
+ if (path === "/") {
514
+ pathname = "/*";
515
+ }
516
+ const basePattern = new URLPattern({ pathname });
517
+ return {
518
+ fetch: async (request, env, ctx) => {
519
+ const corsResponse = handleCORS(request, corsOptions);
520
+ if (corsResponse) {
521
+ return corsResponse;
522
+ }
523
+ const url = new URL(request.url);
524
+ const namespace = env[binding];
525
+ if (request.method === "POST" && basePattern.test(url)) {
526
+ const acceptHeader = request.headers.get("accept");
527
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
528
+ const body2 = JSON.stringify({
529
+ jsonrpc: "2.0",
530
+ error: {
531
+ code: -32e3,
532
+ message: "Not Acceptable: Client must accept both application/json and text/event-stream"
533
+ },
534
+ id: null
535
+ });
536
+ return new Response(body2, { status: 406 });
537
+ }
538
+ const ct = request.headers.get("content-type");
539
+ if (!ct || !ct.includes("application/json")) {
540
+ const body2 = JSON.stringify({
541
+ jsonrpc: "2.0",
542
+ error: {
543
+ code: -32e3,
544
+ message: "Unsupported Media Type: Content-Type must be application/json"
545
+ },
546
+ id: null
547
+ });
548
+ return new Response(body2, { status: 415 });
549
+ }
550
+ const contentLength = Number.parseInt(
551
+ request.headers.get("content-length") ?? "0",
552
+ 10
553
+ );
554
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
555
+ const body2 = JSON.stringify({
556
+ jsonrpc: "2.0",
557
+ error: {
558
+ code: -32e3,
559
+ message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
560
+ },
561
+ id: null
562
+ });
563
+ return new Response(body2, { status: 413 });
564
+ }
565
+ let sessionId = request.headers.get("mcp-session-id");
566
+ let rawMessage;
567
+ try {
568
+ rawMessage = await request.json();
569
+ } catch (error) {
570
+ const body2 = JSON.stringify({
571
+ jsonrpc: "2.0",
572
+ error: {
573
+ code: -32700,
574
+ message: "Parse error: Invalid JSON"
575
+ },
576
+ id: null
577
+ });
578
+ return new Response(body2, { status: 400 });
579
+ }
580
+ let arrayMessage;
581
+ if (Array.isArray(rawMessage)) {
582
+ arrayMessage = rawMessage;
583
+ } else {
584
+ arrayMessage = [rawMessage];
585
+ }
586
+ let messages = [];
587
+ for (const msg of arrayMessage) {
588
+ if (!JSONRPCMessageSchema.safeParse(msg).success) {
589
+ const body2 = JSON.stringify({
590
+ jsonrpc: "2.0",
591
+ error: {
592
+ code: -32700,
593
+ message: "Parse error: Invalid JSON-RPC message"
594
+ },
595
+ id: null
596
+ });
597
+ return new Response(body2, { status: 400 });
598
+ }
599
+ }
600
+ messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
601
+ const isInitializationRequest = messages.some(
602
+ (msg) => InitializeRequestSchema.safeParse(msg).success
603
+ );
604
+ if (isInitializationRequest && sessionId) {
605
+ const body2 = JSON.stringify({
606
+ jsonrpc: "2.0",
607
+ error: {
608
+ code: -32600,
609
+ message: "Invalid Request: Initialization requests must not include a sessionId"
610
+ },
611
+ id: null
612
+ });
613
+ return new Response(body2, { status: 400 });
614
+ }
615
+ if (isInitializationRequest && messages.length > 1) {
616
+ const body2 = JSON.stringify({
617
+ jsonrpc: "2.0",
618
+ error: {
619
+ code: -32600,
620
+ message: "Invalid Request: Only one initialization request is allowed"
621
+ },
622
+ id: null
623
+ });
624
+ return new Response(body2, { status: 400 });
625
+ }
626
+ if (!isInitializationRequest && !sessionId) {
627
+ const body2 = JSON.stringify({
628
+ jsonrpc: "2.0",
629
+ error: {
630
+ code: -32e3,
631
+ message: "Bad Request: Mcp-Session-Id header is required"
632
+ },
633
+ id: null
634
+ });
635
+ return new Response(body2, { status: 400 });
636
+ }
637
+ sessionId = sessionId ?? namespace.newUniqueId().toString();
638
+ const id = namespace.idFromName(`streamable-http:${sessionId}`);
639
+ const doStub = namespace.get(id);
640
+ const isInitialized = await doStub.isInitialized();
641
+ if (isInitializationRequest) {
642
+ await doStub.setInitialized();
643
+ } else if (!isInitialized) {
644
+ const body2 = JSON.stringify({
645
+ jsonrpc: "2.0",
646
+ error: {
647
+ code: -32001,
648
+ message: "Session not found"
649
+ },
650
+ id: null
651
+ });
652
+ return new Response(body2, { status: 404 });
653
+ }
654
+ const { readable, writable } = new TransformStream();
655
+ const writer = writable.getWriter();
656
+ const encoder = new TextEncoder();
657
+ const upgradeUrl = new URL(request.url);
658
+ upgradeUrl.pathname = "/streamable-http";
659
+ const response = await doStub.fetch(
660
+ new Request(upgradeUrl, {
661
+ headers: {
662
+ Upgrade: "websocket",
663
+ // Required by PartyServer
664
+ "x-partykit-room": sessionId
665
+ }
666
+ })
667
+ );
668
+ const ws = response.webSocket;
669
+ if (!ws) {
670
+ console.error("Failed to establish WebSocket connection");
671
+ await writer.close();
672
+ const body2 = JSON.stringify({
673
+ jsonrpc: "2.0",
674
+ error: {
675
+ code: -32001,
676
+ message: "Failed to establish WebSocket connection"
677
+ },
678
+ id: null
679
+ });
680
+ return new Response(body2, { status: 500 });
681
+ }
682
+ const requestIds = /* @__PURE__ */ new Set();
683
+ ws.accept();
684
+ ws.addEventListener("message", (event) => {
685
+ async function onMessage(event2) {
686
+ try {
687
+ const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
688
+ const message = JSON.parse(data);
689
+ const result = JSONRPCMessageSchema.safeParse(message);
690
+ if (!result.success) {
691
+ return;
692
+ }
693
+ if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
694
+ requestIds.delete(result.data.id);
695
+ }
696
+ const messageText = `event: message
697
+ data: ${JSON.stringify(result.data)}
698
+
699
+ `;
700
+ await writer.write(encoder.encode(messageText));
701
+ if (requestIds.size === 0) {
702
+ ws.close();
703
+ }
704
+ } catch (error) {
705
+ console.error("Error forwarding message to SSE:", error);
706
+ }
707
+ }
708
+ onMessage(event).catch(console.error);
709
+ });
710
+ ws.addEventListener("error", (error) => {
711
+ async function onError(error2) {
712
+ try {
713
+ await writer.close();
714
+ } catch (e) {
715
+ }
716
+ }
717
+ onError(error).catch(console.error);
718
+ });
719
+ ws.addEventListener("close", () => {
720
+ async function onClose() {
721
+ try {
722
+ await writer.close();
723
+ } catch (error) {
724
+ console.error("Error closing SSE connection:", error);
725
+ }
726
+ }
727
+ onClose().catch(console.error);
728
+ });
729
+ const hasOnlyNotificationsOrResponses = messages.every(
730
+ (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
731
+ );
732
+ if (hasOnlyNotificationsOrResponses) {
733
+ for (const message of messages) {
734
+ ws.send(JSON.stringify(message));
735
+ }
736
+ ws.close();
737
+ return new Response(null, { status: 202 });
738
+ }
739
+ for (const message of messages) {
740
+ if (isJSONRPCRequest(message)) {
741
+ requestIds.add(message.id);
742
+ }
743
+ ws.send(JSON.stringify(message));
744
+ }
745
+ return new Response(readable, {
746
+ headers: {
747
+ "Content-Type": "text/event-stream",
748
+ "Cache-Control": "no-cache",
749
+ Connection: "keep-alive",
750
+ "mcp-session-id": sessionId,
751
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
752
+ },
753
+ status: 200
754
+ });
755
+ }
756
+ const body = JSON.stringify({
757
+ jsonrpc: "2.0",
758
+ error: {
759
+ code: -32e3,
760
+ message: "Method not allowed"
761
+ },
762
+ id: null
763
+ });
764
+ return new Response(body, { status: 405 });
765
+ }
766
+ };
767
+ }
327
768
  };
328
769
  _status = new WeakMap();
329
770
  _transport = new WeakMap();
330
- _connected = new WeakMap();
771
+ _transportType = new WeakMap();
772
+ _requestIdToConnectionId = new WeakMap();
331
773
  _agent = new WeakMap();
332
774
  _McpAgent_instances = new WeakSet();
333
775
  initialize_fn = async function() {
@@ -337,6 +779,7 @@ initialize_fn = async function() {
337
779
  __privateSet(this, _status, "started");
338
780
  });
339
781
  };
782
+ var McpAgent = _McpAgent;
340
783
  export {
341
784
  McpAgent
342
785
  };