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