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