agents 0.0.0-74a8c74 → 0.0.0-77368ff

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