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