agents 0.0.0-eede2bd → 0.0.0-f0c6dce

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 (56) hide show
  1. package/README.md +131 -25
  2. package/dist/ai-chat-agent.d.ts +40 -10
  3. package/dist/ai-chat-agent.js +246 -143
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +152 -0
  6. package/dist/ai-chat-v5-migration.js +19 -0
  7. package/dist/ai-react.d.ts +71 -67
  8. package/dist/ai-react.js +160 -55
  9. package/dist/ai-react.js.map +1 -1
  10. package/dist/ai-types.d.ts +36 -19
  11. package/dist/ai-types.js +6 -0
  12. package/dist/chunk-AVYJQSLW.js +17 -0
  13. package/dist/chunk-AVYJQSLW.js.map +1 -0
  14. package/dist/chunk-MWQSU7GK.js +1301 -0
  15. package/dist/chunk-MWQSU7GK.js.map +1 -0
  16. package/dist/chunk-PVQZBKN7.js +106 -0
  17. package/dist/chunk-PVQZBKN7.js.map +1 -0
  18. package/dist/chunk-QEVM4BVL.js +116 -0
  19. package/dist/chunk-QEVM4BVL.js.map +1 -0
  20. package/dist/chunk-UJVEAURM.js +150 -0
  21. package/dist/chunk-UJVEAURM.js.map +1 -0
  22. package/dist/{chunk-Q5ZBHY4Z.js → chunk-VYENMKFS.js} +209 -53
  23. package/dist/chunk-VYENMKFS.js.map +1 -0
  24. package/dist/client-B9tFv5gX.d.ts +4607 -0
  25. package/dist/client.d.ts +16 -2
  26. package/dist/client.js +7 -126
  27. package/dist/client.js.map +1 -1
  28. package/dist/index.d.ts +264 -23
  29. package/dist/index.js +13 -3
  30. package/dist/mcp/client.d.ts +9 -775
  31. package/dist/mcp/client.js +1 -2
  32. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  33. package/dist/mcp/do-oauth-client-provider.js +3 -103
  34. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  35. package/dist/mcp/index.d.ts +49 -11
  36. package/dist/mcp/index.js +330 -184
  37. package/dist/mcp/index.js.map +1 -1
  38. package/dist/observability/index.d.ts +46 -0
  39. package/dist/observability/index.js +11 -0
  40. package/dist/observability/index.js.map +1 -0
  41. package/dist/react.d.ts +89 -5
  42. package/dist/react.js +23 -9
  43. package/dist/react.js.map +1 -1
  44. package/dist/schedule.d.ts +81 -7
  45. package/dist/schedule.js +19 -8
  46. package/dist/schedule.js.map +1 -1
  47. package/dist/serializable.d.ts +32 -0
  48. package/dist/serializable.js +1 -0
  49. package/dist/serializable.js.map +1 -0
  50. package/package.json +83 -68
  51. package/src/index.ts +1132 -145
  52. package/dist/chunk-5W7ZWKOP.js +0 -617
  53. package/dist/chunk-5W7ZWKOP.js.map +0 -1
  54. package/dist/chunk-HMLY7DHA.js +0 -16
  55. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  56. /package/dist/{chunk-HMLY7DHA.js.map → ai-chat-v5-migration.js.map} +0 -0
package/dist/mcp/index.js CHANGED
@@ -1,56 +1,63 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-5W7ZWKOP.js";
4
- import "../chunk-Q5ZBHY4Z.js";
3
+ } from "../chunk-MWQSU7GK.js";
5
4
  import {
6
- __privateAdd,
7
- __privateGet,
8
- __privateMethod,
9
- __privateSet
10
- } from "../chunk-HMLY7DHA.js";
5
+ SSEEdgeClientTransport,
6
+ StreamableHTTPEdgeClientTransport
7
+ } from "../chunk-VYENMKFS.js";
8
+ import "../chunk-PVQZBKN7.js";
9
+ import "../chunk-QEVM4BVL.js";
10
+ import "../chunk-AVYJQSLW.js";
11
11
 
12
12
  // src/mcp/index.ts
13
13
  import { DurableObject } from "cloudflare:workers";
14
14
  import {
15
15
  InitializeRequestSchema,
16
+ JSONRPCMessageSchema,
16
17
  isJSONRPCError,
17
18
  isJSONRPCNotification,
18
19
  isJSONRPCRequest,
19
- isJSONRPCResponse,
20
- JSONRPCMessageSchema
20
+ isJSONRPCResponse
21
+ } from "@modelcontextprotocol/sdk/types.js";
22
+ import {
23
+ ElicitRequestSchema
21
24
  } from "@modelcontextprotocol/sdk/types.js";
22
25
  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()
26
+ function corsHeaders(_request, corsOptions = {}) {
27
+ const origin = "*";
28
+ return {
29
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id, mcp-protocol-version",
30
+ "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, OPTIONS",
31
+ "Access-Control-Allow-Origin": corsOptions.origin || origin,
32
+ "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
33
+ "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
30
34
  };
35
+ }
36
+ function isDurableObjectNamespace(namespace) {
37
+ return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
38
+ }
39
+ function handleCORS(request, corsOptions) {
31
40
  if (request.method === "OPTIONS") {
32
- return new Response(null, { headers: corsHeaders });
41
+ return new Response(null, { headers: corsHeaders(request, corsOptions) });
33
42
  }
34
43
  return null;
35
44
  }
36
- var _getWebSocket, _started;
37
45
  var McpSSETransport = class {
38
46
  constructor(getWebSocket) {
39
- __privateAdd(this, _getWebSocket);
40
- __privateAdd(this, _started, false);
41
- __privateSet(this, _getWebSocket, getWebSocket);
47
+ this._started = false;
48
+ this._getWebSocket = getWebSocket;
42
49
  }
43
50
  async start() {
44
- if (__privateGet(this, _started)) {
51
+ if (this._started) {
45
52
  throw new Error("Transport already started");
46
53
  }
47
- __privateSet(this, _started, true);
54
+ this._started = true;
48
55
  }
49
56
  async send(message) {
50
- if (!__privateGet(this, _started)) {
57
+ if (!this._started) {
51
58
  throw new Error("Transport not started");
52
59
  }
53
- const websocket = __privateGet(this, _getWebSocket).call(this);
60
+ const websocket = this._getWebSocket();
54
61
  if (!websocket) {
55
62
  throw new Error("WebSocket not connected");
56
63
  }
@@ -65,52 +72,40 @@ var McpSSETransport = class {
65
72
  this.onclose?.();
66
73
  }
67
74
  };
68
- _getWebSocket = new WeakMap();
69
- _started = new WeakMap();
70
- var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
71
75
  var McpStreamableHttpTransport = class {
72
76
  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);
77
+ this._started = false;
78
+ this._getWebSocketForMessageID = getWebSocketForMessageID;
79
+ this._notifyResponseIdSent = notifyResponseIdSent;
80
+ this._getWebSocketForGetRequest = () => null;
86
81
  }
87
82
  async start() {
88
- if (__privateGet(this, _started2)) {
83
+ if (this._started) {
89
84
  throw new Error("Transport already started");
90
85
  }
91
- __privateSet(this, _started2, true);
86
+ this._started = true;
92
87
  }
93
88
  async send(message) {
94
- if (!__privateGet(this, _started2)) {
89
+ if (!this._started) {
95
90
  throw new Error("Transport not started");
96
91
  }
97
92
  let websocket = null;
98
93
  if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
99
- websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
94
+ websocket = this._getWebSocketForMessageID(message.id.toString());
100
95
  if (!websocket) {
101
96
  throw new Error(
102
97
  `Could not find WebSocket for message id: ${message.id}`
103
98
  );
104
99
  }
105
100
  } else if (isJSONRPCRequest(message)) {
106
- websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
101
+ websocket = this._getWebSocketForGetRequest();
107
102
  } else if (isJSONRPCNotification(message)) {
108
103
  websocket = null;
109
104
  }
110
105
  try {
111
106
  websocket?.send(JSON.stringify(message));
112
107
  if (isJSONRPCResponse(message)) {
113
- __privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
108
+ this._notifyResponseIdSent(message.id.toString());
114
109
  }
115
110
  } catch (error) {
116
111
  this.onerror?.(error);
@@ -121,28 +116,16 @@ var McpStreamableHttpTransport = class {
121
116
  this.onclose?.();
122
117
  }
123
118
  };
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 {
119
+ var McpAgent = class _McpAgent extends DurableObject {
130
120
  constructor(ctx, env) {
131
121
  var _a;
132
122
  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);
123
+ this._status = "zero";
124
+ this._transportType = "unset";
125
+ this._requestIdToConnectionId = /* @__PURE__ */ new Map();
143
126
  this.initRun = false;
144
127
  const self = this;
145
- __privateSet(this, _agent, new (_a = class extends Agent {
128
+ this._agent = new (_a = class extends Agent {
146
129
  onStateUpdate(state, source) {
147
130
  return self.onStateUpdate(state, source);
148
131
  }
@@ -151,26 +134,66 @@ var _McpAgent = class _McpAgent extends DurableObject {
151
134
  }
152
135
  }, _a.options = {
153
136
  hibernate: true
154
- }, _a)(ctx, env));
137
+ }, _a)(ctx, env);
155
138
  }
156
139
  get mcp() {
157
- return __privateGet(this, _agent).mcp;
140
+ return this._agent.mcp;
158
141
  }
159
142
  get state() {
160
- return __privateGet(this, _agent).state;
143
+ return this._agent.state;
161
144
  }
162
145
  sql(strings, ...values) {
163
- return __privateGet(this, _agent).sql(strings, ...values);
146
+ return this._agent.sql(strings, ...values);
164
147
  }
165
148
  setState(state) {
166
- return __privateGet(this, _agent).setState(state);
149
+ return this._agent.setState(state);
167
150
  }
151
+ /**
152
+ * Elicit user input with a message and schema
153
+ */
154
+ async elicitInput(params) {
155
+ const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
156
+ await this.ctx.storage.put(`elicitation:${requestId}`, {
157
+ message: params.message,
158
+ requestedSchema: params.requestedSchema,
159
+ timestamp: Date.now()
160
+ });
161
+ const elicitRequest = {
162
+ jsonrpc: "2.0",
163
+ id: requestId,
164
+ method: "elicitation/create",
165
+ params: {
166
+ message: params.message,
167
+ requestedSchema: params.requestedSchema
168
+ }
169
+ };
170
+ if (this._transport) {
171
+ await this._transport.send(elicitRequest);
172
+ } else {
173
+ const connections = this._agent?.getConnections();
174
+ if (!connections || Array.from(connections).length === 0) {
175
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
176
+ throw new Error("No active connections available for elicitation");
177
+ }
178
+ const connectionList = Array.from(connections);
179
+ for (const connection of connectionList) {
180
+ try {
181
+ connection.send(JSON.stringify(elicitRequest));
182
+ } catch (error) {
183
+ console.error("Failed to send elicitation request:", error);
184
+ }
185
+ }
186
+ }
187
+ return this._waitForElicitationResponse(requestId);
188
+ }
189
+ // we leave the variables as unused for autocomplete purposes
190
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
168
191
  onStateUpdate(state, source) {
169
192
  }
170
193
  async onStart() {
171
194
  var _a;
172
195
  const self = this;
173
- __privateSet(this, _agent, new (_a = class extends Agent {
196
+ this._agent = new (_a = class extends Agent {
174
197
  constructor() {
175
198
  super(...arguments);
176
199
  this.initialState = self.initialState;
@@ -183,33 +206,50 @@ var _McpAgent = class _McpAgent extends DurableObject {
183
206
  }
184
207
  }, _a.options = {
185
208
  hibernate: true
186
- }, _a)(this.ctx, this.env));
209
+ }, _a)(this.ctx, this.env);
187
210
  this.props = await this.ctx.storage.get("props");
188
- __privateSet(this, _transportType, await this.ctx.storage.get(
211
+ this._transportType = await this.ctx.storage.get(
189
212
  "transportType"
190
- ));
213
+ );
191
214
  await this._init(this.props);
192
215
  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(
216
+ if (this._transportType === "sse") {
217
+ this._transport = new McpSSETransport(() => this.getWebSocket());
218
+ await server.connect(this._transport);
219
+ } else if (this._transportType === "streamable-http") {
220
+ this._transport = new McpStreamableHttpTransport(
198
221
  (id) => this.getWebSocketForResponseID(id),
199
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
200
- ));
201
- await server.connect(__privateGet(this, _transport));
222
+ (id) => this._requestIdToConnectionId.delete(id)
223
+ );
224
+ await server.connect(this._transport);
202
225
  }
203
226
  }
227
+ /**
228
+ * Handle errors that occur during initialization or operation.
229
+ * Override this method to provide custom error handling.
230
+ * @param error - The error that occurred
231
+ * @returns An error response object with status code and message
232
+ */
233
+ onError(error) {
234
+ console.error("McpAgent error:", error);
235
+ return {
236
+ status: 500,
237
+ message: error.message || "An unexpected error occurred during initialization"
238
+ };
239
+ }
204
240
  async _init(props) {
205
- await this.ctx.storage.put("props", props ?? {});
241
+ await this.updateProps(props);
206
242
  if (!this.ctx.storage.get("transportType")) {
207
243
  await this.ctx.storage.put("transportType", "unset");
208
244
  }
209
- this.props = props;
210
245
  if (!this.initRun) {
211
246
  this.initRun = true;
212
- await this.init();
247
+ try {
248
+ await this.init();
249
+ } catch (error) {
250
+ const errorResponse = this.onError(error);
251
+ throw new Error(`Initialization failed: ${errorResponse.message}`);
252
+ }
213
253
  }
214
254
  }
215
255
  async setInitialized() {
@@ -218,10 +258,21 @@ var _McpAgent = class _McpAgent extends DurableObject {
218
258
  async isInitialized() {
219
259
  return await this.ctx.storage.get("initialized") === true;
220
260
  }
261
+ async updateProps(props) {
262
+ await this.ctx.storage.put("props", props ?? {});
263
+ this.props = props;
264
+ }
265
+ async _initialize() {
266
+ await this.ctx.blockConcurrencyWhile(async () => {
267
+ this._status = "starting";
268
+ await this.onStart();
269
+ this._status = "started";
270
+ });
271
+ }
221
272
  // Allow the worker to fetch a websocket connection to the agent
222
273
  async fetch(request) {
223
- if (__privateGet(this, _status) !== "started") {
224
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
274
+ if (this._status !== "started") {
275
+ await this._initialize();
225
276
  }
226
277
  if (request.headers.get("Upgrade") !== "websocket") {
227
278
  return new Response("Expected WebSocket Upgrade request", {
@@ -238,24 +289,24 @@ var _McpAgent = class _McpAgent extends DurableObject {
238
289
  return new Response("Websocket already connected", { status: 400 });
239
290
  }
240
291
  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));
292
+ this._transportType = "sse";
293
+ if (!this._transport) {
294
+ this._transport = new McpSSETransport(() => this.getWebSocket());
295
+ await server.connect(this._transport);
245
296
  }
246
- return __privateGet(this, _agent).fetch(request);
297
+ return this._agent.fetch(request);
247
298
  }
248
299
  case "/streamable-http": {
249
- if (!__privateGet(this, _transport)) {
250
- __privateSet(this, _transport, new McpStreamableHttpTransport(
300
+ if (!this._transport) {
301
+ this._transport = new McpStreamableHttpTransport(
251
302
  (id) => this.getWebSocketForResponseID(id),
252
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
253
- ));
254
- await server.connect(__privateGet(this, _transport));
303
+ (id) => this._requestIdToConnectionId.delete(id)
304
+ );
305
+ await server.connect(this._transport);
255
306
  }
256
307
  await this.ctx.storage.put("transportType", "streamable-http");
257
- __privateSet(this, _transportType, "streamable-http");
258
- return __privateGet(this, _agent).fetch(request);
308
+ this._transportType = "streamable-http";
309
+ return this._agent.fetch(request);
259
310
  }
260
311
  default:
261
312
  return new Response(
@@ -274,19 +325,19 @@ var _McpAgent = class _McpAgent extends DurableObject {
274
325
  return websockets[0];
275
326
  }
276
327
  getWebSocketForResponseID(id) {
277
- const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
328
+ const connectionId = this._requestIdToConnectionId.get(id);
278
329
  if (connectionId === void 0) {
279
330
  return null;
280
331
  }
281
- return __privateGet(this, _agent).getConnection(connectionId) ?? null;
332
+ return this._agent.getConnection(connectionId) ?? null;
282
333
  }
283
334
  // All messages received here. This is currently never called
284
335
  async onMessage(connection, event) {
285
- if (__privateGet(this, _transportType) !== "streamable-http") {
336
+ if (this._transportType !== "streamable-http") {
286
337
  const err = new Error(
287
338
  "Internal Server Error: Expected streamable-http protocol"
288
339
  );
289
- __privateGet(this, _transport)?.onerror?.(err);
340
+ this._transport?.onerror?.(err);
290
341
  return;
291
342
  }
292
343
  let message;
@@ -294,59 +345,125 @@ var _McpAgent = class _McpAgent extends DurableObject {
294
345
  const data = typeof event === "string" ? event : new TextDecoder().decode(event);
295
346
  message = JSONRPCMessageSchema.parse(JSON.parse(data));
296
347
  } catch (error) {
297
- __privateGet(this, _transport)?.onerror?.(error);
348
+ this._transport?.onerror?.(error);
349
+ return;
350
+ }
351
+ if (await this._handleElicitationResponse(message)) {
298
352
  return;
299
353
  }
300
354
  if (isJSONRPCRequest(message)) {
301
- __privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
355
+ this._requestIdToConnectionId.set(message.id.toString(), connection.id);
356
+ }
357
+ this._transport?.onmessage?.(message);
358
+ }
359
+ /**
360
+ * Wait for elicitation response through storage polling
361
+ */
362
+ async _waitForElicitationResponse(requestId) {
363
+ const startTime = Date.now();
364
+ const timeout = 6e4;
365
+ try {
366
+ while (Date.now() - startTime < timeout) {
367
+ const response = await this.ctx.storage.get(
368
+ `elicitation:response:${requestId}`
369
+ );
370
+ if (response) {
371
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
372
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
373
+ return response;
374
+ }
375
+ await new Promise((resolve) => setTimeout(resolve, 100));
376
+ }
377
+ throw new Error("Elicitation request timed out");
378
+ } finally {
379
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
380
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
381
+ }
382
+ }
383
+ /**
384
+ * Handle elicitation responses */
385
+ async _handleElicitationResponse(message) {
386
+ if (isJSONRPCResponse(message) && message.result) {
387
+ const requestId = message.id?.toString();
388
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
389
+ const pendingRequest = await this.ctx.storage.get(
390
+ `elicitation:${requestId}`
391
+ );
392
+ if (!pendingRequest) return false;
393
+ await this.ctx.storage.put(
394
+ `elicitation:response:${requestId}`,
395
+ message.result
396
+ );
397
+ return true;
398
+ }
399
+ if (isJSONRPCError(message)) {
400
+ const requestId = message.id?.toString();
401
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
402
+ const pendingRequest = await this.ctx.storage.get(
403
+ `elicitation:${requestId}`
404
+ );
405
+ if (!pendingRequest) return false;
406
+ const errorResult = {
407
+ action: "cancel",
408
+ content: {
409
+ error: message.error.message || "Elicitation request failed"
410
+ }
411
+ };
412
+ await this.ctx.storage.put(
413
+ `elicitation:response:${requestId}`,
414
+ errorResult
415
+ );
416
+ return true;
302
417
  }
303
- __privateGet(this, _transport)?.onmessage?.(message);
418
+ return false;
304
419
  }
305
420
  // All messages received over SSE after the initial connection has been established
306
421
  // 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);
422
+ async onSSEMcpMessage(_sessionId, messageBody) {
423
+ if (this._status !== "started") {
424
+ await this._initialize();
310
425
  }
311
- if (__privateGet(this, _transportType) !== "sse") {
426
+ if (this._transportType !== "sse") {
312
427
  return new Error("Internal Server Error: Expected SSE protocol");
313
428
  }
314
429
  try {
315
- const message = await request.json();
316
430
  let parsedMessage;
317
431
  try {
318
- parsedMessage = JSONRPCMessageSchema.parse(message);
432
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
319
433
  } catch (error) {
320
- __privateGet(this, _transport)?.onerror?.(error);
434
+ this._transport?.onerror?.(error);
321
435
  throw error;
322
436
  }
323
- __privateGet(this, _transport)?.onmessage?.(parsedMessage);
437
+ if (await this._handleElicitationResponse(parsedMessage)) {
438
+ return null;
439
+ }
440
+ this._transport?.onmessage?.(parsedMessage);
324
441
  return null;
325
442
  } catch (error) {
326
443
  console.error("Error forwarding message to SSE:", error);
327
- __privateGet(this, _transport)?.onerror?.(error);
444
+ this._transport?.onerror?.(error);
328
445
  return error;
329
446
  }
330
447
  }
331
448
  // Delegate all websocket events to the underlying agent
332
449
  async webSocketMessage(ws, event) {
333
- if (__privateGet(this, _status) !== "started") {
334
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
450
+ if (this._status !== "started") {
451
+ await this._initialize();
335
452
  }
336
- return await __privateGet(this, _agent).webSocketMessage(ws, event);
453
+ return await this._agent.webSocketMessage(ws, event);
337
454
  }
338
455
  // WebSocket event handlers for hibernation support
339
456
  async webSocketError(ws, error) {
340
- if (__privateGet(this, _status) !== "started") {
341
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
457
+ if (this._status !== "started") {
458
+ await this._initialize();
342
459
  }
343
- return await __privateGet(this, _agent).webSocketError(ws, error);
460
+ return await this._agent.webSocketError(ws, error);
344
461
  }
345
462
  async webSocketClose(ws, code, reason, wasClean) {
346
- if (__privateGet(this, _status) !== "started") {
347
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
463
+ if (this._status !== "started") {
464
+ await this._initialize();
348
465
  }
349
- return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
466
+ return await this._agent.webSocketClose(ws, code, reason, wasClean);
350
467
  }
351
468
  static mount(path, {
352
469
  binding = "MCP_OBJECT",
@@ -376,7 +493,7 @@ var _McpAgent = class _McpAgent extends DurableObject {
376
493
  );
377
494
  return new Response("Invalid binding", { status: 500 });
378
495
  }
379
- if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
496
+ if (!isDurableObjectNamespace(bindingValue)) {
380
497
  return new Response("Invalid binding", { status: 500 });
381
498
  }
382
499
  const namespace = bindingValue;
@@ -396,12 +513,26 @@ data: ${relativeUrlWithSession}
396
513
  writer.write(encoder.encode(endpointMessage));
397
514
  const id = namespace.idFromName(`sse:${sessionId}`);
398
515
  const doStub = namespace.get(id);
399
- await doStub._init(ctx.props);
516
+ try {
517
+ await doStub._init(ctx.props);
518
+ } catch (error) {
519
+ console.error("Failed to initialize McpAgent:", error);
520
+ await writer.close();
521
+ const errorMessage = error instanceof Error ? error.message : String(error);
522
+ return new Response(`Initialization failed: ${errorMessage}`, {
523
+ status: 500
524
+ });
525
+ }
400
526
  const upgradeUrl = new URL(request.url);
401
527
  upgradeUrl.pathname = "/sse";
528
+ const existingHeaders = {};
529
+ request.headers.forEach((value, key) => {
530
+ existingHeaders[key] = value;
531
+ });
402
532
  const response = await doStub.fetch(
403
533
  new Request(upgradeUrl, {
404
534
  headers: {
535
+ ...existingHeaders,
405
536
  Upgrade: "websocket",
406
537
  // Required by PartyServer
407
538
  "x-partykit-room": sessionId
@@ -437,10 +568,10 @@ data: ${JSON.stringify(result.data)}
437
568
  onMessage(event).catch(console.error);
438
569
  });
439
570
  ws.addEventListener("error", (error) => {
440
- async function onError(error2) {
571
+ async function onError(_error) {
441
572
  try {
442
573
  await writer.close();
443
- } catch (e) {
574
+ } catch (_e) {
444
575
  }
445
576
  }
446
577
  onError(error).catch(console.error);
@@ -457,10 +588,10 @@ data: ${JSON.stringify(result.data)}
457
588
  });
458
589
  return new Response(readable, {
459
590
  headers: {
460
- "Content-Type": "text/event-stream",
461
591
  "Cache-Control": "no-cache",
462
592
  Connection: "keep-alive",
463
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
593
+ "Content-Type": "text/event-stream",
594
+ ...corsHeaders(request, corsOptions)
464
595
  }
465
596
  });
466
597
  }
@@ -492,26 +623,28 @@ data: ${JSON.stringify(result.data)}
492
623
  }
493
624
  const id = namespace.idFromName(`sse:${sessionId}`);
494
625
  const doStub = namespace.get(id);
495
- const error = await doStub.onSSEMcpMessage(sessionId, request);
626
+ const messageBody = await request.json();
627
+ await doStub.updateProps(ctx.props);
628
+ const error = await doStub.onSSEMcpMessage(sessionId, messageBody);
496
629
  if (error) {
497
630
  return new Response(error.message, {
498
- status: 400,
499
631
  headers: {
500
- "Content-Type": "text/event-stream",
501
632
  "Cache-Control": "no-cache",
502
633
  Connection: "keep-alive",
503
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
504
- }
634
+ "Content-Type": "text/event-stream",
635
+ ...corsHeaders(request, corsOptions)
636
+ },
637
+ status: 400
505
638
  });
506
639
  }
507
640
  return new Response("Accepted", {
508
- status: 202,
509
641
  headers: {
510
- "Content-Type": "text/event-stream",
511
642
  "Cache-Control": "no-cache",
512
643
  Connection: "keep-alive",
513
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
514
- }
644
+ "Content-Type": "text/event-stream",
645
+ ...corsHeaders(request, corsOptions)
646
+ },
647
+ status: 202
515
648
  });
516
649
  }
517
650
  return new Response("Not Found", { status: 404 });
@@ -541,7 +674,7 @@ data: ${JSON.stringify(result.data)}
541
674
  );
542
675
  return new Response("Invalid binding", { status: 500 });
543
676
  }
544
- if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
677
+ if (!isDurableObjectNamespace(bindingValue)) {
545
678
  return new Response("Invalid binding", { status: 500 });
546
679
  }
547
680
  const namespace = bindingValue;
@@ -549,24 +682,24 @@ data: ${JSON.stringify(result.data)}
549
682
  const acceptHeader = request.headers.get("accept");
550
683
  if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
551
684
  const body2 = JSON.stringify({
552
- jsonrpc: "2.0",
553
685
  error: {
554
686
  code: -32e3,
555
687
  message: "Not Acceptable: Client must accept both application/json and text/event-stream"
556
688
  },
557
- id: null
689
+ id: null,
690
+ jsonrpc: "2.0"
558
691
  });
559
692
  return new Response(body2, { status: 406 });
560
693
  }
561
694
  const ct = request.headers.get("content-type");
562
695
  if (!ct || !ct.includes("application/json")) {
563
696
  const body2 = JSON.stringify({
564
- jsonrpc: "2.0",
565
697
  error: {
566
698
  code: -32e3,
567
699
  message: "Unsupported Media Type: Content-Type must be application/json"
568
700
  },
569
- id: null
701
+ id: null,
702
+ jsonrpc: "2.0"
570
703
  });
571
704
  return new Response(body2, { status: 415 });
572
705
  }
@@ -576,12 +709,12 @@ data: ${JSON.stringify(result.data)}
576
709
  );
577
710
  if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
578
711
  const body2 = JSON.stringify({
579
- jsonrpc: "2.0",
580
712
  error: {
581
713
  code: -32e3,
582
714
  message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
583
715
  },
584
- id: null
716
+ id: null,
717
+ jsonrpc: "2.0"
585
718
  });
586
719
  return new Response(body2, { status: 413 });
587
720
  }
@@ -589,14 +722,14 @@ data: ${JSON.stringify(result.data)}
589
722
  let rawMessage;
590
723
  try {
591
724
  rawMessage = await request.json();
592
- } catch (error) {
725
+ } catch (_error) {
593
726
  const body2 = JSON.stringify({
594
- jsonrpc: "2.0",
595
727
  error: {
596
728
  code: -32700,
597
729
  message: "Parse error: Invalid JSON"
598
730
  },
599
- id: null
731
+ id: null,
732
+ jsonrpc: "2.0"
600
733
  });
601
734
  return new Response(body2, { status: 400 });
602
735
  }
@@ -610,12 +743,12 @@ data: ${JSON.stringify(result.data)}
610
743
  for (const msg of arrayMessage) {
611
744
  if (!JSONRPCMessageSchema.safeParse(msg).success) {
612
745
  const body2 = JSON.stringify({
613
- jsonrpc: "2.0",
614
746
  error: {
615
747
  code: -32700,
616
748
  message: "Parse error: Invalid JSON-RPC message"
617
749
  },
618
- id: null
750
+ id: null,
751
+ jsonrpc: "2.0"
619
752
  });
620
753
  return new Response(body2, { status: 400 });
621
754
  }
@@ -626,34 +759,34 @@ data: ${JSON.stringify(result.data)}
626
759
  );
627
760
  if (isInitializationRequest && sessionId) {
628
761
  const body2 = JSON.stringify({
629
- jsonrpc: "2.0",
630
762
  error: {
631
763
  code: -32600,
632
764
  message: "Invalid Request: Initialization requests must not include a sessionId"
633
765
  },
634
- id: null
766
+ id: null,
767
+ jsonrpc: "2.0"
635
768
  });
636
769
  return new Response(body2, { status: 400 });
637
770
  }
638
771
  if (isInitializationRequest && messages.length > 1) {
639
772
  const body2 = JSON.stringify({
640
- jsonrpc: "2.0",
641
773
  error: {
642
774
  code: -32600,
643
775
  message: "Invalid Request: Only one initialization request is allowed"
644
776
  },
645
- id: null
777
+ id: null,
778
+ jsonrpc: "2.0"
646
779
  });
647
780
  return new Response(body2, { status: 400 });
648
781
  }
649
782
  if (!isInitializationRequest && !sessionId) {
650
783
  const body2 = JSON.stringify({
651
- jsonrpc: "2.0",
652
784
  error: {
653
785
  code: -32e3,
654
786
  message: "Bad Request: Mcp-Session-Id header is required"
655
787
  },
656
- id: null
788
+ id: null,
789
+ jsonrpc: "2.0"
657
790
  });
658
791
  return new Response(body2, { status: 400 });
659
792
  }
@@ -662,27 +795,48 @@ data: ${JSON.stringify(result.data)}
662
795
  const doStub = namespace.get(id);
663
796
  const isInitialized = await doStub.isInitialized();
664
797
  if (isInitializationRequest) {
665
- await doStub._init(ctx.props);
666
- await doStub.setInitialized();
798
+ try {
799
+ await doStub._init(ctx.props);
800
+ await doStub.setInitialized();
801
+ } catch (error) {
802
+ console.error("Failed to initialize McpAgent:", error);
803
+ const errorMessage = error instanceof Error ? error.message : String(error);
804
+ const body2 = JSON.stringify({
805
+ error: {
806
+ code: -32001,
807
+ message: `Initialization failed: ${errorMessage}`
808
+ },
809
+ id: null,
810
+ jsonrpc: "2.0"
811
+ });
812
+ return new Response(body2, { status: 500 });
813
+ }
667
814
  } else if (!isInitialized) {
668
815
  const body2 = JSON.stringify({
669
- jsonrpc: "2.0",
670
816
  error: {
671
817
  code: -32001,
672
818
  message: "Session not found"
673
819
  },
674
- id: null
820
+ id: null,
821
+ jsonrpc: "2.0"
675
822
  });
676
823
  return new Response(body2, { status: 404 });
824
+ } else {
825
+ await doStub.updateProps(ctx.props);
677
826
  }
678
827
  const { readable, writable } = new TransformStream();
679
828
  const writer = writable.getWriter();
680
829
  const encoder = new TextEncoder();
681
830
  const upgradeUrl = new URL(request.url);
682
831
  upgradeUrl.pathname = "/streamable-http";
832
+ const existingHeaders = {};
833
+ request.headers.forEach((value, key) => {
834
+ existingHeaders[key] = value;
835
+ });
683
836
  const response = await doStub.fetch(
684
837
  new Request(upgradeUrl, {
685
838
  headers: {
839
+ ...existingHeaders,
686
840
  Upgrade: "websocket",
687
841
  // Required by PartyServer
688
842
  "x-partykit-room": sessionId
@@ -694,12 +848,12 @@ data: ${JSON.stringify(result.data)}
694
848
  console.error("Failed to establish WebSocket connection");
695
849
  await writer.close();
696
850
  const body2 = JSON.stringify({
697
- jsonrpc: "2.0",
698
851
  error: {
699
852
  code: -32001,
700
853
  message: "Failed to establish WebSocket connection"
701
854
  },
702
- id: null
855
+ id: null,
856
+ jsonrpc: "2.0"
703
857
  });
704
858
  return new Response(body2, { status: 500 });
705
859
  }
@@ -732,10 +886,10 @@ data: ${JSON.stringify(result.data)}
732
886
  onMessage(event).catch(console.error);
733
887
  });
734
888
  ws.addEventListener("error", (error) => {
735
- async function onError(error2) {
889
+ async function onError(_error) {
736
890
  try {
737
891
  await writer.close();
738
- } catch (e) {
892
+ } catch (_e) {
739
893
  }
740
894
  }
741
895
  onError(error).catch(console.error);
@@ -758,7 +912,10 @@ data: ${JSON.stringify(result.data)}
758
912
  ws.send(JSON.stringify(message));
759
913
  }
760
914
  ws.close();
761
- return new Response(null, { status: 202 });
915
+ return new Response(null, {
916
+ headers: corsHeaders(request, corsOptions),
917
+ status: 202
918
+ });
762
919
  }
763
920
  for (const message of messages) {
764
921
  if (isJSONRPCRequest(message)) {
@@ -768,43 +925,32 @@ data: ${JSON.stringify(result.data)}
768
925
  }
769
926
  return new Response(readable, {
770
927
  headers: {
771
- "Content-Type": "text/event-stream",
772
928
  "Cache-Control": "no-cache",
773
929
  Connection: "keep-alive",
930
+ "Content-Type": "text/event-stream",
774
931
  "mcp-session-id": sessionId,
775
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
932
+ ...corsHeaders(request, corsOptions)
776
933
  },
777
934
  status: 200
778
935
  });
779
936
  }
780
937
  const body = JSON.stringify({
781
- jsonrpc: "2.0",
782
938
  error: {
783
939
  code: -32e3,
784
940
  message: "Method not allowed"
785
941
  },
786
- id: null
942
+ id: null,
943
+ jsonrpc: "2.0"
787
944
  });
788
945
  return new Response(body, { status: 405 });
789
946
  }
790
947
  };
791
948
  }
792
949
  };
793
- _status = new WeakMap();
794
- _transport = new WeakMap();
795
- _transportType = new WeakMap();
796
- _requestIdToConnectionId = new WeakMap();
797
- _agent = new WeakMap();
798
- _McpAgent_instances = new WeakSet();
799
- initialize_fn = async function() {
800
- await this.ctx.blockConcurrencyWhile(async () => {
801
- __privateSet(this, _status, "starting");
802
- await this.onStart();
803
- __privateSet(this, _status, "started");
804
- });
805
- };
806
- var McpAgent = _McpAgent;
807
950
  export {
808
- McpAgent
951
+ ElicitRequestSchema,
952
+ McpAgent,
953
+ SSEEdgeClientTransport,
954
+ StreamableHTTPEdgeClientTransport
809
955
  };
810
956
  //# sourceMappingURL=index.js.map