agents 0.0.0-b25bc37 → 0.0.0-b275dea

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-AXSPGBHI.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,48 +62,88 @@ 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
- return __privateGet(this, _agent).state;
133
+ return this._agent.state;
89
134
  }
90
135
  sql(strings, ...values) {
91
- return __privateGet(this, _agent).sql(strings, ...values);
136
+ return this._agent.sql(strings, ...values);
92
137
  }
93
138
  setState(state) {
94
- return __privateGet(this, _agent).setState(state);
139
+ return this._agent.setState(state);
95
140
  }
96
141
  onStateUpdate(state, source) {
97
142
  }
98
143
  async onStart() {
99
144
  var _a;
100
145
  const self = this;
101
- __privateSet(this, _agent, new (_a = class extends Agent {
146
+ this._agent = new (_a = class extends Agent {
102
147
  constructor() {
103
148
  super(...arguments);
104
149
  this.initialState = self.initialState;
@@ -106,26 +151,57 @@ var McpAgent = class extends DurableObject {
106
151
  onStateUpdate(state, source) {
107
152
  return self.onStateUpdate(state, source);
108
153
  }
154
+ async onMessage(connection, event) {
155
+ return self.onMessage(connection, event);
156
+ }
109
157
  }, _a.options = {
110
158
  hibernate: true
111
- }, _a)(this.ctx, this.env));
159
+ }, _a)(this.ctx, this.env);
112
160
  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));
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
+ }
116
176
  }
117
177
  async _init(props) {
118
- 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
+ }
119
182
  this.props = props;
120
183
  if (!this.initRun) {
121
184
  this.initRun = true;
122
185
  await this.init();
123
186
  }
124
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
+ }
125
201
  // Allow the worker to fetch a websocket connection to the agent
126
202
  async fetch(request) {
127
- if (__privateGet(this, _status) !== "started") {
128
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
203
+ if (this._status !== "started") {
204
+ await this._initialize();
129
205
  }
130
206
  if (request.headers.get("Upgrade") !== "websocket") {
131
207
  return new Response("Expected WebSocket Upgrade request", {
@@ -133,18 +209,42 @@ var McpAgent = class extends DurableObject {
133
209
  });
134
210
  }
135
211
  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 });
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
+ );
142
247
  }
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
248
  }
149
249
  getWebSocket() {
150
250
  const websockets = this.ctx.getWebSockets();
@@ -153,73 +253,90 @@ var McpAgent = class extends DurableObject {
153
253
  }
154
254
  return websockets[0];
155
255
  }
156
- async onMCPMessage(sessionId, request) {
157
- if (__privateGet(this, _status) !== "started") {
158
- 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;
260
+ }
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"
268
+ );
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");
159
293
  }
160
294
  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
295
  const message = await request.json();
177
296
  let parsedMessage;
178
297
  try {
179
298
  parsedMessage = JSONRPCMessageSchema.parse(message);
180
299
  } catch (error) {
181
- __privateGet(this, _transport)?.onerror?.(error);
300
+ this._transport?.onerror?.(error);
182
301
  throw error;
183
302
  }
184
- __privateGet(this, _transport)?.onmessage?.(parsedMessage);
185
- return new Response("Accepted", { status: 202 });
303
+ this._transport?.onmessage?.(parsedMessage);
304
+ return null;
186
305
  } catch (error) {
187
- __privateGet(this, _transport)?.onerror?.(error);
188
- return new Response(String(error), { status: 400 });
306
+ console.error("Error forwarding message to SSE:", error);
307
+ this._transport?.onerror?.(error);
308
+ return error;
189
309
  }
190
310
  }
191
- // This is unused since there are no incoming websocket messages
311
+ // Delegate all websocket events to the underlying agent
192
312
  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
- if (__privateGet(this, _status) !== "started") {
202
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
313
+ if (this._status !== "started") {
314
+ await this._initialize();
203
315
  }
204
- __privateGet(this, _transport)?.onmessage?.(message);
316
+ return await this._agent.webSocketMessage(ws, event);
205
317
  }
206
318
  // WebSocket event handlers for hibernation support
207
319
  async webSocketError(ws, error) {
208
- if (__privateGet(this, _status) !== "started") {
209
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
320
+ if (this._status !== "started") {
321
+ await this._initialize();
210
322
  }
211
- __privateGet(this, _transport)?.onerror?.(error);
323
+ return await this._agent.webSocketError(ws, error);
212
324
  }
213
325
  async webSocketClose(ws, code, reason, wasClean) {
214
- if (__privateGet(this, _status) !== "started") {
215
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
326
+ if (this._status !== "started") {
327
+ await this._initialize();
216
328
  }
217
- __privateGet(this, _transport)?.onclose?.();
218
- __privateSet(this, _connected, false);
329
+ return await this._agent.webSocketClose(ws, code, reason, wasClean);
219
330
  }
220
331
  static mount(path, {
221
332
  binding = "MCP_OBJECT",
222
333
  corsOptions
334
+ } = {}) {
335
+ return _McpAgent.serveSSE(path, { binding, corsOptions });
336
+ }
337
+ static serveSSE(path, {
338
+ binding = "MCP_OBJECT",
339
+ corsOptions
223
340
  } = {}) {
224
341
  let pathname = path;
225
342
  if (path === "/") {
@@ -228,26 +345,40 @@ var McpAgent = class extends DurableObject {
228
345
  const basePattern = new URLPattern({ pathname });
229
346
  const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
230
347
  return {
231
- fetch: async (request, env, ctx) => {
348
+ async fetch(request, env, ctx) {
232
349
  const corsResponse = handleCORS(request, corsOptions);
233
350
  if (corsResponse) return corsResponse;
234
351
  const url = new URL(request.url);
235
- 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;
236
363
  if (request.method === "GET" && basePattern.test(url)) {
237
364
  const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
238
365
  const { readable, writable } = new TransformStream();
239
366
  const writer = writable.getWriter();
240
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;
241
372
  const endpointMessage = `event: endpoint
242
- data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
373
+ data: ${relativeUrlWithSession}
243
374
 
244
375
  `;
245
376
  writer.write(encoder.encode(endpointMessage));
246
- const id = namespace.idFromString(sessionId);
377
+ const id = namespace.idFromName(`sse:${sessionId}`);
247
378
  const doStub = namespace.get(id);
248
379
  await doStub._init(ctx.props);
249
380
  const upgradeUrl = new URL(request.url);
250
- upgradeUrl.searchParams.set("sessionId", sessionId);
381
+ upgradeUrl.pathname = "/sse";
251
382
  const response = await doStub.fetch(
252
383
  new Request(upgradeUrl, {
253
384
  headers: {
@@ -261,44 +392,55 @@ data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
261
392
  if (!ws) {
262
393
  console.error("Failed to establish WebSocket connection");
263
394
  await writer.close();
264
- return;
395
+ return new Response("Failed to establish WebSocket connection", {
396
+ status: 500
397
+ });
265
398
  }
266
399
  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
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
275
409
  data: ${JSON.stringify(result.data)}
276
410
 
277
411
  `;
278
- await writer.write(encoder.encode(messageText));
279
- } catch (error) {
280
- 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
+ }
281
416
  }
417
+ onMessage(event).catch(console.error);
282
418
  });
283
- ws.addEventListener("error", async (error) => {
284
- try {
285
- await writer.close();
286
- } catch (e) {
419
+ ws.addEventListener("error", (error) => {
420
+ async function onError(error2) {
421
+ try {
422
+ await writer.close();
423
+ } catch (e) {
424
+ }
287
425
  }
426
+ onError(error).catch(console.error);
288
427
  });
289
- ws.addEventListener("close", async () => {
290
- try {
291
- await writer.close();
292
- } catch (error) {
293
- 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
+ }
294
435
  }
436
+ onClose().catch(console.error);
295
437
  });
296
438
  return new Response(readable, {
297
439
  headers: {
298
440
  "Content-Type": "text/event-stream",
299
441
  "Cache-Control": "no-cache",
300
442
  Connection: "keep-alive",
301
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
443
+ ...corsHeaders(request, corsOptions)
302
444
  }
303
445
  });
304
446
  }
@@ -310,38 +452,326 @@ data: ${JSON.stringify(result.data)}
310
452
  { status: 400 }
311
453
  );
312
454
  }
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 || "*"
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
322
464
  );
323
- return new Response(response.body, {
324
- status: response.status,
325
- statusText: response.statusText,
326
- 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
+ }
327
495
  });
328
496
  }
329
497
  return new Response("Not Found", { status: 404 });
330
498
  }
331
499
  };
332
500
  }
333
- };
334
- _status = new WeakMap();
335
- _transport = new WeakMap();
336
- _connected = new WeakMap();
337
- _agent = new WeakMap();
338
- _McpAgent_instances = new WeakSet();
339
- initialize_fn = async function() {
340
- await this.ctx.blockConcurrencyWhile(async () => {
341
- __privateSet(this, _status, "starting");
342
- await this.onStart();
343
- __privateSet(this, _status, "started");
344
- });
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
+ }
345
775
  };
346
776
  export {
347
777
  McpAgent