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