agents 0.0.0-3824fd4 → 0.0.0-385f0b2

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