agents 0.0.0-0cd2489 → 0.0.0-0cf8e80

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