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