agents 0.0.0-ac74811 → 0.0.0-afd9efd
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 +255 -27
- package/dist/_esm-LV5FJ3HK.js +3922 -0
- package/dist/_esm-LV5FJ3HK.js.map +1 -0
- package/dist/ai-chat-agent.d.ts +14 -9
- 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 +69 -71
- 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-JFRK72K3.js → chunk-2Y6KNRNP.js} +591 -158
- 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-767EASBA.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-NKZZ66QY.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.d.ts +2 -2
- 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 +550 -24
- package/dist/index.js +14 -4
- package/dist/mcp/client.d.ts +10 -1053
- 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 +58 -63
- package/dist/mcp/index.js +969 -637
- 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 -12
- package/dist/observability/index.js +6 -4
- package/dist/react.d.ts +19 -11
- package/dist/react.js +107 -7
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +83 -9
- 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 +41 -12
- package/src/index.ts +874 -208
- package/dist/chunk-767EASBA.js.map +0 -1
- package/dist/chunk-E3LCYPCB.js +0 -469
- package/dist/chunk-E3LCYPCB.js.map +0 -1
- package/dist/chunk-JFRK72K3.js.map +0 -1
- package/dist/chunk-NKZZ66QY.js.map +0 -1
- package/dist/index-CITGJflw.d.ts +0 -486
package/dist/mcp/index.js
CHANGED
|
@@ -1,40 +1,584 @@
|
|
|
1
1
|
import {
|
|
2
|
-
Agent
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
import
|
|
2
|
+
Agent,
|
|
3
|
+
getAgentByName,
|
|
4
|
+
getCurrentAgent
|
|
5
|
+
} from "../chunk-2Y6KNRNP.js";
|
|
6
|
+
import {
|
|
7
|
+
SSEEdgeClientTransport,
|
|
8
|
+
StreamableHTTPEdgeClientTransport
|
|
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";
|
|
7
14
|
|
|
8
15
|
// src/mcp/index.ts
|
|
9
|
-
import { DurableObject } from "cloudflare:workers";
|
|
10
16
|
import {
|
|
17
|
+
JSONRPCMessageSchema as JSONRPCMessageSchema3,
|
|
18
|
+
isJSONRPCError as isJSONRPCError2,
|
|
19
|
+
isJSONRPCResponse as isJSONRPCResponse3
|
|
20
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
21
|
+
|
|
22
|
+
// src/mcp/utils.ts
|
|
23
|
+
import {
|
|
24
|
+
JSONRPCMessageSchema,
|
|
11
25
|
InitializeRequestSchema,
|
|
12
|
-
isJSONRPCError,
|
|
13
|
-
isJSONRPCNotification,
|
|
14
|
-
isJSONRPCRequest,
|
|
15
26
|
isJSONRPCResponse,
|
|
16
|
-
|
|
27
|
+
isJSONRPCNotification
|
|
17
28
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
29
|
+
var MCP_HTTP_METHOD_HEADER = "cf-mcp-method";
|
|
30
|
+
var MCP_MESSAGE_HEADER = "cf-mcp-message";
|
|
18
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
|
+
};
|
|
19
555
|
function corsHeaders(_request, corsOptions = {}) {
|
|
20
556
|
const origin = "*";
|
|
21
557
|
return {
|
|
22
|
-
"Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id, mcp-protocol-version",
|
|
23
|
-
"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",
|
|
24
560
|
"Access-Control-Allow-Origin": corsOptions.origin || origin,
|
|
25
561
|
"Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
|
|
26
562
|
"Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
|
|
27
563
|
};
|
|
28
564
|
}
|
|
29
|
-
function isDurableObjectNamespace(namespace) {
|
|
30
|
-
return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
|
|
31
|
-
}
|
|
32
565
|
function handleCORS(request, corsOptions) {
|
|
33
566
|
if (request.method === "OPTIONS") {
|
|
34
567
|
return new Response(null, { headers: corsHeaders(request, corsOptions) });
|
|
35
568
|
}
|
|
36
569
|
return null;
|
|
37
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";
|
|
38
582
|
var McpSSETransport = class {
|
|
39
583
|
constructor(getWebSocket) {
|
|
40
584
|
this._started = false;
|
|
@@ -58,252 +602,346 @@ var McpSSETransport = class {
|
|
|
58
602
|
websocket.send(JSON.stringify(message));
|
|
59
603
|
} catch (error) {
|
|
60
604
|
this.onerror?.(error);
|
|
61
|
-
throw error;
|
|
62
605
|
}
|
|
63
606
|
}
|
|
64
607
|
async close() {
|
|
65
608
|
this.onclose?.();
|
|
66
609
|
}
|
|
67
610
|
};
|
|
68
|
-
var
|
|
69
|
-
constructor(
|
|
611
|
+
var StreamableHTTPServerTransport = class {
|
|
612
|
+
constructor(options) {
|
|
70
613
|
this._started = false;
|
|
71
|
-
|
|
72
|
-
this
|
|
73
|
-
|
|
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;
|
|
74
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
|
+
*/
|
|
75
628
|
async start() {
|
|
76
629
|
if (this._started) {
|
|
77
630
|
throw new Error("Transport already started");
|
|
78
631
|
}
|
|
79
632
|
this._started = true;
|
|
80
633
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if (
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
);
|
|
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;
|
|
92
646
|
}
|
|
93
|
-
} else if (isJSONRPCRequest(message)) {
|
|
94
|
-
websocket = this._getWebSocketForGetRequest();
|
|
95
|
-
} else if (isJSONRPCNotification(message)) {
|
|
96
|
-
websocket = null;
|
|
97
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");
|
|
98
663
|
try {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
+
});
|
|
103
673
|
} catch (error) {
|
|
104
674
|
this.onerror?.(error);
|
|
105
|
-
throw error;
|
|
106
675
|
}
|
|
107
676
|
}
|
|
108
|
-
|
|
109
|
-
|
|
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
|
+
);
|
|
110
696
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
697
|
+
/**
|
|
698
|
+
* Handles POST requests containing JSON-RPC messages
|
|
699
|
+
*/
|
|
700
|
+
async handlePostRequest(req, parsedBody) {
|
|
701
|
+
const authInfo = req.auth;
|
|
702
|
+
const requestInfo = {
|
|
703
|
+
headers: Object.fromEntries(req.headers.entries())
|
|
704
|
+
};
|
|
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));
|
|
712
|
+
} else {
|
|
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 });
|
|
124
719
|
}
|
|
125
|
-
|
|
126
|
-
|
|
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 });
|
|
127
730
|
}
|
|
128
|
-
}
|
|
129
|
-
hibernate: true
|
|
130
|
-
}, _a)(ctx, env);
|
|
131
|
-
}
|
|
132
|
-
get mcp() {
|
|
133
|
-
return this._agent.mcp;
|
|
134
|
-
}
|
|
135
|
-
get state() {
|
|
136
|
-
return this._agent.state;
|
|
137
|
-
}
|
|
138
|
-
sql(strings, ...values) {
|
|
139
|
-
return this._agent.sql(strings, ...values);
|
|
140
|
-
}
|
|
141
|
-
setState(state) {
|
|
142
|
-
return this._agent.setState(state);
|
|
731
|
+
}
|
|
143
732
|
}
|
|
144
|
-
|
|
145
|
-
|
|
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?.();
|
|
146
740
|
}
|
|
147
|
-
async
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
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
|
+
);
|
|
154
753
|
}
|
|
155
|
-
|
|
156
|
-
|
|
754
|
+
let standaloneConnection;
|
|
755
|
+
for (const conn of agent.getConnections()) {
|
|
756
|
+
if (conn.state?._standaloneSse) standaloneConnection = conn;
|
|
157
757
|
}
|
|
158
|
-
|
|
159
|
-
return
|
|
758
|
+
if (standaloneConnection === void 0) {
|
|
759
|
+
return;
|
|
160
760
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
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)}`
|
|
177
777
|
);
|
|
178
|
-
await server.connect(this._transport);
|
|
179
778
|
}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
if (!this.ctx.storage.get("transportType")) {
|
|
184
|
-
await this.ctx.storage.put("transportType", "unset");
|
|
779
|
+
let eventId;
|
|
780
|
+
if (this._eventStore) {
|
|
781
|
+
eventId = await this._eventStore.storeEvent(connection.id, message);
|
|
185
782
|
}
|
|
186
|
-
|
|
187
|
-
if (
|
|
188
|
-
this.
|
|
189
|
-
|
|
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
|
+
}
|
|
190
793
|
}
|
|
794
|
+
this.writeSSEEvent(connection, message, eventId, shouldClose);
|
|
191
795
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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);
|
|
197
808
|
}
|
|
198
|
-
async
|
|
199
|
-
|
|
200
|
-
this._status = "starting";
|
|
201
|
-
await this.onStart();
|
|
202
|
-
this._status = "started";
|
|
203
|
-
});
|
|
809
|
+
async getInitializeRequest() {
|
|
810
|
+
return this.ctx.storage.get("initializeRequest");
|
|
204
811
|
}
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
const path = url.pathname;
|
|
217
|
-
const server = await this.server;
|
|
218
|
-
switch (path) {
|
|
219
|
-
case "/sse": {
|
|
220
|
-
const websockets = this.ctx.getWebSockets();
|
|
221
|
-
if (websockets.length > 0) {
|
|
222
|
-
return new Response("Websocket already connected", { status: 400 });
|
|
223
|
-
}
|
|
224
|
-
await this.ctx.storage.put("transportType", "sse");
|
|
225
|
-
this._transportType = "sse";
|
|
226
|
-
if (!this._transport) {
|
|
227
|
-
this._transport = new McpSSETransport(() => this.getWebSocket());
|
|
228
|
-
await server.connect(this._transport);
|
|
229
|
-
}
|
|
230
|
-
return this._agent.fetch(request);
|
|
231
|
-
}
|
|
232
|
-
case "/streamable-http": {
|
|
233
|
-
if (!this._transport) {
|
|
234
|
-
this._transport = new McpStreamableHttpTransport(
|
|
235
|
-
(id) => this.getWebSocketForResponseID(id),
|
|
236
|
-
(id) => this._requestIdToConnectionId.delete(id)
|
|
237
|
-
);
|
|
238
|
-
await server.connect(this._transport);
|
|
239
|
-
}
|
|
240
|
-
await this.ctx.storage.put("transportType", "streamable-http");
|
|
241
|
-
this._transportType = "streamable-http";
|
|
242
|
-
return this._agent.fetch(request);
|
|
243
|
-
}
|
|
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";
|
|
244
823
|
default:
|
|
245
|
-
|
|
246
|
-
"
|
|
247
|
-
{
|
|
248
|
-
status: 500
|
|
249
|
-
}
|
|
824
|
+
throw new Error(
|
|
825
|
+
"Invalid transport type. McpAgent must be addressed with a valid protocol."
|
|
250
826
|
);
|
|
251
827
|
}
|
|
252
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. */
|
|
253
843
|
getWebSocket() {
|
|
254
|
-
const websockets = this.
|
|
844
|
+
const websockets = Array.from(this.getConnections());
|
|
255
845
|
if (websockets.length === 0) {
|
|
256
846
|
return null;
|
|
257
847
|
}
|
|
258
848
|
return websockets[0];
|
|
259
849
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
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
|
+
}
|
|
264
859
|
}
|
|
265
|
-
return this._agent.getConnection(connectionId) ?? null;
|
|
266
860
|
}
|
|
267
|
-
|
|
268
|
-
async
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
let message;
|
|
277
|
-
try {
|
|
278
|
-
const data = typeof event === "string" ? event : new TextDecoder().decode(event);
|
|
279
|
-
message = JSONRPCMessageSchema.parse(JSON.parse(data));
|
|
280
|
-
} catch (error) {
|
|
281
|
-
this._transport?.onerror?.(error);
|
|
282
|
-
return;
|
|
283
|
-
}
|
|
284
|
-
if (isJSONRPCRequest(message)) {
|
|
285
|
-
this._requestIdToConnectionId.set(message.id.toString(), connection.id);
|
|
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);
|
|
286
870
|
}
|
|
287
|
-
this._transport?.onmessage?.(message);
|
|
288
871
|
}
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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
|
+
}
|
|
294
924
|
}
|
|
295
|
-
|
|
296
|
-
|
|
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");
|
|
297
933
|
}
|
|
298
934
|
try {
|
|
299
|
-
const message = await request.json();
|
|
300
935
|
let parsedMessage;
|
|
301
936
|
try {
|
|
302
|
-
parsedMessage =
|
|
937
|
+
parsedMessage = JSONRPCMessageSchema3.parse(messageBody);
|
|
303
938
|
} catch (error) {
|
|
304
939
|
this._transport?.onerror?.(error);
|
|
305
940
|
throw error;
|
|
306
941
|
}
|
|
942
|
+
if (await this._handleElicitationResponse(parsedMessage)) {
|
|
943
|
+
return null;
|
|
944
|
+
}
|
|
307
945
|
this._transport?.onmessage?.(parsedMessage);
|
|
308
946
|
return null;
|
|
309
947
|
} catch (error) {
|
|
@@ -312,472 +950,166 @@ var McpAgent = class _McpAgent extends DurableObject {
|
|
|
312
950
|
return error;
|
|
313
951
|
}
|
|
314
952
|
}
|
|
315
|
-
|
|
316
|
-
async
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
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
|
+
}
|
|
326
986
|
}
|
|
327
|
-
return
|
|
987
|
+
return this._waitForElicitationResponse(requestId);
|
|
328
988
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
989
|
+
/** Wait for elicitation response through storage polling */
|
|
990
|
+
async _waitForElicitationResponse(requestId) {
|
|
991
|
+
const startTime = Date.now();
|
|
992
|
+
const timeout = 6e4;
|
|
993
|
+
try {
|
|
994
|
+
while (Date.now() - startTime < timeout) {
|
|
995
|
+
const response = await this.ctx.storage.get(
|
|
996
|
+
`elicitation:response:${requestId}`
|
|
997
|
+
);
|
|
998
|
+
if (response) {
|
|
999
|
+
await this.ctx.storage.delete(`elicitation:${requestId}`);
|
|
1000
|
+
await this.ctx.storage.delete(`elicitation:response:${requestId}`);
|
|
1001
|
+
return response;
|
|
1002
|
+
}
|
|
1003
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
1004
|
+
}
|
|
1005
|
+
throw new Error("Elicitation request timed out");
|
|
1006
|
+
} finally {
|
|
1007
|
+
await this.ctx.storage.delete(`elicitation:${requestId}`);
|
|
1008
|
+
await this.ctx.storage.delete(`elicitation:response:${requestId}`);
|
|
332
1009
|
}
|
|
333
|
-
return await this._agent.webSocketClose(ws, code, reason, wasClean);
|
|
334
1010
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
1011
|
+
/** Handle elicitation responses */
|
|
1012
|
+
async _handleElicitationResponse(message) {
|
|
1013
|
+
if (isJSONRPCResponse3(message) && message.result) {
|
|
1014
|
+
const requestId = message.id?.toString();
|
|
1015
|
+
if (!requestId || !requestId.startsWith("elicit_")) return false;
|
|
1016
|
+
const pendingRequest = await this.ctx.storage.get(
|
|
1017
|
+
`elicitation:${requestId}`
|
|
1018
|
+
);
|
|
1019
|
+
if (!pendingRequest) return false;
|
|
1020
|
+
await this.ctx.storage.put(
|
|
1021
|
+
`elicitation:response:${requestId}`,
|
|
1022
|
+
message.result
|
|
1023
|
+
);
|
|
1024
|
+
return true;
|
|
348
1025
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
);
|
|
361
|
-
return new Response("Invalid binding", { status: 500 });
|
|
362
|
-
}
|
|
363
|
-
if (!isDurableObjectNamespace(bindingValue)) {
|
|
364
|
-
return new Response("Invalid binding", { status: 500 });
|
|
365
|
-
}
|
|
366
|
-
const namespace = bindingValue;
|
|
367
|
-
if (request.method === "GET" && basePattern.test(url)) {
|
|
368
|
-
const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
|
|
369
|
-
const { readable, writable } = new TransformStream();
|
|
370
|
-
const writer = writable.getWriter();
|
|
371
|
-
const encoder = new TextEncoder();
|
|
372
|
-
const endpointUrl = new URL(request.url);
|
|
373
|
-
endpointUrl.pathname = encodeURI(`${pathname}/message`);
|
|
374
|
-
endpointUrl.searchParams.set("sessionId", sessionId);
|
|
375
|
-
const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;
|
|
376
|
-
const endpointMessage = `event: endpoint
|
|
377
|
-
data: ${relativeUrlWithSession}
|
|
378
|
-
|
|
379
|
-
`;
|
|
380
|
-
writer.write(encoder.encode(endpointMessage));
|
|
381
|
-
const id = namespace.idFromName(`sse:${sessionId}`);
|
|
382
|
-
const doStub = namespace.get(id);
|
|
383
|
-
await doStub._init(ctx.props);
|
|
384
|
-
const upgradeUrl = new URL(request.url);
|
|
385
|
-
upgradeUrl.pathname = "/sse";
|
|
386
|
-
const response = await doStub.fetch(
|
|
387
|
-
new Request(upgradeUrl, {
|
|
388
|
-
headers: {
|
|
389
|
-
Upgrade: "websocket",
|
|
390
|
-
// Required by PartyServer
|
|
391
|
-
"x-partykit-room": sessionId
|
|
392
|
-
}
|
|
393
|
-
})
|
|
394
|
-
);
|
|
395
|
-
const ws = response.webSocket;
|
|
396
|
-
if (!ws) {
|
|
397
|
-
console.error("Failed to establish WebSocket connection");
|
|
398
|
-
await writer.close();
|
|
399
|
-
return new Response("Failed to establish WebSocket connection", {
|
|
400
|
-
status: 500
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
ws.accept();
|
|
404
|
-
ws.addEventListener("message", (event) => {
|
|
405
|
-
async function onMessage(event2) {
|
|
406
|
-
try {
|
|
407
|
-
const message = JSON.parse(event2.data);
|
|
408
|
-
const result = JSONRPCMessageSchema.safeParse(message);
|
|
409
|
-
if (!result.success) {
|
|
410
|
-
return;
|
|
411
|
-
}
|
|
412
|
-
const messageText = `event: message
|
|
413
|
-
data: ${JSON.stringify(result.data)}
|
|
414
|
-
|
|
415
|
-
`;
|
|
416
|
-
await writer.write(encoder.encode(messageText));
|
|
417
|
-
} catch (error) {
|
|
418
|
-
console.error("Error forwarding message to SSE:", error);
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
onMessage(event).catch(console.error);
|
|
422
|
-
});
|
|
423
|
-
ws.addEventListener("error", (error) => {
|
|
424
|
-
async function onError(_error) {
|
|
425
|
-
try {
|
|
426
|
-
await writer.close();
|
|
427
|
-
} catch (_e) {
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
onError(error).catch(console.error);
|
|
431
|
-
});
|
|
432
|
-
ws.addEventListener("close", () => {
|
|
433
|
-
async function onClose() {
|
|
434
|
-
try {
|
|
435
|
-
await writer.close();
|
|
436
|
-
} catch (error) {
|
|
437
|
-
console.error("Error closing SSE connection:", error);
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
onClose().catch(console.error);
|
|
441
|
-
});
|
|
442
|
-
return new Response(readable, {
|
|
443
|
-
headers: {
|
|
444
|
-
"Cache-Control": "no-cache",
|
|
445
|
-
Connection: "keep-alive",
|
|
446
|
-
"Content-Type": "text/event-stream",
|
|
447
|
-
...corsHeaders(request, corsOptions)
|
|
448
|
-
}
|
|
449
|
-
});
|
|
450
|
-
}
|
|
451
|
-
if (request.method === "POST" && messagePattern.test(url)) {
|
|
452
|
-
const sessionId = url.searchParams.get("sessionId");
|
|
453
|
-
if (!sessionId) {
|
|
454
|
-
return new Response(
|
|
455
|
-
`Missing sessionId. Expected POST to ${pathname} to initiate new one`,
|
|
456
|
-
{ status: 400 }
|
|
457
|
-
);
|
|
458
|
-
}
|
|
459
|
-
const contentType = request.headers.get("content-type") || "";
|
|
460
|
-
if (!contentType.includes("application/json")) {
|
|
461
|
-
return new Response(`Unsupported content-type: ${contentType}`, {
|
|
462
|
-
status: 400
|
|
463
|
-
});
|
|
464
|
-
}
|
|
465
|
-
const contentLength = Number.parseInt(
|
|
466
|
-
request.headers.get("content-length") || "0",
|
|
467
|
-
10
|
|
468
|
-
);
|
|
469
|
-
if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
|
|
470
|
-
return new Response(
|
|
471
|
-
`Request body too large: ${contentLength} bytes`,
|
|
472
|
-
{
|
|
473
|
-
status: 400
|
|
474
|
-
}
|
|
475
|
-
);
|
|
476
|
-
}
|
|
477
|
-
const id = namespace.idFromName(`sse:${sessionId}`);
|
|
478
|
-
const doStub = namespace.get(id);
|
|
479
|
-
const error = await doStub.onSSEMcpMessage(sessionId, request);
|
|
480
|
-
if (error) {
|
|
481
|
-
return new Response(error.message, {
|
|
482
|
-
headers: {
|
|
483
|
-
"Cache-Control": "no-cache",
|
|
484
|
-
Connection: "keep-alive",
|
|
485
|
-
"Content-Type": "text/event-stream",
|
|
486
|
-
...corsHeaders(request, corsOptions)
|
|
487
|
-
},
|
|
488
|
-
status: 400
|
|
489
|
-
});
|
|
490
|
-
}
|
|
491
|
-
return new Response("Accepted", {
|
|
492
|
-
headers: {
|
|
493
|
-
"Cache-Control": "no-cache",
|
|
494
|
-
Connection: "keep-alive",
|
|
495
|
-
"Content-Type": "text/event-stream",
|
|
496
|
-
...corsHeaders(request, corsOptions)
|
|
497
|
-
},
|
|
498
|
-
status: 202
|
|
499
|
-
});
|
|
1026
|
+
if (isJSONRPCError2(message)) {
|
|
1027
|
+
const requestId = message.id?.toString();
|
|
1028
|
+
if (!requestId || !requestId.startsWith("elicit_")) return false;
|
|
1029
|
+
const pendingRequest = await this.ctx.storage.get(
|
|
1030
|
+
`elicitation:${requestId}`
|
|
1031
|
+
);
|
|
1032
|
+
if (!pendingRequest) return false;
|
|
1033
|
+
const errorResult = {
|
|
1034
|
+
action: "cancel",
|
|
1035
|
+
content: {
|
|
1036
|
+
error: message.error.message || "Elicitation request failed"
|
|
500
1037
|
}
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
1038
|
+
};
|
|
1039
|
+
await this.ctx.storage.put(
|
|
1040
|
+
`elicitation:response:${requestId}`,
|
|
1041
|
+
errorResult
|
|
1042
|
+
);
|
|
1043
|
+
return true;
|
|
1044
|
+
}
|
|
1045
|
+
return false;
|
|
504
1046
|
}
|
|
1047
|
+
/** Return a handler for the given path for this MCP.
|
|
1048
|
+
* Defaults to Streamable HTTP transport.
|
|
1049
|
+
*/
|
|
505
1050
|
static serve(path, {
|
|
506
1051
|
binding = "MCP_OBJECT",
|
|
507
|
-
corsOptions
|
|
1052
|
+
corsOptions,
|
|
1053
|
+
transport = "streamable-http"
|
|
508
1054
|
} = {}) {
|
|
509
|
-
let pathname = path;
|
|
510
|
-
if (path === "/") {
|
|
511
|
-
pathname = "/*";
|
|
512
|
-
}
|
|
513
|
-
const basePattern = new URLPattern({ pathname });
|
|
514
1055
|
return {
|
|
515
1056
|
async fetch(request, env, ctx) {
|
|
516
1057
|
const corsResponse = handleCORS(request, corsOptions);
|
|
517
1058
|
if (corsResponse) {
|
|
518
1059
|
return corsResponse;
|
|
519
1060
|
}
|
|
520
|
-
const url = new URL(request.url);
|
|
521
1061
|
const bindingValue = env[binding];
|
|
522
1062
|
if (bindingValue == null || typeof bindingValue !== "object") {
|
|
523
|
-
|
|
1063
|
+
throw new Error(
|
|
524
1064
|
`Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
|
|
525
1065
|
);
|
|
526
|
-
return new Response("Invalid binding", { status: 500 });
|
|
527
1066
|
}
|
|
528
1067
|
if (!isDurableObjectNamespace(bindingValue)) {
|
|
529
|
-
|
|
1068
|
+
throw new Error(
|
|
1069
|
+
`Invalid McpAgent binding for ${binding}. Make sure it's a Durable Object binding.`
|
|
1070
|
+
);
|
|
530
1071
|
}
|
|
531
1072
|
const namespace = bindingValue;
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
id: null,
|
|
541
|
-
jsonrpc: "2.0"
|
|
542
|
-
});
|
|
543
|
-
return new Response(body2, { status: 406 });
|
|
544
|
-
}
|
|
545
|
-
const ct = request.headers.get("content-type");
|
|
546
|
-
if (!ct || !ct.includes("application/json")) {
|
|
547
|
-
const body2 = JSON.stringify({
|
|
548
|
-
error: {
|
|
549
|
-
code: -32e3,
|
|
550
|
-
message: "Unsupported Media Type: Content-Type must be application/json"
|
|
551
|
-
},
|
|
552
|
-
id: null,
|
|
553
|
-
jsonrpc: "2.0"
|
|
554
|
-
});
|
|
555
|
-
return new Response(body2, { status: 415 });
|
|
556
|
-
}
|
|
557
|
-
const contentLength = Number.parseInt(
|
|
558
|
-
request.headers.get("content-length") ?? "0",
|
|
559
|
-
10
|
|
560
|
-
);
|
|
561
|
-
if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
|
|
562
|
-
const body2 = JSON.stringify({
|
|
563
|
-
error: {
|
|
564
|
-
code: -32e3,
|
|
565
|
-
message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
|
|
566
|
-
},
|
|
567
|
-
id: null,
|
|
568
|
-
jsonrpc: "2.0"
|
|
569
|
-
});
|
|
570
|
-
return new Response(body2, { status: 413 });
|
|
571
|
-
}
|
|
572
|
-
let sessionId = request.headers.get("mcp-session-id");
|
|
573
|
-
let rawMessage;
|
|
574
|
-
try {
|
|
575
|
-
rawMessage = await request.json();
|
|
576
|
-
} catch (_error) {
|
|
577
|
-
const body2 = JSON.stringify({
|
|
578
|
-
error: {
|
|
579
|
-
code: -32700,
|
|
580
|
-
message: "Parse error: Invalid JSON"
|
|
581
|
-
},
|
|
582
|
-
id: null,
|
|
583
|
-
jsonrpc: "2.0"
|
|
584
|
-
});
|
|
585
|
-
return new Response(body2, { status: 400 });
|
|
586
|
-
}
|
|
587
|
-
let arrayMessage;
|
|
588
|
-
if (Array.isArray(rawMessage)) {
|
|
589
|
-
arrayMessage = rawMessage;
|
|
590
|
-
} else {
|
|
591
|
-
arrayMessage = [rawMessage];
|
|
592
|
-
}
|
|
593
|
-
let messages = [];
|
|
594
|
-
for (const msg of arrayMessage) {
|
|
595
|
-
if (!JSONRPCMessageSchema.safeParse(msg).success) {
|
|
596
|
-
const body2 = JSON.stringify({
|
|
597
|
-
error: {
|
|
598
|
-
code: -32700,
|
|
599
|
-
message: "Parse error: Invalid JSON-RPC message"
|
|
600
|
-
},
|
|
601
|
-
id: null,
|
|
602
|
-
jsonrpc: "2.0"
|
|
603
|
-
});
|
|
604
|
-
return new Response(body2, { status: 400 });
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
|
|
608
|
-
const isInitializationRequest = messages.some(
|
|
609
|
-
(msg) => InitializeRequestSchema.safeParse(msg).success
|
|
610
|
-
);
|
|
611
|
-
if (isInitializationRequest && sessionId) {
|
|
612
|
-
const body2 = JSON.stringify({
|
|
613
|
-
error: {
|
|
614
|
-
code: -32600,
|
|
615
|
-
message: "Invalid Request: Initialization requests must not include a sessionId"
|
|
616
|
-
},
|
|
617
|
-
id: null,
|
|
618
|
-
jsonrpc: "2.0"
|
|
619
|
-
});
|
|
620
|
-
return new Response(body2, { status: 400 });
|
|
621
|
-
}
|
|
622
|
-
if (isInitializationRequest && messages.length > 1) {
|
|
623
|
-
const body2 = JSON.stringify({
|
|
624
|
-
error: {
|
|
625
|
-
code: -32600,
|
|
626
|
-
message: "Invalid Request: Only one initialization request is allowed"
|
|
627
|
-
},
|
|
628
|
-
id: null,
|
|
629
|
-
jsonrpc: "2.0"
|
|
630
|
-
});
|
|
631
|
-
return new Response(body2, { status: 400 });
|
|
632
|
-
}
|
|
633
|
-
if (!isInitializationRequest && !sessionId) {
|
|
634
|
-
const body2 = JSON.stringify({
|
|
635
|
-
error: {
|
|
636
|
-
code: -32e3,
|
|
637
|
-
message: "Bad Request: Mcp-Session-Id header is required"
|
|
638
|
-
},
|
|
639
|
-
id: null,
|
|
640
|
-
jsonrpc: "2.0"
|
|
641
|
-
});
|
|
642
|
-
return new Response(body2, { status: 400 });
|
|
643
|
-
}
|
|
644
|
-
sessionId = sessionId ?? namespace.newUniqueId().toString();
|
|
645
|
-
const id = namespace.idFromName(`streamable-http:${sessionId}`);
|
|
646
|
-
const doStub = namespace.get(id);
|
|
647
|
-
const isInitialized = await doStub.isInitialized();
|
|
648
|
-
if (isInitializationRequest) {
|
|
649
|
-
await doStub._init(ctx.props);
|
|
650
|
-
await doStub.setInitialized();
|
|
651
|
-
} else if (!isInitialized) {
|
|
652
|
-
const body2 = JSON.stringify({
|
|
653
|
-
error: {
|
|
654
|
-
code: -32001,
|
|
655
|
-
message: "Session not found"
|
|
656
|
-
},
|
|
657
|
-
id: null,
|
|
658
|
-
jsonrpc: "2.0"
|
|
659
|
-
});
|
|
660
|
-
return new Response(body2, { status: 404 });
|
|
661
|
-
}
|
|
662
|
-
const { readable, writable } = new TransformStream();
|
|
663
|
-
const writer = writable.getWriter();
|
|
664
|
-
const encoder = new TextEncoder();
|
|
665
|
-
const upgradeUrl = new URL(request.url);
|
|
666
|
-
upgradeUrl.pathname = "/streamable-http";
|
|
667
|
-
const response = await doStub.fetch(
|
|
668
|
-
new Request(upgradeUrl, {
|
|
669
|
-
headers: {
|
|
670
|
-
Upgrade: "websocket",
|
|
671
|
-
// Required by PartyServer
|
|
672
|
-
"x-partykit-room": sessionId
|
|
673
|
-
}
|
|
674
|
-
})
|
|
675
|
-
);
|
|
676
|
-
const ws = response.webSocket;
|
|
677
|
-
if (!ws) {
|
|
678
|
-
console.error("Failed to establish WebSocket connection");
|
|
679
|
-
await writer.close();
|
|
680
|
-
const body2 = JSON.stringify({
|
|
681
|
-
error: {
|
|
682
|
-
code: -32001,
|
|
683
|
-
message: "Failed to establish WebSocket connection"
|
|
684
|
-
},
|
|
685
|
-
id: null,
|
|
686
|
-
jsonrpc: "2.0"
|
|
687
|
-
});
|
|
688
|
-
return new Response(body2, { status: 500 });
|
|
689
|
-
}
|
|
690
|
-
const requestIds = /* @__PURE__ */ new Set();
|
|
691
|
-
ws.accept();
|
|
692
|
-
ws.addEventListener("message", (event) => {
|
|
693
|
-
async function onMessage(event2) {
|
|
694
|
-
try {
|
|
695
|
-
const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
|
|
696
|
-
const message = JSON.parse(data);
|
|
697
|
-
const result = JSONRPCMessageSchema.safeParse(message);
|
|
698
|
-
if (!result.success) {
|
|
699
|
-
return;
|
|
700
|
-
}
|
|
701
|
-
if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
|
|
702
|
-
requestIds.delete(result.data.id);
|
|
703
|
-
}
|
|
704
|
-
const messageText = `event: message
|
|
705
|
-
data: ${JSON.stringify(result.data)}
|
|
706
|
-
|
|
707
|
-
`;
|
|
708
|
-
await writer.write(encoder.encode(messageText));
|
|
709
|
-
if (requestIds.size === 0) {
|
|
710
|
-
ws.close();
|
|
711
|
-
}
|
|
712
|
-
} catch (error) {
|
|
713
|
-
console.error("Error forwarding message to SSE:", error);
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
onMessage(event).catch(console.error);
|
|
717
|
-
});
|
|
718
|
-
ws.addEventListener("error", (error) => {
|
|
719
|
-
async function onError(_error) {
|
|
720
|
-
try {
|
|
721
|
-
await writer.close();
|
|
722
|
-
} catch (_e) {
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
onError(error).catch(console.error);
|
|
726
|
-
});
|
|
727
|
-
ws.addEventListener("close", () => {
|
|
728
|
-
async function onClose() {
|
|
729
|
-
try {
|
|
730
|
-
await writer.close();
|
|
731
|
-
} catch (error) {
|
|
732
|
-
console.error("Error closing SSE connection:", error);
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
onClose().catch(console.error);
|
|
736
|
-
});
|
|
737
|
-
const hasOnlyNotificationsOrResponses = messages.every(
|
|
738
|
-
(msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
|
|
739
|
-
);
|
|
740
|
-
if (hasOnlyNotificationsOrResponses) {
|
|
741
|
-
for (const message of messages) {
|
|
742
|
-
ws.send(JSON.stringify(message));
|
|
743
|
-
}
|
|
744
|
-
ws.close();
|
|
745
|
-
return new Response(null, {
|
|
746
|
-
headers: corsHeaders(request, corsOptions),
|
|
747
|
-
status: 202
|
|
748
|
-
});
|
|
1073
|
+
switch (transport) {
|
|
1074
|
+
case "streamable-http": {
|
|
1075
|
+
const handleStreamableHttp = createStreamingHttpHandler(
|
|
1076
|
+
path,
|
|
1077
|
+
namespace,
|
|
1078
|
+
corsOptions
|
|
1079
|
+
);
|
|
1080
|
+
return handleStreamableHttp(request, ctx);
|
|
749
1081
|
}
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
1082
|
+
case "sse": {
|
|
1083
|
+
const handleLegacySse = createLegacySseHandler(
|
|
1084
|
+
path,
|
|
1085
|
+
namespace,
|
|
1086
|
+
corsOptions
|
|
1087
|
+
);
|
|
1088
|
+
return handleLegacySse(request, ctx);
|
|
755
1089
|
}
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
"
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
"mcp-session-id": sessionId,
|
|
762
|
-
...corsHeaders(request, corsOptions)
|
|
763
|
-
},
|
|
764
|
-
status: 200
|
|
765
|
-
});
|
|
1090
|
+
default:
|
|
1091
|
+
return new Response(
|
|
1092
|
+
"Invalid MCP transport mode. Only `streamable-http` or `sse` are allowed.",
|
|
1093
|
+
{ status: 500 }
|
|
1094
|
+
);
|
|
766
1095
|
}
|
|
767
|
-
const body = JSON.stringify({
|
|
768
|
-
error: {
|
|
769
|
-
code: -32e3,
|
|
770
|
-
message: "Method not allowed"
|
|
771
|
-
},
|
|
772
|
-
id: null,
|
|
773
|
-
jsonrpc: "2.0"
|
|
774
|
-
});
|
|
775
|
-
return new Response(body, { status: 405 });
|
|
776
1096
|
}
|
|
777
1097
|
};
|
|
778
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
|
+
}
|
|
779
1108
|
};
|
|
780
1109
|
export {
|
|
781
|
-
|
|
1110
|
+
ElicitRequestSchema,
|
|
1111
|
+
McpAgent,
|
|
1112
|
+
SSEEdgeClientTransport,
|
|
1113
|
+
StreamableHTTPEdgeClientTransport
|
|
782
1114
|
};
|
|
783
1115
|
//# sourceMappingURL=index.js.map
|