agents 0.0.0-3d0c872 → 0.0.0-4100b67

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