agents 0.0.0-e4a2352 → 0.0.0-e8f693b

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 (77) hide show
  1. package/README.md +129 -7
  2. package/dist/ai-chat-agent.d.ts +20 -20
  3. package/dist/ai-chat-agent.js +532 -260
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
  6. package/dist/ai-chat-v5-migration-DBHGW4Hv.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -87
  10. package/dist/ai-react.js +261 -199
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-B3aQaFv3.js +20 -0
  13. package/dist/ai-types-B3aQaFv3.js.map +1 -0
  14. package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/client-9Ld2_lnt.js +786 -0
  18. package/dist/client-9Ld2_lnt.js.map +1 -0
  19. package/dist/client-B17XUTV7.d.ts +5313 -0
  20. package/dist/client-BfiZ3HQd.js +117 -0
  21. package/dist/client-BfiZ3HQd.js.map +1 -0
  22. package/dist/client-CbWe9FBd.d.ts +104 -0
  23. package/dist/client.d.ts +11 -92
  24. package/dist/client.js +4 -11
  25. package/dist/codemode/ai.d.ts +27 -0
  26. package/dist/codemode/ai.js +151 -0
  27. package/dist/codemode/ai.js.map +1 -0
  28. package/dist/do-oauth-client-provider-CswoD5Lu.js +93 -0
  29. package/dist/do-oauth-client-provider-CswoD5Lu.js.map +1 -0
  30. package/dist/do-oauth-client-provider-DGc5pP0l.d.ts +55 -0
  31. package/dist/{index-BCJclX6q.d.ts → index-B6MjW6n-.d.ts} +100 -155
  32. package/dist/index-DhJCaDWd.d.ts +58 -0
  33. package/dist/index.d.ts +69 -40
  34. package/dist/index.js +7 -28
  35. package/dist/mcp/client.d.ts +4 -11
  36. package/dist/mcp/client.js +3 -9
  37. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  38. package/dist/mcp/do-oauth-client-provider.js +3 -7
  39. package/dist/mcp/index.d.ts +126 -99
  40. package/dist/mcp/index.js +1222 -901
  41. package/dist/mcp/index.js.map +1 -1
  42. package/dist/mcp/x402.d.ts +34 -0
  43. package/dist/mcp/x402.js +194 -0
  44. package/dist/mcp/x402.js.map +1 -0
  45. package/dist/mcp-Dw5vDrY8.d.ts +61 -0
  46. package/dist/observability/index.d.ts +3 -14
  47. package/dist/observability/index.js +7 -10
  48. package/dist/react-CRBsIQ1z.d.ts +115 -0
  49. package/dist/react.d.ts +10 -121
  50. package/dist/react.js +183 -110
  51. package/dist/react.js.map +1 -1
  52. package/dist/schedule.d.ts +87 -10
  53. package/dist/schedule.js +46 -21
  54. package/dist/schedule.js.map +1 -1
  55. package/dist/serializable-CymX8ovI.d.ts +39 -0
  56. package/dist/serializable.d.ts +7 -32
  57. package/dist/serializable.js +1 -1
  58. package/dist/src-Dz0H9hSU.js +1200 -0
  59. package/dist/src-Dz0H9hSU.js.map +1 -0
  60. package/package.json +45 -11
  61. package/dist/ai-types.js.map +0 -1
  62. package/dist/chunk-HY7ZLHJB.js +0 -598
  63. package/dist/chunk-HY7ZLHJB.js.map +0 -1
  64. package/dist/chunk-JXN5WZFQ.js +0 -1287
  65. package/dist/chunk-JXN5WZFQ.js.map +0 -1
  66. package/dist/chunk-KUH345EY.js +0 -116
  67. package/dist/chunk-KUH345EY.js.map +0 -1
  68. package/dist/chunk-PVQZBKN7.js +0 -106
  69. package/dist/chunk-PVQZBKN7.js.map +0 -1
  70. package/dist/client-DgyzBU_8.d.ts +0 -4601
  71. package/dist/client.js.map +0 -1
  72. package/dist/index.js.map +0 -1
  73. package/dist/mcp/client.js.map +0 -1
  74. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  75. package/dist/observability/index.js.map +0 -1
  76. package/dist/serializable.js.map +0 -1
  77. package/src/index.ts +0 -1917
package/dist/mcp/index.js CHANGED
@@ -1,914 +1,1235 @@
1
- import {
2
- Agent
3
- } from "../chunk-JXN5WZFQ.js";
4
- import {
5
- SSEEdgeClientTransport,
6
- StreamableHTTPEdgeClientTransport
7
- } from "../chunk-HY7ZLHJB.js";
8
- import "../chunk-PVQZBKN7.js";
9
- import "../chunk-KUH345EY.js";
1
+ import { t as MessageType } from "../ai-types-B3aQaFv3.js";
2
+ import "../client-BfiZ3HQd.js";
3
+ import { a as SSEEdgeClientTransport, i as StreamableHTTPEdgeClientTransport } from "../client-9Ld2_lnt.js";
4
+ import "../do-oauth-client-provider-CswoD5Lu.js";
5
+ import { c as getCurrentAgent, s as getAgentByName, t as Agent } from "../src-Dz0H9hSU.js";
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
+ import { ElicitRequestSchema, InitializeRequestSchema, JSONRPCMessageSchema, isInitializeRequest, isJSONRPCError, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResponse } from "@modelcontextprotocol/sdk/types.js";
10
8
 
11
- // src/mcp/index.ts
12
- import { DurableObject } from "cloudflare:workers";
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;
9
+ //#region src/mcp/utils.ts
10
+ /**
11
+ * Since we use WebSockets to bridge the client to the
12
+ * MCP transport in the Agent, we use this header to signal
13
+ * the method of the original request the user made, while
14
+ * leaving the WS Upgrade request as GET.
15
+ */
16
+ const MCP_HTTP_METHOD_HEADER = "cf-mcp-method";
17
+ /**
18
+ * Since we use WebSockets to bridge the client to the
19
+ * MCP transport in the Agent, we use this header to include
20
+ * the original request body.
21
+ */
22
+ const MCP_MESSAGE_HEADER = "cf-mcp-message";
23
+ const MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
24
+ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
25
+ let pathname = basePath;
26
+ if (basePath === "/") pathname = "/*";
27
+ const basePattern = new URLPattern({ pathname });
28
+ return async (request, ctx) => {
29
+ const url = new URL(request.url);
30
+ if (basePattern.test(url)) {
31
+ if (request.method === "POST") {
32
+ const acceptHeader = request.headers.get("accept");
33
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
34
+ const body$1 = JSON.stringify({
35
+ error: {
36
+ code: -32e3,
37
+ message: "Not Acceptable: Client must accept both application/json and text/event-stream"
38
+ },
39
+ id: null,
40
+ jsonrpc: "2.0"
41
+ });
42
+ return new Response(body$1, { status: 406 });
43
+ }
44
+ const ct = request.headers.get("content-type");
45
+ if (!ct || !ct.includes("application/json")) {
46
+ const body$1 = JSON.stringify({
47
+ error: {
48
+ code: -32e3,
49
+ message: "Unsupported Media Type: Content-Type must be application/json"
50
+ },
51
+ id: null,
52
+ jsonrpc: "2.0"
53
+ });
54
+ return new Response(body$1, { status: 415 });
55
+ }
56
+ if (Number.parseInt(request.headers.get("content-length") ?? "0", 10) > MAXIMUM_MESSAGE_SIZE_BYTES) {
57
+ const body$1 = JSON.stringify({
58
+ error: {
59
+ code: -32e3,
60
+ message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
61
+ },
62
+ id: null,
63
+ jsonrpc: "2.0"
64
+ });
65
+ return new Response(body$1, { status: 413 });
66
+ }
67
+ let sessionId = request.headers.get("mcp-session-id");
68
+ let rawMessage;
69
+ try {
70
+ rawMessage = await request.json();
71
+ } catch (_error) {
72
+ const body$1 = JSON.stringify({
73
+ error: {
74
+ code: -32700,
75
+ message: "Parse error: Invalid JSON"
76
+ },
77
+ id: null,
78
+ jsonrpc: "2.0"
79
+ });
80
+ return new Response(body$1, { status: 400 });
81
+ }
82
+ let arrayMessage;
83
+ if (Array.isArray(rawMessage)) arrayMessage = rawMessage;
84
+ else arrayMessage = [rawMessage];
85
+ let messages = [];
86
+ for (const msg of arrayMessage) if (!JSONRPCMessageSchema.safeParse(msg).success) {
87
+ const body$1 = JSON.stringify({
88
+ error: {
89
+ code: -32700,
90
+ message: "Parse error: Invalid JSON-RPC message"
91
+ },
92
+ id: null,
93
+ jsonrpc: "2.0"
94
+ });
95
+ return new Response(body$1, { status: 400 });
96
+ }
97
+ messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
98
+ const maybeInitializeRequest = messages.find((msg) => InitializeRequestSchema.safeParse(msg).success);
99
+ if (!!maybeInitializeRequest && sessionId) {
100
+ const body$1 = JSON.stringify({
101
+ error: {
102
+ code: -32600,
103
+ message: "Invalid Request: Initialization requests must not include a sessionId"
104
+ },
105
+ id: null,
106
+ jsonrpc: "2.0"
107
+ });
108
+ return new Response(body$1, { status: 400 });
109
+ }
110
+ if (!!maybeInitializeRequest && messages.length > 1) {
111
+ const body$1 = JSON.stringify({
112
+ error: {
113
+ code: -32600,
114
+ message: "Invalid Request: Only one initialization request is allowed"
115
+ },
116
+ id: null,
117
+ jsonrpc: "2.0"
118
+ });
119
+ return new Response(body$1, { status: 400 });
120
+ }
121
+ if (!maybeInitializeRequest && !sessionId) {
122
+ const body$1 = JSON.stringify({
123
+ error: {
124
+ code: -32e3,
125
+ message: "Bad Request: Mcp-Session-Id header is required"
126
+ },
127
+ id: null,
128
+ jsonrpc: "2.0"
129
+ });
130
+ return new Response(body$1, { status: 400 });
131
+ }
132
+ sessionId = sessionId ?? namespace.newUniqueId().toString();
133
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
134
+ const isInitialized = await agent.getInitializeRequest();
135
+ if (maybeInitializeRequest) await agent.setInitializeRequest(maybeInitializeRequest);
136
+ else if (!isInitialized) {
137
+ const body$1 = JSON.stringify({
138
+ error: {
139
+ code: -32001,
140
+ message: "Session not found"
141
+ },
142
+ id: null,
143
+ jsonrpc: "2.0"
144
+ });
145
+ return new Response(body$1, { status: 404 });
146
+ }
147
+ const { readable, writable } = new TransformStream();
148
+ const writer = writable.getWriter();
149
+ const encoder = new TextEncoder();
150
+ const existingHeaders = {};
151
+ request.headers.forEach((value, key) => {
152
+ existingHeaders[key] = value;
153
+ });
154
+ const req = new Request(request.url, { headers: {
155
+ ...existingHeaders,
156
+ [MCP_HTTP_METHOD_HEADER]: "POST",
157
+ [MCP_MESSAGE_HEADER]: Buffer.from(JSON.stringify(messages)).toString("base64"),
158
+ Upgrade: "websocket"
159
+ } });
160
+ if (ctx.props) agent.updateProps(ctx.props);
161
+ const ws = (await agent.fetch(req)).webSocket;
162
+ if (!ws) {
163
+ console.error("Failed to establish WebSocket connection");
164
+ await writer.close();
165
+ const body$1 = JSON.stringify({
166
+ error: {
167
+ code: -32001,
168
+ message: "Failed to establish WebSocket connection"
169
+ },
170
+ id: null,
171
+ jsonrpc: "2.0"
172
+ });
173
+ return new Response(body$1, { status: 500 });
174
+ }
175
+ ws.accept();
176
+ ws.addEventListener("message", (event) => {
177
+ async function onMessage(event$1) {
178
+ try {
179
+ const data = typeof event$1.data === "string" ? event$1.data : new TextDecoder().decode(event$1.data);
180
+ const message = JSON.parse(data);
181
+ if (message.type !== MessageType.CF_MCP_AGENT_EVENT) return;
182
+ await writer.write(encoder.encode(message.event));
183
+ if (message.close) {
184
+ ws?.close();
185
+ await writer.close().catch(() => {});
186
+ }
187
+ } catch (error) {
188
+ console.error("Error forwarding message to SSE:", error);
189
+ }
190
+ }
191
+ onMessage(event).catch(console.error);
192
+ });
193
+ ws.addEventListener("error", (error) => {
194
+ async function onError(_error) {
195
+ await writer.close().catch(() => {});
196
+ }
197
+ onError(error).catch(console.error);
198
+ });
199
+ ws.addEventListener("close", () => {
200
+ async function onClose() {
201
+ await writer.close().catch(() => {});
202
+ }
203
+ onClose().catch(console.error);
204
+ });
205
+ if (messages.every((msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg))) {
206
+ ws.close();
207
+ return new Response(null, {
208
+ headers: corsHeaders(request, corsOptions),
209
+ status: 202
210
+ });
211
+ }
212
+ return new Response(readable, {
213
+ headers: {
214
+ "Cache-Control": "no-cache",
215
+ Connection: "keep-alive",
216
+ "Content-Type": "text/event-stream",
217
+ "mcp-session-id": sessionId,
218
+ ...corsHeaders(request, corsOptions)
219
+ },
220
+ status: 200
221
+ });
222
+ } else if (request.method === "GET") {
223
+ if (!request.headers.get("accept")?.includes("text/event-stream")) {
224
+ const body$1 = JSON.stringify({
225
+ jsonrpc: "2.0",
226
+ error: {
227
+ code: -32e3,
228
+ message: "Not Acceptable: Client must accept text/event-stream"
229
+ },
230
+ id: null
231
+ });
232
+ return new Response(body$1, { status: 406 });
233
+ }
234
+ const sessionId = request.headers.get("mcp-session-id");
235
+ if (!sessionId) return new Response(JSON.stringify({
236
+ error: {
237
+ code: -32e3,
238
+ message: "Bad Request: Mcp-Session-Id header is required"
239
+ },
240
+ id: null,
241
+ jsonrpc: "2.0"
242
+ }), { status: 400 });
243
+ const { readable, writable } = new TransformStream();
244
+ const writer = writable.getWriter();
245
+ const encoder = new TextEncoder();
246
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
247
+ if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
248
+ jsonrpc: "2.0",
249
+ error: {
250
+ code: -32001,
251
+ message: "Session not found"
252
+ },
253
+ id: null
254
+ }), { status: 404 });
255
+ const existingHeaders = {};
256
+ request.headers.forEach((v, k) => {
257
+ existingHeaders[k] = v;
258
+ });
259
+ if (ctx.props) agent.updateProps(ctx.props);
260
+ const ws = (await agent.fetch(new Request(request.url, { headers: {
261
+ ...existingHeaders,
262
+ [MCP_HTTP_METHOD_HEADER]: "GET",
263
+ Upgrade: "websocket"
264
+ } }))).webSocket;
265
+ if (!ws) {
266
+ await writer.close();
267
+ return new Response("Failed to establish WS to DO", { status: 500 });
268
+ }
269
+ ws.accept();
270
+ ws.addEventListener("message", (event) => {
271
+ try {
272
+ async function onMessage(ev) {
273
+ const data = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
274
+ const message = JSON.parse(data);
275
+ if (message.type !== MessageType.CF_MCP_AGENT_EVENT) return;
276
+ await writer.write(encoder.encode(message.event));
277
+ }
278
+ onMessage(event).catch(console.error);
279
+ } catch (e) {
280
+ console.error("Error forwarding message to SSE:", e);
281
+ }
282
+ });
283
+ ws.addEventListener("error", () => {
284
+ writer.close().catch(() => {});
285
+ });
286
+ ws.addEventListener("close", () => {
287
+ writer.close().catch(() => {});
288
+ });
289
+ return new Response(readable, {
290
+ headers: {
291
+ "Cache-Control": "no-cache",
292
+ Connection: "keep-alive",
293
+ "Content-Type": "text/event-stream",
294
+ "mcp-session-id": sessionId,
295
+ ...corsHeaders(request, corsOptions)
296
+ },
297
+ status: 200
298
+ });
299
+ } else if (request.method === "DELETE") {
300
+ const sessionId = request.headers.get("mcp-session-id");
301
+ if (!sessionId) return new Response(JSON.stringify({
302
+ jsonrpc: "2.0",
303
+ error: {
304
+ code: -32e3,
305
+ message: "Bad Request: Mcp-Session-Id header is required"
306
+ },
307
+ id: null
308
+ }), {
309
+ status: 400,
310
+ headers: corsHeaders(request, corsOptions)
311
+ });
312
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`);
313
+ if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
314
+ jsonrpc: "2.0",
315
+ error: {
316
+ code: -32001,
317
+ message: "Session not found"
318
+ },
319
+ id: null
320
+ }), {
321
+ status: 404,
322
+ headers: corsHeaders(request, corsOptions)
323
+ });
324
+ ctx.waitUntil(agent.destroy().catch(() => {}));
325
+ return new Response(null, {
326
+ status: 204,
327
+ headers: corsHeaders(request, corsOptions)
328
+ });
329
+ }
330
+ }
331
+ const body = JSON.stringify({
332
+ error: {
333
+ code: -32e3,
334
+ message: "Not found"
335
+ },
336
+ id: null,
337
+ jsonrpc: "2.0"
338
+ });
339
+ return new Response(body, { status: 404 });
340
+ };
341
+ };
342
+ const createLegacySseHandler = (basePath, namespace, corsOptions) => {
343
+ let pathname = basePath;
344
+ if (basePath === "/") pathname = "/*";
345
+ const basePattern = new URLPattern({ pathname });
346
+ const messagePattern = new URLPattern({ pathname: `${basePath}/message` });
347
+ return async (request, ctx) => {
348
+ const url = new URL(request.url);
349
+ if (request.method === "GET" && basePattern.test(url)) {
350
+ const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
351
+ const { readable, writable } = new TransformStream();
352
+ const writer = writable.getWriter();
353
+ const encoder = new TextEncoder();
354
+ const endpointUrl = new URL(request.url);
355
+ endpointUrl.pathname = encodeURI(`${basePath}/message`);
356
+ endpointUrl.searchParams.set("sessionId", sessionId);
357
+ const endpointMessage = `event: endpoint\ndata: ${endpointUrl.pathname + endpointUrl.search + endpointUrl.hash}\n\n`;
358
+ writer.write(encoder.encode(endpointMessage));
359
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
360
+ const existingHeaders = {};
361
+ request.headers.forEach((value, key) => {
362
+ existingHeaders[key] = value;
363
+ });
364
+ if (ctx.props) agent.updateProps(ctx.props);
365
+ const ws = (await agent.fetch(new Request(request.url, { headers: {
366
+ ...existingHeaders,
367
+ Upgrade: "websocket"
368
+ } }))).webSocket;
369
+ if (!ws) {
370
+ console.error("Failed to establish WebSocket connection");
371
+ await writer.close();
372
+ return new Response("Failed to establish WebSocket connection", { status: 500 });
373
+ }
374
+ ws.accept();
375
+ ws.addEventListener("message", (event) => {
376
+ async function onMessage(event$1) {
377
+ try {
378
+ const message = JSON.parse(event$1.data);
379
+ const result = JSONRPCMessageSchema.safeParse(message);
380
+ if (!result.success) return;
381
+ const messageText = `event: message\ndata: ${JSON.stringify(result.data)}\n\n`;
382
+ await writer.write(encoder.encode(messageText));
383
+ } catch (error) {
384
+ console.error("Error forwarding message to SSE:", error);
385
+ }
386
+ }
387
+ onMessage(event).catch(console.error);
388
+ });
389
+ ws.addEventListener("error", (error) => {
390
+ async function onError(_error) {
391
+ try {
392
+ await writer.close();
393
+ } catch (_e) {}
394
+ }
395
+ onError(error).catch(console.error);
396
+ });
397
+ ws.addEventListener("close", () => {
398
+ async function onClose() {
399
+ try {
400
+ await writer.close();
401
+ } catch (error) {
402
+ console.error("Error closing SSE connection:", error);
403
+ }
404
+ }
405
+ onClose().catch(console.error);
406
+ });
407
+ return new Response(readable, { headers: {
408
+ "Cache-Control": "no-cache",
409
+ Connection: "keep-alive",
410
+ "Content-Type": "text/event-stream",
411
+ ...corsHeaders(request, corsOptions)
412
+ } });
413
+ }
414
+ if (request.method === "POST" && messagePattern.test(url)) {
415
+ const sessionId = url.searchParams.get("sessionId");
416
+ if (!sessionId) return new Response(`Missing sessionId. Expected POST to ${basePath} to initiate new one`, { status: 400 });
417
+ const contentType = request.headers.get("content-type") || "";
418
+ if (!contentType.includes("application/json")) return new Response(`Unsupported content-type: ${contentType}`, { status: 400 });
419
+ const contentLength = Number.parseInt(request.headers.get("content-length") || "0", 10);
420
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) return new Response(`Request body too large: ${contentLength} bytes`, { status: 400 });
421
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
422
+ const messageBody = await request.json();
423
+ const error = await agent.onSSEMcpMessage(sessionId, messageBody);
424
+ if (error) return new Response(error.message, {
425
+ headers: {
426
+ "Cache-Control": "no-cache",
427
+ Connection: "keep-alive",
428
+ "Content-Type": "text/event-stream",
429
+ ...corsHeaders(request, corsOptions)
430
+ },
431
+ status: 400
432
+ });
433
+ return new Response("Accepted", {
434
+ headers: {
435
+ "Cache-Control": "no-cache",
436
+ Connection: "keep-alive",
437
+ "Content-Type": "text/event-stream",
438
+ ...corsHeaders(request, corsOptions)
439
+ },
440
+ status: 202
441
+ });
442
+ }
443
+ return new Response("Not Found", { status: 404 });
444
+ };
445
+ };
25
446
  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()
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";
447
+ const origin = "*";
448
+ return {
449
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, Accept, mcp-session-id, mcp-protocol-version",
450
+ "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, DELETE, OPTIONS",
451
+ "Access-Control-Allow-Origin": corsOptions.origin || origin,
452
+ "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
453
+ "Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
454
+ };
37
455
  }
38
456
  function handleCORS(request, corsOptions) {
39
- if (request.method === "OPTIONS") {
40
- return new Response(null, { headers: corsHeaders(request, corsOptions) });
41
- }
42
- return null;
457
+ if (request.method === "OPTIONS") return new Response(null, { headers: corsHeaders(request, corsOptions) });
458
+ return null;
43
459
  }
460
+ function isDurableObjectNamespace(namespace) {
461
+ return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
462
+ }
463
+
464
+ //#endregion
465
+ //#region src/mcp/transport.ts
44
466
  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
- }
467
+ constructor(getWebSocket) {
468
+ this._started = false;
469
+ this._getWebSocket = getWebSocket;
470
+ }
471
+ async start() {
472
+ if (this._started) throw new Error("Transport already started");
473
+ this._started = true;
474
+ }
475
+ async send(message) {
476
+ if (!this._started) throw new Error("Transport not started");
477
+ const websocket = this._getWebSocket();
478
+ if (!websocket) throw new Error("WebSocket not connected");
479
+ try {
480
+ websocket.send(JSON.stringify(message));
481
+ } catch (error) {
482
+ this.onerror?.(error);
483
+ }
484
+ }
485
+ async close() {
486
+ this.onclose?.();
487
+ }
73
488
  };
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
- }
489
+ /**
490
+ * Adapted from: https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/client/streamableHttp.ts
491
+ * - Validation and initialization are removed as they're handled in `McpAgent.serve()` handler.
492
+ * - Replaces the Node-style `req`/`res` with Worker's `Request`.
493
+ * - Writes events as WS messages that the Worker forwards to the client as SSE events.
494
+ * - Replaces the in-memory maps that track requestID/stream by using `connection.setState()` and `agent.getConnections()`.
495
+ *
496
+ * Besides these points, the implementation is the same and should be updated to match the original as new features are added.
497
+ */
498
+ var StreamableHTTPServerTransport = class {
499
+ constructor(options) {
500
+ this._started = false;
501
+ this._requestResponseMap = /* @__PURE__ */ new Map();
502
+ const { agent } = getCurrentAgent();
503
+ if (!agent) throw new Error("McpAgent was not found in Transport constructor");
504
+ this.sessionId = agent.getSessionId();
505
+ this._eventStore = options.eventStore;
506
+ }
507
+ /**
508
+ * Starts the transport. This is required by the Transport interface but is a no-op
509
+ * for the Streamable HTTP transport as connections are managed per-request.
510
+ */
511
+ async start() {
512
+ if (this._started) throw new Error("Transport already started");
513
+ this._started = true;
514
+ }
515
+ /**
516
+ * Handles GET requests for SSE stream
517
+ */
518
+ async handleGetRequest(req) {
519
+ const { connection } = getCurrentAgent();
520
+ if (!connection) throw new Error("Connection was not found in handleGetRequest");
521
+ if (this._eventStore) {
522
+ const lastEventId = req.headers.get("last-event-id");
523
+ if (lastEventId) {
524
+ await this.replayEvents(lastEventId);
525
+ return;
526
+ }
527
+ }
528
+ connection.setState({ _standaloneSse: true });
529
+ }
530
+ /**
531
+ * Replays events that would have been sent after the specified event ID
532
+ * Only used when resumability is enabled
533
+ */
534
+ async replayEvents(lastEventId) {
535
+ if (!this._eventStore) return;
536
+ const { connection } = getCurrentAgent();
537
+ if (!connection) throw new Error("Connection was not available in replayEvents");
538
+ try {
539
+ await this._eventStore?.replayEventsAfter(lastEventId, { send: async (eventId, message) => {
540
+ try {
541
+ this.writeSSEEvent(connection, message, eventId);
542
+ } catch (error) {
543
+ this.onerror?.(error);
544
+ }
545
+ } });
546
+ } catch (error) {
547
+ this.onerror?.(error);
548
+ }
549
+ }
550
+ /**
551
+ * Writes an event to the SSE stream with proper formatting
552
+ */
553
+ writeSSEEvent(connection, message, eventId, close) {
554
+ let eventData = "event: message\n";
555
+ if (eventId) eventData += `id: ${eventId}\n`;
556
+ eventData += `data: ${JSON.stringify(message)}\n\n`;
557
+ return connection.send(JSON.stringify({
558
+ type: MessageType.CF_MCP_AGENT_EVENT,
559
+ event: eventData,
560
+ close
561
+ }));
562
+ }
563
+ /**
564
+ * Handles POST requests containing JSON-RPC messages
565
+ */
566
+ async handlePostRequest(req, parsedBody) {
567
+ const authInfo = req.auth;
568
+ const requestInfo = { headers: Object.fromEntries(req.headers.entries()) };
569
+ delete requestInfo.headers[MCP_HTTP_METHOD_HEADER];
570
+ delete requestInfo.headers[MCP_MESSAGE_HEADER];
571
+ delete requestInfo.headers.upgrade;
572
+ const rawMessage = parsedBody;
573
+ let messages;
574
+ if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
575
+ else messages = [JSONRPCMessageSchema.parse(rawMessage)];
576
+ const hasRequests = messages.some(isJSONRPCRequest);
577
+ if (!hasRequests) for (const message of messages) this.onmessage?.(message, {
578
+ authInfo,
579
+ requestInfo
580
+ });
581
+ else if (hasRequests) {
582
+ const { connection } = getCurrentAgent();
583
+ if (!connection) throw new Error("Connection was not found in handlePostRequest");
584
+ const requestIds = messages.filter(isJSONRPCRequest).map((message) => message.id);
585
+ connection.setState({ requestIds });
586
+ for (const message of messages) this.onmessage?.(message, {
587
+ authInfo,
588
+ requestInfo
589
+ });
590
+ }
591
+ }
592
+ async close() {
593
+ const { agent } = getCurrentAgent();
594
+ if (!agent) throw new Error("Agent was not found in close");
595
+ for (const conn of agent.getConnections()) conn.close(1e3, "Session closed");
596
+ this.onclose?.();
597
+ }
598
+ async send(message, options) {
599
+ const { agent } = getCurrentAgent();
600
+ if (!agent) throw new Error("Agent was not found in send");
601
+ let requestId = options?.relatedRequestId;
602
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) requestId = message.id;
603
+ if (requestId === void 0) {
604
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
605
+ let standaloneConnection;
606
+ for (const conn of agent.getConnections()) if (conn.state?._standaloneSse) standaloneConnection = conn;
607
+ if (standaloneConnection === void 0) return;
608
+ let eventId$1;
609
+ if (this._eventStore) eventId$1 = await this._eventStore.storeEvent(standaloneConnection.id, message);
610
+ this.writeSSEEvent(standaloneConnection, message, eventId$1);
611
+ return;
612
+ }
613
+ const connection = Array.from(agent.getConnections()).find((conn) => conn.state?.requestIds?.includes(requestId));
614
+ if (!connection) throw new Error(`No connection established for request ID: ${String(requestId)}`);
615
+ let eventId;
616
+ if (this._eventStore) eventId = await this._eventStore.storeEvent(connection.id, message);
617
+ let shouldClose = false;
618
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
619
+ this._requestResponseMap.set(requestId, message);
620
+ const relatedIds = connection.state?.requestIds ?? [];
621
+ shouldClose = relatedIds.every((id) => this._requestResponseMap.has(id));
622
+ if (shouldClose) for (const id of relatedIds) this._requestResponseMap.delete(id);
623
+ }
624
+ this.writeSSEEvent(connection, message, eventId, shouldClose);
625
+ }
117
626
  };
118
- var McpAgent = class _McpAgent extends DurableObject {
119
- constructor(ctx, env) {
120
- var _a;
121
- super(ctx, env);
122
- this._status = "zero";
123
- this._transportType = "unset";
124
- this._requestIdToConnectionId = /* @__PURE__ */ new Map();
125
- this.initRun = false;
126
- const self = this;
127
- this._agent = new (_a = class extends Agent {
128
- onStateUpdate(state, source) {
129
- return self.onStateUpdate(state, source);
130
- }
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;
140
- }
141
- get state() {
142
- return this._agent.state;
143
- }
144
- sql(strings, ...values) {
145
- return this._agent.sql(strings, ...values);
146
- }
147
- 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);
187
- }
188
- // we leave the variables as unused for autocomplete purposes
189
- // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
190
- onStateUpdate(state, source) {
191
- }
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
- }
226
- async _init(props) {
227
- await this.updateProps(props);
228
- if (!this.ctx.storage.get("transportType")) {
229
- await this.ctx.storage.put("transportType", "unset");
230
- }
231
- if (!this.initRun) {
232
- this.initRun = true;
233
- await this.init();
234
- }
235
- }
236
- async setInitialized() {
237
- await this.ctx.storage.put("initialized", true);
238
- }
239
- async isInitialized() {
240
- return await this.ctx.storage.get("initialized") === true;
241
- }
242
- async updateProps(props) {
243
- await this.ctx.storage.put("props", props ?? {});
244
- this.props = props;
245
- }
246
- async _initialize() {
247
- await this.ctx.blockConcurrencyWhile(async () => {
248
- this._status = "starting";
249
- await this.onStart();
250
- this._status = "started";
251
- });
252
- }
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
- }
428
- }
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);
448
- }
449
- static mount(path, {
450
- binding = "MCP_OBJECT",
451
- corsOptions
452
- } = {}) {
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` });
465
- return {
466
- async fetch(request, env, ctx) {
467
- const corsResponse = handleCORS(request, corsOptions);
468
- if (corsResponse) return corsResponse;
469
- const url = new URL(request.url);
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;
481
- if (request.method === "GET" && basePattern.test(url)) {
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
627
 
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;
503
- });
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)}
628
+ //#endregion
629
+ //#region src/mcp/worker-transport.ts
630
+ var WorkerTransport = class {
631
+ constructor(options) {
632
+ this.started = false;
633
+ this.initialized = false;
634
+ this.enableJsonResponse = false;
635
+ this.standaloneSseStreamId = "_GET_stream";
636
+ this.streamMapping = /* @__PURE__ */ new Map();
637
+ this.requestToStreamMapping = /* @__PURE__ */ new Map();
638
+ this.requestResponseMap = /* @__PURE__ */ new Map();
639
+ this.sessionIdGenerator = options?.sessionIdGenerator;
640
+ this.enableJsonResponse = options?.enableJsonResponse ?? false;
641
+ this.onsessioninitialized = options?.onsessioninitialized;
642
+ }
643
+ async start() {
644
+ if (this.started) throw new Error("Transport already started");
645
+ this.started = true;
646
+ }
647
+ async handleRequest(request, parsedBody) {
648
+ switch (request.method) {
649
+ case "OPTIONS": return this.handleOptionsRequest(request);
650
+ case "GET": return this.handleGetRequest(request);
651
+ case "POST": return this.handlePostRequest(request, parsedBody);
652
+ case "DELETE": return this.handleDeleteRequest(request);
653
+ default: return this.handleUnsupportedRequest();
654
+ }
655
+ }
656
+ async handleGetRequest(request) {
657
+ if (!request.headers.get("Accept")?.includes("text/event-stream")) return new Response(JSON.stringify({
658
+ jsonrpc: "2.0",
659
+ error: {
660
+ code: -32e3,
661
+ message: "Not Acceptable: Client must accept text/event-stream"
662
+ },
663
+ id: null
664
+ }), {
665
+ status: 406,
666
+ headers: { "Content-Type": "application/json" }
667
+ });
668
+ const sessionValid = this.validateSession(request);
669
+ if (sessionValid !== true) return sessionValid;
670
+ const streamId = this.standaloneSseStreamId;
671
+ if (this.streamMapping.get(streamId) !== void 0) return new Response(JSON.stringify({
672
+ jsonrpc: "2.0",
673
+ error: {
674
+ code: -32e3,
675
+ message: "Conflict: Only one SSE stream is allowed per session"
676
+ },
677
+ id: null
678
+ }), {
679
+ status: 409,
680
+ headers: { "Content-Type": "application/json" }
681
+ });
682
+ const { readable, writable } = new TransformStream();
683
+ const writer = writable.getWriter();
684
+ const encoder = new TextEncoder();
685
+ const headers = new Headers({
686
+ "Content-Type": "text/event-stream",
687
+ "Cache-Control": "no-cache",
688
+ Connection: "keep-alive",
689
+ "Access-Control-Allow-Origin": "*",
690
+ "Access-Control-Expose-Headers": "mcp-session-id"
691
+ });
692
+ if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
693
+ const keepAlive = setInterval(() => {
694
+ try {
695
+ writer.write(encoder.encode("event: ping\ndata: \n\n"));
696
+ } catch {
697
+ clearInterval(keepAlive);
698
+ }
699
+ }, 3e4);
700
+ this.streamMapping.set(streamId, {
701
+ writer,
702
+ encoder,
703
+ cleanup: () => {
704
+ clearInterval(keepAlive);
705
+ this.streamMapping.delete(streamId);
706
+ writer.close().catch(() => {});
707
+ }
708
+ });
709
+ return new Response(readable, { headers });
710
+ }
711
+ async handlePostRequest(request, parsedBody) {
712
+ const acceptHeader = request.headers.get("Accept");
713
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) return new Response(JSON.stringify({
714
+ jsonrpc: "2.0",
715
+ error: {
716
+ code: -32e3,
717
+ message: "Not Acceptable: Client must accept both application/json and text/event-stream"
718
+ },
719
+ id: null
720
+ }), {
721
+ status: 406,
722
+ headers: { "Content-Type": "application/json" }
723
+ });
724
+ if (!request.headers.get("Content-Type")?.includes("application/json")) return new Response(JSON.stringify({
725
+ jsonrpc: "2.0",
726
+ error: {
727
+ code: -32e3,
728
+ message: "Unsupported Media Type: Content-Type must be application/json"
729
+ },
730
+ id: null
731
+ }), {
732
+ status: 415,
733
+ headers: { "Content-Type": "application/json" }
734
+ });
735
+ let rawMessage = parsedBody;
736
+ if (rawMessage === void 0) try {
737
+ rawMessage = await request.json();
738
+ } catch {
739
+ return new Response(JSON.stringify({
740
+ jsonrpc: "2.0",
741
+ error: {
742
+ code: -32700,
743
+ message: "Parse error: Invalid JSON"
744
+ },
745
+ id: null
746
+ }), {
747
+ status: 400,
748
+ headers: { "Content-Type": "application/json" }
749
+ });
750
+ }
751
+ let messages;
752
+ try {
753
+ if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
754
+ else messages = [JSONRPCMessageSchema.parse(rawMessage)];
755
+ } catch {
756
+ return new Response(JSON.stringify({
757
+ jsonrpc: "2.0",
758
+ error: {
759
+ code: -32700,
760
+ message: "Parse error: Invalid JSON-RPC message"
761
+ },
762
+ id: null
763
+ }), {
764
+ status: 400,
765
+ headers: { "Content-Type": "application/json" }
766
+ });
767
+ }
768
+ const isInitializationRequest = messages.some(isInitializeRequest);
769
+ if (isInitializationRequest) {
770
+ if (this.initialized && this.sessionId !== void 0) return new Response(JSON.stringify({
771
+ jsonrpc: "2.0",
772
+ error: {
773
+ code: -32600,
774
+ message: "Invalid Request: Server already initialized"
775
+ },
776
+ id: null
777
+ }), {
778
+ status: 400,
779
+ headers: { "Content-Type": "application/json" }
780
+ });
781
+ if (messages.length > 1) return new Response(JSON.stringify({
782
+ jsonrpc: "2.0",
783
+ error: {
784
+ code: -32600,
785
+ message: "Invalid Request: Only one initialization request is allowed"
786
+ },
787
+ id: null
788
+ }), {
789
+ status: 400,
790
+ headers: { "Content-Type": "application/json" }
791
+ });
792
+ this.sessionId = this.sessionIdGenerator?.();
793
+ this.initialized = true;
794
+ if (this.sessionId && this.onsessioninitialized) this.onsessioninitialized(this.sessionId);
795
+ }
796
+ if (!isInitializationRequest) {
797
+ const sessionValid = this.validateSession(request);
798
+ if (sessionValid !== true) return sessionValid;
799
+ }
800
+ if (!messages.some(isJSONRPCRequest)) {
801
+ for (const message of messages) this.onmessage?.(message);
802
+ return new Response(null, {
803
+ status: 202,
804
+ headers: { "Access-Control-Allow-Origin": "*" }
805
+ });
806
+ }
807
+ const streamId = crypto.randomUUID();
808
+ if (this.enableJsonResponse) return new Promise((resolve) => {
809
+ this.streamMapping.set(streamId, {
810
+ resolveJson: resolve,
811
+ cleanup: () => {
812
+ this.streamMapping.delete(streamId);
813
+ }
814
+ });
815
+ for (const message of messages) if (isJSONRPCRequest(message)) this.requestToStreamMapping.set(message.id, streamId);
816
+ for (const message of messages) this.onmessage?.(message);
817
+ });
818
+ const { readable, writable } = new TransformStream();
819
+ const writer = writable.getWriter();
820
+ const encoder = new TextEncoder();
821
+ const headers = new Headers({
822
+ "Content-Type": "text/event-stream",
823
+ "Cache-Control": "no-cache",
824
+ Connection: "keep-alive",
825
+ "Access-Control-Allow-Origin": "*",
826
+ "Access-Control-Expose-Headers": "mcp-session-id"
827
+ });
828
+ if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
829
+ this.streamMapping.set(streamId, {
830
+ writer,
831
+ encoder,
832
+ cleanup: () => {
833
+ this.streamMapping.delete(streamId);
834
+ writer.close().catch(() => {});
835
+ }
836
+ });
837
+ for (const message of messages) if (isJSONRPCRequest(message)) this.requestToStreamMapping.set(message.id, streamId);
838
+ for (const message of messages) this.onmessage?.(message);
839
+ return new Response(readable, { headers });
840
+ }
841
+ async handleDeleteRequest(request) {
842
+ const sessionValid = this.validateSession(request);
843
+ if (sessionValid !== true) return sessionValid;
844
+ await this.close();
845
+ return new Response(null, {
846
+ status: 200,
847
+ headers: { "Access-Control-Allow-Origin": "*" }
848
+ });
849
+ }
850
+ handleOptionsRequest(_request) {
851
+ const headers = new Headers({
852
+ "Access-Control-Allow-Origin": "*",
853
+ "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
854
+ "Access-Control-Allow-Headers": "Content-Type, Accept, Authorization, mcp-session-id",
855
+ "Access-Control-Max-Age": "86400"
856
+ });
857
+ return new Response(null, {
858
+ status: 204,
859
+ headers
860
+ });
861
+ }
862
+ handleUnsupportedRequest() {
863
+ return new Response(JSON.stringify({
864
+ jsonrpc: "2.0",
865
+ error: {
866
+ code: -32e3,
867
+ message: "Method not allowed."
868
+ },
869
+ id: null
870
+ }), {
871
+ status: 405,
872
+ headers: {
873
+ Allow: "GET, POST, DELETE, OPTIONS",
874
+ "Content-Type": "application/json"
875
+ }
876
+ });
877
+ }
878
+ validateSession(request) {
879
+ if (this.sessionIdGenerator === void 0) return true;
880
+ if (!this.initialized) return new Response(JSON.stringify({
881
+ jsonrpc: "2.0",
882
+ error: {
883
+ code: -32e3,
884
+ message: "Bad Request: Server not initialized"
885
+ },
886
+ id: null
887
+ }), {
888
+ status: 400,
889
+ headers: { "Content-Type": "application/json" }
890
+ });
891
+ const sessionId = request.headers.get("mcp-session-id");
892
+ if (!sessionId) return new Response(JSON.stringify({
893
+ jsonrpc: "2.0",
894
+ error: {
895
+ code: -32e3,
896
+ message: "Bad Request: Mcp-Session-Id header is required"
897
+ },
898
+ id: null
899
+ }), {
900
+ status: 400,
901
+ headers: { "Content-Type": "application/json" }
902
+ });
903
+ if (sessionId !== this.sessionId) return new Response(JSON.stringify({
904
+ jsonrpc: "2.0",
905
+ error: {
906
+ code: -32001,
907
+ message: "Session not found"
908
+ },
909
+ id: null
910
+ }), {
911
+ status: 404,
912
+ headers: { "Content-Type": "application/json" }
913
+ });
914
+ return true;
915
+ }
916
+ async close() {
917
+ for (const { cleanup } of this.streamMapping.values()) cleanup();
918
+ this.streamMapping.clear();
919
+ this.requestResponseMap.clear();
920
+ this.onclose?.();
921
+ }
922
+ async send(message) {
923
+ let requestId;
924
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) requestId = message.id;
925
+ if (requestId === void 0) {
926
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
927
+ const standaloneSse = this.streamMapping.get(this.standaloneSseStreamId);
928
+ if (standaloneSse === void 0) return;
929
+ if (standaloneSse.writer && standaloneSse.encoder) {
930
+ const data = `event: message\ndata: ${JSON.stringify(message)}\n\n`;
931
+ await standaloneSse.writer.write(standaloneSse.encoder.encode(data));
932
+ }
933
+ return;
934
+ }
935
+ const streamId = this.requestToStreamMapping.get(requestId);
936
+ if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`);
937
+ const response = this.streamMapping.get(streamId);
938
+ if (!response) throw new Error(`No connection established for request ID: ${String(requestId)}`);
939
+ if (!this.enableJsonResponse) {
940
+ if (response.writer && response.encoder) {
941
+ const data = `event: message\ndata: ${JSON.stringify(message)}\n\n`;
942
+ await response.writer.write(response.encoder.encode(data));
943
+ }
944
+ }
945
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
946
+ this.requestResponseMap.set(requestId, message);
947
+ const relatedIds = Array.from(this.requestToStreamMapping.entries()).filter(([, sid]) => sid === streamId).map(([id]) => id);
948
+ if (relatedIds.every((id) => this.requestResponseMap.has(id))) {
949
+ if (this.enableJsonResponse && response.resolveJson) {
950
+ const responses = relatedIds.map((id) => this.requestResponseMap.get(id));
951
+ const headers = new Headers({
952
+ "Content-Type": "application/json",
953
+ "Access-Control-Allow-Origin": "*",
954
+ "Access-Control-Expose-Headers": "mcp-session-id"
955
+ });
956
+ if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
957
+ const body = responses.length === 1 ? responses[0] : responses;
958
+ response.resolveJson(new Response(JSON.stringify(body), { headers }));
959
+ } else response.cleanup();
960
+ for (const id of relatedIds) {
961
+ this.requestResponseMap.delete(id);
962
+ this.requestToStreamMapping.delete(id);
963
+ }
964
+ }
965
+ }
966
+ }
967
+ };
533
968
 
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
- }
568
- });
569
- }
570
- if (request.method === "POST" && messagePattern.test(url)) {
571
- const sessionId = url.searchParams.get("sessionId");
572
- if (!sessionId) {
573
- return new Response(
574
- `Missing sessionId. Expected POST to ${pathname} to initiate new one`,
575
- { status: 400 }
576
- );
577
- }
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
620
- });
621
- }
622
- return new Response("Not Found", { status: 404 });
623
- }
624
- };
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)}
969
+ //#endregion
970
+ //#region src/mcp/auth-context.ts
971
+ const authContextStorage = new AsyncLocalStorage();
972
+ function getMcpAuthContext() {
973
+ return authContextStorage.getStore();
974
+ }
975
+ function runWithAuthContext(context, fn) {
976
+ return authContextStorage.run(context, fn);
977
+ }
834
978
 
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
- }
907
- };
908
- export {
909
- ElicitRequestSchema,
910
- McpAgent,
911
- SSEEdgeClientTransport,
912
- StreamableHTTPEdgeClientTransport
979
+ //#endregion
980
+ //#region src/mcp/handler.ts
981
+ function experimental_createMcpHandler(server, options = {}) {
982
+ const route = options.route ?? "/mcp";
983
+ return async (request, _env, ctx) => {
984
+ const url = new URL(request.url);
985
+ if (route && url.pathname !== route) return new Response("Not Found", { status: 404 });
986
+ const oauthCtx = ctx;
987
+ const authContext = oauthCtx.props ? { props: oauthCtx.props } : void 0;
988
+ const transport = new WorkerTransport(options);
989
+ await server.connect(transport);
990
+ const handleRequest = async () => {
991
+ return await transport.handleRequest(request);
992
+ };
993
+ try {
994
+ let response;
995
+ if (authContext) response = await runWithAuthContext(authContext, handleRequest);
996
+ else response = await handleRequest();
997
+ return response;
998
+ } catch (error) {
999
+ console.error("MCP handler error:", error);
1000
+ return new Response(JSON.stringify({
1001
+ jsonrpc: "2.0",
1002
+ error: {
1003
+ code: -32603,
1004
+ message: error instanceof Error ? error.message : "Internal server error"
1005
+ },
1006
+ id: null
1007
+ }), {
1008
+ status: 500,
1009
+ headers: { "Content-Type": "application/json" }
1010
+ });
1011
+ }
1012
+ };
1013
+ }
1014
+
1015
+ //#endregion
1016
+ //#region src/mcp/index.ts
1017
+ var McpAgent = class McpAgent extends Agent {
1018
+ async setInitializeRequest(initializeRequest) {
1019
+ await this.ctx.storage.put("initializeRequest", initializeRequest);
1020
+ }
1021
+ async getInitializeRequest() {
1022
+ return this.ctx.storage.get("initializeRequest");
1023
+ }
1024
+ /** Read the transport type for this agent.
1025
+ * This relies on the naming scheme being `sse:${sessionId}`
1026
+ * or `streamable-http:${sessionId}`.
1027
+ */
1028
+ getTransportType() {
1029
+ const [t, ..._] = this.name.split(":");
1030
+ switch (t) {
1031
+ case "sse": return "sse";
1032
+ case "streamable-http": return "streamable-http";
1033
+ default: throw new Error("Invalid transport type. McpAgent must be addressed with a valid protocol.");
1034
+ }
1035
+ }
1036
+ /** Read the sessionId for this agent.
1037
+ * This relies on the naming scheme being `sse:${sessionId}`
1038
+ * or `streamable-http:${sessionId}`.
1039
+ */
1040
+ getSessionId() {
1041
+ const [_, sessionId] = this.name.split(":");
1042
+ if (!sessionId) throw new Error("Invalid session id. McpAgent must be addressed with a valid session id.");
1043
+ return sessionId;
1044
+ }
1045
+ /** Get the unique WebSocket. SSE transport only. */
1046
+ getWebSocket() {
1047
+ const websockets = Array.from(this.getConnections());
1048
+ if (websockets.length === 0) return null;
1049
+ return websockets[0];
1050
+ }
1051
+ /** Returns a new transport matching the type of the Agent. */
1052
+ initTransport() {
1053
+ switch (this.getTransportType()) {
1054
+ case "sse": return new McpSSETransport(() => this.getWebSocket());
1055
+ case "streamable-http": return new StreamableHTTPServerTransport({});
1056
+ }
1057
+ }
1058
+ /** Update and store the props */
1059
+ async updateProps(props) {
1060
+ await this.ctx.storage.put("props", props ?? {});
1061
+ this.props = props;
1062
+ }
1063
+ async reinitializeServer() {
1064
+ const initializeRequest = await this.getInitializeRequest();
1065
+ if (initializeRequest) this._transport?.onmessage?.(initializeRequest);
1066
+ }
1067
+ /** Sets up the MCP transport and server every time the Agent is started.*/
1068
+ async onStart(props) {
1069
+ if (props) await this.updateProps(props);
1070
+ this.props = await this.ctx.storage.get("props");
1071
+ await this.init();
1072
+ const server = await this.server;
1073
+ this._transport = this.initTransport();
1074
+ await server.connect(this._transport);
1075
+ await this.reinitializeServer();
1076
+ }
1077
+ /** Validates new WebSocket connections. */
1078
+ async onConnect(conn, { request: req }) {
1079
+ switch (this.getTransportType()) {
1080
+ case "sse":
1081
+ if (Array.from(this.getConnections()).length > 1) {
1082
+ conn.close(1008, "Websocket already connected");
1083
+ return;
1084
+ }
1085
+ break;
1086
+ case "streamable-http": if (this._transport instanceof StreamableHTTPServerTransport) switch (req.headers.get(MCP_HTTP_METHOD_HEADER)) {
1087
+ case "POST": {
1088
+ const payloadHeader = req.headers.get(MCP_MESSAGE_HEADER);
1089
+ let rawPayload;
1090
+ if (!payloadHeader) rawPayload = "{}";
1091
+ else try {
1092
+ rawPayload = Buffer.from(payloadHeader, "base64").toString("utf-8");
1093
+ } catch (_error) {
1094
+ throw new Error("Internal Server Error: Failed to decode MCP message header");
1095
+ }
1096
+ const parsedBody = JSON.parse(rawPayload);
1097
+ this._transport?.handlePostRequest(req, parsedBody);
1098
+ break;
1099
+ }
1100
+ case "GET":
1101
+ this._transport?.handleGetRequest(req);
1102
+ break;
1103
+ }
1104
+ }
1105
+ }
1106
+ /** Handles MCP Messages for the legacy SSE transport. */
1107
+ async onSSEMcpMessage(_sessionId, messageBody) {
1108
+ if (this.getTransportType() !== "sse") return /* @__PURE__ */ new Error("Internal Server Error: Expected SSE transport");
1109
+ try {
1110
+ let parsedMessage;
1111
+ try {
1112
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
1113
+ } catch (error) {
1114
+ this._transport?.onerror?.(error);
1115
+ throw error;
1116
+ }
1117
+ if (await this._handleElicitationResponse(parsedMessage)) return null;
1118
+ this._transport?.onmessage?.(parsedMessage);
1119
+ return null;
1120
+ } catch (error) {
1121
+ console.error("Error forwarding message to SSE:", error);
1122
+ this._transport?.onerror?.(error);
1123
+ return error;
1124
+ }
1125
+ }
1126
+ /** Elicit user input with a message and schema */
1127
+ async elicitInput(params) {
1128
+ const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
1129
+ await this.ctx.storage.put(`elicitation:${requestId}`, {
1130
+ message: params.message,
1131
+ requestedSchema: params.requestedSchema,
1132
+ timestamp: Date.now()
1133
+ });
1134
+ const elicitRequest = {
1135
+ jsonrpc: "2.0",
1136
+ id: requestId,
1137
+ method: "elicitation/create",
1138
+ params: {
1139
+ message: params.message,
1140
+ requestedSchema: params.requestedSchema
1141
+ }
1142
+ };
1143
+ if (this._transport) await this._transport.send(elicitRequest);
1144
+ else {
1145
+ const connections = this.getConnections();
1146
+ if (!connections || Array.from(connections).length === 0) {
1147
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
1148
+ throw new Error("No active connections available for elicitation");
1149
+ }
1150
+ const connectionList = Array.from(connections);
1151
+ for (const connection of connectionList) try {
1152
+ connection.send(JSON.stringify(elicitRequest));
1153
+ } catch (error) {
1154
+ console.error("Failed to send elicitation request:", error);
1155
+ }
1156
+ }
1157
+ return this._waitForElicitationResponse(requestId);
1158
+ }
1159
+ /** Wait for elicitation response through storage polling */
1160
+ async _waitForElicitationResponse(requestId) {
1161
+ const startTime = Date.now();
1162
+ const timeout = 6e4;
1163
+ try {
1164
+ while (Date.now() - startTime < timeout) {
1165
+ const response = await this.ctx.storage.get(`elicitation:response:${requestId}`);
1166
+ if (response) {
1167
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
1168
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
1169
+ return response;
1170
+ }
1171
+ await new Promise((resolve) => setTimeout(resolve, 100));
1172
+ }
1173
+ throw new Error("Elicitation request timed out");
1174
+ } finally {
1175
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
1176
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
1177
+ }
1178
+ }
1179
+ /** Handle elicitation responses */
1180
+ async _handleElicitationResponse(message) {
1181
+ if (isJSONRPCResponse(message) && message.result) {
1182
+ const requestId = message.id?.toString();
1183
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
1184
+ if (!await this.ctx.storage.get(`elicitation:${requestId}`)) return false;
1185
+ await this.ctx.storage.put(`elicitation:response:${requestId}`, message.result);
1186
+ return true;
1187
+ }
1188
+ if (isJSONRPCError(message)) {
1189
+ const requestId = message.id?.toString();
1190
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
1191
+ if (!await this.ctx.storage.get(`elicitation:${requestId}`)) return false;
1192
+ const errorResult = {
1193
+ action: "cancel",
1194
+ content: { error: message.error.message || "Elicitation request failed" }
1195
+ };
1196
+ await this.ctx.storage.put(`elicitation:response:${requestId}`, errorResult);
1197
+ return true;
1198
+ }
1199
+ return false;
1200
+ }
1201
+ /** Return a handler for the given path for this MCP.
1202
+ * Defaults to Streamable HTTP transport.
1203
+ */
1204
+ static serve(path, { binding = "MCP_OBJECT", corsOptions, transport = "streamable-http" } = {}) {
1205
+ return { async fetch(request, env, ctx) {
1206
+ const corsResponse = handleCORS(request, corsOptions);
1207
+ if (corsResponse) return corsResponse;
1208
+ const bindingValue = env[binding];
1209
+ if (bindingValue == null || typeof bindingValue !== "object") throw new Error(`Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`);
1210
+ if (!isDurableObjectNamespace(bindingValue)) throw new Error(`Invalid McpAgent binding for ${binding}. Make sure it's a Durable Object binding.`);
1211
+ const namespace = bindingValue;
1212
+ switch (transport) {
1213
+ case "streamable-http": return createStreamingHttpHandler(path, namespace, corsOptions)(request, ctx);
1214
+ case "sse": return createLegacySseHandler(path, namespace, corsOptions)(request, ctx);
1215
+ default: return new Response("Invalid MCP transport mode. Only `streamable-http` or `sse` are allowed.", { status: 500 });
1216
+ }
1217
+ } };
1218
+ }
1219
+ /**
1220
+ * Legacy api
1221
+ **/
1222
+ static mount(path, opts = {}) {
1223
+ return McpAgent.serveSSE(path, opts);
1224
+ }
1225
+ static serveSSE(path, opts = {}) {
1226
+ return McpAgent.serve(path, {
1227
+ ...opts,
1228
+ transport: "sse"
1229
+ });
1230
+ }
913
1231
  };
1232
+
1233
+ //#endregion
1234
+ export { ElicitRequestSchema, McpAgent, SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport, WorkerTransport, experimental_createMcpHandler, getMcpAuthContext };
914
1235
  //# sourceMappingURL=index.js.map