agents 0.0.0-85d8edd → 0.0.0-86cae6f

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-VCSB47AK.js +116 -0
  11. package/dist/chunk-VCSB47AK.js.map +1 -0
  12. package/dist/{chunk-XG52S6YY.js → chunk-VNSFDJYL.js} +325 -133
  13. package/dist/chunk-VNSFDJYL.js.map +1 -0
  14. package/dist/chunk-Y67CHZBI.js +464 -0
  15. package/dist/chunk-Y67CHZBI.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 +139 -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 +389 -51
  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-VNSFDJYL.js";
4
+ import "../chunk-Y67CHZBI.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,38 @@ 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 handleCORS(request, corsOptions) {
30
30
  if (request.method === "OPTIONS") {
31
- return new Response(null, { headers: corsHeaders });
31
+ return new Response(null, { headers: corsHeaders(request, corsOptions) });
32
32
  }
33
33
  return null;
34
34
  }
35
- var _getWebSocket, _started;
36
35
  var McpSSETransport = class {
37
36
  constructor(getWebSocket) {
38
- __privateAdd(this, _getWebSocket);
39
- __privateAdd(this, _started, false);
40
- __privateSet(this, _getWebSocket, getWebSocket);
37
+ this._started = false;
38
+ this._getWebSocket = getWebSocket;
41
39
  }
42
40
  async start() {
43
- if (__privateGet(this, _started)) {
41
+ if (this._started) {
44
42
  throw new Error("Transport already started");
45
43
  }
46
- __privateSet(this, _started, true);
44
+ this._started = true;
47
45
  }
48
46
  async send(message) {
49
- if (!__privateGet(this, _started)) {
47
+ if (!this._started) {
50
48
  throw new Error("Transport not started");
51
49
  }
52
- const websocket = __privateGet(this, _getWebSocket).call(this);
50
+ const websocket = this._getWebSocket();
53
51
  if (!websocket) {
54
52
  throw new Error("WebSocket not connected");
55
53
  }
@@ -64,52 +62,40 @@ var McpSSETransport = class {
64
62
  this.onclose?.();
65
63
  }
66
64
  };
67
- _getWebSocket = new WeakMap();
68
- _started = new WeakMap();
69
- var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
70
65
  var McpStreamableHttpTransport = class {
71
66
  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);
67
+ this._started = false;
68
+ this._getWebSocketForMessageID = getWebSocketForMessageID;
69
+ this._notifyResponseIdSent = notifyResponseIdSent;
70
+ this._getWebSocketForGetRequest = () => null;
85
71
  }
86
72
  async start() {
87
- if (__privateGet(this, _started2)) {
73
+ if (this._started) {
88
74
  throw new Error("Transport already started");
89
75
  }
90
- __privateSet(this, _started2, true);
76
+ this._started = true;
91
77
  }
92
78
  async send(message) {
93
- if (!__privateGet(this, _started2)) {
79
+ if (!this._started) {
94
80
  throw new Error("Transport not started");
95
81
  }
96
82
  let websocket = null;
97
83
  if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
98
- websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
84
+ websocket = this._getWebSocketForMessageID(message.id.toString());
99
85
  if (!websocket) {
100
86
  throw new Error(
101
87
  `Could not find WebSocket for message id: ${message.id}`
102
88
  );
103
89
  }
104
90
  } else if (isJSONRPCRequest(message)) {
105
- websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
91
+ websocket = this._getWebSocketForGetRequest();
106
92
  } else if (isJSONRPCNotification(message)) {
107
93
  websocket = null;
108
94
  }
109
95
  try {
110
96
  websocket?.send(JSON.stringify(message));
111
97
  if (isJSONRPCResponse(message)) {
112
- __privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
98
+ this._notifyResponseIdSent(message.id.toString());
113
99
  }
114
100
  } catch (error) {
115
101
  this.onerror?.(error);
@@ -120,28 +106,16 @@ var McpStreamableHttpTransport = class {
120
106
  this.onclose?.();
121
107
  }
122
108
  };
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 {
109
+ var McpAgent = class _McpAgent extends DurableObject {
129
110
  constructor(ctx, env) {
130
111
  var _a;
131
112
  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);
113
+ this._status = "zero";
114
+ this._transportType = "unset";
115
+ this._requestIdToConnectionId = /* @__PURE__ */ new Map();
142
116
  this.initRun = false;
143
117
  const self = this;
144
- __privateSet(this, _agent, new (_a = class extends Agent {
118
+ this._agent = new (_a = class extends Agent {
145
119
  onStateUpdate(state, source) {
146
120
  return self.onStateUpdate(state, source);
147
121
  }
@@ -150,23 +124,26 @@ var _McpAgent = class _McpAgent extends DurableObject {
150
124
  }
151
125
  }, _a.options = {
152
126
  hibernate: true
153
- }, _a)(ctx, env));
127
+ }, _a)(ctx, env);
128
+ }
129
+ get mcp() {
130
+ return this._agent.mcp;
154
131
  }
155
132
  get state() {
156
- return __privateGet(this, _agent).state;
133
+ return this._agent.state;
157
134
  }
158
135
  sql(strings, ...values) {
159
- return __privateGet(this, _agent).sql(strings, ...values);
136
+ return this._agent.sql(strings, ...values);
160
137
  }
161
138
  setState(state) {
162
- return __privateGet(this, _agent).setState(state);
139
+ return this._agent.setState(state);
163
140
  }
164
141
  onStateUpdate(state, source) {
165
142
  }
166
143
  async onStart() {
167
144
  var _a;
168
145
  const self = this;
169
- __privateSet(this, _agent, new (_a = class extends Agent {
146
+ this._agent = new (_a = class extends Agent {
170
147
  constructor() {
171
148
  super(...arguments);
172
149
  this.initialState = self.initialState;
@@ -179,21 +156,22 @@ var _McpAgent = class _McpAgent extends DurableObject {
179
156
  }
180
157
  }, _a.options = {
181
158
  hibernate: true
182
- }, _a)(this.ctx, this.env));
159
+ }, _a)(this.ctx, this.env);
183
160
  this.props = await this.ctx.storage.get("props");
184
- __privateSet(this, _transportType, await this.ctx.storage.get(
161
+ this._transportType = await this.ctx.storage.get(
185
162
  "transportType"
186
- ));
163
+ );
187
164
  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(
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(
193
171
  (id) => this.getWebSocketForResponseID(id),
194
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
195
- ));
196
- await this.server.connect(__privateGet(this, _transport));
172
+ (id) => this._requestIdToConnectionId.delete(id)
173
+ );
174
+ await server.connect(this._transport);
197
175
  }
198
176
  }
199
177
  async _init(props) {
@@ -213,10 +191,17 @@ var _McpAgent = class _McpAgent extends DurableObject {
213
191
  async isInitialized() {
214
192
  return await this.ctx.storage.get("initialized") === true;
215
193
  }
194
+ async _initialize() {
195
+ await this.ctx.blockConcurrencyWhile(async () => {
196
+ this._status = "starting";
197
+ await this.onStart();
198
+ this._status = "started";
199
+ });
200
+ }
216
201
  // Allow the worker to fetch a websocket connection to the agent
217
202
  async fetch(request) {
218
- if (__privateGet(this, _status) !== "started") {
219
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
203
+ if (this._status !== "started") {
204
+ await this._initialize();
220
205
  }
221
206
  if (request.headers.get("Upgrade") !== "websocket") {
222
207
  return new Response("Expected WebSocket Upgrade request", {
@@ -225,6 +210,7 @@ var _McpAgent = class _McpAgent extends DurableObject {
225
210
  }
226
211
  const url = new URL(request.url);
227
212
  const path = url.pathname;
213
+ const server = await this.server;
228
214
  switch (path) {
229
215
  case "/sse": {
230
216
  const websockets = this.ctx.getWebSockets();
@@ -232,24 +218,24 @@ var _McpAgent = class _McpAgent extends DurableObject {
232
218
  return new Response("Websocket already connected", { status: 400 });
233
219
  }
234
220
  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));
221
+ this._transportType = "sse";
222
+ if (!this._transport) {
223
+ this._transport = new McpSSETransport(() => this.getWebSocket());
224
+ await server.connect(this._transport);
239
225
  }
240
- return __privateGet(this, _agent).fetch(request);
226
+ return this._agent.fetch(request);
241
227
  }
242
228
  case "/streamable-http": {
243
- if (!__privateGet(this, _transport)) {
244
- __privateSet(this, _transport, new McpStreamableHttpTransport(
229
+ if (!this._transport) {
230
+ this._transport = new McpStreamableHttpTransport(
245
231
  (id) => this.getWebSocketForResponseID(id),
246
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
247
- ));
248
- await this.server.connect(__privateGet(this, _transport));
232
+ (id) => this._requestIdToConnectionId.delete(id)
233
+ );
234
+ await server.connect(this._transport);
249
235
  }
250
236
  await this.ctx.storage.put("transportType", "streamable-http");
251
- __privateSet(this, _transportType, "streamable-http");
252
- return __privateGet(this, _agent).fetch(request);
237
+ this._transportType = "streamable-http";
238
+ return this._agent.fetch(request);
253
239
  }
254
240
  default:
255
241
  return new Response(
@@ -268,19 +254,19 @@ var _McpAgent = class _McpAgent extends DurableObject {
268
254
  return websockets[0];
269
255
  }
270
256
  getWebSocketForResponseID(id) {
271
- const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
257
+ const connectionId = this._requestIdToConnectionId.get(id);
272
258
  if (connectionId === void 0) {
273
259
  return null;
274
260
  }
275
- return __privateGet(this, _agent).getConnection(connectionId) ?? null;
261
+ return this._agent.getConnection(connectionId) ?? null;
276
262
  }
277
263
  // All messages received here. This is currently never called
278
264
  async onMessage(connection, event) {
279
- if (__privateGet(this, _transportType) !== "streamable-http") {
265
+ if (this._transportType !== "streamable-http") {
280
266
  const err = new Error(
281
267
  "Internal Server Error: Expected streamable-http protocol"
282
268
  );
283
- __privateGet(this, _transport)?.onerror?.(err);
269
+ this._transport?.onerror?.(err);
284
270
  return;
285
271
  }
286
272
  let message;
@@ -288,21 +274,21 @@ var _McpAgent = class _McpAgent extends DurableObject {
288
274
  const data = typeof event === "string" ? event : new TextDecoder().decode(event);
289
275
  message = JSONRPCMessageSchema.parse(JSON.parse(data));
290
276
  } catch (error) {
291
- __privateGet(this, _transport)?.onerror?.(error);
277
+ this._transport?.onerror?.(error);
292
278
  return;
293
279
  }
294
280
  if (isJSONRPCRequest(message)) {
295
- __privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
281
+ this._requestIdToConnectionId.set(message.id.toString(), connection.id);
296
282
  }
297
- __privateGet(this, _transport)?.onmessage?.(message);
283
+ this._transport?.onmessage?.(message);
298
284
  }
299
285
  // All messages received over SSE after the initial connection has been established
300
286
  // will be passed here
301
287
  async onSSEMcpMessage(sessionId, request) {
302
- if (__privateGet(this, _status) !== "started") {
303
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
288
+ if (this._status !== "started") {
289
+ await this._initialize();
304
290
  }
305
- if (__privateGet(this, _transportType) !== "sse") {
291
+ if (this._transportType !== "sse") {
306
292
  return new Error("Internal Server Error: Expected SSE protocol");
307
293
  }
308
294
  try {
@@ -311,35 +297,36 @@ var _McpAgent = class _McpAgent extends DurableObject {
311
297
  try {
312
298
  parsedMessage = JSONRPCMessageSchema.parse(message);
313
299
  } catch (error) {
314
- __privateGet(this, _transport)?.onerror?.(error);
300
+ this._transport?.onerror?.(error);
315
301
  throw error;
316
302
  }
317
- __privateGet(this, _transport)?.onmessage?.(parsedMessage);
303
+ this._transport?.onmessage?.(parsedMessage);
318
304
  return null;
319
305
  } catch (error) {
320
- __privateGet(this, _transport)?.onerror?.(error);
306
+ console.error("Error forwarding message to SSE:", error);
307
+ this._transport?.onerror?.(error);
321
308
  return error;
322
309
  }
323
310
  }
324
311
  // Delegate all websocket events to the underlying agent
325
312
  async webSocketMessage(ws, event) {
326
- if (__privateGet(this, _status) !== "started") {
327
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
313
+ if (this._status !== "started") {
314
+ await this._initialize();
328
315
  }
329
- return await __privateGet(this, _agent).webSocketMessage(ws, event);
316
+ return await this._agent.webSocketMessage(ws, event);
330
317
  }
331
318
  // WebSocket event handlers for hibernation support
332
319
  async webSocketError(ws, error) {
333
- if (__privateGet(this, _status) !== "started") {
334
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
320
+ if (this._status !== "started") {
321
+ await this._initialize();
335
322
  }
336
- return await __privateGet(this, _agent).webSocketError(ws, error);
323
+ return await this._agent.webSocketError(ws, error);
337
324
  }
338
325
  async webSocketClose(ws, code, reason, wasClean) {
339
- if (__privateGet(this, _status) !== "started") {
340
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
326
+ if (this._status !== "started") {
327
+ await this._initialize();
341
328
  }
342
- return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
329
+ return await this._agent.webSocketClose(ws, code, reason, wasClean);
343
330
  }
344
331
  static mount(path, {
345
332
  binding = "MCP_OBJECT",
@@ -358,18 +345,32 @@ var _McpAgent = class _McpAgent extends DurableObject {
358
345
  const basePattern = new URLPattern({ pathname });
359
346
  const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
360
347
  return {
361
- fetch: async (request, env, ctx) => {
348
+ async fetch(request, env, ctx) {
362
349
  const corsResponse = handleCORS(request, corsOptions);
363
350
  if (corsResponse) return corsResponse;
364
351
  const url = new URL(request.url);
365
- 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;
366
363
  if (request.method === "GET" && basePattern.test(url)) {
367
364
  const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
368
365
  const { readable, writable } = new TransformStream();
369
366
  const writer = writable.getWriter();
370
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;
371
372
  const endpointMessage = `event: endpoint
372
- data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
373
+ data: ${relativeUrlWithSession}
373
374
 
374
375
  `;
375
376
  writer.write(encoder.encode(endpointMessage));
@@ -439,7 +440,7 @@ data: ${JSON.stringify(result.data)}
439
440
  "Content-Type": "text/event-stream",
440
441
  "Cache-Control": "no-cache",
441
442
  Connection: "keep-alive",
442
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
443
+ ...corsHeaders(request, corsOptions)
443
444
  }
444
445
  });
445
446
  }
@@ -479,7 +480,7 @@ data: ${JSON.stringify(result.data)}
479
480
  "Content-Type": "text/event-stream",
480
481
  "Cache-Control": "no-cache",
481
482
  Connection: "keep-alive",
482
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
483
+ ...corsHeaders(request, corsOptions)
483
484
  }
484
485
  });
485
486
  }
@@ -489,7 +490,7 @@ data: ${JSON.stringify(result.data)}
489
490
  "Content-Type": "text/event-stream",
490
491
  "Cache-Control": "no-cache",
491
492
  Connection: "keep-alive",
492
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
493
+ ...corsHeaders(request, corsOptions)
493
494
  }
494
495
  });
495
496
  }
@@ -507,13 +508,23 @@ data: ${JSON.stringify(result.data)}
507
508
  }
508
509
  const basePattern = new URLPattern({ pathname });
509
510
  return {
510
- fetch: async (request, env, ctx) => {
511
+ async fetch(request, env, ctx) {
511
512
  const corsResponse = handleCORS(request, corsOptions);
512
513
  if (corsResponse) {
513
514
  return corsResponse;
514
515
  }
515
516
  const url = new URL(request.url);
516
- const namespace = env[binding];
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;
517
528
  if (request.method === "POST" && basePattern.test(url)) {
518
529
  const acceptHeader = request.headers.get("accept");
519
530
  if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
@@ -631,6 +642,7 @@ data: ${JSON.stringify(result.data)}
631
642
  const doStub = namespace.get(id);
632
643
  const isInitialized = await doStub.isInitialized();
633
644
  if (isInitializationRequest) {
645
+ await doStub._init(ctx.props);
634
646
  await doStub.setInitialized();
635
647
  } else if (!isInitialized) {
636
648
  const body2 = JSON.stringify({
@@ -726,7 +738,10 @@ data: ${JSON.stringify(result.data)}
726
738
  ws.send(JSON.stringify(message));
727
739
  }
728
740
  ws.close();
729
- return new Response(null, { status: 202 });
741
+ return new Response(null, {
742
+ status: 202,
743
+ headers: corsHeaders(request, corsOptions)
744
+ });
730
745
  }
731
746
  for (const message of messages) {
732
747
  if (isJSONRPCRequest(message)) {
@@ -740,7 +755,7 @@ data: ${JSON.stringify(result.data)}
740
755
  "Cache-Control": "no-cache",
741
756
  Connection: "keep-alive",
742
757
  "mcp-session-id": sessionId,
743
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
758
+ ...corsHeaders(request, corsOptions)
744
759
  },
745
760
  status: 200
746
761
  });
@@ -758,20 +773,6 @@ data: ${JSON.stringify(result.data)}
758
773
  };
759
774
  }
760
775
  };
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
776
  export {
776
777
  McpAgent
777
778
  };