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.
- package/dist/ai-chat-agent.d.ts +15 -18
- package/dist/ai-chat-agent.js +544 -656
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration-gdyLiTd8.js +155 -0
- package/dist/ai-chat-v5-migration-gdyLiTd8.js.map +1 -0
- package/dist/ai-chat-v5-migration.d.ts +7 -4
- package/dist/ai-chat-v5-migration.js +3 -20
- package/dist/ai-react.d.ts +14 -24
- package/dist/ai-react.js +257 -343
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types-B0GBFDwi.js +20 -0
- package/dist/ai-types-B0GBFDwi.js.map +1 -0
- package/dist/ai-types-BWW4umHY.d.ts +95 -0
- package/dist/ai-types.d.ts +6 -92
- package/dist/ai-types.js +3 -8
- package/dist/client-C-u-lCFT.d.ts +5311 -0
- package/dist/client-CmMi85Sj.d.ts +104 -0
- package/dist/client-WbaRgKYN.js +788 -0
- package/dist/client-WbaRgKYN.js.map +1 -0
- package/dist/client-zS-OCVJA.js +117 -0
- package/dist/client-zS-OCVJA.js.map +1 -0
- package/dist/client.d.ts +11 -92
- package/dist/client.js +4 -13
- package/dist/codemode/ai.d.ts +19 -17
- package/dist/codemode/ai.js +90 -5139
- package/dist/codemode/ai.js.map +1 -1
- package/dist/do-oauth-client-provider-B2jr6UNq.js +93 -0
- package/dist/do-oauth-client-provider-B2jr6UNq.js.map +1 -0
- package/dist/do-oauth-client-provider-CCwGwnrA.d.ts +55 -0
- package/dist/index-DWcUTPtX.d.ts +558 -0
- package/dist/index-W4JUkafc.d.ts +54 -0
- package/dist/index.d.ts +55 -542
- package/dist/index.js +7 -32
- package/dist/mcp/client.d.ts +4 -12
- package/dist/mcp/client.js +3 -10
- package/dist/mcp/do-oauth-client-provider.d.ts +2 -42
- package/dist/mcp/do-oauth-client-provider.js +3 -8
- package/dist/mcp/index.d.ts +72 -76
- package/dist/mcp/index.js +830 -1082
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.d.ts +22 -27
- package/dist/mcp/x402.js +186 -3187
- package/dist/mcp/x402.js.map +1 -1
- package/dist/{mcp-BH1fJeiU.d.ts → mcp-BEwaCsxO.d.ts} +6 -3
- package/dist/observability/index.d.ts +3 -34
- package/dist/observability/index.js +7 -12
- package/dist/react-B8BT6PYZ.d.ts +113 -0
- package/dist/react.d.ts +10 -127
- package/dist/react.js +173 -200
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +13 -10
- package/dist/schedule.js +43 -33
- package/dist/schedule.js.map +1 -1
- package/dist/serializable-gtr9YMhp.d.ts +34 -0
- package/dist/serializable.d.ts +7 -32
- package/dist/serializable.js +1 -1
- package/dist/src-C9xZ0CrH.js +1179 -0
- package/dist/src-C9xZ0CrH.js.map +1 -0
- package/package.json +9 -3
- package/dist/_esm-LV5FJ3HK.js +0 -3922
- package/dist/_esm-LV5FJ3HK.js.map +0 -1
- package/dist/ai-chat-v5-migration.js.map +0 -1
- package/dist/ai-types.js.map +0 -1
- package/dist/ccip-CMBYN64O.js +0 -15
- package/dist/ccip-CMBYN64O.js.map +0 -1
- package/dist/chunk-5Y6BEZDY.js +0 -276
- package/dist/chunk-5Y6BEZDY.js.map +0 -1
- package/dist/chunk-BER7KXUJ.js +0 -18
- package/dist/chunk-BER7KXUJ.js.map +0 -1
- package/dist/chunk-C2OEBJZ2.js +0 -113
- package/dist/chunk-C2OEBJZ2.js.map +0 -1
- package/dist/chunk-JJBFIGUC.js +0 -5202
- package/dist/chunk-JJBFIGUC.js.map +0 -1
- package/dist/chunk-PR4QN5HX.js +0 -43
- package/dist/chunk-PR4QN5HX.js.map +0 -1
- package/dist/chunk-QEVM4BVL.js +0 -116
- package/dist/chunk-QEVM4BVL.js.map +0 -1
- package/dist/chunk-TYAY6AU6.js +0 -159
- package/dist/chunk-TYAY6AU6.js.map +0 -1
- package/dist/chunk-UJVEAURM.js +0 -150
- package/dist/chunk-UJVEAURM.js.map +0 -1
- package/dist/chunk-XGMKNUJA.js +0 -1343
- package/dist/chunk-XGMKNUJA.js.map +0 -1
- package/dist/chunk-ZMMHNOMZ.js +0 -942
- package/dist/chunk-ZMMHNOMZ.js.map +0 -1
- package/dist/client-C8tswVoM.d.ts +0 -5248
- package/dist/client.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/mcp/client.js.map +0 -1
- package/dist/mcp/do-oauth-client-provider.js.map +0 -1
- package/dist/observability/index.js.map +0 -1
- package/dist/secp256k1-M22GZP2U.js +0 -2193
- package/dist/secp256k1-M22GZP2U.js.map +0 -1
- package/dist/serializable.js.map +0 -1
package/dist/mcp/index.js
CHANGED
|
@@ -1,1099 +1,847 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
} from "../
|
|
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
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
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
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
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
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
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
|
-
|
|
565
|
-
|
|
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
|
-
|
|
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
|
-
|
|
574
|
-
|
|
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
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
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
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
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
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
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
|