agents 0.0.0-aa5f972 → 0.0.0-ac0e999

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