agents 0.0.0-62d4e85 → 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 (50) 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 +148 -51
  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 +62 -46
  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 -7
  24. package/dist/mcp/client.d.ts +11 -675
  25. package/dist/mcp/client.js +3 -780
  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/do-oauth-client-provider.js.map +1 -0
  30. package/dist/mcp/index.d.ts +69 -8
  31. package/dist/mcp/index.js +851 -72
  32. package/dist/mcp/index.js.map +1 -1
  33. package/dist/observability/index.d.ts +14 -0
  34. package/dist/observability/index.js +10 -0
  35. package/dist/observability/index.js.map +1 -0
  36. package/dist/react.d.ts +87 -5
  37. package/dist/react.js +50 -29
  38. package/dist/react.js.map +1 -1
  39. package/dist/schedule.d.ts +10 -10
  40. package/dist/schedule.js +4 -4
  41. package/dist/schedule.js.map +1 -1
  42. package/dist/serializable.d.ts +32 -0
  43. package/dist/serializable.js +1 -0
  44. package/dist/serializable.js.map +1 -0
  45. package/package.json +81 -53
  46. package/src/index.ts +1121 -145
  47. package/dist/chunk-EZ76ZGDB.js +0 -1721
  48. package/dist/chunk-EZ76ZGDB.js.map +0 -1
  49. package/dist/chunk-SZEXGW6W.js +0 -580
  50. package/dist/chunk-SZEXGW6W.js.map +0 -1
package/dist/mcp/index.js CHANGED
@@ -1,135 +1,914 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-SZEXGW6W.js";
3
+ } from "../chunk-OJFA7RKX.js";
4
4
  import {
5
- SSEEdgeServerTransport
6
- } from "../chunk-EZ76ZGDB.js";
5
+ SSEEdgeClientTransport,
6
+ StreamableHTTPEdgeClientTransport
7
+ } from "../chunk-HY7ZLHJB.js";
8
+ import "../chunk-PVQZBKN7.js";
9
+ import "../chunk-KUH345EY.js";
7
10
 
8
11
  // src/mcp/index.ts
9
12
  import { DurableObject } from "cloudflare:workers";
10
- function handleCORS(request, corsOptions) {
11
- const origin = request.headers.get("Origin") || "*";
12
- const corsHeaders = {
13
- "Access-Control-Allow-Origin": corsOptions?.origin || origin,
14
- "Access-Control-Allow-Methods": corsOptions?.methods || "GET, POST, OPTIONS",
15
- "Access-Control-Allow-Headers": corsOptions?.headers || "Content-Type",
16
- "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()
17
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) {
18
39
  if (request.method === "OPTIONS") {
19
- return new Response(null, { headers: corsHeaders });
40
+ return new Response(null, { headers: corsHeaders(request, corsOptions) });
20
41
  }
21
42
  return null;
22
43
  }
23
- var McpAgent = class extends DurableObject {
24
- /**
25
- * Since McpAgent's _aren't_ yet real "Agents" (they route differently, don't support
26
- * websockets, don't support hibernation), let's only expose a couple of the methods
27
- * to the outer class: initialState/state/setState/onStateUpdate/sql
28
- */
29
- #agent;
44
+ var McpSSETransport = class {
45
+ constructor(getWebSocket) {
46
+ this._started = false;
47
+ this._getWebSocket = getWebSocket;
48
+ }
49
+ async start() {
50
+ if (this._started) {
51
+ throw new Error("Transport already started");
52
+ }
53
+ this._started = true;
54
+ }
55
+ async send(message) {
56
+ if (!this._started) {
57
+ throw new Error("Transport not started");
58
+ }
59
+ const websocket = this._getWebSocket();
60
+ if (!websocket) {
61
+ throw new Error("WebSocket not connected");
62
+ }
63
+ try {
64
+ websocket.send(JSON.stringify(message));
65
+ } catch (error) {
66
+ this.onerror?.(error);
67
+ throw error;
68
+ }
69
+ }
70
+ async close() {
71
+ this.onclose?.();
72
+ }
73
+ };
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 {
30
119
  constructor(ctx, env) {
120
+ var _a;
31
121
  super(ctx, env);
122
+ this._status = "zero";
123
+ this._transportType = "unset";
124
+ this._requestIdToConnectionId = /* @__PURE__ */ new Map();
125
+ this.initRun = false;
32
126
  const self = this;
33
- this.#agent = new class extends Agent {
34
- static options = {
35
- hibernate: false
36
- };
127
+ this._agent = new (_a = class extends Agent {
37
128
  onStateUpdate(state, source) {
38
129
  return self.onStateUpdate(state, source);
39
130
  }
40
- }(ctx, env);
131
+ async onMessage(connection, message) {
132
+ return self.onMessage(connection, message);
133
+ }
134
+ }, _a.options = {
135
+ hibernate: true
136
+ }, _a)(ctx, env);
137
+ }
138
+ get mcp() {
139
+ return this._agent.mcp;
41
140
  }
42
- /**
43
- * Agents API allowlist
44
- */
45
- initialState;
46
141
  get state() {
47
- if (this.initialState) this.#agent.initialState = this.initialState;
48
- return this.#agent.state;
142
+ return this._agent.state;
49
143
  }
50
144
  sql(strings, ...values) {
51
- return this.#agent.sql(strings, ...values);
145
+ return this._agent.sql(strings, ...values);
52
146
  }
53
147
  setState(state) {
54
- return this.#agent.setState(state);
148
+ return this._agent.setState(state);
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);
55
187
  }
188
+ // we leave the variables as unused for autocomplete purposes
189
+ // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
56
190
  onStateUpdate(state, source) {
57
191
  }
58
- transport;
59
- props;
60
- initRun = false;
192
+ async onStart() {
193
+ var _a;
194
+ const self = this;
195
+ this._agent = new (_a = class extends Agent {
196
+ constructor() {
197
+ super(...arguments);
198
+ this.initialState = self.initialState;
199
+ }
200
+ onStateUpdate(state, source) {
201
+ return self.onStateUpdate(state, source);
202
+ }
203
+ async onMessage(connection, event) {
204
+ return self.onMessage(connection, event);
205
+ }
206
+ }, _a.options = {
207
+ hibernate: true
208
+ }, _a)(this.ctx, this.env);
209
+ this.props = await this.ctx.storage.get("props");
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
+ }
225
+ }
61
226
  async _init(props) {
62
- this.props = props;
227
+ await this.updateProps(props);
228
+ if (!this.ctx.storage.get("transportType")) {
229
+ await this.ctx.storage.put("transportType", "unset");
230
+ }
63
231
  if (!this.initRun) {
64
232
  this.initRun = true;
65
233
  await this.init();
66
234
  }
67
235
  }
68
- async onSSE(path) {
69
- this.transport = new SSEEdgeServerTransport(
70
- `${path}/message`,
71
- this.ctx.id.toString()
72
- );
73
- await this.server.connect(this.transport);
74
- return this.transport.sseResponse;
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
+ }
253
+ // Allow the worker to fetch a websocket connection to the agent
254
+ async fetch(request) {
255
+ if (this._status !== "started") {
256
+ await this._initialize();
257
+ }
258
+ if (request.headers.get("Upgrade") !== "websocket") {
259
+ return new Response("Expected WebSocket Upgrade request", {
260
+ status: 400
261
+ });
262
+ }
263
+ const url = new URL(request.url);
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
+ );
299
+ }
300
+ }
301
+ getWebSocket() {
302
+ const websockets = this.ctx.getWebSockets();
303
+ if (websockets.length === 0) {
304
+ return null;
305
+ }
306
+ return websockets[0];
307
+ }
308
+ getWebSocketForResponseID(id) {
309
+ const connectionId = this._requestIdToConnectionId.get(id);
310
+ if (connectionId === void 0) {
311
+ return null;
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;
325
+ try {
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));
357
+ }
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}`
372
+ );
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 {
411
+ let parsedMessage;
412
+ try {
413
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
414
+ } catch (error) {
415
+ this._transport?.onerror?.(error);
416
+ throw error;
417
+ }
418
+ if (await this._handleElicitationResponse(parsedMessage)) {
419
+ return null;
420
+ }
421
+ this._transport?.onmessage?.(parsedMessage);
422
+ return null;
423
+ } catch (error) {
424
+ console.error("Error forwarding message to SSE:", error);
425
+ this._transport?.onerror?.(error);
426
+ return error;
427
+ }
75
428
  }
76
- async onMCPMessage(request) {
77
- return this.transport.handlePostMessage(request);
429
+ // Delegate all websocket events to the underlying agent
430
+ async webSocketMessage(ws, event) {
431
+ if (this._status !== "started") {
432
+ await this._initialize();
433
+ }
434
+ return await this._agent.webSocketMessage(ws, event);
435
+ }
436
+ // WebSocket event handlers for hibernation support
437
+ async webSocketError(ws, error) {
438
+ if (this._status !== "started") {
439
+ await this._initialize();
440
+ }
441
+ return await this._agent.webSocketError(ws, error);
442
+ }
443
+ async webSocketClose(ws, code, reason, wasClean) {
444
+ if (this._status !== "started") {
445
+ await this._initialize();
446
+ }
447
+ return await this._agent.webSocketClose(ws, code, reason, wasClean);
78
448
  }
79
449
  static mount(path, {
80
450
  binding = "MCP_OBJECT",
81
451
  corsOptions
82
452
  } = {}) {
83
- const basePattern = new URLPattern({ pathname: path });
84
- const messagePattern = new URLPattern({ pathname: `${path}/message` });
453
+ return _McpAgent.serveSSE(path, { binding, corsOptions });
454
+ }
455
+ static serveSSE(path, {
456
+ binding = "MCP_OBJECT",
457
+ corsOptions
458
+ } = {}) {
459
+ let pathname = path;
460
+ if (path === "/") {
461
+ pathname = "/*";
462
+ }
463
+ const basePattern = new URLPattern({ pathname });
464
+ const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
85
465
  return {
86
- fetch: async (request, env, ctx) => {
466
+ async fetch(request, env, ctx) {
87
467
  const corsResponse = handleCORS(request, corsOptions);
88
468
  if (corsResponse) return corsResponse;
89
469
  const url = new URL(request.url);
90
- 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;
91
481
  if (request.method === "GET" && basePattern.test(url)) {
92
- const object = namespace.get(namespace.newUniqueId());
93
- await object._init(ctx.props);
94
- const response = await object.onSSE(path);
95
- const headerObj = {};
96
- response.headers.forEach((value, key) => {
97
- headerObj[key] = value;
482
+ const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
483
+ const { readable, writable } = new TransformStream();
484
+ const writer = writable.getWriter();
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;
490
+ const endpointMessage = `event: endpoint
491
+ data: ${relativeUrlWithSession}
492
+
493
+ `;
494
+ writer.write(encoder.encode(endpointMessage));
495
+ const id = namespace.idFromName(`sse:${sessionId}`);
496
+ const doStub = namespace.get(id);
497
+ await doStub._init(ctx.props);
498
+ const upgradeUrl = new URL(request.url);
499
+ upgradeUrl.pathname = "/sse";
500
+ const existingHeaders = {};
501
+ request.headers.forEach((value, key) => {
502
+ existingHeaders[key] = value;
98
503
  });
99
- headerObj["Access-Control-Allow-Origin"] = corsOptions?.origin || "*";
100
- return new Response(response.body, {
101
- status: response.status,
102
- statusText: response.statusText,
103
- headers: headerObj
504
+ const response = await doStub.fetch(
505
+ new Request(upgradeUrl, {
506
+ headers: {
507
+ ...existingHeaders,
508
+ Upgrade: "websocket",
509
+ // Required by PartyServer
510
+ "x-partykit-room": sessionId
511
+ }
512
+ })
513
+ );
514
+ const ws = response.webSocket;
515
+ if (!ws) {
516
+ console.error("Failed to establish WebSocket connection");
517
+ await writer.close();
518
+ return new Response("Failed to establish WebSocket connection", {
519
+ status: 500
520
+ });
521
+ }
522
+ ws.accept();
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
532
+ data: ${JSON.stringify(result.data)}
533
+
534
+ `;
535
+ await writer.write(encoder.encode(messageText));
536
+ } catch (error) {
537
+ console.error("Error forwarding message to SSE:", error);
538
+ }
539
+ }
540
+ onMessage(event).catch(console.error);
541
+ });
542
+ ws.addEventListener("error", (error) => {
543
+ async function onError(_error) {
544
+ try {
545
+ await writer.close();
546
+ } catch (_e) {
547
+ }
548
+ }
549
+ onError(error).catch(console.error);
550
+ });
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
+ }
558
+ }
559
+ onClose().catch(console.error);
560
+ });
561
+ return new Response(readable, {
562
+ headers: {
563
+ "Cache-Control": "no-cache",
564
+ Connection: "keep-alive",
565
+ "Content-Type": "text/event-stream",
566
+ ...corsHeaders(request, corsOptions)
567
+ }
104
568
  });
105
569
  }
106
570
  if (request.method === "POST" && messagePattern.test(url)) {
107
571
  const sessionId = url.searchParams.get("sessionId");
108
572
  if (!sessionId) {
109
573
  return new Response(
110
- `Missing sessionId. Expected POST to ${path} to initiate new one`,
574
+ `Missing sessionId. Expected POST to ${pathname} to initiate new one`,
111
575
  { status: 400 }
112
576
  );
113
577
  }
114
- const object = namespace.get(namespace.idFromString(sessionId));
115
- const response = await object.onMCPMessage(request);
116
- const headerObj = {};
117
- response.headers.forEach((value, key) => {
118
- headerObj[key] = value;
119
- });
120
- headerObj["Access-Control-Allow-Origin"] = corsOptions?.origin || "*";
121
- return new Response(response.body, {
122
- status: response.status,
123
- statusText: response.statusText,
124
- headers: headerObj
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
587
+ );
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
125
620
  });
126
621
  }
127
622
  return new Response("Not Found", { status: 404 });
128
623
  }
129
624
  };
130
625
  }
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
+ }
131
907
  };
132
908
  export {
133
- McpAgent
909
+ ElicitRequestSchema,
910
+ McpAgent,
911
+ SSEEdgeClientTransport,
912
+ StreamableHTTPEdgeClientTransport
134
913
  };
135
914
  //# sourceMappingURL=index.js.map