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