agents 0.0.0-63d8af8 → 0.0.0-669a2b0

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