agents 0.0.0-316f98c → 0.0.0-33ff003

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