agents 0.0.0-85d8edd → 0.0.0-8671aae

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 (41) hide show
  1. package/dist/ai-chat-agent.d.ts +45 -3
  2. package/dist/ai-chat-agent.js +117 -55
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +13 -0
  5. package/dist/ai-react.js +9 -3
  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-OYJXQRRH.js +465 -0
  11. package/dist/chunk-OYJXQRRH.js.map +1 -0
  12. package/dist/{chunk-XG52S6YY.js → chunk-P3RZJ72N.js} +328 -136
  13. package/dist/chunk-P3RZJ72N.js.map +1 -0
  14. package/dist/chunk-VCSB47AK.js +116 -0
  15. package/dist/chunk-VCSB47AK.js.map +1 -0
  16. package/dist/client.d.ts +15 -1
  17. package/dist/client.js +6 -126
  18. package/dist/client.js.map +1 -1
  19. package/dist/index.d.ts +120 -11
  20. package/dist/index.js +8 -6
  21. package/dist/mcp/client.d.ts +32 -12
  22. package/dist/mcp/client.js +3 -402
  23. package/dist/mcp/client.js.map +1 -1
  24. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  25. package/dist/mcp/do-oauth-client-provider.js +3 -103
  26. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  27. package/dist/mcp/index.d.ts +27 -5
  28. package/dist/mcp/index.js +142 -138
  29. package/dist/mcp/index.js.map +1 -1
  30. package/dist/react.d.ts +85 -5
  31. package/dist/react.js +14 -2
  32. package/dist/react.js.map +1 -1
  33. package/dist/schedule.js +0 -2
  34. package/dist/schedule.js.map +1 -1
  35. package/dist/serializable.d.ts +32 -0
  36. package/dist/serializable.js +1 -0
  37. package/package.json +10 -7
  38. package/src/index.ts +394 -54
  39. package/dist/chunk-HMLY7DHA.js +0 -16
  40. package/dist/chunk-XG52S6YY.js.map +0 -1
  41. /package/dist/{chunk-HMLY7DHA.js.map → serializable.js.map} +0 -0
package/dist/mcp/index.js CHANGED
@@ -1,12 +1,9 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-XG52S6YY.js";
4
- import {
5
- __privateAdd,
6
- __privateGet,
7
- __privateMethod,
8
- __privateSet
9
- } from "../chunk-HMLY7DHA.js";
3
+ } from "../chunk-P3RZJ72N.js";
4
+ import "../chunk-OYJXQRRH.js";
5
+ import "../chunk-BZXOAZUX.js";
6
+ import "../chunk-VCSB47AK.js";
10
7
 
11
8
  // src/mcp/index.ts
12
9
  import { DurableObject } from "cloudflare:workers";
@@ -19,37 +16,41 @@ import {
19
16
  JSONRPCMessageSchema
20
17
  } from "@modelcontextprotocol/sdk/types.js";
21
18
  var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
22
- function handleCORS(request, corsOptions) {
23
- const origin = request.headers.get("Origin") || "*";
24
- const corsHeaders = {
25
- "Access-Control-Allow-Origin": corsOptions?.origin || origin,
26
- "Access-Control-Allow-Methods": corsOptions?.methods || "GET, POST, OPTIONS",
27
- "Access-Control-Allow-Headers": corsOptions?.headers || "Content-Type",
28
- "Access-Control-Max-Age": (corsOptions?.maxAge || 86400).toString()
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"
29
27
  };
28
+ }
29
+ function isDurableObjectNamespace(namespace) {
30
+ return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
31
+ }
32
+ function handleCORS(request, corsOptions) {
30
33
  if (request.method === "OPTIONS") {
31
- return new Response(null, { headers: corsHeaders });
34
+ return new Response(null, { headers: corsHeaders(request, corsOptions) });
32
35
  }
33
36
  return null;
34
37
  }
35
- var _getWebSocket, _started;
36
38
  var McpSSETransport = class {
37
39
  constructor(getWebSocket) {
38
- __privateAdd(this, _getWebSocket);
39
- __privateAdd(this, _started, false);
40
- __privateSet(this, _getWebSocket, getWebSocket);
40
+ this._started = false;
41
+ this._getWebSocket = getWebSocket;
41
42
  }
42
43
  async start() {
43
- if (__privateGet(this, _started)) {
44
+ if (this._started) {
44
45
  throw new Error("Transport already started");
45
46
  }
46
- __privateSet(this, _started, true);
47
+ this._started = true;
47
48
  }
48
49
  async send(message) {
49
- if (!__privateGet(this, _started)) {
50
+ if (!this._started) {
50
51
  throw new Error("Transport not started");
51
52
  }
52
- const websocket = __privateGet(this, _getWebSocket).call(this);
53
+ const websocket = this._getWebSocket();
53
54
  if (!websocket) {
54
55
  throw new Error("WebSocket not connected");
55
56
  }
@@ -64,52 +65,40 @@ var McpSSETransport = class {
64
65
  this.onclose?.();
65
66
  }
66
67
  };
67
- _getWebSocket = new WeakMap();
68
- _started = new WeakMap();
69
- var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
70
68
  var McpStreamableHttpTransport = class {
71
69
  constructor(getWebSocketForMessageID, notifyResponseIdSent) {
72
- // TODO: If there is an open connection to send server-initiated messages
73
- // back, we should use that connection
74
- __privateAdd(this, _getWebSocketForGetRequest);
75
- // Get the appropriate websocket connection for a given message id
76
- __privateAdd(this, _getWebSocketForMessageID);
77
- // Notify the server that a response has been sent for a given message id
78
- // so that it may clean up it's mapping of message ids to connections
79
- // once they are no longer needed
80
- __privateAdd(this, _notifyResponseIdSent);
81
- __privateAdd(this, _started2, false);
82
- __privateSet(this, _getWebSocketForMessageID, getWebSocketForMessageID);
83
- __privateSet(this, _notifyResponseIdSent, notifyResponseIdSent);
84
- __privateSet(this, _getWebSocketForGetRequest, () => null);
70
+ this._started = false;
71
+ this._getWebSocketForMessageID = getWebSocketForMessageID;
72
+ this._notifyResponseIdSent = notifyResponseIdSent;
73
+ this._getWebSocketForGetRequest = () => null;
85
74
  }
86
75
  async start() {
87
- if (__privateGet(this, _started2)) {
76
+ if (this._started) {
88
77
  throw new Error("Transport already started");
89
78
  }
90
- __privateSet(this, _started2, true);
79
+ this._started = true;
91
80
  }
92
81
  async send(message) {
93
- if (!__privateGet(this, _started2)) {
82
+ if (!this._started) {
94
83
  throw new Error("Transport not started");
95
84
  }
96
85
  let websocket = null;
97
86
  if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
98
- websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
87
+ websocket = this._getWebSocketForMessageID(message.id.toString());
99
88
  if (!websocket) {
100
89
  throw new Error(
101
90
  `Could not find WebSocket for message id: ${message.id}`
102
91
  );
103
92
  }
104
93
  } else if (isJSONRPCRequest(message)) {
105
- websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
94
+ websocket = this._getWebSocketForGetRequest();
106
95
  } else if (isJSONRPCNotification(message)) {
107
96
  websocket = null;
108
97
  }
109
98
  try {
110
99
  websocket?.send(JSON.stringify(message));
111
100
  if (isJSONRPCResponse(message)) {
112
- __privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
101
+ this._notifyResponseIdSent(message.id.toString());
113
102
  }
114
103
  } catch (error) {
115
104
  this.onerror?.(error);
@@ -120,28 +109,16 @@ var McpStreamableHttpTransport = class {
120
109
  this.onclose?.();
121
110
  }
122
111
  };
123
- _getWebSocketForGetRequest = new WeakMap();
124
- _getWebSocketForMessageID = new WeakMap();
125
- _notifyResponseIdSent = new WeakMap();
126
- _started2 = new WeakMap();
127
- var _status, _transport, _transportType, _requestIdToConnectionId, _agent, _McpAgent_instances, initialize_fn;
128
- var _McpAgent = class _McpAgent extends DurableObject {
112
+ var McpAgent = class _McpAgent extends DurableObject {
129
113
  constructor(ctx, env) {
130
114
  var _a;
131
115
  super(ctx, env);
132
- __privateAdd(this, _McpAgent_instances);
133
- __privateAdd(this, _status, "zero");
134
- __privateAdd(this, _transport);
135
- __privateAdd(this, _transportType, "unset");
136
- __privateAdd(this, _requestIdToConnectionId, /* @__PURE__ */ new Map());
137
- /**
138
- * Since McpAgent's _aren't_ yet real "Agents", let's only expose a couple of the methods
139
- * to the outer class: initialState/state/setState/onStateUpdate/sql
140
- */
141
- __privateAdd(this, _agent);
116
+ this._status = "zero";
117
+ this._transportType = "unset";
118
+ this._requestIdToConnectionId = /* @__PURE__ */ new Map();
142
119
  this.initRun = false;
143
120
  const self = this;
144
- __privateSet(this, _agent, new (_a = class extends Agent {
121
+ this._agent = new (_a = class extends Agent {
145
122
  onStateUpdate(state, source) {
146
123
  return self.onStateUpdate(state, source);
147
124
  }
@@ -150,23 +127,26 @@ var _McpAgent = class _McpAgent extends DurableObject {
150
127
  }
151
128
  }, _a.options = {
152
129
  hibernate: true
153
- }, _a)(ctx, env));
130
+ }, _a)(ctx, env);
131
+ }
132
+ get mcp() {
133
+ return this._agent.mcp;
154
134
  }
155
135
  get state() {
156
- return __privateGet(this, _agent).state;
136
+ return this._agent.state;
157
137
  }
158
138
  sql(strings, ...values) {
159
- return __privateGet(this, _agent).sql(strings, ...values);
139
+ return this._agent.sql(strings, ...values);
160
140
  }
161
141
  setState(state) {
162
- return __privateGet(this, _agent).setState(state);
142
+ return this._agent.setState(state);
163
143
  }
164
144
  onStateUpdate(state, source) {
165
145
  }
166
146
  async onStart() {
167
147
  var _a;
168
148
  const self = this;
169
- __privateSet(this, _agent, new (_a = class extends Agent {
149
+ this._agent = new (_a = class extends Agent {
170
150
  constructor() {
171
151
  super(...arguments);
172
152
  this.initialState = self.initialState;
@@ -179,21 +159,22 @@ var _McpAgent = class _McpAgent extends DurableObject {
179
159
  }
180
160
  }, _a.options = {
181
161
  hibernate: true
182
- }, _a)(this.ctx, this.env));
162
+ }, _a)(this.ctx, this.env);
183
163
  this.props = await this.ctx.storage.get("props");
184
- __privateSet(this, _transportType, await this.ctx.storage.get(
164
+ this._transportType = await this.ctx.storage.get(
185
165
  "transportType"
186
- ));
166
+ );
187
167
  await this._init(this.props);
188
- if (__privateGet(this, _transportType) === "sse") {
189
- __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
190
- await this.server.connect(__privateGet(this, _transport));
191
- } else if (__privateGet(this, _transportType) === "streamable-http") {
192
- __privateSet(this, _transport, new McpStreamableHttpTransport(
168
+ const server = await this.server;
169
+ if (this._transportType === "sse") {
170
+ this._transport = new McpSSETransport(() => this.getWebSocket());
171
+ await server.connect(this._transport);
172
+ } else if (this._transportType === "streamable-http") {
173
+ this._transport = new McpStreamableHttpTransport(
193
174
  (id) => this.getWebSocketForResponseID(id),
194
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
195
- ));
196
- await this.server.connect(__privateGet(this, _transport));
175
+ (id) => this._requestIdToConnectionId.delete(id)
176
+ );
177
+ await server.connect(this._transport);
197
178
  }
198
179
  }
199
180
  async _init(props) {
@@ -213,10 +194,17 @@ var _McpAgent = class _McpAgent extends DurableObject {
213
194
  async isInitialized() {
214
195
  return await this.ctx.storage.get("initialized") === true;
215
196
  }
197
+ async _initialize() {
198
+ await this.ctx.blockConcurrencyWhile(async () => {
199
+ this._status = "starting";
200
+ await this.onStart();
201
+ this._status = "started";
202
+ });
203
+ }
216
204
  // Allow the worker to fetch a websocket connection to the agent
217
205
  async fetch(request) {
218
- if (__privateGet(this, _status) !== "started") {
219
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
206
+ if (this._status !== "started") {
207
+ await this._initialize();
220
208
  }
221
209
  if (request.headers.get("Upgrade") !== "websocket") {
222
210
  return new Response("Expected WebSocket Upgrade request", {
@@ -225,6 +213,7 @@ var _McpAgent = class _McpAgent extends DurableObject {
225
213
  }
226
214
  const url = new URL(request.url);
227
215
  const path = url.pathname;
216
+ const server = await this.server;
228
217
  switch (path) {
229
218
  case "/sse": {
230
219
  const websockets = this.ctx.getWebSockets();
@@ -232,24 +221,24 @@ var _McpAgent = class _McpAgent extends DurableObject {
232
221
  return new Response("Websocket already connected", { status: 400 });
233
222
  }
234
223
  await this.ctx.storage.put("transportType", "sse");
235
- __privateSet(this, _transportType, "sse");
236
- if (!__privateGet(this, _transport)) {
237
- __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
238
- await this.server.connect(__privateGet(this, _transport));
224
+ this._transportType = "sse";
225
+ if (!this._transport) {
226
+ this._transport = new McpSSETransport(() => this.getWebSocket());
227
+ await server.connect(this._transport);
239
228
  }
240
- return __privateGet(this, _agent).fetch(request);
229
+ return this._agent.fetch(request);
241
230
  }
242
231
  case "/streamable-http": {
243
- if (!__privateGet(this, _transport)) {
244
- __privateSet(this, _transport, new McpStreamableHttpTransport(
232
+ if (!this._transport) {
233
+ this._transport = new McpStreamableHttpTransport(
245
234
  (id) => this.getWebSocketForResponseID(id),
246
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
247
- ));
248
- await this.server.connect(__privateGet(this, _transport));
235
+ (id) => this._requestIdToConnectionId.delete(id)
236
+ );
237
+ await server.connect(this._transport);
249
238
  }
250
239
  await this.ctx.storage.put("transportType", "streamable-http");
251
- __privateSet(this, _transportType, "streamable-http");
252
- return __privateGet(this, _agent).fetch(request);
240
+ this._transportType = "streamable-http";
241
+ return this._agent.fetch(request);
253
242
  }
254
243
  default:
255
244
  return new Response(
@@ -268,19 +257,19 @@ var _McpAgent = class _McpAgent extends DurableObject {
268
257
  return websockets[0];
269
258
  }
270
259
  getWebSocketForResponseID(id) {
271
- const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
260
+ const connectionId = this._requestIdToConnectionId.get(id);
272
261
  if (connectionId === void 0) {
273
262
  return null;
274
263
  }
275
- return __privateGet(this, _agent).getConnection(connectionId) ?? null;
264
+ return this._agent.getConnection(connectionId) ?? null;
276
265
  }
277
266
  // All messages received here. This is currently never called
278
267
  async onMessage(connection, event) {
279
- if (__privateGet(this, _transportType) !== "streamable-http") {
268
+ if (this._transportType !== "streamable-http") {
280
269
  const err = new Error(
281
270
  "Internal Server Error: Expected streamable-http protocol"
282
271
  );
283
- __privateGet(this, _transport)?.onerror?.(err);
272
+ this._transport?.onerror?.(err);
284
273
  return;
285
274
  }
286
275
  let message;
@@ -288,21 +277,21 @@ var _McpAgent = class _McpAgent extends DurableObject {
288
277
  const data = typeof event === "string" ? event : new TextDecoder().decode(event);
289
278
  message = JSONRPCMessageSchema.parse(JSON.parse(data));
290
279
  } catch (error) {
291
- __privateGet(this, _transport)?.onerror?.(error);
280
+ this._transport?.onerror?.(error);
292
281
  return;
293
282
  }
294
283
  if (isJSONRPCRequest(message)) {
295
- __privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
284
+ this._requestIdToConnectionId.set(message.id.toString(), connection.id);
296
285
  }
297
- __privateGet(this, _transport)?.onmessage?.(message);
286
+ this._transport?.onmessage?.(message);
298
287
  }
299
288
  // All messages received over SSE after the initial connection has been established
300
289
  // will be passed here
301
290
  async onSSEMcpMessage(sessionId, request) {
302
- if (__privateGet(this, _status) !== "started") {
303
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
291
+ if (this._status !== "started") {
292
+ await this._initialize();
304
293
  }
305
- if (__privateGet(this, _transportType) !== "sse") {
294
+ if (this._transportType !== "sse") {
306
295
  return new Error("Internal Server Error: Expected SSE protocol");
307
296
  }
308
297
  try {
@@ -311,35 +300,36 @@ var _McpAgent = class _McpAgent extends DurableObject {
311
300
  try {
312
301
  parsedMessage = JSONRPCMessageSchema.parse(message);
313
302
  } catch (error) {
314
- __privateGet(this, _transport)?.onerror?.(error);
303
+ this._transport?.onerror?.(error);
315
304
  throw error;
316
305
  }
317
- __privateGet(this, _transport)?.onmessage?.(parsedMessage);
306
+ this._transport?.onmessage?.(parsedMessage);
318
307
  return null;
319
308
  } catch (error) {
320
- __privateGet(this, _transport)?.onerror?.(error);
309
+ console.error("Error forwarding message to SSE:", error);
310
+ this._transport?.onerror?.(error);
321
311
  return error;
322
312
  }
323
313
  }
324
314
  // Delegate all websocket events to the underlying agent
325
315
  async webSocketMessage(ws, event) {
326
- if (__privateGet(this, _status) !== "started") {
327
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
316
+ if (this._status !== "started") {
317
+ await this._initialize();
328
318
  }
329
- return await __privateGet(this, _agent).webSocketMessage(ws, event);
319
+ return await this._agent.webSocketMessage(ws, event);
330
320
  }
331
321
  // WebSocket event handlers for hibernation support
332
322
  async webSocketError(ws, error) {
333
- if (__privateGet(this, _status) !== "started") {
334
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
323
+ if (this._status !== "started") {
324
+ await this._initialize();
335
325
  }
336
- return await __privateGet(this, _agent).webSocketError(ws, error);
326
+ return await this._agent.webSocketError(ws, error);
337
327
  }
338
328
  async webSocketClose(ws, code, reason, wasClean) {
339
- if (__privateGet(this, _status) !== "started") {
340
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
329
+ if (this._status !== "started") {
330
+ await this._initialize();
341
331
  }
342
- return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
332
+ return await this._agent.webSocketClose(ws, code, reason, wasClean);
343
333
  }
344
334
  static mount(path, {
345
335
  binding = "MCP_OBJECT",
@@ -358,18 +348,32 @@ var _McpAgent = class _McpAgent extends DurableObject {
358
348
  const basePattern = new URLPattern({ pathname });
359
349
  const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
360
350
  return {
361
- fetch: async (request, env, ctx) => {
351
+ async fetch(request, env, ctx) {
362
352
  const corsResponse = handleCORS(request, corsOptions);
363
353
  if (corsResponse) return corsResponse;
364
354
  const url = new URL(request.url);
365
- const namespace = env[binding];
355
+ const bindingValue = env[binding];
356
+ if (bindingValue == null || typeof bindingValue !== "object") {
357
+ console.error(
358
+ `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
359
+ );
360
+ return new Response("Invalid binding", { status: 500 });
361
+ }
362
+ if (!isDurableObjectNamespace(bindingValue)) {
363
+ return new Response("Invalid binding", { status: 500 });
364
+ }
365
+ const namespace = bindingValue;
366
366
  if (request.method === "GET" && basePattern.test(url)) {
367
367
  const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
368
368
  const { readable, writable } = new TransformStream();
369
369
  const writer = writable.getWriter();
370
370
  const encoder = new TextEncoder();
371
+ const endpointUrl = new URL(request.url);
372
+ endpointUrl.pathname = encodeURI(`${pathname}/message`);
373
+ endpointUrl.searchParams.set("sessionId", sessionId);
374
+ const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;
371
375
  const endpointMessage = `event: endpoint
372
- data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
376
+ data: ${relativeUrlWithSession}
373
377
 
374
378
  `;
375
379
  writer.write(encoder.encode(endpointMessage));
@@ -439,7 +443,7 @@ data: ${JSON.stringify(result.data)}
439
443
  "Content-Type": "text/event-stream",
440
444
  "Cache-Control": "no-cache",
441
445
  Connection: "keep-alive",
442
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
446
+ ...corsHeaders(request, corsOptions)
443
447
  }
444
448
  });
445
449
  }
@@ -479,7 +483,7 @@ data: ${JSON.stringify(result.data)}
479
483
  "Content-Type": "text/event-stream",
480
484
  "Cache-Control": "no-cache",
481
485
  Connection: "keep-alive",
482
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
486
+ ...corsHeaders(request, corsOptions)
483
487
  }
484
488
  });
485
489
  }
@@ -489,7 +493,7 @@ data: ${JSON.stringify(result.data)}
489
493
  "Content-Type": "text/event-stream",
490
494
  "Cache-Control": "no-cache",
491
495
  Connection: "keep-alive",
492
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
496
+ ...corsHeaders(request, corsOptions)
493
497
  }
494
498
  });
495
499
  }
@@ -507,13 +511,23 @@ data: ${JSON.stringify(result.data)}
507
511
  }
508
512
  const basePattern = new URLPattern({ pathname });
509
513
  return {
510
- fetch: async (request, env, ctx) => {
514
+ async fetch(request, env, ctx) {
511
515
  const corsResponse = handleCORS(request, corsOptions);
512
516
  if (corsResponse) {
513
517
  return corsResponse;
514
518
  }
515
519
  const url = new URL(request.url);
516
- const namespace = env[binding];
520
+ const bindingValue = env[binding];
521
+ if (bindingValue == null || typeof bindingValue !== "object") {
522
+ console.error(
523
+ `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
524
+ );
525
+ return new Response("Invalid binding", { status: 500 });
526
+ }
527
+ if (!isDurableObjectNamespace(bindingValue)) {
528
+ return new Response("Invalid binding", { status: 500 });
529
+ }
530
+ const namespace = bindingValue;
517
531
  if (request.method === "POST" && basePattern.test(url)) {
518
532
  const acceptHeader = request.headers.get("accept");
519
533
  if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
@@ -631,6 +645,7 @@ data: ${JSON.stringify(result.data)}
631
645
  const doStub = namespace.get(id);
632
646
  const isInitialized = await doStub.isInitialized();
633
647
  if (isInitializationRequest) {
648
+ await doStub._init(ctx.props);
634
649
  await doStub.setInitialized();
635
650
  } else if (!isInitialized) {
636
651
  const body2 = JSON.stringify({
@@ -726,7 +741,10 @@ data: ${JSON.stringify(result.data)}
726
741
  ws.send(JSON.stringify(message));
727
742
  }
728
743
  ws.close();
729
- return new Response(null, { status: 202 });
744
+ return new Response(null, {
745
+ status: 202,
746
+ headers: corsHeaders(request, corsOptions)
747
+ });
730
748
  }
731
749
  for (const message of messages) {
732
750
  if (isJSONRPCRequest(message)) {
@@ -740,7 +758,7 @@ data: ${JSON.stringify(result.data)}
740
758
  "Cache-Control": "no-cache",
741
759
  Connection: "keep-alive",
742
760
  "mcp-session-id": sessionId,
743
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
761
+ ...corsHeaders(request, corsOptions)
744
762
  },
745
763
  status: 200
746
764
  });
@@ -758,20 +776,6 @@ data: ${JSON.stringify(result.data)}
758
776
  };
759
777
  }
760
778
  };
761
- _status = new WeakMap();
762
- _transport = new WeakMap();
763
- _transportType = new WeakMap();
764
- _requestIdToConnectionId = new WeakMap();
765
- _agent = new WeakMap();
766
- _McpAgent_instances = new WeakSet();
767
- initialize_fn = async function() {
768
- await this.ctx.blockConcurrencyWhile(async () => {
769
- __privateSet(this, _status, "starting");
770
- await this.onStart();
771
- __privateSet(this, _status, "started");
772
- });
773
- };
774
- var McpAgent = _McpAgent;
775
779
  export {
776
780
  McpAgent
777
781
  };