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