agents 0.0.0-fe9e8d3 → 0.0.0-feef082

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 -54
  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-LL2AFX7V.js +109 -0
  15. package/dist/chunk-LL2AFX7V.js.map +1 -0
  16. package/dist/chunk-PNF6ZMUA.js +1296 -0
  17. package/dist/chunk-PNF6ZMUA.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 +4 -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 +52 -14
  36. package/dist/mcp/index.js +331 -183
  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 -67
  51. package/src/index.ts +1147 -151
  52. package/dist/chunk-HD4VEHBA.js +0 -608
  53. package/dist/chunk-HD4VEHBA.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-HD4VEHBA.js";
4
- import "../chunk-Q5ZBHY4Z.js";
3
+ } from "../chunk-PNF6ZMUA.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-LL2AFX7V.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,58 +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
- __privateGet(this, _transport)?.onerror?.(error);
443
+ console.error("Error forwarding message to SSE:", error);
444
+ this._transport?.onerror?.(error);
327
445
  return error;
328
446
  }
329
447
  }
330
448
  // Delegate all websocket events to the underlying agent
331
449
  async webSocketMessage(ws, event) {
332
- if (__privateGet(this, _status) !== "started") {
333
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
450
+ if (this._status !== "started") {
451
+ await this._initialize();
334
452
  }
335
- return await __privateGet(this, _agent).webSocketMessage(ws, event);
453
+ return await this._agent.webSocketMessage(ws, event);
336
454
  }
337
455
  // WebSocket event handlers for hibernation support
338
456
  async webSocketError(ws, error) {
339
- if (__privateGet(this, _status) !== "started") {
340
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
457
+ if (this._status !== "started") {
458
+ await this._initialize();
341
459
  }
342
- return await __privateGet(this, _agent).webSocketError(ws, error);
460
+ return await this._agent.webSocketError(ws, error);
343
461
  }
344
462
  async webSocketClose(ws, code, reason, wasClean) {
345
- if (__privateGet(this, _status) !== "started") {
346
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
463
+ if (this._status !== "started") {
464
+ await this._initialize();
347
465
  }
348
- return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
466
+ return await this._agent.webSocketClose(ws, code, reason, wasClean);
349
467
  }
350
468
  static mount(path, {
351
469
  binding = "MCP_OBJECT",
@@ -375,7 +493,7 @@ var _McpAgent = class _McpAgent extends DurableObject {
375
493
  );
376
494
  return new Response("Invalid binding", { status: 500 });
377
495
  }
378
- if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
496
+ if (!isDurableObjectNamespace(bindingValue)) {
379
497
  return new Response("Invalid binding", { status: 500 });
380
498
  }
381
499
  const namespace = bindingValue;
@@ -395,12 +513,26 @@ data: ${relativeUrlWithSession}
395
513
  writer.write(encoder.encode(endpointMessage));
396
514
  const id = namespace.idFromName(`sse:${sessionId}`);
397
515
  const doStub = namespace.get(id);
398
- 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
+ }
399
526
  const upgradeUrl = new URL(request.url);
400
527
  upgradeUrl.pathname = "/sse";
528
+ const existingHeaders = {};
529
+ request.headers.forEach((value, key) => {
530
+ existingHeaders[key] = value;
531
+ });
401
532
  const response = await doStub.fetch(
402
533
  new Request(upgradeUrl, {
403
534
  headers: {
535
+ ...existingHeaders,
404
536
  Upgrade: "websocket",
405
537
  // Required by PartyServer
406
538
  "x-partykit-room": sessionId
@@ -436,10 +568,10 @@ data: ${JSON.stringify(result.data)}
436
568
  onMessage(event).catch(console.error);
437
569
  });
438
570
  ws.addEventListener("error", (error) => {
439
- async function onError(error2) {
571
+ async function onError(_error) {
440
572
  try {
441
573
  await writer.close();
442
- } catch (e) {
574
+ } catch (_e) {
443
575
  }
444
576
  }
445
577
  onError(error).catch(console.error);
@@ -456,10 +588,10 @@ data: ${JSON.stringify(result.data)}
456
588
  });
457
589
  return new Response(readable, {
458
590
  headers: {
459
- "Content-Type": "text/event-stream",
460
591
  "Cache-Control": "no-cache",
461
592
  Connection: "keep-alive",
462
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
593
+ "Content-Type": "text/event-stream",
594
+ ...corsHeaders(request, corsOptions)
463
595
  }
464
596
  });
465
597
  }
@@ -491,26 +623,28 @@ data: ${JSON.stringify(result.data)}
491
623
  }
492
624
  const id = namespace.idFromName(`sse:${sessionId}`);
493
625
  const doStub = namespace.get(id);
494
- 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);
495
629
  if (error) {
496
630
  return new Response(error.message, {
497
- status: 400,
498
631
  headers: {
499
- "Content-Type": "text/event-stream",
500
632
  "Cache-Control": "no-cache",
501
633
  Connection: "keep-alive",
502
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
503
- }
634
+ "Content-Type": "text/event-stream",
635
+ ...corsHeaders(request, corsOptions)
636
+ },
637
+ status: 400
504
638
  });
505
639
  }
506
640
  return new Response("Accepted", {
507
- status: 202,
508
641
  headers: {
509
- "Content-Type": "text/event-stream",
510
642
  "Cache-Control": "no-cache",
511
643
  Connection: "keep-alive",
512
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
513
- }
644
+ "Content-Type": "text/event-stream",
645
+ ...corsHeaders(request, corsOptions)
646
+ },
647
+ status: 202
514
648
  });
515
649
  }
516
650
  return new Response("Not Found", { status: 404 });
@@ -540,7 +674,7 @@ data: ${JSON.stringify(result.data)}
540
674
  );
541
675
  return new Response("Invalid binding", { status: 500 });
542
676
  }
543
- if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
677
+ if (!isDurableObjectNamespace(bindingValue)) {
544
678
  return new Response("Invalid binding", { status: 500 });
545
679
  }
546
680
  const namespace = bindingValue;
@@ -548,24 +682,24 @@ data: ${JSON.stringify(result.data)}
548
682
  const acceptHeader = request.headers.get("accept");
549
683
  if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
550
684
  const body2 = JSON.stringify({
551
- jsonrpc: "2.0",
552
685
  error: {
553
686
  code: -32e3,
554
687
  message: "Not Acceptable: Client must accept both application/json and text/event-stream"
555
688
  },
556
- id: null
689
+ id: null,
690
+ jsonrpc: "2.0"
557
691
  });
558
692
  return new Response(body2, { status: 406 });
559
693
  }
560
694
  const ct = request.headers.get("content-type");
561
695
  if (!ct || !ct.includes("application/json")) {
562
696
  const body2 = JSON.stringify({
563
- jsonrpc: "2.0",
564
697
  error: {
565
698
  code: -32e3,
566
699
  message: "Unsupported Media Type: Content-Type must be application/json"
567
700
  },
568
- id: null
701
+ id: null,
702
+ jsonrpc: "2.0"
569
703
  });
570
704
  return new Response(body2, { status: 415 });
571
705
  }
@@ -575,12 +709,12 @@ data: ${JSON.stringify(result.data)}
575
709
  );
576
710
  if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
577
711
  const body2 = JSON.stringify({
578
- jsonrpc: "2.0",
579
712
  error: {
580
713
  code: -32e3,
581
714
  message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
582
715
  },
583
- id: null
716
+ id: null,
717
+ jsonrpc: "2.0"
584
718
  });
585
719
  return new Response(body2, { status: 413 });
586
720
  }
@@ -588,14 +722,14 @@ data: ${JSON.stringify(result.data)}
588
722
  let rawMessage;
589
723
  try {
590
724
  rawMessage = await request.json();
591
- } catch (error) {
725
+ } catch (_error) {
592
726
  const body2 = JSON.stringify({
593
- jsonrpc: "2.0",
594
727
  error: {
595
728
  code: -32700,
596
729
  message: "Parse error: Invalid JSON"
597
730
  },
598
- id: null
731
+ id: null,
732
+ jsonrpc: "2.0"
599
733
  });
600
734
  return new Response(body2, { status: 400 });
601
735
  }
@@ -609,12 +743,12 @@ data: ${JSON.stringify(result.data)}
609
743
  for (const msg of arrayMessage) {
610
744
  if (!JSONRPCMessageSchema.safeParse(msg).success) {
611
745
  const body2 = JSON.stringify({
612
- jsonrpc: "2.0",
613
746
  error: {
614
747
  code: -32700,
615
748
  message: "Parse error: Invalid JSON-RPC message"
616
749
  },
617
- id: null
750
+ id: null,
751
+ jsonrpc: "2.0"
618
752
  });
619
753
  return new Response(body2, { status: 400 });
620
754
  }
@@ -625,34 +759,34 @@ data: ${JSON.stringify(result.data)}
625
759
  );
626
760
  if (isInitializationRequest && sessionId) {
627
761
  const body2 = JSON.stringify({
628
- jsonrpc: "2.0",
629
762
  error: {
630
763
  code: -32600,
631
764
  message: "Invalid Request: Initialization requests must not include a sessionId"
632
765
  },
633
- id: null
766
+ id: null,
767
+ jsonrpc: "2.0"
634
768
  });
635
769
  return new Response(body2, { status: 400 });
636
770
  }
637
771
  if (isInitializationRequest && messages.length > 1) {
638
772
  const body2 = JSON.stringify({
639
- jsonrpc: "2.0",
640
773
  error: {
641
774
  code: -32600,
642
775
  message: "Invalid Request: Only one initialization request is allowed"
643
776
  },
644
- id: null
777
+ id: null,
778
+ jsonrpc: "2.0"
645
779
  });
646
780
  return new Response(body2, { status: 400 });
647
781
  }
648
782
  if (!isInitializationRequest && !sessionId) {
649
783
  const body2 = JSON.stringify({
650
- jsonrpc: "2.0",
651
784
  error: {
652
785
  code: -32e3,
653
786
  message: "Bad Request: Mcp-Session-Id header is required"
654
787
  },
655
- id: null
788
+ id: null,
789
+ jsonrpc: "2.0"
656
790
  });
657
791
  return new Response(body2, { status: 400 });
658
792
  }
@@ -661,26 +795,48 @@ data: ${JSON.stringify(result.data)}
661
795
  const doStub = namespace.get(id);
662
796
  const isInitialized = await doStub.isInitialized();
663
797
  if (isInitializationRequest) {
664
- 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
+ }
665
814
  } else if (!isInitialized) {
666
815
  const body2 = JSON.stringify({
667
- jsonrpc: "2.0",
668
816
  error: {
669
817
  code: -32001,
670
818
  message: "Session not found"
671
819
  },
672
- id: null
820
+ id: null,
821
+ jsonrpc: "2.0"
673
822
  });
674
823
  return new Response(body2, { status: 404 });
824
+ } else {
825
+ await doStub.updateProps(ctx.props);
675
826
  }
676
827
  const { readable, writable } = new TransformStream();
677
828
  const writer = writable.getWriter();
678
829
  const encoder = new TextEncoder();
679
830
  const upgradeUrl = new URL(request.url);
680
831
  upgradeUrl.pathname = "/streamable-http";
832
+ const existingHeaders = {};
833
+ request.headers.forEach((value, key) => {
834
+ existingHeaders[key] = value;
835
+ });
681
836
  const response = await doStub.fetch(
682
837
  new Request(upgradeUrl, {
683
838
  headers: {
839
+ ...existingHeaders,
684
840
  Upgrade: "websocket",
685
841
  // Required by PartyServer
686
842
  "x-partykit-room": sessionId
@@ -692,12 +848,12 @@ data: ${JSON.stringify(result.data)}
692
848
  console.error("Failed to establish WebSocket connection");
693
849
  await writer.close();
694
850
  const body2 = JSON.stringify({
695
- jsonrpc: "2.0",
696
851
  error: {
697
852
  code: -32001,
698
853
  message: "Failed to establish WebSocket connection"
699
854
  },
700
- id: null
855
+ id: null,
856
+ jsonrpc: "2.0"
701
857
  });
702
858
  return new Response(body2, { status: 500 });
703
859
  }
@@ -730,10 +886,10 @@ data: ${JSON.stringify(result.data)}
730
886
  onMessage(event).catch(console.error);
731
887
  });
732
888
  ws.addEventListener("error", (error) => {
733
- async function onError(error2) {
889
+ async function onError(_error) {
734
890
  try {
735
891
  await writer.close();
736
- } catch (e) {
892
+ } catch (_e) {
737
893
  }
738
894
  }
739
895
  onError(error).catch(console.error);
@@ -756,7 +912,10 @@ data: ${JSON.stringify(result.data)}
756
912
  ws.send(JSON.stringify(message));
757
913
  }
758
914
  ws.close();
759
- return new Response(null, { status: 202 });
915
+ return new Response(null, {
916
+ headers: corsHeaders(request, corsOptions),
917
+ status: 202
918
+ });
760
919
  }
761
920
  for (const message of messages) {
762
921
  if (isJSONRPCRequest(message)) {
@@ -766,43 +925,32 @@ data: ${JSON.stringify(result.data)}
766
925
  }
767
926
  return new Response(readable, {
768
927
  headers: {
769
- "Content-Type": "text/event-stream",
770
928
  "Cache-Control": "no-cache",
771
929
  Connection: "keep-alive",
930
+ "Content-Type": "text/event-stream",
772
931
  "mcp-session-id": sessionId,
773
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
932
+ ...corsHeaders(request, corsOptions)
774
933
  },
775
934
  status: 200
776
935
  });
777
936
  }
778
937
  const body = JSON.stringify({
779
- jsonrpc: "2.0",
780
938
  error: {
781
939
  code: -32e3,
782
940
  message: "Method not allowed"
783
941
  },
784
- id: null
942
+ id: null,
943
+ jsonrpc: "2.0"
785
944
  });
786
945
  return new Response(body, { status: 405 });
787
946
  }
788
947
  };
789
948
  }
790
949
  };
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
950
  export {
806
- McpAgent
951
+ ElicitRequestSchema,
952
+ McpAgent,
953
+ SSEEdgeClientTransport,
954
+ StreamableHTTPEdgeClientTransport
807
955
  };
808
956
  //# sourceMappingURL=index.js.map