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