agents 0.0.0-8d8216c → 0.0.0-8dac62c

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 +49 -12
  3. package/dist/ai-chat-agent.js +259 -91
  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 +166 -53
  9. package/dist/ai-react.js.map +1 -1
  10. package/dist/ai-types.d.ts +40 -18
  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-PUJ7PRRT.js +1299 -0
  15. package/dist/chunk-PUJ7PRRT.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-YZNSS675.js → chunk-VYENMKFS.js} +230 -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 +268 -26
  29. package/dist/index.js +17 -7
  30. package/dist/mcp/client.d.ts +9 -766
  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 +54 -15
  36. package/dist/mcp/index.js +355 -185
  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 +1173 -154
  52. package/dist/chunk-AV3OMRR4.js +0 -597
  53. package/dist/chunk-AV3OMRR4.js.map +0 -1
  54. package/dist/chunk-HMLY7DHA.js +0 -16
  55. package/dist/chunk-YZNSS675.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-AV3OMRR4.js";
4
- import "../chunk-YZNSS675.js";
3
+ } from "../chunk-PUJ7PRRT.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);
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);
167
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,32 +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
- if (__privateGet(this, _transportType) === "sse") {
193
- __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
194
- await this.server.connect(__privateGet(this, _transport));
195
- } else if (__privateGet(this, _transportType) === "streamable-http") {
196
- __privateSet(this, _transport, new McpStreamableHttpTransport(
215
+ const server = await this.server;
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(
197
221
  (id) => this.getWebSocketForResponseID(id),
198
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
199
- ));
200
- await this.server.connect(__privateGet(this, _transport));
222
+ (id) => this._requestIdToConnectionId.delete(id)
223
+ );
224
+ await server.connect(this._transport);
201
225
  }
202
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
+ }
203
240
  async _init(props) {
204
- await this.ctx.storage.put("props", props ?? {});
241
+ await this.updateProps(props);
205
242
  if (!this.ctx.storage.get("transportType")) {
206
243
  await this.ctx.storage.put("transportType", "unset");
207
244
  }
208
- this.props = props;
209
245
  if (!this.initRun) {
210
246
  this.initRun = true;
211
- 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
+ }
212
253
  }
213
254
  }
214
255
  async setInitialized() {
@@ -217,10 +258,21 @@ var _McpAgent = class _McpAgent extends DurableObject {
217
258
  async isInitialized() {
218
259
  return await this.ctx.storage.get("initialized") === true;
219
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
+ }
220
272
  // Allow the worker to fetch a websocket connection to the agent
221
273
  async fetch(request) {
222
- if (__privateGet(this, _status) !== "started") {
223
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
274
+ if (this._status !== "started") {
275
+ await this._initialize();
224
276
  }
225
277
  if (request.headers.get("Upgrade") !== "websocket") {
226
278
  return new Response("Expected WebSocket Upgrade request", {
@@ -229,6 +281,7 @@ var _McpAgent = class _McpAgent extends DurableObject {
229
281
  }
230
282
  const url = new URL(request.url);
231
283
  const path = url.pathname;
284
+ const server = await this.server;
232
285
  switch (path) {
233
286
  case "/sse": {
234
287
  const websockets = this.ctx.getWebSockets();
@@ -236,24 +289,24 @@ var _McpAgent = class _McpAgent extends DurableObject {
236
289
  return new Response("Websocket already connected", { status: 400 });
237
290
  }
238
291
  await this.ctx.storage.put("transportType", "sse");
239
- __privateSet(this, _transportType, "sse");
240
- if (!__privateGet(this, _transport)) {
241
- __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
242
- await this.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);
243
296
  }
244
- return __privateGet(this, _agent).fetch(request);
297
+ return this._agent.fetch(request);
245
298
  }
246
299
  case "/streamable-http": {
247
- if (!__privateGet(this, _transport)) {
248
- __privateSet(this, _transport, new McpStreamableHttpTransport(
300
+ if (!this._transport) {
301
+ this._transport = new McpStreamableHttpTransport(
249
302
  (id) => this.getWebSocketForResponseID(id),
250
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
251
- ));
252
- await this.server.connect(__privateGet(this, _transport));
303
+ (id) => this._requestIdToConnectionId.delete(id)
304
+ );
305
+ await server.connect(this._transport);
253
306
  }
254
307
  await this.ctx.storage.put("transportType", "streamable-http");
255
- __privateSet(this, _transportType, "streamable-http");
256
- return __privateGet(this, _agent).fetch(request);
308
+ this._transportType = "streamable-http";
309
+ return this._agent.fetch(request);
257
310
  }
258
311
  default:
259
312
  return new Response(
@@ -272,19 +325,19 @@ var _McpAgent = class _McpAgent extends DurableObject {
272
325
  return websockets[0];
273
326
  }
274
327
  getWebSocketForResponseID(id) {
275
- const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
328
+ const connectionId = this._requestIdToConnectionId.get(id);
276
329
  if (connectionId === void 0) {
277
330
  return null;
278
331
  }
279
- return __privateGet(this, _agent).getConnection(connectionId) ?? null;
332
+ return this._agent.getConnection(connectionId) ?? null;
280
333
  }
281
334
  // All messages received here. This is currently never called
282
335
  async onMessage(connection, event) {
283
- if (__privateGet(this, _transportType) !== "streamable-http") {
336
+ if (this._transportType !== "streamable-http") {
284
337
  const err = new Error(
285
338
  "Internal Server Error: Expected streamable-http protocol"
286
339
  );
287
- __privateGet(this, _transport)?.onerror?.(err);
340
+ this._transport?.onerror?.(err);
288
341
  return;
289
342
  }
290
343
  let message;
@@ -292,58 +345,125 @@ var _McpAgent = class _McpAgent extends DurableObject {
292
345
  const data = typeof event === "string" ? event : new TextDecoder().decode(event);
293
346
  message = JSONRPCMessageSchema.parse(JSON.parse(data));
294
347
  } catch (error) {
295
- __privateGet(this, _transport)?.onerror?.(error);
348
+ this._transport?.onerror?.(error);
349
+ return;
350
+ }
351
+ if (await this._handleElicitationResponse(message)) {
296
352
  return;
297
353
  }
298
354
  if (isJSONRPCRequest(message)) {
299
- __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;
300
417
  }
301
- __privateGet(this, _transport)?.onmessage?.(message);
418
+ return false;
302
419
  }
303
420
  // All messages received over SSE after the initial connection has been established
304
421
  // will be passed here
305
- async onSSEMcpMessage(sessionId, request) {
306
- if (__privateGet(this, _status) !== "started") {
307
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
422
+ async onSSEMcpMessage(_sessionId, messageBody) {
423
+ if (this._status !== "started") {
424
+ await this._initialize();
308
425
  }
309
- if (__privateGet(this, _transportType) !== "sse") {
426
+ if (this._transportType !== "sse") {
310
427
  return new Error("Internal Server Error: Expected SSE protocol");
311
428
  }
312
429
  try {
313
- const message = await request.json();
314
430
  let parsedMessage;
315
431
  try {
316
- parsedMessage = JSONRPCMessageSchema.parse(message);
432
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
317
433
  } catch (error) {
318
- __privateGet(this, _transport)?.onerror?.(error);
434
+ this._transport?.onerror?.(error);
319
435
  throw error;
320
436
  }
321
- __privateGet(this, _transport)?.onmessage?.(parsedMessage);
437
+ if (await this._handleElicitationResponse(parsedMessage)) {
438
+ return null;
439
+ }
440
+ this._transport?.onmessage?.(parsedMessage);
322
441
  return null;
323
442
  } catch (error) {
324
- __privateGet(this, _transport)?.onerror?.(error);
443
+ console.error("Error forwarding message to SSE:", error);
444
+ this._transport?.onerror?.(error);
325
445
  return error;
326
446
  }
327
447
  }
328
448
  // Delegate all websocket events to the underlying agent
329
449
  async webSocketMessage(ws, event) {
330
- if (__privateGet(this, _status) !== "started") {
331
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
450
+ if (this._status !== "started") {
451
+ await this._initialize();
332
452
  }
333
- return await __privateGet(this, _agent).webSocketMessage(ws, event);
453
+ return await this._agent.webSocketMessage(ws, event);
334
454
  }
335
455
  // WebSocket event handlers for hibernation support
336
456
  async webSocketError(ws, error) {
337
- if (__privateGet(this, _status) !== "started") {
338
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
457
+ if (this._status !== "started") {
458
+ await this._initialize();
339
459
  }
340
- return await __privateGet(this, _agent).webSocketError(ws, error);
460
+ return await this._agent.webSocketError(ws, error);
341
461
  }
342
462
  async webSocketClose(ws, code, reason, wasClean) {
343
- if (__privateGet(this, _status) !== "started") {
344
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
463
+ if (this._status !== "started") {
464
+ await this._initialize();
345
465
  }
346
- return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
466
+ return await this._agent.webSocketClose(ws, code, reason, wasClean);
347
467
  }
348
468
  static mount(path, {
349
469
  binding = "MCP_OBJECT",
@@ -362,11 +482,21 @@ var _McpAgent = class _McpAgent extends DurableObject {
362
482
  const basePattern = new URLPattern({ pathname });
363
483
  const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
364
484
  return {
365
- fetch: async (request, env, ctx) => {
485
+ async fetch(request, env, ctx) {
366
486
  const corsResponse = handleCORS(request, corsOptions);
367
487
  if (corsResponse) return corsResponse;
368
488
  const url = new URL(request.url);
369
- const namespace = env[binding];
489
+ const bindingValue = env[binding];
490
+ if (bindingValue == null || typeof bindingValue !== "object") {
491
+ console.error(
492
+ `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
493
+ );
494
+ return new Response("Invalid binding", { status: 500 });
495
+ }
496
+ if (!isDurableObjectNamespace(bindingValue)) {
497
+ return new Response("Invalid binding", { status: 500 });
498
+ }
499
+ const namespace = bindingValue;
370
500
  if (request.method === "GET" && basePattern.test(url)) {
371
501
  const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
372
502
  const { readable, writable } = new TransformStream();
@@ -383,12 +513,26 @@ data: ${relativeUrlWithSession}
383
513
  writer.write(encoder.encode(endpointMessage));
384
514
  const id = namespace.idFromName(`sse:${sessionId}`);
385
515
  const doStub = namespace.get(id);
386
- 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
+ }
387
526
  const upgradeUrl = new URL(request.url);
388
527
  upgradeUrl.pathname = "/sse";
528
+ const existingHeaders = {};
529
+ request.headers.forEach((value, key) => {
530
+ existingHeaders[key] = value;
531
+ });
389
532
  const response = await doStub.fetch(
390
533
  new Request(upgradeUrl, {
391
534
  headers: {
535
+ ...existingHeaders,
392
536
  Upgrade: "websocket",
393
537
  // Required by PartyServer
394
538
  "x-partykit-room": sessionId
@@ -424,10 +568,10 @@ data: ${JSON.stringify(result.data)}
424
568
  onMessage(event).catch(console.error);
425
569
  });
426
570
  ws.addEventListener("error", (error) => {
427
- async function onError(error2) {
571
+ async function onError(_error) {
428
572
  try {
429
573
  await writer.close();
430
- } catch (e) {
574
+ } catch (_e) {
431
575
  }
432
576
  }
433
577
  onError(error).catch(console.error);
@@ -444,10 +588,10 @@ data: ${JSON.stringify(result.data)}
444
588
  });
445
589
  return new Response(readable, {
446
590
  headers: {
447
- "Content-Type": "text/event-stream",
448
591
  "Cache-Control": "no-cache",
449
592
  Connection: "keep-alive",
450
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
593
+ "Content-Type": "text/event-stream",
594
+ ...corsHeaders(request, corsOptions)
451
595
  }
452
596
  });
453
597
  }
@@ -479,26 +623,28 @@ data: ${JSON.stringify(result.data)}
479
623
  }
480
624
  const id = namespace.idFromName(`sse:${sessionId}`);
481
625
  const doStub = namespace.get(id);
482
- 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);
483
629
  if (error) {
484
630
  return new Response(error.message, {
485
- status: 400,
486
631
  headers: {
487
- "Content-Type": "text/event-stream",
488
632
  "Cache-Control": "no-cache",
489
633
  Connection: "keep-alive",
490
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
491
- }
634
+ "Content-Type": "text/event-stream",
635
+ ...corsHeaders(request, corsOptions)
636
+ },
637
+ status: 400
492
638
  });
493
639
  }
494
640
  return new Response("Accepted", {
495
- status: 202,
496
641
  headers: {
497
- "Content-Type": "text/event-stream",
498
642
  "Cache-Control": "no-cache",
499
643
  Connection: "keep-alive",
500
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
501
- }
644
+ "Content-Type": "text/event-stream",
645
+ ...corsHeaders(request, corsOptions)
646
+ },
647
+ status: 202
502
648
  });
503
649
  }
504
650
  return new Response("Not Found", { status: 404 });
@@ -515,35 +661,45 @@ data: ${JSON.stringify(result.data)}
515
661
  }
516
662
  const basePattern = new URLPattern({ pathname });
517
663
  return {
518
- fetch: async (request, env, ctx) => {
664
+ async fetch(request, env, ctx) {
519
665
  const corsResponse = handleCORS(request, corsOptions);
520
666
  if (corsResponse) {
521
667
  return corsResponse;
522
668
  }
523
669
  const url = new URL(request.url);
524
- const namespace = env[binding];
670
+ const bindingValue = env[binding];
671
+ if (bindingValue == null || typeof bindingValue !== "object") {
672
+ console.error(
673
+ `Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
674
+ );
675
+ return new Response("Invalid binding", { status: 500 });
676
+ }
677
+ if (!isDurableObjectNamespace(bindingValue)) {
678
+ return new Response("Invalid binding", { status: 500 });
679
+ }
680
+ const namespace = bindingValue;
525
681
  if (request.method === "POST" && basePattern.test(url)) {
526
682
  const acceptHeader = request.headers.get("accept");
527
683
  if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
528
684
  const body2 = JSON.stringify({
529
- jsonrpc: "2.0",
530
685
  error: {
531
686
  code: -32e3,
532
687
  message: "Not Acceptable: Client must accept both application/json and text/event-stream"
533
688
  },
534
- id: null
689
+ id: null,
690
+ jsonrpc: "2.0"
535
691
  });
536
692
  return new Response(body2, { status: 406 });
537
693
  }
538
694
  const ct = request.headers.get("content-type");
539
695
  if (!ct || !ct.includes("application/json")) {
540
696
  const body2 = JSON.stringify({
541
- jsonrpc: "2.0",
542
697
  error: {
543
698
  code: -32e3,
544
699
  message: "Unsupported Media Type: Content-Type must be application/json"
545
700
  },
546
- id: null
701
+ id: null,
702
+ jsonrpc: "2.0"
547
703
  });
548
704
  return new Response(body2, { status: 415 });
549
705
  }
@@ -553,12 +709,12 @@ data: ${JSON.stringify(result.data)}
553
709
  );
554
710
  if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
555
711
  const body2 = JSON.stringify({
556
- jsonrpc: "2.0",
557
712
  error: {
558
713
  code: -32e3,
559
714
  message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
560
715
  },
561
- id: null
716
+ id: null,
717
+ jsonrpc: "2.0"
562
718
  });
563
719
  return new Response(body2, { status: 413 });
564
720
  }
@@ -566,14 +722,14 @@ data: ${JSON.stringify(result.data)}
566
722
  let rawMessage;
567
723
  try {
568
724
  rawMessage = await request.json();
569
- } catch (error) {
725
+ } catch (_error) {
570
726
  const body2 = JSON.stringify({
571
- jsonrpc: "2.0",
572
727
  error: {
573
728
  code: -32700,
574
729
  message: "Parse error: Invalid JSON"
575
730
  },
576
- id: null
731
+ id: null,
732
+ jsonrpc: "2.0"
577
733
  });
578
734
  return new Response(body2, { status: 400 });
579
735
  }
@@ -587,12 +743,12 @@ data: ${JSON.stringify(result.data)}
587
743
  for (const msg of arrayMessage) {
588
744
  if (!JSONRPCMessageSchema.safeParse(msg).success) {
589
745
  const body2 = JSON.stringify({
590
- jsonrpc: "2.0",
591
746
  error: {
592
747
  code: -32700,
593
748
  message: "Parse error: Invalid JSON-RPC message"
594
749
  },
595
- id: null
750
+ id: null,
751
+ jsonrpc: "2.0"
596
752
  });
597
753
  return new Response(body2, { status: 400 });
598
754
  }
@@ -603,34 +759,34 @@ data: ${JSON.stringify(result.data)}
603
759
  );
604
760
  if (isInitializationRequest && sessionId) {
605
761
  const body2 = JSON.stringify({
606
- jsonrpc: "2.0",
607
762
  error: {
608
763
  code: -32600,
609
764
  message: "Invalid Request: Initialization requests must not include a sessionId"
610
765
  },
611
- id: null
766
+ id: null,
767
+ jsonrpc: "2.0"
612
768
  });
613
769
  return new Response(body2, { status: 400 });
614
770
  }
615
771
  if (isInitializationRequest && messages.length > 1) {
616
772
  const body2 = JSON.stringify({
617
- jsonrpc: "2.0",
618
773
  error: {
619
774
  code: -32600,
620
775
  message: "Invalid Request: Only one initialization request is allowed"
621
776
  },
622
- id: null
777
+ id: null,
778
+ jsonrpc: "2.0"
623
779
  });
624
780
  return new Response(body2, { status: 400 });
625
781
  }
626
782
  if (!isInitializationRequest && !sessionId) {
627
783
  const body2 = JSON.stringify({
628
- jsonrpc: "2.0",
629
784
  error: {
630
785
  code: -32e3,
631
786
  message: "Bad Request: Mcp-Session-Id header is required"
632
787
  },
633
- id: null
788
+ id: null,
789
+ jsonrpc: "2.0"
634
790
  });
635
791
  return new Response(body2, { status: 400 });
636
792
  }
@@ -639,26 +795,48 @@ data: ${JSON.stringify(result.data)}
639
795
  const doStub = namespace.get(id);
640
796
  const isInitialized = await doStub.isInitialized();
641
797
  if (isInitializationRequest) {
642
- 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
+ }
643
814
  } else if (!isInitialized) {
644
815
  const body2 = JSON.stringify({
645
- jsonrpc: "2.0",
646
816
  error: {
647
817
  code: -32001,
648
818
  message: "Session not found"
649
819
  },
650
- id: null
820
+ id: null,
821
+ jsonrpc: "2.0"
651
822
  });
652
823
  return new Response(body2, { status: 404 });
824
+ } else {
825
+ await doStub.updateProps(ctx.props);
653
826
  }
654
827
  const { readable, writable } = new TransformStream();
655
828
  const writer = writable.getWriter();
656
829
  const encoder = new TextEncoder();
657
830
  const upgradeUrl = new URL(request.url);
658
831
  upgradeUrl.pathname = "/streamable-http";
832
+ const existingHeaders = {};
833
+ request.headers.forEach((value, key) => {
834
+ existingHeaders[key] = value;
835
+ });
659
836
  const response = await doStub.fetch(
660
837
  new Request(upgradeUrl, {
661
838
  headers: {
839
+ ...existingHeaders,
662
840
  Upgrade: "websocket",
663
841
  // Required by PartyServer
664
842
  "x-partykit-room": sessionId
@@ -670,12 +848,12 @@ data: ${JSON.stringify(result.data)}
670
848
  console.error("Failed to establish WebSocket connection");
671
849
  await writer.close();
672
850
  const body2 = JSON.stringify({
673
- jsonrpc: "2.0",
674
851
  error: {
675
852
  code: -32001,
676
853
  message: "Failed to establish WebSocket connection"
677
854
  },
678
- id: null
855
+ id: null,
856
+ jsonrpc: "2.0"
679
857
  });
680
858
  return new Response(body2, { status: 500 });
681
859
  }
@@ -708,10 +886,10 @@ data: ${JSON.stringify(result.data)}
708
886
  onMessage(event).catch(console.error);
709
887
  });
710
888
  ws.addEventListener("error", (error) => {
711
- async function onError(error2) {
889
+ async function onError(_error) {
712
890
  try {
713
891
  await writer.close();
714
- } catch (e) {
892
+ } catch (_e) {
715
893
  }
716
894
  }
717
895
  onError(error).catch(console.error);
@@ -734,7 +912,10 @@ data: ${JSON.stringify(result.data)}
734
912
  ws.send(JSON.stringify(message));
735
913
  }
736
914
  ws.close();
737
- return new Response(null, { status: 202 });
915
+ return new Response(null, {
916
+ headers: corsHeaders(request, corsOptions),
917
+ status: 202
918
+ });
738
919
  }
739
920
  for (const message of messages) {
740
921
  if (isJSONRPCRequest(message)) {
@@ -744,43 +925,32 @@ data: ${JSON.stringify(result.data)}
744
925
  }
745
926
  return new Response(readable, {
746
927
  headers: {
747
- "Content-Type": "text/event-stream",
748
928
  "Cache-Control": "no-cache",
749
929
  Connection: "keep-alive",
930
+ "Content-Type": "text/event-stream",
750
931
  "mcp-session-id": sessionId,
751
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
932
+ ...corsHeaders(request, corsOptions)
752
933
  },
753
934
  status: 200
754
935
  });
755
936
  }
756
937
  const body = JSON.stringify({
757
- jsonrpc: "2.0",
758
938
  error: {
759
939
  code: -32e3,
760
940
  message: "Method not allowed"
761
941
  },
762
- id: null
942
+ id: null,
943
+ jsonrpc: "2.0"
763
944
  });
764
945
  return new Response(body, { status: 405 });
765
946
  }
766
947
  };
767
948
  }
768
949
  };
769
- _status = new WeakMap();
770
- _transport = new WeakMap();
771
- _transportType = new WeakMap();
772
- _requestIdToConnectionId = new WeakMap();
773
- _agent = new WeakMap();
774
- _McpAgent_instances = new WeakSet();
775
- initialize_fn = async function() {
776
- await this.ctx.blockConcurrencyWhile(async () => {
777
- __privateSet(this, _status, "starting");
778
- await this.onStart();
779
- __privateSet(this, _status, "started");
780
- });
781
- };
782
- var McpAgent = _McpAgent;
783
950
  export {
784
- McpAgent
951
+ ElicitRequestSchema,
952
+ McpAgent,
953
+ SSEEdgeClientTransport,
954
+ StreamableHTTPEdgeClientTransport
785
955
  };
786
956
  //# sourceMappingURL=index.js.map