agents 0.2.15 → 0.2.16
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/dist/ai-chat-agent.d.ts +10 -10
- package/dist/ai-chat-agent.js +6 -6
- package/dist/{ai-chat-v5-migration-gdyLiTd8.js → ai-chat-v5-migration-DBHGW4Hv.js} +2 -2
- package/dist/{ai-chat-v5-migration-gdyLiTd8.js.map → ai-chat-v5-migration-DBHGW4Hv.js.map} +1 -1
- package/dist/ai-chat-v5-migration.js +1 -1
- package/dist/ai-react.d.ts +9 -9
- package/dist/ai-react.js +1 -1
- package/dist/{ai-types-UZlfLOYP.js → ai-types-B3aQaFv3.js} +2 -2
- package/dist/{ai-types-UZlfLOYP.js.map → ai-types-B3aQaFv3.js.map} +1 -1
- package/dist/{ai-types-BWW4umHY.d.ts → ai-types-D5YoPrBZ.d.ts} +2 -2
- package/dist/ai-types.d.ts +4 -4
- package/dist/ai-types.js +1 -1
- package/dist/{client-DjR-lC16.js → client-BfiZ3HQd.js} +3 -3
- package/dist/{client-DjR-lC16.js.map → client-BfiZ3HQd.js.map} +1 -1
- package/dist/{client-C-nwz-3N.d.ts → client-C1R7IU9g.d.ts} +24 -24
- package/dist/{client-CZBVDDoO.js → client-CIvp_OWw.js} +2 -2
- package/dist/{client-CZBVDDoO.js.map → client-CIvp_OWw.js.map} +1 -1
- package/dist/{client-CmMi85Sj.d.ts → client-CbWe9FBd.d.ts} +10 -10
- package/dist/client.d.ts +8 -8
- package/dist/client.js +2 -2
- package/dist/codemode/ai.js +5 -5
- package/dist/{do-oauth-client-provider-B2jr6UNq.js → do-oauth-client-provider-CswoD5Lu.js} +2 -2
- package/dist/{do-oauth-client-provider-B2jr6UNq.js.map → do-oauth-client-provider-CswoD5Lu.js.map} +1 -1
- package/dist/{do-oauth-client-provider-CCwGwnrA.d.ts → do-oauth-client-provider-DGc5pP0l.d.ts} +2 -2
- package/dist/{index-DWJSBMbz.d.ts → index-CaUf7Wsc.d.ts} +47 -215
- package/dist/{index-W4JUkafc.d.ts → index-DhJCaDWd.d.ts} +7 -3
- package/dist/index.d.ts +36 -50
- package/dist/index.js +6 -6
- package/dist/mcp/client.d.ts +3 -3
- package/dist/mcp/client.js +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/do-oauth-client-provider.js +1 -1
- package/dist/mcp/index.d.ts +129 -7
- package/dist/mcp/index.js +1234 -6
- package/dist/mcp/index.js.map +1 -0
- package/dist/{mcp-BEwaCsxO.d.ts → mcp-Dw5vDrY8.d.ts} +2 -2
- package/dist/observability/index.d.ts +2 -2
- package/dist/observability/index.js +5 -5
- package/dist/{react-GnTP-a01.d.ts → react-BWIluznB.d.ts} +28 -26
- package/dist/react.d.ts +9 -9
- package/dist/react.js +1 -1
- package/dist/{serializable-gtr9YMhp.d.ts → serializable-CymX8ovI.d.ts} +8 -3
- package/dist/serializable.d.ts +5 -5
- package/dist/src-CTtjSFyX.js +1231 -0
- package/dist/src-CTtjSFyX.js.map +1 -0
- package/package.json +5 -5
- package/dist/src-tpG9NtHy.js +0 -2457
- package/dist/src-tpG9NtHy.js.map +0 -1
package/dist/mcp/index.js
CHANGED
|
@@ -1,7 +1,1235 @@
|
|
|
1
|
-
import "../ai-types-
|
|
2
|
-
import "../client-
|
|
3
|
-
import { SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport } from "../client-
|
|
4
|
-
import "../do-oauth-client-provider-
|
|
5
|
-
import {
|
|
1
|
+
import { t as MessageType } from "../ai-types-B3aQaFv3.js";
|
|
2
|
+
import "../client-BfiZ3HQd.js";
|
|
3
|
+
import { i as SSEEdgeClientTransport, r as StreamableHTTPEdgeClientTransport } from "../client-CIvp_OWw.js";
|
|
4
|
+
import "../do-oauth-client-provider-CswoD5Lu.js";
|
|
5
|
+
import { c as getCurrentAgent, s as getAgentByName, t as Agent } from "../src-CTtjSFyX.js";
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
|
+
import { ElicitRequestSchema, InitializeRequestSchema, JSONRPCMessageSchema, isInitializeRequest, isJSONRPCError, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResponse } from "@modelcontextprotocol/sdk/types.js";
|
|
6
8
|
|
|
7
|
-
|
|
9
|
+
//#region src/mcp/utils.ts
|
|
10
|
+
/**
|
|
11
|
+
* Since we use WebSockets to bridge the client to the
|
|
12
|
+
* MCP transport in the Agent, we use this header to signal
|
|
13
|
+
* the method of the original request the user made, while
|
|
14
|
+
* leaving the WS Upgrade request as GET.
|
|
15
|
+
*/
|
|
16
|
+
const MCP_HTTP_METHOD_HEADER = "cf-mcp-method";
|
|
17
|
+
/**
|
|
18
|
+
* Since we use WebSockets to bridge the client to the
|
|
19
|
+
* MCP transport in the Agent, we use this header to include
|
|
20
|
+
* the original request body.
|
|
21
|
+
*/
|
|
22
|
+
const MCP_MESSAGE_HEADER = "cf-mcp-message";
|
|
23
|
+
const MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
|
|
24
|
+
const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
|
|
25
|
+
let pathname = basePath;
|
|
26
|
+
if (basePath === "/") pathname = "/*";
|
|
27
|
+
const basePattern = new URLPattern({ pathname });
|
|
28
|
+
return async (request, ctx) => {
|
|
29
|
+
const url = new URL(request.url);
|
|
30
|
+
if (basePattern.test(url)) {
|
|
31
|
+
if (request.method === "POST") {
|
|
32
|
+
const acceptHeader = request.headers.get("accept");
|
|
33
|
+
if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
|
|
34
|
+
const body$1 = JSON.stringify({
|
|
35
|
+
error: {
|
|
36
|
+
code: -32e3,
|
|
37
|
+
message: "Not Acceptable: Client must accept both application/json and text/event-stream"
|
|
38
|
+
},
|
|
39
|
+
id: null,
|
|
40
|
+
jsonrpc: "2.0"
|
|
41
|
+
});
|
|
42
|
+
return new Response(body$1, { status: 406 });
|
|
43
|
+
}
|
|
44
|
+
const ct = request.headers.get("content-type");
|
|
45
|
+
if (!ct || !ct.includes("application/json")) {
|
|
46
|
+
const body$1 = JSON.stringify({
|
|
47
|
+
error: {
|
|
48
|
+
code: -32e3,
|
|
49
|
+
message: "Unsupported Media Type: Content-Type must be application/json"
|
|
50
|
+
},
|
|
51
|
+
id: null,
|
|
52
|
+
jsonrpc: "2.0"
|
|
53
|
+
});
|
|
54
|
+
return new Response(body$1, { status: 415 });
|
|
55
|
+
}
|
|
56
|
+
if (Number.parseInt(request.headers.get("content-length") ?? "0", 10) > MAXIMUM_MESSAGE_SIZE_BYTES) {
|
|
57
|
+
const body$1 = JSON.stringify({
|
|
58
|
+
error: {
|
|
59
|
+
code: -32e3,
|
|
60
|
+
message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
|
|
61
|
+
},
|
|
62
|
+
id: null,
|
|
63
|
+
jsonrpc: "2.0"
|
|
64
|
+
});
|
|
65
|
+
return new Response(body$1, { status: 413 });
|
|
66
|
+
}
|
|
67
|
+
let sessionId = request.headers.get("mcp-session-id");
|
|
68
|
+
let rawMessage;
|
|
69
|
+
try {
|
|
70
|
+
rawMessage = await request.json();
|
|
71
|
+
} catch (_error) {
|
|
72
|
+
const body$1 = JSON.stringify({
|
|
73
|
+
error: {
|
|
74
|
+
code: -32700,
|
|
75
|
+
message: "Parse error: Invalid JSON"
|
|
76
|
+
},
|
|
77
|
+
id: null,
|
|
78
|
+
jsonrpc: "2.0"
|
|
79
|
+
});
|
|
80
|
+
return new Response(body$1, { status: 400 });
|
|
81
|
+
}
|
|
82
|
+
let arrayMessage;
|
|
83
|
+
if (Array.isArray(rawMessage)) arrayMessage = rawMessage;
|
|
84
|
+
else arrayMessage = [rawMessage];
|
|
85
|
+
let messages = [];
|
|
86
|
+
for (const msg of arrayMessage) if (!JSONRPCMessageSchema.safeParse(msg).success) {
|
|
87
|
+
const body$1 = JSON.stringify({
|
|
88
|
+
error: {
|
|
89
|
+
code: -32700,
|
|
90
|
+
message: "Parse error: Invalid JSON-RPC message"
|
|
91
|
+
},
|
|
92
|
+
id: null,
|
|
93
|
+
jsonrpc: "2.0"
|
|
94
|
+
});
|
|
95
|
+
return new Response(body$1, { status: 400 });
|
|
96
|
+
}
|
|
97
|
+
messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
|
|
98
|
+
const maybeInitializeRequest = messages.find((msg) => InitializeRequestSchema.safeParse(msg).success);
|
|
99
|
+
if (!!maybeInitializeRequest && sessionId) {
|
|
100
|
+
const body$1 = JSON.stringify({
|
|
101
|
+
error: {
|
|
102
|
+
code: -32600,
|
|
103
|
+
message: "Invalid Request: Initialization requests must not include a sessionId"
|
|
104
|
+
},
|
|
105
|
+
id: null,
|
|
106
|
+
jsonrpc: "2.0"
|
|
107
|
+
});
|
|
108
|
+
return new Response(body$1, { status: 400 });
|
|
109
|
+
}
|
|
110
|
+
if (!!maybeInitializeRequest && messages.length > 1) {
|
|
111
|
+
const body$1 = JSON.stringify({
|
|
112
|
+
error: {
|
|
113
|
+
code: -32600,
|
|
114
|
+
message: "Invalid Request: Only one initialization request is allowed"
|
|
115
|
+
},
|
|
116
|
+
id: null,
|
|
117
|
+
jsonrpc: "2.0"
|
|
118
|
+
});
|
|
119
|
+
return new Response(body$1, { status: 400 });
|
|
120
|
+
}
|
|
121
|
+
if (!maybeInitializeRequest && !sessionId) {
|
|
122
|
+
const body$1 = JSON.stringify({
|
|
123
|
+
error: {
|
|
124
|
+
code: -32e3,
|
|
125
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
126
|
+
},
|
|
127
|
+
id: null,
|
|
128
|
+
jsonrpc: "2.0"
|
|
129
|
+
});
|
|
130
|
+
return new Response(body$1, { status: 400 });
|
|
131
|
+
}
|
|
132
|
+
sessionId = sessionId ?? namespace.newUniqueId().toString();
|
|
133
|
+
const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
|
|
134
|
+
const isInitialized = await agent.getInitializeRequest();
|
|
135
|
+
if (maybeInitializeRequest) await agent.setInitializeRequest(maybeInitializeRequest);
|
|
136
|
+
else if (!isInitialized) {
|
|
137
|
+
const body$1 = JSON.stringify({
|
|
138
|
+
error: {
|
|
139
|
+
code: -32001,
|
|
140
|
+
message: "Session not found"
|
|
141
|
+
},
|
|
142
|
+
id: null,
|
|
143
|
+
jsonrpc: "2.0"
|
|
144
|
+
});
|
|
145
|
+
return new Response(body$1, { status: 404 });
|
|
146
|
+
}
|
|
147
|
+
const { readable, writable } = new TransformStream();
|
|
148
|
+
const writer = writable.getWriter();
|
|
149
|
+
const encoder = new TextEncoder();
|
|
150
|
+
const existingHeaders = {};
|
|
151
|
+
request.headers.forEach((value, key) => {
|
|
152
|
+
existingHeaders[key] = value;
|
|
153
|
+
});
|
|
154
|
+
const req = new Request(request.url, { headers: {
|
|
155
|
+
...existingHeaders,
|
|
156
|
+
[MCP_HTTP_METHOD_HEADER]: "POST",
|
|
157
|
+
[MCP_MESSAGE_HEADER]: Buffer.from(JSON.stringify(messages)).toString("base64"),
|
|
158
|
+
Upgrade: "websocket"
|
|
159
|
+
} });
|
|
160
|
+
if (ctx.props) agent.updateProps(ctx.props);
|
|
161
|
+
const ws = (await agent.fetch(req)).webSocket;
|
|
162
|
+
if (!ws) {
|
|
163
|
+
console.error("Failed to establish WebSocket connection");
|
|
164
|
+
await writer.close();
|
|
165
|
+
const body$1 = JSON.stringify({
|
|
166
|
+
error: {
|
|
167
|
+
code: -32001,
|
|
168
|
+
message: "Failed to establish WebSocket connection"
|
|
169
|
+
},
|
|
170
|
+
id: null,
|
|
171
|
+
jsonrpc: "2.0"
|
|
172
|
+
});
|
|
173
|
+
return new Response(body$1, { status: 500 });
|
|
174
|
+
}
|
|
175
|
+
ws.accept();
|
|
176
|
+
ws.addEventListener("message", (event) => {
|
|
177
|
+
async function onMessage(event$1) {
|
|
178
|
+
try {
|
|
179
|
+
const data = typeof event$1.data === "string" ? event$1.data : new TextDecoder().decode(event$1.data);
|
|
180
|
+
const message = JSON.parse(data);
|
|
181
|
+
if (message.type !== MessageType.CF_MCP_AGENT_EVENT) return;
|
|
182
|
+
await writer.write(encoder.encode(message.event));
|
|
183
|
+
if (message.close) {
|
|
184
|
+
ws?.close();
|
|
185
|
+
await writer.close().catch(() => {});
|
|
186
|
+
}
|
|
187
|
+
} catch (error) {
|
|
188
|
+
console.error("Error forwarding message to SSE:", error);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
onMessage(event).catch(console.error);
|
|
192
|
+
});
|
|
193
|
+
ws.addEventListener("error", (error) => {
|
|
194
|
+
async function onError(_error) {
|
|
195
|
+
await writer.close().catch(() => {});
|
|
196
|
+
}
|
|
197
|
+
onError(error).catch(console.error);
|
|
198
|
+
});
|
|
199
|
+
ws.addEventListener("close", () => {
|
|
200
|
+
async function onClose() {
|
|
201
|
+
await writer.close().catch(() => {});
|
|
202
|
+
}
|
|
203
|
+
onClose().catch(console.error);
|
|
204
|
+
});
|
|
205
|
+
if (messages.every((msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg))) {
|
|
206
|
+
ws.close();
|
|
207
|
+
return new Response(null, {
|
|
208
|
+
headers: corsHeaders(request, corsOptions),
|
|
209
|
+
status: 202
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return new Response(readable, {
|
|
213
|
+
headers: {
|
|
214
|
+
"Cache-Control": "no-cache",
|
|
215
|
+
Connection: "keep-alive",
|
|
216
|
+
"Content-Type": "text/event-stream",
|
|
217
|
+
"mcp-session-id": sessionId,
|
|
218
|
+
...corsHeaders(request, corsOptions)
|
|
219
|
+
},
|
|
220
|
+
status: 200
|
|
221
|
+
});
|
|
222
|
+
} else if (request.method === "GET") {
|
|
223
|
+
if (!request.headers.get("accept")?.includes("text/event-stream")) {
|
|
224
|
+
const body$1 = JSON.stringify({
|
|
225
|
+
jsonrpc: "2.0",
|
|
226
|
+
error: {
|
|
227
|
+
code: -32e3,
|
|
228
|
+
message: "Not Acceptable: Client must accept text/event-stream"
|
|
229
|
+
},
|
|
230
|
+
id: null
|
|
231
|
+
});
|
|
232
|
+
return new Response(body$1, { status: 406 });
|
|
233
|
+
}
|
|
234
|
+
const sessionId = request.headers.get("mcp-session-id");
|
|
235
|
+
if (!sessionId) return new Response(JSON.stringify({
|
|
236
|
+
error: {
|
|
237
|
+
code: -32e3,
|
|
238
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
239
|
+
},
|
|
240
|
+
id: null,
|
|
241
|
+
jsonrpc: "2.0"
|
|
242
|
+
}), { status: 400 });
|
|
243
|
+
const { readable, writable } = new TransformStream();
|
|
244
|
+
const writer = writable.getWriter();
|
|
245
|
+
const encoder = new TextEncoder();
|
|
246
|
+
const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
|
|
247
|
+
if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
|
|
248
|
+
jsonrpc: "2.0",
|
|
249
|
+
error: {
|
|
250
|
+
code: -32001,
|
|
251
|
+
message: "Session not found"
|
|
252
|
+
},
|
|
253
|
+
id: null
|
|
254
|
+
}), { status: 404 });
|
|
255
|
+
const existingHeaders = {};
|
|
256
|
+
request.headers.forEach((v, k) => {
|
|
257
|
+
existingHeaders[k] = v;
|
|
258
|
+
});
|
|
259
|
+
if (ctx.props) agent.updateProps(ctx.props);
|
|
260
|
+
const ws = (await agent.fetch(new Request(request.url, { headers: {
|
|
261
|
+
...existingHeaders,
|
|
262
|
+
[MCP_HTTP_METHOD_HEADER]: "GET",
|
|
263
|
+
Upgrade: "websocket"
|
|
264
|
+
} }))).webSocket;
|
|
265
|
+
if (!ws) {
|
|
266
|
+
await writer.close();
|
|
267
|
+
return new Response("Failed to establish WS to DO", { status: 500 });
|
|
268
|
+
}
|
|
269
|
+
ws.accept();
|
|
270
|
+
ws.addEventListener("message", (event) => {
|
|
271
|
+
try {
|
|
272
|
+
async function onMessage(ev) {
|
|
273
|
+
const data = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
|
|
274
|
+
const message = JSON.parse(data);
|
|
275
|
+
if (message.type !== MessageType.CF_MCP_AGENT_EVENT) return;
|
|
276
|
+
await writer.write(encoder.encode(message.event));
|
|
277
|
+
}
|
|
278
|
+
onMessage(event).catch(console.error);
|
|
279
|
+
} catch (e) {
|
|
280
|
+
console.error("Error forwarding message to SSE:", e);
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
ws.addEventListener("error", () => {
|
|
284
|
+
writer.close().catch(() => {});
|
|
285
|
+
});
|
|
286
|
+
ws.addEventListener("close", () => {
|
|
287
|
+
writer.close().catch(() => {});
|
|
288
|
+
});
|
|
289
|
+
return new Response(readable, {
|
|
290
|
+
headers: {
|
|
291
|
+
"Cache-Control": "no-cache",
|
|
292
|
+
Connection: "keep-alive",
|
|
293
|
+
"Content-Type": "text/event-stream",
|
|
294
|
+
"mcp-session-id": sessionId,
|
|
295
|
+
...corsHeaders(request, corsOptions)
|
|
296
|
+
},
|
|
297
|
+
status: 200
|
|
298
|
+
});
|
|
299
|
+
} else if (request.method === "DELETE") {
|
|
300
|
+
const sessionId = request.headers.get("mcp-session-id");
|
|
301
|
+
if (!sessionId) return new Response(JSON.stringify({
|
|
302
|
+
jsonrpc: "2.0",
|
|
303
|
+
error: {
|
|
304
|
+
code: -32e3,
|
|
305
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
306
|
+
},
|
|
307
|
+
id: null
|
|
308
|
+
}), {
|
|
309
|
+
status: 400,
|
|
310
|
+
headers: corsHeaders(request, corsOptions)
|
|
311
|
+
});
|
|
312
|
+
const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`);
|
|
313
|
+
if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
|
|
314
|
+
jsonrpc: "2.0",
|
|
315
|
+
error: {
|
|
316
|
+
code: -32001,
|
|
317
|
+
message: "Session not found"
|
|
318
|
+
},
|
|
319
|
+
id: null
|
|
320
|
+
}), {
|
|
321
|
+
status: 404,
|
|
322
|
+
headers: corsHeaders(request, corsOptions)
|
|
323
|
+
});
|
|
324
|
+
ctx.waitUntil(agent.destroy().catch(() => {}));
|
|
325
|
+
return new Response(null, {
|
|
326
|
+
status: 204,
|
|
327
|
+
headers: corsHeaders(request, corsOptions)
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
const body = JSON.stringify({
|
|
332
|
+
error: {
|
|
333
|
+
code: -32e3,
|
|
334
|
+
message: "Not found"
|
|
335
|
+
},
|
|
336
|
+
id: null,
|
|
337
|
+
jsonrpc: "2.0"
|
|
338
|
+
});
|
|
339
|
+
return new Response(body, { status: 404 });
|
|
340
|
+
};
|
|
341
|
+
};
|
|
342
|
+
const createLegacySseHandler = (basePath, namespace, corsOptions) => {
|
|
343
|
+
let pathname = basePath;
|
|
344
|
+
if (basePath === "/") pathname = "/*";
|
|
345
|
+
const basePattern = new URLPattern({ pathname });
|
|
346
|
+
const messagePattern = new URLPattern({ pathname: `${basePath}/message` });
|
|
347
|
+
return async (request, ctx) => {
|
|
348
|
+
const url = new URL(request.url);
|
|
349
|
+
if (request.method === "GET" && basePattern.test(url)) {
|
|
350
|
+
const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
|
|
351
|
+
const { readable, writable } = new TransformStream();
|
|
352
|
+
const writer = writable.getWriter();
|
|
353
|
+
const encoder = new TextEncoder();
|
|
354
|
+
const endpointUrl = new URL(request.url);
|
|
355
|
+
endpointUrl.pathname = encodeURI(`${basePath}/message`);
|
|
356
|
+
endpointUrl.searchParams.set("sessionId", sessionId);
|
|
357
|
+
const endpointMessage = `event: endpoint\ndata: ${endpointUrl.pathname + endpointUrl.search + endpointUrl.hash}\n\n`;
|
|
358
|
+
writer.write(encoder.encode(endpointMessage));
|
|
359
|
+
const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
|
|
360
|
+
const existingHeaders = {};
|
|
361
|
+
request.headers.forEach((value, key) => {
|
|
362
|
+
existingHeaders[key] = value;
|
|
363
|
+
});
|
|
364
|
+
if (ctx.props) agent.updateProps(ctx.props);
|
|
365
|
+
const ws = (await agent.fetch(new Request(request.url, { headers: {
|
|
366
|
+
...existingHeaders,
|
|
367
|
+
Upgrade: "websocket"
|
|
368
|
+
} }))).webSocket;
|
|
369
|
+
if (!ws) {
|
|
370
|
+
console.error("Failed to establish WebSocket connection");
|
|
371
|
+
await writer.close();
|
|
372
|
+
return new Response("Failed to establish WebSocket connection", { status: 500 });
|
|
373
|
+
}
|
|
374
|
+
ws.accept();
|
|
375
|
+
ws.addEventListener("message", (event) => {
|
|
376
|
+
async function onMessage(event$1) {
|
|
377
|
+
try {
|
|
378
|
+
const message = JSON.parse(event$1.data);
|
|
379
|
+
const result = JSONRPCMessageSchema.safeParse(message);
|
|
380
|
+
if (!result.success) return;
|
|
381
|
+
const messageText = `event: message\ndata: ${JSON.stringify(result.data)}\n\n`;
|
|
382
|
+
await writer.write(encoder.encode(messageText));
|
|
383
|
+
} catch (error) {
|
|
384
|
+
console.error("Error forwarding message to SSE:", error);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
onMessage(event).catch(console.error);
|
|
388
|
+
});
|
|
389
|
+
ws.addEventListener("error", (error) => {
|
|
390
|
+
async function onError(_error) {
|
|
391
|
+
try {
|
|
392
|
+
await writer.close();
|
|
393
|
+
} catch (_e) {}
|
|
394
|
+
}
|
|
395
|
+
onError(error).catch(console.error);
|
|
396
|
+
});
|
|
397
|
+
ws.addEventListener("close", () => {
|
|
398
|
+
async function onClose() {
|
|
399
|
+
try {
|
|
400
|
+
await writer.close();
|
|
401
|
+
} catch (error) {
|
|
402
|
+
console.error("Error closing SSE connection:", error);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
onClose().catch(console.error);
|
|
406
|
+
});
|
|
407
|
+
return new Response(readable, { headers: {
|
|
408
|
+
"Cache-Control": "no-cache",
|
|
409
|
+
Connection: "keep-alive",
|
|
410
|
+
"Content-Type": "text/event-stream",
|
|
411
|
+
...corsHeaders(request, corsOptions)
|
|
412
|
+
} });
|
|
413
|
+
}
|
|
414
|
+
if (request.method === "POST" && messagePattern.test(url)) {
|
|
415
|
+
const sessionId = url.searchParams.get("sessionId");
|
|
416
|
+
if (!sessionId) return new Response(`Missing sessionId. Expected POST to ${basePath} to initiate new one`, { status: 400 });
|
|
417
|
+
const contentType = request.headers.get("content-type") || "";
|
|
418
|
+
if (!contentType.includes("application/json")) return new Response(`Unsupported content-type: ${contentType}`, { status: 400 });
|
|
419
|
+
const contentLength = Number.parseInt(request.headers.get("content-length") || "0", 10);
|
|
420
|
+
if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) return new Response(`Request body too large: ${contentLength} bytes`, { status: 400 });
|
|
421
|
+
const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
|
|
422
|
+
const messageBody = await request.json();
|
|
423
|
+
const error = await agent.onSSEMcpMessage(sessionId, messageBody);
|
|
424
|
+
if (error) return new Response(error.message, {
|
|
425
|
+
headers: {
|
|
426
|
+
"Cache-Control": "no-cache",
|
|
427
|
+
Connection: "keep-alive",
|
|
428
|
+
"Content-Type": "text/event-stream",
|
|
429
|
+
...corsHeaders(request, corsOptions)
|
|
430
|
+
},
|
|
431
|
+
status: 400
|
|
432
|
+
});
|
|
433
|
+
return new Response("Accepted", {
|
|
434
|
+
headers: {
|
|
435
|
+
"Cache-Control": "no-cache",
|
|
436
|
+
Connection: "keep-alive",
|
|
437
|
+
"Content-Type": "text/event-stream",
|
|
438
|
+
...corsHeaders(request, corsOptions)
|
|
439
|
+
},
|
|
440
|
+
status: 202
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
return new Response("Not Found", { status: 404 });
|
|
444
|
+
};
|
|
445
|
+
};
|
|
446
|
+
function corsHeaders(_request, corsOptions = {}) {
|
|
447
|
+
const origin = "*";
|
|
448
|
+
return {
|
|
449
|
+
"Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, Accept, mcp-session-id, mcp-protocol-version",
|
|
450
|
+
"Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, DELETE, OPTIONS",
|
|
451
|
+
"Access-Control-Allow-Origin": corsOptions.origin || origin,
|
|
452
|
+
"Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
|
|
453
|
+
"Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
function handleCORS(request, corsOptions) {
|
|
457
|
+
if (request.method === "OPTIONS") return new Response(null, { headers: corsHeaders(request, corsOptions) });
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
function isDurableObjectNamespace(namespace) {
|
|
461
|
+
return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
//#endregion
|
|
465
|
+
//#region src/mcp/transport.ts
|
|
466
|
+
var McpSSETransport = class {
|
|
467
|
+
constructor(getWebSocket) {
|
|
468
|
+
this._started = false;
|
|
469
|
+
this._getWebSocket = getWebSocket;
|
|
470
|
+
}
|
|
471
|
+
async start() {
|
|
472
|
+
if (this._started) throw new Error("Transport already started");
|
|
473
|
+
this._started = true;
|
|
474
|
+
}
|
|
475
|
+
async send(message) {
|
|
476
|
+
if (!this._started) throw new Error("Transport not started");
|
|
477
|
+
const websocket = this._getWebSocket();
|
|
478
|
+
if (!websocket) throw new Error("WebSocket not connected");
|
|
479
|
+
try {
|
|
480
|
+
websocket.send(JSON.stringify(message));
|
|
481
|
+
} catch (error) {
|
|
482
|
+
this.onerror?.(error);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
async close() {
|
|
486
|
+
this.onclose?.();
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
/**
|
|
490
|
+
* Adapted from: https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/client/streamableHttp.ts
|
|
491
|
+
* - Validation and initialization are removed as they're handled in `McpAgent.serve()` handler.
|
|
492
|
+
* - Replaces the Node-style `req`/`res` with Worker's `Request`.
|
|
493
|
+
* - Writes events as WS messages that the Worker forwards to the client as SSE events.
|
|
494
|
+
* - Replaces the in-memory maps that track requestID/stream by using `connection.setState()` and `agent.getConnections()`.
|
|
495
|
+
*
|
|
496
|
+
* Besides these points, the implementation is the same and should be updated to match the original as new features are added.
|
|
497
|
+
*/
|
|
498
|
+
var StreamableHTTPServerTransport = class {
|
|
499
|
+
constructor(options) {
|
|
500
|
+
this._started = false;
|
|
501
|
+
this._requestResponseMap = /* @__PURE__ */ new Map();
|
|
502
|
+
const { agent } = getCurrentAgent();
|
|
503
|
+
if (!agent) throw new Error("McpAgent was not found in Transport constructor");
|
|
504
|
+
this.sessionId = agent.getSessionId();
|
|
505
|
+
this._eventStore = options.eventStore;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Starts the transport. This is required by the Transport interface but is a no-op
|
|
509
|
+
* for the Streamable HTTP transport as connections are managed per-request.
|
|
510
|
+
*/
|
|
511
|
+
async start() {
|
|
512
|
+
if (this._started) throw new Error("Transport already started");
|
|
513
|
+
this._started = true;
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Handles GET requests for SSE stream
|
|
517
|
+
*/
|
|
518
|
+
async handleGetRequest(req) {
|
|
519
|
+
const { connection } = getCurrentAgent();
|
|
520
|
+
if (!connection) throw new Error("Connection was not found in handleGetRequest");
|
|
521
|
+
if (this._eventStore) {
|
|
522
|
+
const lastEventId = req.headers.get("last-event-id");
|
|
523
|
+
if (lastEventId) {
|
|
524
|
+
await this.replayEvents(lastEventId);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
connection.setState({ _standaloneSse: true });
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Replays events that would have been sent after the specified event ID
|
|
532
|
+
* Only used when resumability is enabled
|
|
533
|
+
*/
|
|
534
|
+
async replayEvents(lastEventId) {
|
|
535
|
+
if (!this._eventStore) return;
|
|
536
|
+
const { connection } = getCurrentAgent();
|
|
537
|
+
if (!connection) throw new Error("Connection was not available in replayEvents");
|
|
538
|
+
try {
|
|
539
|
+
await this._eventStore?.replayEventsAfter(lastEventId, { send: async (eventId, message) => {
|
|
540
|
+
try {
|
|
541
|
+
this.writeSSEEvent(connection, message, eventId);
|
|
542
|
+
} catch (error) {
|
|
543
|
+
this.onerror?.(error);
|
|
544
|
+
}
|
|
545
|
+
} });
|
|
546
|
+
} catch (error) {
|
|
547
|
+
this.onerror?.(error);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Writes an event to the SSE stream with proper formatting
|
|
552
|
+
*/
|
|
553
|
+
writeSSEEvent(connection, message, eventId, close) {
|
|
554
|
+
let eventData = "event: message\n";
|
|
555
|
+
if (eventId) eventData += `id: ${eventId}\n`;
|
|
556
|
+
eventData += `data: ${JSON.stringify(message)}\n\n`;
|
|
557
|
+
return connection.send(JSON.stringify({
|
|
558
|
+
type: MessageType.CF_MCP_AGENT_EVENT,
|
|
559
|
+
event: eventData,
|
|
560
|
+
close
|
|
561
|
+
}));
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Handles POST requests containing JSON-RPC messages
|
|
565
|
+
*/
|
|
566
|
+
async handlePostRequest(req, parsedBody) {
|
|
567
|
+
const authInfo = req.auth;
|
|
568
|
+
const requestInfo = { headers: Object.fromEntries(req.headers.entries()) };
|
|
569
|
+
delete requestInfo.headers[MCP_HTTP_METHOD_HEADER];
|
|
570
|
+
delete requestInfo.headers[MCP_MESSAGE_HEADER];
|
|
571
|
+
delete requestInfo.headers.upgrade;
|
|
572
|
+
const rawMessage = parsedBody;
|
|
573
|
+
let messages;
|
|
574
|
+
if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
|
|
575
|
+
else messages = [JSONRPCMessageSchema.parse(rawMessage)];
|
|
576
|
+
const hasRequests = messages.some(isJSONRPCRequest);
|
|
577
|
+
if (!hasRequests) for (const message of messages) this.onmessage?.(message, {
|
|
578
|
+
authInfo,
|
|
579
|
+
requestInfo
|
|
580
|
+
});
|
|
581
|
+
else if (hasRequests) {
|
|
582
|
+
const { connection } = getCurrentAgent();
|
|
583
|
+
if (!connection) throw new Error("Connection was not found in handlePostRequest");
|
|
584
|
+
const requestIds = messages.filter(isJSONRPCRequest).map((message) => message.id);
|
|
585
|
+
connection.setState({ requestIds });
|
|
586
|
+
for (const message of messages) this.onmessage?.(message, {
|
|
587
|
+
authInfo,
|
|
588
|
+
requestInfo
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
async close() {
|
|
593
|
+
const { agent } = getCurrentAgent();
|
|
594
|
+
if (!agent) throw new Error("Agent was not found in close");
|
|
595
|
+
for (const conn of agent.getConnections()) conn.close(1e3, "Session closed");
|
|
596
|
+
this.onclose?.();
|
|
597
|
+
}
|
|
598
|
+
async send(message, options) {
|
|
599
|
+
const { agent } = getCurrentAgent();
|
|
600
|
+
if (!agent) throw new Error("Agent was not found in send");
|
|
601
|
+
let requestId = options?.relatedRequestId;
|
|
602
|
+
if (isJSONRPCResponse(message) || isJSONRPCError(message)) requestId = message.id;
|
|
603
|
+
if (requestId === void 0) {
|
|
604
|
+
if (isJSONRPCResponse(message) || isJSONRPCError(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
|
|
605
|
+
let standaloneConnection;
|
|
606
|
+
for (const conn of agent.getConnections()) if (conn.state?._standaloneSse) standaloneConnection = conn;
|
|
607
|
+
if (standaloneConnection === void 0) return;
|
|
608
|
+
let eventId$1;
|
|
609
|
+
if (this._eventStore) eventId$1 = await this._eventStore.storeEvent(standaloneConnection.id, message);
|
|
610
|
+
this.writeSSEEvent(standaloneConnection, message, eventId$1);
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
const connection = Array.from(agent.getConnections()).find((conn) => conn.state?.requestIds?.includes(requestId));
|
|
614
|
+
if (!connection) throw new Error(`No connection established for request ID: ${String(requestId)}`);
|
|
615
|
+
let eventId;
|
|
616
|
+
if (this._eventStore) eventId = await this._eventStore.storeEvent(connection.id, message);
|
|
617
|
+
let shouldClose = false;
|
|
618
|
+
if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
|
|
619
|
+
this._requestResponseMap.set(requestId, message);
|
|
620
|
+
const relatedIds = connection.state?.requestIds ?? [];
|
|
621
|
+
shouldClose = relatedIds.every((id) => this._requestResponseMap.has(id));
|
|
622
|
+
if (shouldClose) for (const id of relatedIds) this._requestResponseMap.delete(id);
|
|
623
|
+
}
|
|
624
|
+
this.writeSSEEvent(connection, message, eventId, shouldClose);
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
//#endregion
|
|
629
|
+
//#region src/mcp/worker-transport.ts
|
|
630
|
+
var WorkerTransport = class {
|
|
631
|
+
constructor(options) {
|
|
632
|
+
this.started = false;
|
|
633
|
+
this.initialized = false;
|
|
634
|
+
this.enableJsonResponse = false;
|
|
635
|
+
this.standaloneSseStreamId = "_GET_stream";
|
|
636
|
+
this.streamMapping = /* @__PURE__ */ new Map();
|
|
637
|
+
this.requestToStreamMapping = /* @__PURE__ */ new Map();
|
|
638
|
+
this.requestResponseMap = /* @__PURE__ */ new Map();
|
|
639
|
+
this.sessionIdGenerator = options?.sessionIdGenerator;
|
|
640
|
+
this.enableJsonResponse = options?.enableJsonResponse ?? false;
|
|
641
|
+
this.onsessioninitialized = options?.onsessioninitialized;
|
|
642
|
+
}
|
|
643
|
+
async start() {
|
|
644
|
+
if (this.started) throw new Error("Transport already started");
|
|
645
|
+
this.started = true;
|
|
646
|
+
}
|
|
647
|
+
async handleRequest(request, parsedBody) {
|
|
648
|
+
switch (request.method) {
|
|
649
|
+
case "OPTIONS": return this.handleOptionsRequest(request);
|
|
650
|
+
case "GET": return this.handleGetRequest(request);
|
|
651
|
+
case "POST": return this.handlePostRequest(request, parsedBody);
|
|
652
|
+
case "DELETE": return this.handleDeleteRequest(request);
|
|
653
|
+
default: return this.handleUnsupportedRequest();
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
async handleGetRequest(request) {
|
|
657
|
+
if (!request.headers.get("Accept")?.includes("text/event-stream")) return new Response(JSON.stringify({
|
|
658
|
+
jsonrpc: "2.0",
|
|
659
|
+
error: {
|
|
660
|
+
code: -32e3,
|
|
661
|
+
message: "Not Acceptable: Client must accept text/event-stream"
|
|
662
|
+
},
|
|
663
|
+
id: null
|
|
664
|
+
}), {
|
|
665
|
+
status: 406,
|
|
666
|
+
headers: { "Content-Type": "application/json" }
|
|
667
|
+
});
|
|
668
|
+
const sessionValid = this.validateSession(request);
|
|
669
|
+
if (sessionValid !== true) return sessionValid;
|
|
670
|
+
const streamId = this.standaloneSseStreamId;
|
|
671
|
+
if (this.streamMapping.get(streamId) !== void 0) return new Response(JSON.stringify({
|
|
672
|
+
jsonrpc: "2.0",
|
|
673
|
+
error: {
|
|
674
|
+
code: -32e3,
|
|
675
|
+
message: "Conflict: Only one SSE stream is allowed per session"
|
|
676
|
+
},
|
|
677
|
+
id: null
|
|
678
|
+
}), {
|
|
679
|
+
status: 409,
|
|
680
|
+
headers: { "Content-Type": "application/json" }
|
|
681
|
+
});
|
|
682
|
+
const { readable, writable } = new TransformStream();
|
|
683
|
+
const writer = writable.getWriter();
|
|
684
|
+
const encoder = new TextEncoder();
|
|
685
|
+
const headers = new Headers({
|
|
686
|
+
"Content-Type": "text/event-stream",
|
|
687
|
+
"Cache-Control": "no-cache",
|
|
688
|
+
Connection: "keep-alive",
|
|
689
|
+
"Access-Control-Allow-Origin": "*",
|
|
690
|
+
"Access-Control-Expose-Headers": "mcp-session-id"
|
|
691
|
+
});
|
|
692
|
+
if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
|
|
693
|
+
const keepAlive = setInterval(() => {
|
|
694
|
+
try {
|
|
695
|
+
writer.write(encoder.encode("event: ping\ndata: \n\n"));
|
|
696
|
+
} catch {
|
|
697
|
+
clearInterval(keepAlive);
|
|
698
|
+
}
|
|
699
|
+
}, 3e4);
|
|
700
|
+
this.streamMapping.set(streamId, {
|
|
701
|
+
writer,
|
|
702
|
+
encoder,
|
|
703
|
+
cleanup: () => {
|
|
704
|
+
clearInterval(keepAlive);
|
|
705
|
+
this.streamMapping.delete(streamId);
|
|
706
|
+
writer.close().catch(() => {});
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
return new Response(readable, { headers });
|
|
710
|
+
}
|
|
711
|
+
async handlePostRequest(request, parsedBody) {
|
|
712
|
+
const acceptHeader = request.headers.get("Accept");
|
|
713
|
+
if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) return new Response(JSON.stringify({
|
|
714
|
+
jsonrpc: "2.0",
|
|
715
|
+
error: {
|
|
716
|
+
code: -32e3,
|
|
717
|
+
message: "Not Acceptable: Client must accept both application/json and text/event-stream"
|
|
718
|
+
},
|
|
719
|
+
id: null
|
|
720
|
+
}), {
|
|
721
|
+
status: 406,
|
|
722
|
+
headers: { "Content-Type": "application/json" }
|
|
723
|
+
});
|
|
724
|
+
if (!request.headers.get("Content-Type")?.includes("application/json")) return new Response(JSON.stringify({
|
|
725
|
+
jsonrpc: "2.0",
|
|
726
|
+
error: {
|
|
727
|
+
code: -32e3,
|
|
728
|
+
message: "Unsupported Media Type: Content-Type must be application/json"
|
|
729
|
+
},
|
|
730
|
+
id: null
|
|
731
|
+
}), {
|
|
732
|
+
status: 415,
|
|
733
|
+
headers: { "Content-Type": "application/json" }
|
|
734
|
+
});
|
|
735
|
+
let rawMessage = parsedBody;
|
|
736
|
+
if (rawMessage === void 0) try {
|
|
737
|
+
rawMessage = await request.json();
|
|
738
|
+
} catch {
|
|
739
|
+
return new Response(JSON.stringify({
|
|
740
|
+
jsonrpc: "2.0",
|
|
741
|
+
error: {
|
|
742
|
+
code: -32700,
|
|
743
|
+
message: "Parse error: Invalid JSON"
|
|
744
|
+
},
|
|
745
|
+
id: null
|
|
746
|
+
}), {
|
|
747
|
+
status: 400,
|
|
748
|
+
headers: { "Content-Type": "application/json" }
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
let messages;
|
|
752
|
+
try {
|
|
753
|
+
if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
|
|
754
|
+
else messages = [JSONRPCMessageSchema.parse(rawMessage)];
|
|
755
|
+
} catch {
|
|
756
|
+
return new Response(JSON.stringify({
|
|
757
|
+
jsonrpc: "2.0",
|
|
758
|
+
error: {
|
|
759
|
+
code: -32700,
|
|
760
|
+
message: "Parse error: Invalid JSON-RPC message"
|
|
761
|
+
},
|
|
762
|
+
id: null
|
|
763
|
+
}), {
|
|
764
|
+
status: 400,
|
|
765
|
+
headers: { "Content-Type": "application/json" }
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
const isInitializationRequest = messages.some(isInitializeRequest);
|
|
769
|
+
if (isInitializationRequest) {
|
|
770
|
+
if (this.initialized && this.sessionId !== void 0) return new Response(JSON.stringify({
|
|
771
|
+
jsonrpc: "2.0",
|
|
772
|
+
error: {
|
|
773
|
+
code: -32600,
|
|
774
|
+
message: "Invalid Request: Server already initialized"
|
|
775
|
+
},
|
|
776
|
+
id: null
|
|
777
|
+
}), {
|
|
778
|
+
status: 400,
|
|
779
|
+
headers: { "Content-Type": "application/json" }
|
|
780
|
+
});
|
|
781
|
+
if (messages.length > 1) return new Response(JSON.stringify({
|
|
782
|
+
jsonrpc: "2.0",
|
|
783
|
+
error: {
|
|
784
|
+
code: -32600,
|
|
785
|
+
message: "Invalid Request: Only one initialization request is allowed"
|
|
786
|
+
},
|
|
787
|
+
id: null
|
|
788
|
+
}), {
|
|
789
|
+
status: 400,
|
|
790
|
+
headers: { "Content-Type": "application/json" }
|
|
791
|
+
});
|
|
792
|
+
this.sessionId = this.sessionIdGenerator?.();
|
|
793
|
+
this.initialized = true;
|
|
794
|
+
if (this.sessionId && this.onsessioninitialized) this.onsessioninitialized(this.sessionId);
|
|
795
|
+
}
|
|
796
|
+
if (!isInitializationRequest) {
|
|
797
|
+
const sessionValid = this.validateSession(request);
|
|
798
|
+
if (sessionValid !== true) return sessionValid;
|
|
799
|
+
}
|
|
800
|
+
if (!messages.some(isJSONRPCRequest)) {
|
|
801
|
+
for (const message of messages) this.onmessage?.(message);
|
|
802
|
+
return new Response(null, {
|
|
803
|
+
status: 202,
|
|
804
|
+
headers: { "Access-Control-Allow-Origin": "*" }
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
const streamId = crypto.randomUUID();
|
|
808
|
+
if (this.enableJsonResponse) return new Promise((resolve) => {
|
|
809
|
+
this.streamMapping.set(streamId, {
|
|
810
|
+
resolveJson: resolve,
|
|
811
|
+
cleanup: () => {
|
|
812
|
+
this.streamMapping.delete(streamId);
|
|
813
|
+
}
|
|
814
|
+
});
|
|
815
|
+
for (const message of messages) if (isJSONRPCRequest(message)) this.requestToStreamMapping.set(message.id, streamId);
|
|
816
|
+
for (const message of messages) this.onmessage?.(message);
|
|
817
|
+
});
|
|
818
|
+
const { readable, writable } = new TransformStream();
|
|
819
|
+
const writer = writable.getWriter();
|
|
820
|
+
const encoder = new TextEncoder();
|
|
821
|
+
const headers = new Headers({
|
|
822
|
+
"Content-Type": "text/event-stream",
|
|
823
|
+
"Cache-Control": "no-cache",
|
|
824
|
+
Connection: "keep-alive",
|
|
825
|
+
"Access-Control-Allow-Origin": "*",
|
|
826
|
+
"Access-Control-Expose-Headers": "mcp-session-id"
|
|
827
|
+
});
|
|
828
|
+
if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
|
|
829
|
+
this.streamMapping.set(streamId, {
|
|
830
|
+
writer,
|
|
831
|
+
encoder,
|
|
832
|
+
cleanup: () => {
|
|
833
|
+
this.streamMapping.delete(streamId);
|
|
834
|
+
writer.close().catch(() => {});
|
|
835
|
+
}
|
|
836
|
+
});
|
|
837
|
+
for (const message of messages) if (isJSONRPCRequest(message)) this.requestToStreamMapping.set(message.id, streamId);
|
|
838
|
+
for (const message of messages) this.onmessage?.(message);
|
|
839
|
+
return new Response(readable, { headers });
|
|
840
|
+
}
|
|
841
|
+
async handleDeleteRequest(request) {
|
|
842
|
+
const sessionValid = this.validateSession(request);
|
|
843
|
+
if (sessionValid !== true) return sessionValid;
|
|
844
|
+
await this.close();
|
|
845
|
+
return new Response(null, {
|
|
846
|
+
status: 200,
|
|
847
|
+
headers: { "Access-Control-Allow-Origin": "*" }
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
handleOptionsRequest(_request) {
|
|
851
|
+
const headers = new Headers({
|
|
852
|
+
"Access-Control-Allow-Origin": "*",
|
|
853
|
+
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
|
|
854
|
+
"Access-Control-Allow-Headers": "Content-Type, Accept, Authorization, mcp-session-id",
|
|
855
|
+
"Access-Control-Max-Age": "86400"
|
|
856
|
+
});
|
|
857
|
+
return new Response(null, {
|
|
858
|
+
status: 204,
|
|
859
|
+
headers
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
handleUnsupportedRequest() {
|
|
863
|
+
return new Response(JSON.stringify({
|
|
864
|
+
jsonrpc: "2.0",
|
|
865
|
+
error: {
|
|
866
|
+
code: -32e3,
|
|
867
|
+
message: "Method not allowed."
|
|
868
|
+
},
|
|
869
|
+
id: null
|
|
870
|
+
}), {
|
|
871
|
+
status: 405,
|
|
872
|
+
headers: {
|
|
873
|
+
Allow: "GET, POST, DELETE, OPTIONS",
|
|
874
|
+
"Content-Type": "application/json"
|
|
875
|
+
}
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
validateSession(request) {
|
|
879
|
+
if (this.sessionIdGenerator === void 0) return true;
|
|
880
|
+
if (!this.initialized) return new Response(JSON.stringify({
|
|
881
|
+
jsonrpc: "2.0",
|
|
882
|
+
error: {
|
|
883
|
+
code: -32e3,
|
|
884
|
+
message: "Bad Request: Server not initialized"
|
|
885
|
+
},
|
|
886
|
+
id: null
|
|
887
|
+
}), {
|
|
888
|
+
status: 400,
|
|
889
|
+
headers: { "Content-Type": "application/json" }
|
|
890
|
+
});
|
|
891
|
+
const sessionId = request.headers.get("mcp-session-id");
|
|
892
|
+
if (!sessionId) return new Response(JSON.stringify({
|
|
893
|
+
jsonrpc: "2.0",
|
|
894
|
+
error: {
|
|
895
|
+
code: -32e3,
|
|
896
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
897
|
+
},
|
|
898
|
+
id: null
|
|
899
|
+
}), {
|
|
900
|
+
status: 400,
|
|
901
|
+
headers: { "Content-Type": "application/json" }
|
|
902
|
+
});
|
|
903
|
+
if (sessionId !== this.sessionId) return new Response(JSON.stringify({
|
|
904
|
+
jsonrpc: "2.0",
|
|
905
|
+
error: {
|
|
906
|
+
code: -32001,
|
|
907
|
+
message: "Session not found"
|
|
908
|
+
},
|
|
909
|
+
id: null
|
|
910
|
+
}), {
|
|
911
|
+
status: 404,
|
|
912
|
+
headers: { "Content-Type": "application/json" }
|
|
913
|
+
});
|
|
914
|
+
return true;
|
|
915
|
+
}
|
|
916
|
+
async close() {
|
|
917
|
+
for (const { cleanup } of this.streamMapping.values()) cleanup();
|
|
918
|
+
this.streamMapping.clear();
|
|
919
|
+
this.requestResponseMap.clear();
|
|
920
|
+
this.onclose?.();
|
|
921
|
+
}
|
|
922
|
+
async send(message) {
|
|
923
|
+
let requestId;
|
|
924
|
+
if (isJSONRPCResponse(message) || isJSONRPCError(message)) requestId = message.id;
|
|
925
|
+
if (requestId === void 0) {
|
|
926
|
+
if (isJSONRPCResponse(message) || isJSONRPCError(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
|
|
927
|
+
const standaloneSse = this.streamMapping.get(this.standaloneSseStreamId);
|
|
928
|
+
if (standaloneSse === void 0) return;
|
|
929
|
+
if (standaloneSse.writer && standaloneSse.encoder) {
|
|
930
|
+
const data = `event: message\ndata: ${JSON.stringify(message)}\n\n`;
|
|
931
|
+
await standaloneSse.writer.write(standaloneSse.encoder.encode(data));
|
|
932
|
+
}
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
const streamId = this.requestToStreamMapping.get(requestId);
|
|
936
|
+
if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`);
|
|
937
|
+
const response = this.streamMapping.get(streamId);
|
|
938
|
+
if (!response) throw new Error(`No connection established for request ID: ${String(requestId)}`);
|
|
939
|
+
if (!this.enableJsonResponse) {
|
|
940
|
+
if (response.writer && response.encoder) {
|
|
941
|
+
const data = `event: message\ndata: ${JSON.stringify(message)}\n\n`;
|
|
942
|
+
await response.writer.write(response.encoder.encode(data));
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
|
|
946
|
+
this.requestResponseMap.set(requestId, message);
|
|
947
|
+
const relatedIds = Array.from(this.requestToStreamMapping.entries()).filter(([, sid]) => sid === streamId).map(([id]) => id);
|
|
948
|
+
if (relatedIds.every((id) => this.requestResponseMap.has(id))) {
|
|
949
|
+
if (this.enableJsonResponse && response.resolveJson) {
|
|
950
|
+
const responses = relatedIds.map((id) => this.requestResponseMap.get(id));
|
|
951
|
+
const headers = new Headers({
|
|
952
|
+
"Content-Type": "application/json",
|
|
953
|
+
"Access-Control-Allow-Origin": "*",
|
|
954
|
+
"Access-Control-Expose-Headers": "mcp-session-id"
|
|
955
|
+
});
|
|
956
|
+
if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
|
|
957
|
+
const body = responses.length === 1 ? responses[0] : responses;
|
|
958
|
+
response.resolveJson(new Response(JSON.stringify(body), { headers }));
|
|
959
|
+
} else response.cleanup();
|
|
960
|
+
for (const id of relatedIds) {
|
|
961
|
+
this.requestResponseMap.delete(id);
|
|
962
|
+
this.requestToStreamMapping.delete(id);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
|
|
969
|
+
//#endregion
|
|
970
|
+
//#region src/mcp/auth-context.ts
|
|
971
|
+
const authContextStorage = new AsyncLocalStorage();
|
|
972
|
+
function getMcpAuthContext() {
|
|
973
|
+
return authContextStorage.getStore();
|
|
974
|
+
}
|
|
975
|
+
function runWithAuthContext(context, fn) {
|
|
976
|
+
return authContextStorage.run(context, fn);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
//#endregion
|
|
980
|
+
//#region src/mcp/handler.ts
|
|
981
|
+
function experimental_createMcpHandler(server, options = {}) {
|
|
982
|
+
const route = options.route ?? "/mcp";
|
|
983
|
+
return async (request, _env, ctx) => {
|
|
984
|
+
const url = new URL(request.url);
|
|
985
|
+
if (route && url.pathname !== route) return new Response("Not Found", { status: 404 });
|
|
986
|
+
const oauthCtx = ctx;
|
|
987
|
+
const authContext = oauthCtx.props ? { props: oauthCtx.props } : void 0;
|
|
988
|
+
const transport = new WorkerTransport(options);
|
|
989
|
+
await server.connect(transport);
|
|
990
|
+
const handleRequest = async () => {
|
|
991
|
+
return await transport.handleRequest(request);
|
|
992
|
+
};
|
|
993
|
+
try {
|
|
994
|
+
let response;
|
|
995
|
+
if (authContext) response = await runWithAuthContext(authContext, handleRequest);
|
|
996
|
+
else response = await handleRequest();
|
|
997
|
+
return response;
|
|
998
|
+
} catch (error) {
|
|
999
|
+
console.error("MCP handler error:", error);
|
|
1000
|
+
return new Response(JSON.stringify({
|
|
1001
|
+
jsonrpc: "2.0",
|
|
1002
|
+
error: {
|
|
1003
|
+
code: -32603,
|
|
1004
|
+
message: error instanceof Error ? error.message : "Internal server error"
|
|
1005
|
+
},
|
|
1006
|
+
id: null
|
|
1007
|
+
}), {
|
|
1008
|
+
status: 500,
|
|
1009
|
+
headers: { "Content-Type": "application/json" }
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
//#endregion
|
|
1016
|
+
//#region src/mcp/index.ts
|
|
1017
|
+
var McpAgent = class McpAgent extends Agent {
|
|
1018
|
+
async setInitializeRequest(initializeRequest) {
|
|
1019
|
+
await this.ctx.storage.put("initializeRequest", initializeRequest);
|
|
1020
|
+
}
|
|
1021
|
+
async getInitializeRequest() {
|
|
1022
|
+
return this.ctx.storage.get("initializeRequest");
|
|
1023
|
+
}
|
|
1024
|
+
/** Read the transport type for this agent.
|
|
1025
|
+
* This relies on the naming scheme being `sse:${sessionId}`
|
|
1026
|
+
* or `streamable-http:${sessionId}`.
|
|
1027
|
+
*/
|
|
1028
|
+
getTransportType() {
|
|
1029
|
+
const [t, ..._] = this.name.split(":");
|
|
1030
|
+
switch (t) {
|
|
1031
|
+
case "sse": return "sse";
|
|
1032
|
+
case "streamable-http": return "streamable-http";
|
|
1033
|
+
default: throw new Error("Invalid transport type. McpAgent must be addressed with a valid protocol.");
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
/** Read the sessionId for this agent.
|
|
1037
|
+
* This relies on the naming scheme being `sse:${sessionId}`
|
|
1038
|
+
* or `streamable-http:${sessionId}`.
|
|
1039
|
+
*/
|
|
1040
|
+
getSessionId() {
|
|
1041
|
+
const [_, sessionId] = this.name.split(":");
|
|
1042
|
+
if (!sessionId) throw new Error("Invalid session id. McpAgent must be addressed with a valid session id.");
|
|
1043
|
+
return sessionId;
|
|
1044
|
+
}
|
|
1045
|
+
/** Get the unique WebSocket. SSE transport only. */
|
|
1046
|
+
getWebSocket() {
|
|
1047
|
+
const websockets = Array.from(this.getConnections());
|
|
1048
|
+
if (websockets.length === 0) return null;
|
|
1049
|
+
return websockets[0];
|
|
1050
|
+
}
|
|
1051
|
+
/** Returns a new transport matching the type of the Agent. */
|
|
1052
|
+
initTransport() {
|
|
1053
|
+
switch (this.getTransportType()) {
|
|
1054
|
+
case "sse": return new McpSSETransport(() => this.getWebSocket());
|
|
1055
|
+
case "streamable-http": return new StreamableHTTPServerTransport({});
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
/** Update and store the props */
|
|
1059
|
+
async updateProps(props) {
|
|
1060
|
+
await this.ctx.storage.put("props", props ?? {});
|
|
1061
|
+
this.props = props;
|
|
1062
|
+
}
|
|
1063
|
+
async reinitializeServer() {
|
|
1064
|
+
const initializeRequest = await this.getInitializeRequest();
|
|
1065
|
+
if (initializeRequest) this._transport?.onmessage?.(initializeRequest);
|
|
1066
|
+
}
|
|
1067
|
+
/** Sets up the MCP transport and server every time the Agent is started.*/
|
|
1068
|
+
async onStart(props) {
|
|
1069
|
+
if (props) await this.updateProps(props);
|
|
1070
|
+
this.props = await this.ctx.storage.get("props");
|
|
1071
|
+
await this.init();
|
|
1072
|
+
const server = await this.server;
|
|
1073
|
+
this._transport = this.initTransport();
|
|
1074
|
+
await server.connect(this._transport);
|
|
1075
|
+
await this.reinitializeServer();
|
|
1076
|
+
}
|
|
1077
|
+
/** Validates new WebSocket connections. */
|
|
1078
|
+
async onConnect(conn, { request: req }) {
|
|
1079
|
+
switch (this.getTransportType()) {
|
|
1080
|
+
case "sse":
|
|
1081
|
+
if (Array.from(this.getConnections()).length > 1) {
|
|
1082
|
+
conn.close(1008, "Websocket already connected");
|
|
1083
|
+
return;
|
|
1084
|
+
}
|
|
1085
|
+
break;
|
|
1086
|
+
case "streamable-http": if (this._transport instanceof StreamableHTTPServerTransport) switch (req.headers.get(MCP_HTTP_METHOD_HEADER)) {
|
|
1087
|
+
case "POST": {
|
|
1088
|
+
const payloadHeader = req.headers.get(MCP_MESSAGE_HEADER);
|
|
1089
|
+
let rawPayload;
|
|
1090
|
+
if (!payloadHeader) rawPayload = "{}";
|
|
1091
|
+
else try {
|
|
1092
|
+
rawPayload = Buffer.from(payloadHeader, "base64").toString("utf-8");
|
|
1093
|
+
} catch (_error) {
|
|
1094
|
+
throw new Error("Internal Server Error: Failed to decode MCP message header");
|
|
1095
|
+
}
|
|
1096
|
+
const parsedBody = JSON.parse(rawPayload);
|
|
1097
|
+
this._transport?.handlePostRequest(req, parsedBody);
|
|
1098
|
+
break;
|
|
1099
|
+
}
|
|
1100
|
+
case "GET":
|
|
1101
|
+
this._transport?.handleGetRequest(req);
|
|
1102
|
+
break;
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
/** Handles MCP Messages for the legacy SSE transport. */
|
|
1107
|
+
async onSSEMcpMessage(_sessionId, messageBody) {
|
|
1108
|
+
if (this.getTransportType() !== "sse") return /* @__PURE__ */ new Error("Internal Server Error: Expected SSE transport");
|
|
1109
|
+
try {
|
|
1110
|
+
let parsedMessage;
|
|
1111
|
+
try {
|
|
1112
|
+
parsedMessage = JSONRPCMessageSchema.parse(messageBody);
|
|
1113
|
+
} catch (error) {
|
|
1114
|
+
this._transport?.onerror?.(error);
|
|
1115
|
+
throw error;
|
|
1116
|
+
}
|
|
1117
|
+
if (await this._handleElicitationResponse(parsedMessage)) return null;
|
|
1118
|
+
this._transport?.onmessage?.(parsedMessage);
|
|
1119
|
+
return null;
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
console.error("Error forwarding message to SSE:", error);
|
|
1122
|
+
this._transport?.onerror?.(error);
|
|
1123
|
+
return error;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
/** Elicit user input with a message and schema */
|
|
1127
|
+
async elicitInput(params) {
|
|
1128
|
+
const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
|
|
1129
|
+
await this.ctx.storage.put(`elicitation:${requestId}`, {
|
|
1130
|
+
message: params.message,
|
|
1131
|
+
requestedSchema: params.requestedSchema,
|
|
1132
|
+
timestamp: Date.now()
|
|
1133
|
+
});
|
|
1134
|
+
const elicitRequest = {
|
|
1135
|
+
jsonrpc: "2.0",
|
|
1136
|
+
id: requestId,
|
|
1137
|
+
method: "elicitation/create",
|
|
1138
|
+
params: {
|
|
1139
|
+
message: params.message,
|
|
1140
|
+
requestedSchema: params.requestedSchema
|
|
1141
|
+
}
|
|
1142
|
+
};
|
|
1143
|
+
if (this._transport) await this._transport.send(elicitRequest);
|
|
1144
|
+
else {
|
|
1145
|
+
const connections = this.getConnections();
|
|
1146
|
+
if (!connections || Array.from(connections).length === 0) {
|
|
1147
|
+
await this.ctx.storage.delete(`elicitation:${requestId}`);
|
|
1148
|
+
throw new Error("No active connections available for elicitation");
|
|
1149
|
+
}
|
|
1150
|
+
const connectionList = Array.from(connections);
|
|
1151
|
+
for (const connection of connectionList) try {
|
|
1152
|
+
connection.send(JSON.stringify(elicitRequest));
|
|
1153
|
+
} catch (error) {
|
|
1154
|
+
console.error("Failed to send elicitation request:", error);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
return this._waitForElicitationResponse(requestId);
|
|
1158
|
+
}
|
|
1159
|
+
/** Wait for elicitation response through storage polling */
|
|
1160
|
+
async _waitForElicitationResponse(requestId) {
|
|
1161
|
+
const startTime = Date.now();
|
|
1162
|
+
const timeout = 6e4;
|
|
1163
|
+
try {
|
|
1164
|
+
while (Date.now() - startTime < timeout) {
|
|
1165
|
+
const response = await this.ctx.storage.get(`elicitation:response:${requestId}`);
|
|
1166
|
+
if (response) {
|
|
1167
|
+
await this.ctx.storage.delete(`elicitation:${requestId}`);
|
|
1168
|
+
await this.ctx.storage.delete(`elicitation:response:${requestId}`);
|
|
1169
|
+
return response;
|
|
1170
|
+
}
|
|
1171
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
1172
|
+
}
|
|
1173
|
+
throw new Error("Elicitation request timed out");
|
|
1174
|
+
} finally {
|
|
1175
|
+
await this.ctx.storage.delete(`elicitation:${requestId}`);
|
|
1176
|
+
await this.ctx.storage.delete(`elicitation:response:${requestId}`);
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
/** Handle elicitation responses */
|
|
1180
|
+
async _handleElicitationResponse(message) {
|
|
1181
|
+
if (isJSONRPCResponse(message) && message.result) {
|
|
1182
|
+
const requestId = message.id?.toString();
|
|
1183
|
+
if (!requestId || !requestId.startsWith("elicit_")) return false;
|
|
1184
|
+
if (!await this.ctx.storage.get(`elicitation:${requestId}`)) return false;
|
|
1185
|
+
await this.ctx.storage.put(`elicitation:response:${requestId}`, message.result);
|
|
1186
|
+
return true;
|
|
1187
|
+
}
|
|
1188
|
+
if (isJSONRPCError(message)) {
|
|
1189
|
+
const requestId = message.id?.toString();
|
|
1190
|
+
if (!requestId || !requestId.startsWith("elicit_")) return false;
|
|
1191
|
+
if (!await this.ctx.storage.get(`elicitation:${requestId}`)) return false;
|
|
1192
|
+
const errorResult = {
|
|
1193
|
+
action: "cancel",
|
|
1194
|
+
content: { error: message.error.message || "Elicitation request failed" }
|
|
1195
|
+
};
|
|
1196
|
+
await this.ctx.storage.put(`elicitation:response:${requestId}`, errorResult);
|
|
1197
|
+
return true;
|
|
1198
|
+
}
|
|
1199
|
+
return false;
|
|
1200
|
+
}
|
|
1201
|
+
/** Return a handler for the given path for this MCP.
|
|
1202
|
+
* Defaults to Streamable HTTP transport.
|
|
1203
|
+
*/
|
|
1204
|
+
static serve(path, { binding = "MCP_OBJECT", corsOptions, transport = "streamable-http" } = {}) {
|
|
1205
|
+
return { async fetch(request, env, ctx) {
|
|
1206
|
+
const corsResponse = handleCORS(request, corsOptions);
|
|
1207
|
+
if (corsResponse) return corsResponse;
|
|
1208
|
+
const bindingValue = env[binding];
|
|
1209
|
+
if (bindingValue == null || typeof bindingValue !== "object") throw new Error(`Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`);
|
|
1210
|
+
if (!isDurableObjectNamespace(bindingValue)) throw new Error(`Invalid McpAgent binding for ${binding}. Make sure it's a Durable Object binding.`);
|
|
1211
|
+
const namespace = bindingValue;
|
|
1212
|
+
switch (transport) {
|
|
1213
|
+
case "streamable-http": return createStreamingHttpHandler(path, namespace, corsOptions)(request, ctx);
|
|
1214
|
+
case "sse": return createLegacySseHandler(path, namespace, corsOptions)(request, ctx);
|
|
1215
|
+
default: return new Response("Invalid MCP transport mode. Only `streamable-http` or `sse` are allowed.", { status: 500 });
|
|
1216
|
+
}
|
|
1217
|
+
} };
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Legacy api
|
|
1221
|
+
**/
|
|
1222
|
+
static mount(path, opts = {}) {
|
|
1223
|
+
return McpAgent.serveSSE(path, opts);
|
|
1224
|
+
}
|
|
1225
|
+
static serveSSE(path, opts = {}) {
|
|
1226
|
+
return McpAgent.serve(path, {
|
|
1227
|
+
...opts,
|
|
1228
|
+
transport: "sse"
|
|
1229
|
+
});
|
|
1230
|
+
}
|
|
1231
|
+
};
|
|
1232
|
+
|
|
1233
|
+
//#endregion
|
|
1234
|
+
export { ElicitRequestSchema, McpAgent, SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport, WorkerTransport, experimental_createMcpHandler, getMcpAuthContext };
|
|
1235
|
+
//# sourceMappingURL=index.js.map
|