agents 0.0.0-a25eb55 → 0.0.0-a45f8f3

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 (47) hide show
  1. package/README.md +127 -22
  2. package/dist/ai-chat-agent.d.ts +34 -5
  3. package/dist/ai-chat-agent.js +149 -115
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +20 -5
  6. package/dist/ai-react.js +28 -29
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/chunk-3IQQY2UH.js +1270 -0
  9. package/dist/chunk-3IQQY2UH.js.map +1 -0
  10. package/dist/chunk-KUH345EY.js +116 -0
  11. package/dist/chunk-KUH345EY.js.map +1 -0
  12. package/dist/chunk-PVQZBKN7.js +106 -0
  13. package/dist/chunk-PVQZBKN7.js.map +1 -0
  14. package/dist/{chunk-Q5ZBHY4Z.js → chunk-UNG3FXYX.js} +106 -37
  15. package/dist/chunk-UNG3FXYX.js.map +1 -0
  16. package/dist/client.d.ts +16 -2
  17. package/dist/client.js +6 -126
  18. package/dist/client.js.map +1 -1
  19. package/dist/index-CLW1aEBr.d.ts +615 -0
  20. package/dist/index.d.ts +35 -308
  21. package/dist/index.js +10 -3
  22. package/dist/mcp/client.d.ts +310 -33
  23. package/dist/mcp/client.js +1 -2
  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 +48 -15
  28. package/dist/mcp/index.js +165 -175
  29. package/dist/mcp/index.js.map +1 -1
  30. package/dist/observability/index.d.ts +14 -0
  31. package/dist/observability/index.js +10 -0
  32. package/dist/react.d.ts +87 -5
  33. package/dist/react.js +20 -8
  34. package/dist/react.js.map +1 -1
  35. package/dist/schedule.d.ts +6 -6
  36. package/dist/schedule.js +4 -6
  37. package/dist/schedule.js.map +1 -1
  38. package/dist/serializable.d.ts +32 -0
  39. package/dist/serializable.js +1 -0
  40. package/dist/serializable.js.map +1 -0
  41. package/package.json +76 -68
  42. package/src/index.ts +1092 -139
  43. package/dist/chunk-HMLY7DHA.js +0 -16
  44. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  45. package/dist/chunk-WNIGPPNB.js +0 -608
  46. package/dist/chunk-WNIGPPNB.js.map +0 -1
  47. /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
package/dist/mcp/index.js CHANGED
@@ -1,56 +1,59 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-WNIGPPNB.js";
4
- import "../chunk-Q5ZBHY4Z.js";
3
+ } from "../chunk-3IQQY2UH.js";
5
4
  import {
6
- __privateAdd,
7
- __privateGet,
8
- __privateMethod,
9
- __privateSet
10
- } from "../chunk-HMLY7DHA.js";
5
+ SSEEdgeClientTransport,
6
+ StreamableHTTPEdgeClientTransport
7
+ } from "../chunk-UNG3FXYX.js";
8
+ import "../chunk-PVQZBKN7.js";
9
+ import "../chunk-KUH345EY.js";
11
10
 
12
11
  // src/mcp/index.ts
13
12
  import { DurableObject } from "cloudflare:workers";
14
13
  import {
15
14
  InitializeRequestSchema,
15
+ JSONRPCMessageSchema,
16
16
  isJSONRPCError,
17
17
  isJSONRPCNotification,
18
18
  isJSONRPCRequest,
19
- isJSONRPCResponse,
20
- JSONRPCMessageSchema
19
+ isJSONRPCResponse
21
20
  } from "@modelcontextprotocol/sdk/types.js";
22
21
  var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
23
- function handleCORS(request, corsOptions) {
24
- const origin = request.headers.get("Origin") || "*";
25
- const corsHeaders = {
26
- "Access-Control-Allow-Origin": corsOptions?.origin || origin,
27
- "Access-Control-Allow-Methods": corsOptions?.methods || "GET, POST, OPTIONS",
28
- "Access-Control-Allow-Headers": corsOptions?.headers || "Content-Type",
29
- "Access-Control-Max-Age": (corsOptions?.maxAge || 86400).toString()
22
+ function corsHeaders(_request, corsOptions = {}) {
23
+ const origin = "*";
24
+ return {
25
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id, mcp-protocol-version",
26
+ "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, OPTIONS",
27
+ "Access-Control-Allow-Origin": corsOptions.origin || origin,
28
+ "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
29
+ "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
30
30
  };
31
+ }
32
+ function isDurableObjectNamespace(namespace) {
33
+ return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
34
+ }
35
+ function handleCORS(request, corsOptions) {
31
36
  if (request.method === "OPTIONS") {
32
- return new Response(null, { headers: corsHeaders });
37
+ return new Response(null, { headers: corsHeaders(request, corsOptions) });
33
38
  }
34
39
  return null;
35
40
  }
36
- var _getWebSocket, _started;
37
41
  var McpSSETransport = class {
38
42
  constructor(getWebSocket) {
39
- __privateAdd(this, _getWebSocket);
40
- __privateAdd(this, _started, false);
41
- __privateSet(this, _getWebSocket, getWebSocket);
43
+ this._started = false;
44
+ this._getWebSocket = getWebSocket;
42
45
  }
43
46
  async start() {
44
- if (__privateGet(this, _started)) {
47
+ if (this._started) {
45
48
  throw new Error("Transport already started");
46
49
  }
47
- __privateSet(this, _started, true);
50
+ this._started = true;
48
51
  }
49
52
  async send(message) {
50
- if (!__privateGet(this, _started)) {
53
+ if (!this._started) {
51
54
  throw new Error("Transport not started");
52
55
  }
53
- const websocket = __privateGet(this, _getWebSocket).call(this);
56
+ const websocket = this._getWebSocket();
54
57
  if (!websocket) {
55
58
  throw new Error("WebSocket not connected");
56
59
  }
@@ -65,52 +68,40 @@ var McpSSETransport = class {
65
68
  this.onclose?.();
66
69
  }
67
70
  };
68
- _getWebSocket = new WeakMap();
69
- _started = new WeakMap();
70
- var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
71
71
  var McpStreamableHttpTransport = class {
72
72
  constructor(getWebSocketForMessageID, notifyResponseIdSent) {
73
- // TODO: If there is an open connection to send server-initiated messages
74
- // back, we should use that connection
75
- __privateAdd(this, _getWebSocketForGetRequest);
76
- // Get the appropriate websocket connection for a given message id
77
- __privateAdd(this, _getWebSocketForMessageID);
78
- // Notify the server that a response has been sent for a given message id
79
- // so that it may clean up it's mapping of message ids to connections
80
- // once they are no longer needed
81
- __privateAdd(this, _notifyResponseIdSent);
82
- __privateAdd(this, _started2, false);
83
- __privateSet(this, _getWebSocketForMessageID, getWebSocketForMessageID);
84
- __privateSet(this, _notifyResponseIdSent, notifyResponseIdSent);
85
- __privateSet(this, _getWebSocketForGetRequest, () => null);
73
+ this._started = false;
74
+ this._getWebSocketForMessageID = getWebSocketForMessageID;
75
+ this._notifyResponseIdSent = notifyResponseIdSent;
76
+ this._getWebSocketForGetRequest = () => null;
86
77
  }
87
78
  async start() {
88
- if (__privateGet(this, _started2)) {
79
+ if (this._started) {
89
80
  throw new Error("Transport already started");
90
81
  }
91
- __privateSet(this, _started2, true);
82
+ this._started = true;
92
83
  }
93
84
  async send(message) {
94
- if (!__privateGet(this, _started2)) {
85
+ if (!this._started) {
95
86
  throw new Error("Transport not started");
96
87
  }
97
88
  let websocket = null;
98
89
  if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
99
- websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
90
+ websocket = this._getWebSocketForMessageID(message.id.toString());
100
91
  if (!websocket) {
101
92
  throw new Error(
102
93
  `Could not find WebSocket for message id: ${message.id}`
103
94
  );
104
95
  }
105
96
  } else if (isJSONRPCRequest(message)) {
106
- websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
97
+ websocket = this._getWebSocketForGetRequest();
107
98
  } else if (isJSONRPCNotification(message)) {
108
99
  websocket = null;
109
100
  }
110
101
  try {
111
102
  websocket?.send(JSON.stringify(message));
112
103
  if (isJSONRPCResponse(message)) {
113
- __privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
104
+ this._notifyResponseIdSent(message.id.toString());
114
105
  }
115
106
  } catch (error) {
116
107
  this.onerror?.(error);
@@ -121,28 +112,16 @@ var McpStreamableHttpTransport = class {
121
112
  this.onclose?.();
122
113
  }
123
114
  };
124
- _getWebSocketForGetRequest = new WeakMap();
125
- _getWebSocketForMessageID = new WeakMap();
126
- _notifyResponseIdSent = new WeakMap();
127
- _started2 = new WeakMap();
128
- var _status, _transport, _transportType, _requestIdToConnectionId, _agent, _McpAgent_instances, initialize_fn;
129
- var _McpAgent = class _McpAgent extends DurableObject {
115
+ var McpAgent = class _McpAgent extends DurableObject {
130
116
  constructor(ctx, env) {
131
117
  var _a;
132
118
  super(ctx, env);
133
- __privateAdd(this, _McpAgent_instances);
134
- __privateAdd(this, _status, "zero");
135
- __privateAdd(this, _transport);
136
- __privateAdd(this, _transportType, "unset");
137
- __privateAdd(this, _requestIdToConnectionId, /* @__PURE__ */ new Map());
138
- /**
139
- * Since McpAgent's _aren't_ yet real "Agents", let's only expose a couple of the methods
140
- * to the outer class: initialState/state/setState/onStateUpdate/sql
141
- */
142
- __privateAdd(this, _agent);
119
+ this._status = "zero";
120
+ this._transportType = "unset";
121
+ this._requestIdToConnectionId = /* @__PURE__ */ new Map();
143
122
  this.initRun = false;
144
123
  const self = this;
145
- __privateSet(this, _agent, new (_a = class extends Agent {
124
+ this._agent = new (_a = class extends Agent {
146
125
  onStateUpdate(state, source) {
147
126
  return self.onStateUpdate(state, source);
148
127
  }
@@ -151,26 +130,27 @@ var _McpAgent = class _McpAgent extends DurableObject {
151
130
  }
152
131
  }, _a.options = {
153
132
  hibernate: true
154
- }, _a)(ctx, env));
133
+ }, _a)(ctx, env);
155
134
  }
156
135
  get mcp() {
157
- return __privateGet(this, _agent).mcp;
136
+ return this._agent.mcp;
158
137
  }
159
138
  get state() {
160
- return __privateGet(this, _agent).state;
139
+ return this._agent.state;
161
140
  }
162
141
  sql(strings, ...values) {
163
- return __privateGet(this, _agent).sql(strings, ...values);
142
+ return this._agent.sql(strings, ...values);
164
143
  }
165
144
  setState(state) {
166
- return __privateGet(this, _agent).setState(state);
145
+ return this._agent.setState(state);
167
146
  }
147
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
168
148
  onStateUpdate(state, source) {
169
149
  }
170
150
  async onStart() {
171
151
  var _a;
172
152
  const self = this;
173
- __privateSet(this, _agent, new (_a = class extends Agent {
153
+ this._agent = new (_a = class extends Agent {
174
154
  constructor() {
175
155
  super(...arguments);
176
156
  this.initialState = self.initialState;
@@ -183,22 +163,22 @@ var _McpAgent = class _McpAgent extends DurableObject {
183
163
  }
184
164
  }, _a.options = {
185
165
  hibernate: true
186
- }, _a)(this.ctx, this.env));
166
+ }, _a)(this.ctx, this.env);
187
167
  this.props = await this.ctx.storage.get("props");
188
- __privateSet(this, _transportType, await this.ctx.storage.get(
168
+ this._transportType = await this.ctx.storage.get(
189
169
  "transportType"
190
- ));
170
+ );
191
171
  await this._init(this.props);
192
172
  const server = await this.server;
193
- if (__privateGet(this, _transportType) === "sse") {
194
- __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
195
- await server.connect(__privateGet(this, _transport));
196
- } else if (__privateGet(this, _transportType) === "streamable-http") {
197
- __privateSet(this, _transport, new McpStreamableHttpTransport(
173
+ if (this._transportType === "sse") {
174
+ this._transport = new McpSSETransport(() => this.getWebSocket());
175
+ await server.connect(this._transport);
176
+ } else if (this._transportType === "streamable-http") {
177
+ this._transport = new McpStreamableHttpTransport(
198
178
  (id) => this.getWebSocketForResponseID(id),
199
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
200
- ));
201
- await server.connect(__privateGet(this, _transport));
179
+ (id) => this._requestIdToConnectionId.delete(id)
180
+ );
181
+ await server.connect(this._transport);
202
182
  }
203
183
  }
204
184
  async _init(props) {
@@ -218,10 +198,17 @@ var _McpAgent = class _McpAgent extends DurableObject {
218
198
  async isInitialized() {
219
199
  return await this.ctx.storage.get("initialized") === true;
220
200
  }
201
+ async _initialize() {
202
+ await this.ctx.blockConcurrencyWhile(async () => {
203
+ this._status = "starting";
204
+ await this.onStart();
205
+ this._status = "started";
206
+ });
207
+ }
221
208
  // Allow the worker to fetch a websocket connection to the agent
222
209
  async fetch(request) {
223
- if (__privateGet(this, _status) !== "started") {
224
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
210
+ if (this._status !== "started") {
211
+ await this._initialize();
225
212
  }
226
213
  if (request.headers.get("Upgrade") !== "websocket") {
227
214
  return new Response("Expected WebSocket Upgrade request", {
@@ -238,24 +225,24 @@ var _McpAgent = class _McpAgent extends DurableObject {
238
225
  return new Response("Websocket already connected", { status: 400 });
239
226
  }
240
227
  await this.ctx.storage.put("transportType", "sse");
241
- __privateSet(this, _transportType, "sse");
242
- if (!__privateGet(this, _transport)) {
243
- __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
244
- await server.connect(__privateGet(this, _transport));
228
+ this._transportType = "sse";
229
+ if (!this._transport) {
230
+ this._transport = new McpSSETransport(() => this.getWebSocket());
231
+ await server.connect(this._transport);
245
232
  }
246
- return __privateGet(this, _agent).fetch(request);
233
+ return this._agent.fetch(request);
247
234
  }
248
235
  case "/streamable-http": {
249
- if (!__privateGet(this, _transport)) {
250
- __privateSet(this, _transport, new McpStreamableHttpTransport(
236
+ if (!this._transport) {
237
+ this._transport = new McpStreamableHttpTransport(
251
238
  (id) => this.getWebSocketForResponseID(id),
252
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
253
- ));
254
- await server.connect(__privateGet(this, _transport));
239
+ (id) => this._requestIdToConnectionId.delete(id)
240
+ );
241
+ await server.connect(this._transport);
255
242
  }
256
243
  await this.ctx.storage.put("transportType", "streamable-http");
257
- __privateSet(this, _transportType, "streamable-http");
258
- return __privateGet(this, _agent).fetch(request);
244
+ this._transportType = "streamable-http";
245
+ return this._agent.fetch(request);
259
246
  }
260
247
  default:
261
248
  return new Response(
@@ -274,19 +261,19 @@ var _McpAgent = class _McpAgent extends DurableObject {
274
261
  return websockets[0];
275
262
  }
276
263
  getWebSocketForResponseID(id) {
277
- const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
264
+ const connectionId = this._requestIdToConnectionId.get(id);
278
265
  if (connectionId === void 0) {
279
266
  return null;
280
267
  }
281
- return __privateGet(this, _agent).getConnection(connectionId) ?? null;
268
+ return this._agent.getConnection(connectionId) ?? null;
282
269
  }
283
270
  // All messages received here. This is currently never called
284
271
  async onMessage(connection, event) {
285
- if (__privateGet(this, _transportType) !== "streamable-http") {
272
+ if (this._transportType !== "streamable-http") {
286
273
  const err = new Error(
287
274
  "Internal Server Error: Expected streamable-http protocol"
288
275
  );
289
- __privateGet(this, _transport)?.onerror?.(err);
276
+ this._transport?.onerror?.(err);
290
277
  return;
291
278
  }
292
279
  let message;
@@ -294,21 +281,21 @@ var _McpAgent = class _McpAgent extends DurableObject {
294
281
  const data = typeof event === "string" ? event : new TextDecoder().decode(event);
295
282
  message = JSONRPCMessageSchema.parse(JSON.parse(data));
296
283
  } catch (error) {
297
- __privateGet(this, _transport)?.onerror?.(error);
284
+ this._transport?.onerror?.(error);
298
285
  return;
299
286
  }
300
287
  if (isJSONRPCRequest(message)) {
301
- __privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
288
+ this._requestIdToConnectionId.set(message.id.toString(), connection.id);
302
289
  }
303
- __privateGet(this, _transport)?.onmessage?.(message);
290
+ this._transport?.onmessage?.(message);
304
291
  }
305
292
  // All messages received over SSE after the initial connection has been established
306
293
  // will be passed here
307
- async onSSEMcpMessage(sessionId, request) {
308
- if (__privateGet(this, _status) !== "started") {
309
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
294
+ async onSSEMcpMessage(_sessionId, request) {
295
+ if (this._status !== "started") {
296
+ await this._initialize();
310
297
  }
311
- if (__privateGet(this, _transportType) !== "sse") {
298
+ if (this._transportType !== "sse") {
312
299
  return new Error("Internal Server Error: Expected SSE protocol");
313
300
  }
314
301
  try {
@@ -317,35 +304,36 @@ var _McpAgent = class _McpAgent extends DurableObject {
317
304
  try {
318
305
  parsedMessage = JSONRPCMessageSchema.parse(message);
319
306
  } catch (error) {
320
- __privateGet(this, _transport)?.onerror?.(error);
307
+ this._transport?.onerror?.(error);
321
308
  throw error;
322
309
  }
323
- __privateGet(this, _transport)?.onmessage?.(parsedMessage);
310
+ this._transport?.onmessage?.(parsedMessage);
324
311
  return null;
325
312
  } catch (error) {
326
- __privateGet(this, _transport)?.onerror?.(error);
313
+ console.error("Error forwarding message to SSE:", error);
314
+ this._transport?.onerror?.(error);
327
315
  return error;
328
316
  }
329
317
  }
330
318
  // Delegate all websocket events to the underlying agent
331
319
  async webSocketMessage(ws, event) {
332
- if (__privateGet(this, _status) !== "started") {
333
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
320
+ if (this._status !== "started") {
321
+ await this._initialize();
334
322
  }
335
- return await __privateGet(this, _agent).webSocketMessage(ws, event);
323
+ return await this._agent.webSocketMessage(ws, event);
336
324
  }
337
325
  // WebSocket event handlers for hibernation support
338
326
  async webSocketError(ws, error) {
339
- if (__privateGet(this, _status) !== "started") {
340
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
327
+ if (this._status !== "started") {
328
+ await this._initialize();
341
329
  }
342
- return await __privateGet(this, _agent).webSocketError(ws, error);
330
+ return await this._agent.webSocketError(ws, error);
343
331
  }
344
332
  async webSocketClose(ws, code, reason, wasClean) {
345
- if (__privateGet(this, _status) !== "started") {
346
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
333
+ if (this._status !== "started") {
334
+ await this._initialize();
347
335
  }
348
- return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
336
+ return await this._agent.webSocketClose(ws, code, reason, wasClean);
349
337
  }
350
338
  static mount(path, {
351
339
  binding = "MCP_OBJECT",
@@ -375,7 +363,7 @@ var _McpAgent = class _McpAgent extends DurableObject {
375
363
  );
376
364
  return new Response("Invalid binding", { status: 500 });
377
365
  }
378
- if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
366
+ if (!isDurableObjectNamespace(bindingValue)) {
379
367
  return new Response("Invalid binding", { status: 500 });
380
368
  }
381
369
  const namespace = bindingValue;
@@ -398,9 +386,14 @@ data: ${relativeUrlWithSession}
398
386
  await doStub._init(ctx.props);
399
387
  const upgradeUrl = new URL(request.url);
400
388
  upgradeUrl.pathname = "/sse";
389
+ const existingHeaders = {};
390
+ request.headers.forEach((value, key) => {
391
+ existingHeaders[key] = value;
392
+ });
401
393
  const response = await doStub.fetch(
402
394
  new Request(upgradeUrl, {
403
395
  headers: {
396
+ ...existingHeaders,
404
397
  Upgrade: "websocket",
405
398
  // Required by PartyServer
406
399
  "x-partykit-room": sessionId
@@ -436,10 +429,10 @@ data: ${JSON.stringify(result.data)}
436
429
  onMessage(event).catch(console.error);
437
430
  });
438
431
  ws.addEventListener("error", (error) => {
439
- async function onError(error2) {
432
+ async function onError(_error) {
440
433
  try {
441
434
  await writer.close();
442
- } catch (e) {
435
+ } catch (_e) {
443
436
  }
444
437
  }
445
438
  onError(error).catch(console.error);
@@ -456,10 +449,10 @@ data: ${JSON.stringify(result.data)}
456
449
  });
457
450
  return new Response(readable, {
458
451
  headers: {
459
- "Content-Type": "text/event-stream",
460
452
  "Cache-Control": "no-cache",
461
453
  Connection: "keep-alive",
462
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
454
+ "Content-Type": "text/event-stream",
455
+ ...corsHeaders(request, corsOptions)
463
456
  }
464
457
  });
465
458
  }
@@ -494,23 +487,23 @@ data: ${JSON.stringify(result.data)}
494
487
  const error = await doStub.onSSEMcpMessage(sessionId, request);
495
488
  if (error) {
496
489
  return new Response(error.message, {
497
- status: 400,
498
490
  headers: {
499
- "Content-Type": "text/event-stream",
500
491
  "Cache-Control": "no-cache",
501
492
  Connection: "keep-alive",
502
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
503
- }
493
+ "Content-Type": "text/event-stream",
494
+ ...corsHeaders(request, corsOptions)
495
+ },
496
+ status: 400
504
497
  });
505
498
  }
506
499
  return new Response("Accepted", {
507
- status: 202,
508
500
  headers: {
509
- "Content-Type": "text/event-stream",
510
501
  "Cache-Control": "no-cache",
511
502
  Connection: "keep-alive",
512
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
513
- }
503
+ "Content-Type": "text/event-stream",
504
+ ...corsHeaders(request, corsOptions)
505
+ },
506
+ status: 202
514
507
  });
515
508
  }
516
509
  return new Response("Not Found", { status: 404 });
@@ -540,7 +533,7 @@ data: ${JSON.stringify(result.data)}
540
533
  );
541
534
  return new Response("Invalid binding", { status: 500 });
542
535
  }
543
- if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
536
+ if (!isDurableObjectNamespace(bindingValue)) {
544
537
  return new Response("Invalid binding", { status: 500 });
545
538
  }
546
539
  const namespace = bindingValue;
@@ -548,24 +541,24 @@ data: ${JSON.stringify(result.data)}
548
541
  const acceptHeader = request.headers.get("accept");
549
542
  if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
550
543
  const body2 = JSON.stringify({
551
- jsonrpc: "2.0",
552
544
  error: {
553
545
  code: -32e3,
554
546
  message: "Not Acceptable: Client must accept both application/json and text/event-stream"
555
547
  },
556
- id: null
548
+ id: null,
549
+ jsonrpc: "2.0"
557
550
  });
558
551
  return new Response(body2, { status: 406 });
559
552
  }
560
553
  const ct = request.headers.get("content-type");
561
554
  if (!ct || !ct.includes("application/json")) {
562
555
  const body2 = JSON.stringify({
563
- jsonrpc: "2.0",
564
556
  error: {
565
557
  code: -32e3,
566
558
  message: "Unsupported Media Type: Content-Type must be application/json"
567
559
  },
568
- id: null
560
+ id: null,
561
+ jsonrpc: "2.0"
569
562
  });
570
563
  return new Response(body2, { status: 415 });
571
564
  }
@@ -575,12 +568,12 @@ data: ${JSON.stringify(result.data)}
575
568
  );
576
569
  if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
577
570
  const body2 = JSON.stringify({
578
- jsonrpc: "2.0",
579
571
  error: {
580
572
  code: -32e3,
581
573
  message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
582
574
  },
583
- id: null
575
+ id: null,
576
+ jsonrpc: "2.0"
584
577
  });
585
578
  return new Response(body2, { status: 413 });
586
579
  }
@@ -588,14 +581,14 @@ data: ${JSON.stringify(result.data)}
588
581
  let rawMessage;
589
582
  try {
590
583
  rawMessage = await request.json();
591
- } catch (error) {
584
+ } catch (_error) {
592
585
  const body2 = JSON.stringify({
593
- jsonrpc: "2.0",
594
586
  error: {
595
587
  code: -32700,
596
588
  message: "Parse error: Invalid JSON"
597
589
  },
598
- id: null
590
+ id: null,
591
+ jsonrpc: "2.0"
599
592
  });
600
593
  return new Response(body2, { status: 400 });
601
594
  }
@@ -609,12 +602,12 @@ data: ${JSON.stringify(result.data)}
609
602
  for (const msg of arrayMessage) {
610
603
  if (!JSONRPCMessageSchema.safeParse(msg).success) {
611
604
  const body2 = JSON.stringify({
612
- jsonrpc: "2.0",
613
605
  error: {
614
606
  code: -32700,
615
607
  message: "Parse error: Invalid JSON-RPC message"
616
608
  },
617
- id: null
609
+ id: null,
610
+ jsonrpc: "2.0"
618
611
  });
619
612
  return new Response(body2, { status: 400 });
620
613
  }
@@ -625,34 +618,34 @@ data: ${JSON.stringify(result.data)}
625
618
  );
626
619
  if (isInitializationRequest && sessionId) {
627
620
  const body2 = JSON.stringify({
628
- jsonrpc: "2.0",
629
621
  error: {
630
622
  code: -32600,
631
623
  message: "Invalid Request: Initialization requests must not include a sessionId"
632
624
  },
633
- id: null
625
+ id: null,
626
+ jsonrpc: "2.0"
634
627
  });
635
628
  return new Response(body2, { status: 400 });
636
629
  }
637
630
  if (isInitializationRequest && messages.length > 1) {
638
631
  const body2 = JSON.stringify({
639
- jsonrpc: "2.0",
640
632
  error: {
641
633
  code: -32600,
642
634
  message: "Invalid Request: Only one initialization request is allowed"
643
635
  },
644
- id: null
636
+ id: null,
637
+ jsonrpc: "2.0"
645
638
  });
646
639
  return new Response(body2, { status: 400 });
647
640
  }
648
641
  if (!isInitializationRequest && !sessionId) {
649
642
  const body2 = JSON.stringify({
650
- jsonrpc: "2.0",
651
643
  error: {
652
644
  code: -32e3,
653
645
  message: "Bad Request: Mcp-Session-Id header is required"
654
646
  },
655
- id: null
647
+ id: null,
648
+ jsonrpc: "2.0"
656
649
  });
657
650
  return new Response(body2, { status: 400 });
658
651
  }
@@ -661,15 +654,16 @@ data: ${JSON.stringify(result.data)}
661
654
  const doStub = namespace.get(id);
662
655
  const isInitialized = await doStub.isInitialized();
663
656
  if (isInitializationRequest) {
657
+ await doStub._init(ctx.props);
664
658
  await doStub.setInitialized();
665
659
  } else if (!isInitialized) {
666
660
  const body2 = JSON.stringify({
667
- jsonrpc: "2.0",
668
661
  error: {
669
662
  code: -32001,
670
663
  message: "Session not found"
671
664
  },
672
- id: null
665
+ id: null,
666
+ jsonrpc: "2.0"
673
667
  });
674
668
  return new Response(body2, { status: 404 });
675
669
  }
@@ -678,9 +672,14 @@ data: ${JSON.stringify(result.data)}
678
672
  const encoder = new TextEncoder();
679
673
  const upgradeUrl = new URL(request.url);
680
674
  upgradeUrl.pathname = "/streamable-http";
675
+ const existingHeaders = {};
676
+ request.headers.forEach((value, key) => {
677
+ existingHeaders[key] = value;
678
+ });
681
679
  const response = await doStub.fetch(
682
680
  new Request(upgradeUrl, {
683
681
  headers: {
682
+ ...existingHeaders,
684
683
  Upgrade: "websocket",
685
684
  // Required by PartyServer
686
685
  "x-partykit-room": sessionId
@@ -692,12 +691,12 @@ data: ${JSON.stringify(result.data)}
692
691
  console.error("Failed to establish WebSocket connection");
693
692
  await writer.close();
694
693
  const body2 = JSON.stringify({
695
- jsonrpc: "2.0",
696
694
  error: {
697
695
  code: -32001,
698
696
  message: "Failed to establish WebSocket connection"
699
697
  },
700
- id: null
698
+ id: null,
699
+ jsonrpc: "2.0"
701
700
  });
702
701
  return new Response(body2, { status: 500 });
703
702
  }
@@ -730,10 +729,10 @@ data: ${JSON.stringify(result.data)}
730
729
  onMessage(event).catch(console.error);
731
730
  });
732
731
  ws.addEventListener("error", (error) => {
733
- async function onError(error2) {
732
+ async function onError(_error) {
734
733
  try {
735
734
  await writer.close();
736
- } catch (e) {
735
+ } catch (_e) {
737
736
  }
738
737
  }
739
738
  onError(error).catch(console.error);
@@ -756,7 +755,10 @@ data: ${JSON.stringify(result.data)}
756
755
  ws.send(JSON.stringify(message));
757
756
  }
758
757
  ws.close();
759
- return new Response(null, { status: 202 });
758
+ return new Response(null, {
759
+ headers: corsHeaders(request, corsOptions),
760
+ status: 202
761
+ });
760
762
  }
761
763
  for (const message of messages) {
762
764
  if (isJSONRPCRequest(message)) {
@@ -766,43 +768,31 @@ data: ${JSON.stringify(result.data)}
766
768
  }
767
769
  return new Response(readable, {
768
770
  headers: {
769
- "Content-Type": "text/event-stream",
770
771
  "Cache-Control": "no-cache",
771
772
  Connection: "keep-alive",
773
+ "Content-Type": "text/event-stream",
772
774
  "mcp-session-id": sessionId,
773
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
775
+ ...corsHeaders(request, corsOptions)
774
776
  },
775
777
  status: 200
776
778
  });
777
779
  }
778
780
  const body = JSON.stringify({
779
- jsonrpc: "2.0",
780
781
  error: {
781
782
  code: -32e3,
782
783
  message: "Method not allowed"
783
784
  },
784
- id: null
785
+ id: null,
786
+ jsonrpc: "2.0"
785
787
  });
786
788
  return new Response(body, { status: 405 });
787
789
  }
788
790
  };
789
791
  }
790
792
  };
791
- _status = new WeakMap();
792
- _transport = new WeakMap();
793
- _transportType = new WeakMap();
794
- _requestIdToConnectionId = new WeakMap();
795
- _agent = new WeakMap();
796
- _McpAgent_instances = new WeakSet();
797
- initialize_fn = async function() {
798
- await this.ctx.blockConcurrencyWhile(async () => {
799
- __privateSet(this, _status, "starting");
800
- await this.onStart();
801
- __privateSet(this, _status, "started");
802
- });
803
- };
804
- var McpAgent = _McpAgent;
805
793
  export {
806
- McpAgent
794
+ McpAgent,
795
+ SSEEdgeClientTransport,
796
+ StreamableHTTPEdgeClientTransport
807
797
  };
808
798
  //# sourceMappingURL=index.js.map