agents 0.0.0-b342dcf → 0.0.0-b803d5e

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.
package/dist/mcp/index.js CHANGED
@@ -1,13 +1,9 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-UAKVEVG5.js";
4
- import "../chunk-WNICV3OI.js";
5
- import {
6
- __privateAdd,
7
- __privateGet,
8
- __privateMethod,
9
- __privateSet
10
- } from "../chunk-HMLY7DHA.js";
3
+ } from "../chunk-J6T74FUS.js";
4
+ import "../chunk-BZXOAZUX.js";
5
+ import "../chunk-QSGN3REV.js";
6
+ import "../chunk-Y67CHZBI.js";
11
7
 
12
8
  // src/mcp/index.ts
13
9
  import { DurableObject } from "cloudflare:workers";
@@ -20,37 +16,38 @@ import {
20
16
  JSONRPCMessageSchema
21
17
  } from "@modelcontextprotocol/sdk/types.js";
22
18
  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()
19
+ function corsHeaders(request, corsOptions = {}) {
20
+ const origin = "*";
21
+ return {
22
+ "Access-Control-Allow-Origin": corsOptions.origin || origin,
23
+ "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, OPTIONS",
24
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id",
25
+ "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString(),
26
+ "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id"
30
27
  };
28
+ }
29
+ function handleCORS(request, corsOptions) {
31
30
  if (request.method === "OPTIONS") {
32
- return new Response(null, { headers: corsHeaders });
31
+ return new Response(null, { headers: corsHeaders(request, corsOptions) });
33
32
  }
34
33
  return null;
35
34
  }
36
- var _getWebSocket, _started;
37
35
  var McpSSETransport = class {
38
36
  constructor(getWebSocket) {
39
- __privateAdd(this, _getWebSocket);
40
- __privateAdd(this, _started, false);
41
- __privateSet(this, _getWebSocket, getWebSocket);
37
+ this._started = false;
38
+ this._getWebSocket = getWebSocket;
42
39
  }
43
40
  async start() {
44
- if (__privateGet(this, _started)) {
41
+ if (this._started) {
45
42
  throw new Error("Transport already started");
46
43
  }
47
- __privateSet(this, _started, true);
44
+ this._started = true;
48
45
  }
49
46
  async send(message) {
50
- if (!__privateGet(this, _started)) {
47
+ if (!this._started) {
51
48
  throw new Error("Transport not started");
52
49
  }
53
- const websocket = __privateGet(this, _getWebSocket).call(this);
50
+ const websocket = this._getWebSocket();
54
51
  if (!websocket) {
55
52
  throw new Error("WebSocket not connected");
56
53
  }
@@ -65,52 +62,40 @@ var McpSSETransport = class {
65
62
  this.onclose?.();
66
63
  }
67
64
  };
68
- _getWebSocket = new WeakMap();
69
- _started = new WeakMap();
70
- var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
71
65
  var McpStreamableHttpTransport = class {
72
66
  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);
67
+ this._started = false;
68
+ this._getWebSocketForMessageID = getWebSocketForMessageID;
69
+ this._notifyResponseIdSent = notifyResponseIdSent;
70
+ this._getWebSocketForGetRequest = () => null;
86
71
  }
87
72
  async start() {
88
- if (__privateGet(this, _started2)) {
73
+ if (this._started) {
89
74
  throw new Error("Transport already started");
90
75
  }
91
- __privateSet(this, _started2, true);
76
+ this._started = true;
92
77
  }
93
78
  async send(message) {
94
- if (!__privateGet(this, _started2)) {
79
+ if (!this._started) {
95
80
  throw new Error("Transport not started");
96
81
  }
97
82
  let websocket = null;
98
83
  if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
99
- websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
84
+ websocket = this._getWebSocketForMessageID(message.id.toString());
100
85
  if (!websocket) {
101
86
  throw new Error(
102
87
  `Could not find WebSocket for message id: ${message.id}`
103
88
  );
104
89
  }
105
90
  } else if (isJSONRPCRequest(message)) {
106
- websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
91
+ websocket = this._getWebSocketForGetRequest();
107
92
  } else if (isJSONRPCNotification(message)) {
108
93
  websocket = null;
109
94
  }
110
95
  try {
111
96
  websocket?.send(JSON.stringify(message));
112
97
  if (isJSONRPCResponse(message)) {
113
- __privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
98
+ this._notifyResponseIdSent(message.id.toString());
114
99
  }
115
100
  } catch (error) {
116
101
  this.onerror?.(error);
@@ -121,28 +106,16 @@ var McpStreamableHttpTransport = class {
121
106
  this.onclose?.();
122
107
  }
123
108
  };
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 {
109
+ var McpAgent = class _McpAgent extends DurableObject {
130
110
  constructor(ctx, env) {
131
111
  var _a;
132
112
  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);
113
+ this._status = "zero";
114
+ this._transportType = "unset";
115
+ this._requestIdToConnectionId = /* @__PURE__ */ new Map();
143
116
  this.initRun = false;
144
117
  const self = this;
145
- __privateSet(this, _agent, new (_a = class extends Agent {
118
+ this._agent = new (_a = class extends Agent {
146
119
  onStateUpdate(state, source) {
147
120
  return self.onStateUpdate(state, source);
148
121
  }
@@ -151,26 +124,26 @@ var _McpAgent = class _McpAgent extends DurableObject {
151
124
  }
152
125
  }, _a.options = {
153
126
  hibernate: true
154
- }, _a)(ctx, env));
127
+ }, _a)(ctx, env);
155
128
  }
156
129
  get mcp() {
157
- return __privateGet(this, _agent).mcp;
130
+ return this._agent.mcp;
158
131
  }
159
132
  get state() {
160
- return __privateGet(this, _agent).state;
133
+ return this._agent.state;
161
134
  }
162
135
  sql(strings, ...values) {
163
- return __privateGet(this, _agent).sql(strings, ...values);
136
+ return this._agent.sql(strings, ...values);
164
137
  }
165
138
  setState(state) {
166
- return __privateGet(this, _agent).setState(state);
139
+ return this._agent.setState(state);
167
140
  }
168
141
  onStateUpdate(state, source) {
169
142
  }
170
143
  async onStart() {
171
144
  var _a;
172
145
  const self = this;
173
- __privateSet(this, _agent, new (_a = class extends Agent {
146
+ this._agent = new (_a = class extends Agent {
174
147
  constructor() {
175
148
  super(...arguments);
176
149
  this.initialState = self.initialState;
@@ -183,22 +156,22 @@ var _McpAgent = class _McpAgent extends DurableObject {
183
156
  }
184
157
  }, _a.options = {
185
158
  hibernate: true
186
- }, _a)(this.ctx, this.env));
159
+ }, _a)(this.ctx, this.env);
187
160
  this.props = await this.ctx.storage.get("props");
188
- __privateSet(this, _transportType, await this.ctx.storage.get(
161
+ this._transportType = await this.ctx.storage.get(
189
162
  "transportType"
190
- ));
163
+ );
191
164
  await this._init(this.props);
192
165
  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(
166
+ if (this._transportType === "sse") {
167
+ this._transport = new McpSSETransport(() => this.getWebSocket());
168
+ await server.connect(this._transport);
169
+ } else if (this._transportType === "streamable-http") {
170
+ this._transport = new McpStreamableHttpTransport(
198
171
  (id) => this.getWebSocketForResponseID(id),
199
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
200
- ));
201
- await server.connect(__privateGet(this, _transport));
172
+ (id) => this._requestIdToConnectionId.delete(id)
173
+ );
174
+ await server.connect(this._transport);
202
175
  }
203
176
  }
204
177
  async _init(props) {
@@ -218,10 +191,17 @@ var _McpAgent = class _McpAgent extends DurableObject {
218
191
  async isInitialized() {
219
192
  return await this.ctx.storage.get("initialized") === true;
220
193
  }
194
+ async _initialize() {
195
+ await this.ctx.blockConcurrencyWhile(async () => {
196
+ this._status = "starting";
197
+ await this.onStart();
198
+ this._status = "started";
199
+ });
200
+ }
221
201
  // Allow the worker to fetch a websocket connection to the agent
222
202
  async fetch(request) {
223
- if (__privateGet(this, _status) !== "started") {
224
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
203
+ if (this._status !== "started") {
204
+ await this._initialize();
225
205
  }
226
206
  if (request.headers.get("Upgrade") !== "websocket") {
227
207
  return new Response("Expected WebSocket Upgrade request", {
@@ -238,24 +218,24 @@ var _McpAgent = class _McpAgent extends DurableObject {
238
218
  return new Response("Websocket already connected", { status: 400 });
239
219
  }
240
220
  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));
221
+ this._transportType = "sse";
222
+ if (!this._transport) {
223
+ this._transport = new McpSSETransport(() => this.getWebSocket());
224
+ await server.connect(this._transport);
245
225
  }
246
- return __privateGet(this, _agent).fetch(request);
226
+ return this._agent.fetch(request);
247
227
  }
248
228
  case "/streamable-http": {
249
- if (!__privateGet(this, _transport)) {
250
- __privateSet(this, _transport, new McpStreamableHttpTransport(
229
+ if (!this._transport) {
230
+ this._transport = new McpStreamableHttpTransport(
251
231
  (id) => this.getWebSocketForResponseID(id),
252
- (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
253
- ));
254
- await server.connect(__privateGet(this, _transport));
232
+ (id) => this._requestIdToConnectionId.delete(id)
233
+ );
234
+ await server.connect(this._transport);
255
235
  }
256
236
  await this.ctx.storage.put("transportType", "streamable-http");
257
- __privateSet(this, _transportType, "streamable-http");
258
- return __privateGet(this, _agent).fetch(request);
237
+ this._transportType = "streamable-http";
238
+ return this._agent.fetch(request);
259
239
  }
260
240
  default:
261
241
  return new Response(
@@ -274,19 +254,19 @@ var _McpAgent = class _McpAgent extends DurableObject {
274
254
  return websockets[0];
275
255
  }
276
256
  getWebSocketForResponseID(id) {
277
- const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
257
+ const connectionId = this._requestIdToConnectionId.get(id);
278
258
  if (connectionId === void 0) {
279
259
  return null;
280
260
  }
281
- return __privateGet(this, _agent).getConnection(connectionId) ?? null;
261
+ return this._agent.getConnection(connectionId) ?? null;
282
262
  }
283
263
  // All messages received here. This is currently never called
284
264
  async onMessage(connection, event) {
285
- if (__privateGet(this, _transportType) !== "streamable-http") {
265
+ if (this._transportType !== "streamable-http") {
286
266
  const err = new Error(
287
267
  "Internal Server Error: Expected streamable-http protocol"
288
268
  );
289
- __privateGet(this, _transport)?.onerror?.(err);
269
+ this._transport?.onerror?.(err);
290
270
  return;
291
271
  }
292
272
  let message;
@@ -294,21 +274,21 @@ var _McpAgent = class _McpAgent extends DurableObject {
294
274
  const data = typeof event === "string" ? event : new TextDecoder().decode(event);
295
275
  message = JSONRPCMessageSchema.parse(JSON.parse(data));
296
276
  } catch (error) {
297
- __privateGet(this, _transport)?.onerror?.(error);
277
+ this._transport?.onerror?.(error);
298
278
  return;
299
279
  }
300
280
  if (isJSONRPCRequest(message)) {
301
- __privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
281
+ this._requestIdToConnectionId.set(message.id.toString(), connection.id);
302
282
  }
303
- __privateGet(this, _transport)?.onmessage?.(message);
283
+ this._transport?.onmessage?.(message);
304
284
  }
305
285
  // All messages received over SSE after the initial connection has been established
306
286
  // will be passed here
307
287
  async onSSEMcpMessage(sessionId, request) {
308
- if (__privateGet(this, _status) !== "started") {
309
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
288
+ if (this._status !== "started") {
289
+ await this._initialize();
310
290
  }
311
- if (__privateGet(this, _transportType) !== "sse") {
291
+ if (this._transportType !== "sse") {
312
292
  return new Error("Internal Server Error: Expected SSE protocol");
313
293
  }
314
294
  try {
@@ -317,35 +297,36 @@ var _McpAgent = class _McpAgent extends DurableObject {
317
297
  try {
318
298
  parsedMessage = JSONRPCMessageSchema.parse(message);
319
299
  } catch (error) {
320
- __privateGet(this, _transport)?.onerror?.(error);
300
+ this._transport?.onerror?.(error);
321
301
  throw error;
322
302
  }
323
- __privateGet(this, _transport)?.onmessage?.(parsedMessage);
303
+ this._transport?.onmessage?.(parsedMessage);
324
304
  return null;
325
305
  } catch (error) {
326
- __privateGet(this, _transport)?.onerror?.(error);
306
+ console.error("Error forwarding message to SSE:", error);
307
+ this._transport?.onerror?.(error);
327
308
  return error;
328
309
  }
329
310
  }
330
311
  // Delegate all websocket events to the underlying agent
331
312
  async webSocketMessage(ws, event) {
332
- if (__privateGet(this, _status) !== "started") {
333
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
313
+ if (this._status !== "started") {
314
+ await this._initialize();
334
315
  }
335
- return await __privateGet(this, _agent).webSocketMessage(ws, event);
316
+ return await this._agent.webSocketMessage(ws, event);
336
317
  }
337
318
  // WebSocket event handlers for hibernation support
338
319
  async webSocketError(ws, error) {
339
- if (__privateGet(this, _status) !== "started") {
340
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
320
+ if (this._status !== "started") {
321
+ await this._initialize();
341
322
  }
342
- return await __privateGet(this, _agent).webSocketError(ws, error);
323
+ return await this._agent.webSocketError(ws, error);
343
324
  }
344
325
  async webSocketClose(ws, code, reason, wasClean) {
345
- if (__privateGet(this, _status) !== "started") {
346
- await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
326
+ if (this._status !== "started") {
327
+ await this._initialize();
347
328
  }
348
- return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
329
+ return await this._agent.webSocketClose(ws, code, reason, wasClean);
349
330
  }
350
331
  static mount(path, {
351
332
  binding = "MCP_OBJECT",
@@ -459,7 +440,7 @@ data: ${JSON.stringify(result.data)}
459
440
  "Content-Type": "text/event-stream",
460
441
  "Cache-Control": "no-cache",
461
442
  Connection: "keep-alive",
462
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
443
+ ...corsHeaders(request, corsOptions)
463
444
  }
464
445
  });
465
446
  }
@@ -499,7 +480,7 @@ data: ${JSON.stringify(result.data)}
499
480
  "Content-Type": "text/event-stream",
500
481
  "Cache-Control": "no-cache",
501
482
  Connection: "keep-alive",
502
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
483
+ ...corsHeaders(request, corsOptions)
503
484
  }
504
485
  });
505
486
  }
@@ -509,7 +490,7 @@ data: ${JSON.stringify(result.data)}
509
490
  "Content-Type": "text/event-stream",
510
491
  "Cache-Control": "no-cache",
511
492
  Connection: "keep-alive",
512
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
493
+ ...corsHeaders(request, corsOptions)
513
494
  }
514
495
  });
515
496
  }
@@ -661,6 +642,7 @@ data: ${JSON.stringify(result.data)}
661
642
  const doStub = namespace.get(id);
662
643
  const isInitialized = await doStub.isInitialized();
663
644
  if (isInitializationRequest) {
645
+ await doStub._init(ctx.props);
664
646
  await doStub.setInitialized();
665
647
  } else if (!isInitialized) {
666
648
  const body2 = JSON.stringify({
@@ -756,7 +738,10 @@ data: ${JSON.stringify(result.data)}
756
738
  ws.send(JSON.stringify(message));
757
739
  }
758
740
  ws.close();
759
- return new Response(null, { status: 202 });
741
+ return new Response(null, {
742
+ status: 202,
743
+ headers: corsHeaders(request, corsOptions)
744
+ });
760
745
  }
761
746
  for (const message of messages) {
762
747
  if (isJSONRPCRequest(message)) {
@@ -770,7 +755,7 @@ data: ${JSON.stringify(result.data)}
770
755
  "Cache-Control": "no-cache",
771
756
  Connection: "keep-alive",
772
757
  "mcp-session-id": sessionId,
773
- "Access-Control-Allow-Origin": corsOptions?.origin || "*"
758
+ ...corsHeaders(request, corsOptions)
774
759
  },
775
760
  status: 200
776
761
  });
@@ -788,20 +773,6 @@ data: ${JSON.stringify(result.data)}
788
773
  };
789
774
  }
790
775
  };
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
776
  export {
806
777
  McpAgent
807
778
  };