agents 0.2.9 → 0.2.11

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