agents 0.0.0-ad0054b → 0.0.0-b213982

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