agents 0.0.0-63d8af8 → 0.0.0-671bdf7
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 +4 -1
- package/dist/ai-chat-agent.js +18 -18
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.js +16 -15
- package/dist/ai-react.js.map +1 -1
- package/dist/{chunk-YMUU7QHV.js → chunk-XG52S6YY.js} +1 -5
- package/dist/chunk-XG52S6YY.js.map +1 -0
- package/dist/index.d.ts +0 -6
- package/dist/index.js +1 -3
- package/dist/mcp/client.d.ts +77 -28
- package/dist/mcp/client.js +63 -126
- package/dist/mcp/client.js.map +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
- package/dist/mcp/do-oauth-client-provider.js +107 -0
- package/dist/mcp/do-oauth-client-provider.js.map +1 -0
- package/dist/mcp/index.d.ts +21 -4
- package/dist/mcp/index.js +521 -92
- package/dist/mcp/index.js.map +1 -1
- package/dist/react.js +20 -20
- package/dist/react.js.map +1 -1
- package/package.json +22 -5
- package/src/index.ts +0 -7
- package/dist/chunk-YMUU7QHV.js.map +0 -1
package/dist/mcp/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Agent
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-XG52S6YY.js";
|
|
4
4
|
import {
|
|
5
5
|
__privateAdd,
|
|
6
6
|
__privateGet,
|
|
@@ -10,8 +10,15 @@ import {
|
|
|
10
10
|
|
|
11
11
|
// src/mcp/index.ts
|
|
12
12
|
import { DurableObject } from "cloudflare:workers";
|
|
13
|
-
import {
|
|
14
|
-
|
|
13
|
+
import {
|
|
14
|
+
InitializeRequestSchema,
|
|
15
|
+
isJSONRPCError,
|
|
16
|
+
isJSONRPCNotification,
|
|
17
|
+
isJSONRPCRequest,
|
|
18
|
+
isJSONRPCResponse,
|
|
19
|
+
JSONRPCMessageSchema
|
|
20
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
21
|
+
var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
|
|
15
22
|
function handleCORS(request, corsOptions) {
|
|
16
23
|
const origin = request.headers.get("Origin") || "*";
|
|
17
24
|
const corsHeaders = {
|
|
@@ -26,7 +33,7 @@ function handleCORS(request, corsOptions) {
|
|
|
26
33
|
return null;
|
|
27
34
|
}
|
|
28
35
|
var _getWebSocket, _started;
|
|
29
|
-
var
|
|
36
|
+
var McpSSETransport = class {
|
|
30
37
|
constructor(getWebSocket) {
|
|
31
38
|
__privateAdd(this, _getWebSocket);
|
|
32
39
|
__privateAdd(this, _started, false);
|
|
@@ -59,18 +66,76 @@ var McpTransport = class {
|
|
|
59
66
|
};
|
|
60
67
|
_getWebSocket = new WeakMap();
|
|
61
68
|
_started = new WeakMap();
|
|
62
|
-
var
|
|
63
|
-
var
|
|
69
|
+
var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
|
|
70
|
+
var McpStreamableHttpTransport = class {
|
|
71
|
+
constructor(getWebSocketForMessageID, notifyResponseIdSent) {
|
|
72
|
+
// TODO: If there is an open connection to send server-initiated messages
|
|
73
|
+
// back, we should use that connection
|
|
74
|
+
__privateAdd(this, _getWebSocketForGetRequest);
|
|
75
|
+
// Get the appropriate websocket connection for a given message id
|
|
76
|
+
__privateAdd(this, _getWebSocketForMessageID);
|
|
77
|
+
// Notify the server that a response has been sent for a given message id
|
|
78
|
+
// so that it may clean up it's mapping of message ids to connections
|
|
79
|
+
// once they are no longer needed
|
|
80
|
+
__privateAdd(this, _notifyResponseIdSent);
|
|
81
|
+
__privateAdd(this, _started2, false);
|
|
82
|
+
__privateSet(this, _getWebSocketForMessageID, getWebSocketForMessageID);
|
|
83
|
+
__privateSet(this, _notifyResponseIdSent, notifyResponseIdSent);
|
|
84
|
+
__privateSet(this, _getWebSocketForGetRequest, () => null);
|
|
85
|
+
}
|
|
86
|
+
async start() {
|
|
87
|
+
if (__privateGet(this, _started2)) {
|
|
88
|
+
throw new Error("Transport already started");
|
|
89
|
+
}
|
|
90
|
+
__privateSet(this, _started2, true);
|
|
91
|
+
}
|
|
92
|
+
async send(message) {
|
|
93
|
+
if (!__privateGet(this, _started2)) {
|
|
94
|
+
throw new Error("Transport not started");
|
|
95
|
+
}
|
|
96
|
+
let websocket = null;
|
|
97
|
+
if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
|
|
98
|
+
websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
|
|
99
|
+
if (!websocket) {
|
|
100
|
+
throw new Error(
|
|
101
|
+
`Could not find WebSocket for message id: ${message.id}`
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
} else if (isJSONRPCRequest(message)) {
|
|
105
|
+
websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
|
|
106
|
+
} else if (isJSONRPCNotification(message)) {
|
|
107
|
+
websocket = null;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
websocket?.send(JSON.stringify(message));
|
|
111
|
+
if (isJSONRPCResponse(message)) {
|
|
112
|
+
__privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
|
|
113
|
+
}
|
|
114
|
+
} catch (error) {
|
|
115
|
+
this.onerror?.(error);
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async close() {
|
|
120
|
+
this.onclose?.();
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
_getWebSocketForGetRequest = new WeakMap();
|
|
124
|
+
_getWebSocketForMessageID = new WeakMap();
|
|
125
|
+
_notifyResponseIdSent = new WeakMap();
|
|
126
|
+
_started2 = new WeakMap();
|
|
127
|
+
var _status, _transport, _transportType, _requestIdToConnectionId, _agent, _McpAgent_instances, initialize_fn;
|
|
128
|
+
var _McpAgent = class _McpAgent extends DurableObject {
|
|
64
129
|
constructor(ctx, env) {
|
|
65
130
|
var _a;
|
|
66
131
|
super(ctx, env);
|
|
67
132
|
__privateAdd(this, _McpAgent_instances);
|
|
68
133
|
__privateAdd(this, _status, "zero");
|
|
69
134
|
__privateAdd(this, _transport);
|
|
70
|
-
__privateAdd(this,
|
|
135
|
+
__privateAdd(this, _transportType, "unset");
|
|
136
|
+
__privateAdd(this, _requestIdToConnectionId, /* @__PURE__ */ new Map());
|
|
71
137
|
/**
|
|
72
|
-
* Since McpAgent's _aren't_ yet real "Agents"
|
|
73
|
-
* websockets, don't support hibernation), let's only expose a couple of the methods
|
|
138
|
+
* Since McpAgent's _aren't_ yet real "Agents", let's only expose a couple of the methods
|
|
74
139
|
* to the outer class: initialState/state/setState/onStateUpdate/sql
|
|
75
140
|
*/
|
|
76
141
|
__privateAdd(this, _agent);
|
|
@@ -80,6 +145,9 @@ var McpAgent = class extends DurableObject {
|
|
|
80
145
|
onStateUpdate(state, source) {
|
|
81
146
|
return self.onStateUpdate(state, source);
|
|
82
147
|
}
|
|
148
|
+
async onMessage(connection, message) {
|
|
149
|
+
return self.onMessage(connection, message);
|
|
150
|
+
}
|
|
83
151
|
}, _a.options = {
|
|
84
152
|
hibernate: true
|
|
85
153
|
}, _a)(ctx, env));
|
|
@@ -106,22 +174,45 @@ var McpAgent = class extends DurableObject {
|
|
|
106
174
|
onStateUpdate(state, source) {
|
|
107
175
|
return self.onStateUpdate(state, source);
|
|
108
176
|
}
|
|
177
|
+
async onMessage(connection, event) {
|
|
178
|
+
return self.onMessage(connection, event);
|
|
179
|
+
}
|
|
109
180
|
}, _a.options = {
|
|
110
181
|
hibernate: true
|
|
111
182
|
}, _a)(this.ctx, this.env));
|
|
112
183
|
this.props = await this.ctx.storage.get("props");
|
|
113
|
-
this.
|
|
114
|
-
|
|
115
|
-
|
|
184
|
+
__privateSet(this, _transportType, await this.ctx.storage.get(
|
|
185
|
+
"transportType"
|
|
186
|
+
));
|
|
187
|
+
await this._init(this.props);
|
|
188
|
+
if (__privateGet(this, _transportType) === "sse") {
|
|
189
|
+
__privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
|
|
190
|
+
await this.server.connect(__privateGet(this, _transport));
|
|
191
|
+
} else if (__privateGet(this, _transportType) === "streamable-http") {
|
|
192
|
+
__privateSet(this, _transport, new McpStreamableHttpTransport(
|
|
193
|
+
(id) => this.getWebSocketForResponseID(id),
|
|
194
|
+
(id) => __privateGet(this, _requestIdToConnectionId).delete(id)
|
|
195
|
+
));
|
|
196
|
+
await this.server.connect(__privateGet(this, _transport));
|
|
197
|
+
}
|
|
116
198
|
}
|
|
117
199
|
async _init(props) {
|
|
118
|
-
await this.ctx.storage.put("props", props);
|
|
200
|
+
await this.ctx.storage.put("props", props ?? {});
|
|
201
|
+
if (!this.ctx.storage.get("transportType")) {
|
|
202
|
+
await this.ctx.storage.put("transportType", "unset");
|
|
203
|
+
}
|
|
119
204
|
this.props = props;
|
|
120
205
|
if (!this.initRun) {
|
|
121
206
|
this.initRun = true;
|
|
122
207
|
await this.init();
|
|
123
208
|
}
|
|
124
209
|
}
|
|
210
|
+
async setInitialized() {
|
|
211
|
+
await this.ctx.storage.put("initialized", true);
|
|
212
|
+
}
|
|
213
|
+
async isInitialized() {
|
|
214
|
+
return await this.ctx.storage.get("initialized") === true;
|
|
215
|
+
}
|
|
125
216
|
// Allow the worker to fetch a websocket connection to the agent
|
|
126
217
|
async fetch(request) {
|
|
127
218
|
if (__privateGet(this, _status) !== "started") {
|
|
@@ -133,18 +224,41 @@ var McpAgent = class extends DurableObject {
|
|
|
133
224
|
});
|
|
134
225
|
}
|
|
135
226
|
const url = new URL(request.url);
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
227
|
+
const path = url.pathname;
|
|
228
|
+
switch (path) {
|
|
229
|
+
case "/sse": {
|
|
230
|
+
const websockets = this.ctx.getWebSockets();
|
|
231
|
+
if (websockets.length > 0) {
|
|
232
|
+
return new Response("Websocket already connected", { status: 400 });
|
|
233
|
+
}
|
|
234
|
+
await this.ctx.storage.put("transportType", "sse");
|
|
235
|
+
__privateSet(this, _transportType, "sse");
|
|
236
|
+
if (!__privateGet(this, _transport)) {
|
|
237
|
+
__privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
|
|
238
|
+
await this.server.connect(__privateGet(this, _transport));
|
|
239
|
+
}
|
|
240
|
+
return __privateGet(this, _agent).fetch(request);
|
|
241
|
+
}
|
|
242
|
+
case "/streamable-http": {
|
|
243
|
+
if (!__privateGet(this, _transport)) {
|
|
244
|
+
__privateSet(this, _transport, new McpStreamableHttpTransport(
|
|
245
|
+
(id) => this.getWebSocketForResponseID(id),
|
|
246
|
+
(id) => __privateGet(this, _requestIdToConnectionId).delete(id)
|
|
247
|
+
));
|
|
248
|
+
await this.server.connect(__privateGet(this, _transport));
|
|
249
|
+
}
|
|
250
|
+
await this.ctx.storage.put("transportType", "streamable-http");
|
|
251
|
+
__privateSet(this, _transportType, "streamable-http");
|
|
252
|
+
return __privateGet(this, _agent).fetch(request);
|
|
253
|
+
}
|
|
254
|
+
default:
|
|
255
|
+
return new Response(
|
|
256
|
+
"Internal Server Error: Expected /sse or /streamable-http path",
|
|
257
|
+
{
|
|
258
|
+
status: 500
|
|
259
|
+
}
|
|
260
|
+
);
|
|
142
261
|
}
|
|
143
|
-
const response = await __privateGet(this, _agent).fetch(request);
|
|
144
|
-
__privateSet(this, _connected, true);
|
|
145
|
-
__privateSet(this, _transport, new McpTransport(() => this.getWebSocket()));
|
|
146
|
-
await this.server.connect(__privateGet(this, _transport));
|
|
147
|
-
return response;
|
|
148
262
|
}
|
|
149
263
|
getWebSocket() {
|
|
150
264
|
const websockets = this.ctx.getWebSockets();
|
|
@@ -153,26 +267,45 @@ var McpAgent = class extends DurableObject {
|
|
|
153
267
|
}
|
|
154
268
|
return websockets[0];
|
|
155
269
|
}
|
|
156
|
-
|
|
270
|
+
getWebSocketForResponseID(id) {
|
|
271
|
+
const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
|
|
272
|
+
if (connectionId === void 0) {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
return __privateGet(this, _agent).getConnection(connectionId) ?? null;
|
|
276
|
+
}
|
|
277
|
+
// All messages received here. This is currently never called
|
|
278
|
+
async onMessage(connection, event) {
|
|
279
|
+
if (__privateGet(this, _transportType) !== "streamable-http") {
|
|
280
|
+
const err = new Error(
|
|
281
|
+
"Internal Server Error: Expected streamable-http protocol"
|
|
282
|
+
);
|
|
283
|
+
__privateGet(this, _transport)?.onerror?.(err);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
let message;
|
|
287
|
+
try {
|
|
288
|
+
const data = typeof event === "string" ? event : new TextDecoder().decode(event);
|
|
289
|
+
message = JSONRPCMessageSchema.parse(JSON.parse(data));
|
|
290
|
+
} catch (error) {
|
|
291
|
+
__privateGet(this, _transport)?.onerror?.(error);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (isJSONRPCRequest(message)) {
|
|
295
|
+
__privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
|
|
296
|
+
}
|
|
297
|
+
__privateGet(this, _transport)?.onmessage?.(message);
|
|
298
|
+
}
|
|
299
|
+
// All messages received over SSE after the initial connection has been established
|
|
300
|
+
// will be passed here
|
|
301
|
+
async onSSEMcpMessage(sessionId, request) {
|
|
157
302
|
if (__privateGet(this, _status) !== "started") {
|
|
158
303
|
await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
|
|
159
304
|
}
|
|
305
|
+
if (__privateGet(this, _transportType) !== "sse") {
|
|
306
|
+
return new Error("Internal Server Error: Expected SSE protocol");
|
|
307
|
+
}
|
|
160
308
|
try {
|
|
161
|
-
const contentType = request.headers.get("content-type") || "";
|
|
162
|
-
if (!contentType.includes("application/json")) {
|
|
163
|
-
return new Response(`Unsupported content-type: ${contentType}`, {
|
|
164
|
-
status: 400
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
const contentLength = Number.parseInt(
|
|
168
|
-
request.headers.get("content-length") || "0",
|
|
169
|
-
10
|
|
170
|
-
);
|
|
171
|
-
if (contentLength > MAXIMUM_MESSAGE_SIZE) {
|
|
172
|
-
return new Response(`Request body too large: ${contentLength} bytes`, {
|
|
173
|
-
status: 400
|
|
174
|
-
});
|
|
175
|
-
}
|
|
176
309
|
const message = await request.json();
|
|
177
310
|
let parsedMessage;
|
|
178
311
|
try {
|
|
@@ -182,44 +315,41 @@ var McpAgent = class extends DurableObject {
|
|
|
182
315
|
throw error;
|
|
183
316
|
}
|
|
184
317
|
__privateGet(this, _transport)?.onmessage?.(parsedMessage);
|
|
185
|
-
return
|
|
318
|
+
return null;
|
|
186
319
|
} catch (error) {
|
|
187
320
|
__privateGet(this, _transport)?.onerror?.(error);
|
|
188
|
-
return
|
|
321
|
+
return error;
|
|
189
322
|
}
|
|
190
323
|
}
|
|
191
|
-
//
|
|
324
|
+
// Delegate all websocket events to the underlying agent
|
|
192
325
|
async webSocketMessage(ws, event) {
|
|
193
|
-
let message;
|
|
194
|
-
try {
|
|
195
|
-
const data = typeof event === "string" ? event : new TextDecoder().decode(event);
|
|
196
|
-
message = JSONRPCMessageSchema.parse(JSON.parse(data));
|
|
197
|
-
} catch (error) {
|
|
198
|
-
__privateGet(this, _transport)?.onerror?.(error);
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
326
|
if (__privateGet(this, _status) !== "started") {
|
|
202
327
|
await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
|
|
203
328
|
}
|
|
204
|
-
__privateGet(this,
|
|
329
|
+
return await __privateGet(this, _agent).webSocketMessage(ws, event);
|
|
205
330
|
}
|
|
206
331
|
// WebSocket event handlers for hibernation support
|
|
207
332
|
async webSocketError(ws, error) {
|
|
208
333
|
if (__privateGet(this, _status) !== "started") {
|
|
209
334
|
await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
|
|
210
335
|
}
|
|
211
|
-
__privateGet(this,
|
|
336
|
+
return await __privateGet(this, _agent).webSocketError(ws, error);
|
|
212
337
|
}
|
|
213
338
|
async webSocketClose(ws, code, reason, wasClean) {
|
|
214
339
|
if (__privateGet(this, _status) !== "started") {
|
|
215
340
|
await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
|
|
216
341
|
}
|
|
217
|
-
__privateGet(this,
|
|
218
|
-
__privateSet(this, _connected, false);
|
|
342
|
+
return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
|
|
219
343
|
}
|
|
220
344
|
static mount(path, {
|
|
221
345
|
binding = "MCP_OBJECT",
|
|
222
346
|
corsOptions
|
|
347
|
+
} = {}) {
|
|
348
|
+
return _McpAgent.serveSSE(path, { binding, corsOptions });
|
|
349
|
+
}
|
|
350
|
+
static serveSSE(path, {
|
|
351
|
+
binding = "MCP_OBJECT",
|
|
352
|
+
corsOptions
|
|
223
353
|
} = {}) {
|
|
224
354
|
let pathname = path;
|
|
225
355
|
if (path === "/") {
|
|
@@ -243,11 +373,11 @@ data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
|
|
|
243
373
|
|
|
244
374
|
`;
|
|
245
375
|
writer.write(encoder.encode(endpointMessage));
|
|
246
|
-
const id = namespace.
|
|
376
|
+
const id = namespace.idFromName(`sse:${sessionId}`);
|
|
247
377
|
const doStub = namespace.get(id);
|
|
248
378
|
await doStub._init(ctx.props);
|
|
249
379
|
const upgradeUrl = new URL(request.url);
|
|
250
|
-
upgradeUrl.
|
|
380
|
+
upgradeUrl.pathname = "/sse";
|
|
251
381
|
const response = await doStub.fetch(
|
|
252
382
|
new Request(upgradeUrl, {
|
|
253
383
|
headers: {
|
|
@@ -261,37 +391,48 @@ data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
|
|
|
261
391
|
if (!ws) {
|
|
262
392
|
console.error("Failed to establish WebSocket connection");
|
|
263
393
|
await writer.close();
|
|
264
|
-
return
|
|
394
|
+
return new Response("Failed to establish WebSocket connection", {
|
|
395
|
+
status: 500
|
|
396
|
+
});
|
|
265
397
|
}
|
|
266
398
|
ws.accept();
|
|
267
|
-
ws.addEventListener("message",
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
399
|
+
ws.addEventListener("message", (event) => {
|
|
400
|
+
async function onMessage(event2) {
|
|
401
|
+
try {
|
|
402
|
+
const message = JSON.parse(event2.data);
|
|
403
|
+
const result = JSONRPCMessageSchema.safeParse(message);
|
|
404
|
+
if (!result.success) {
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const messageText = `event: message
|
|
275
408
|
data: ${JSON.stringify(result.data)}
|
|
276
409
|
|
|
277
410
|
`;
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
411
|
+
await writer.write(encoder.encode(messageText));
|
|
412
|
+
} catch (error) {
|
|
413
|
+
console.error("Error forwarding message to SSE:", error);
|
|
414
|
+
}
|
|
281
415
|
}
|
|
416
|
+
onMessage(event).catch(console.error);
|
|
282
417
|
});
|
|
283
|
-
ws.addEventListener("error",
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
418
|
+
ws.addEventListener("error", (error) => {
|
|
419
|
+
async function onError(error2) {
|
|
420
|
+
try {
|
|
421
|
+
await writer.close();
|
|
422
|
+
} catch (e) {
|
|
423
|
+
}
|
|
287
424
|
}
|
|
425
|
+
onError(error).catch(console.error);
|
|
288
426
|
});
|
|
289
|
-
ws.addEventListener("close",
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
427
|
+
ws.addEventListener("close", () => {
|
|
428
|
+
async function onClose() {
|
|
429
|
+
try {
|
|
430
|
+
await writer.close();
|
|
431
|
+
} catch (error) {
|
|
432
|
+
console.error("Error closing SSE connection:", error);
|
|
433
|
+
}
|
|
294
434
|
}
|
|
435
|
+
onClose().catch(console.error);
|
|
295
436
|
});
|
|
296
437
|
return new Response(readable, {
|
|
297
438
|
headers: {
|
|
@@ -310,30 +451,317 @@ data: ${JSON.stringify(result.data)}
|
|
|
310
451
|
{ status: 400 }
|
|
311
452
|
);
|
|
312
453
|
}
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
"
|
|
321
|
-
|
|
454
|
+
const contentType = request.headers.get("content-type") || "";
|
|
455
|
+
if (!contentType.includes("application/json")) {
|
|
456
|
+
return new Response(`Unsupported content-type: ${contentType}`, {
|
|
457
|
+
status: 400
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
const contentLength = Number.parseInt(
|
|
461
|
+
request.headers.get("content-length") || "0",
|
|
462
|
+
10
|
|
322
463
|
);
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
464
|
+
if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
|
|
465
|
+
return new Response(
|
|
466
|
+
`Request body too large: ${contentLength} bytes`,
|
|
467
|
+
{
|
|
468
|
+
status: 400
|
|
469
|
+
}
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
const id = namespace.idFromName(`sse:${sessionId}`);
|
|
473
|
+
const doStub = namespace.get(id);
|
|
474
|
+
const error = await doStub.onSSEMcpMessage(sessionId, request);
|
|
475
|
+
if (error) {
|
|
476
|
+
return new Response(error.message, {
|
|
477
|
+
status: 400,
|
|
478
|
+
headers: {
|
|
479
|
+
"Content-Type": "text/event-stream",
|
|
480
|
+
"Cache-Control": "no-cache",
|
|
481
|
+
Connection: "keep-alive",
|
|
482
|
+
"Access-Control-Allow-Origin": corsOptions?.origin || "*"
|
|
483
|
+
}
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
return new Response("Accepted", {
|
|
487
|
+
status: 202,
|
|
488
|
+
headers: {
|
|
489
|
+
"Content-Type": "text/event-stream",
|
|
490
|
+
"Cache-Control": "no-cache",
|
|
491
|
+
Connection: "keep-alive",
|
|
492
|
+
"Access-Control-Allow-Origin": corsOptions?.origin || "*"
|
|
493
|
+
}
|
|
327
494
|
});
|
|
328
495
|
}
|
|
329
496
|
return new Response("Not Found", { status: 404 });
|
|
330
497
|
}
|
|
331
498
|
};
|
|
332
499
|
}
|
|
500
|
+
static serve(path, {
|
|
501
|
+
binding = "MCP_OBJECT",
|
|
502
|
+
corsOptions
|
|
503
|
+
} = {}) {
|
|
504
|
+
let pathname = path;
|
|
505
|
+
if (path === "/") {
|
|
506
|
+
pathname = "/*";
|
|
507
|
+
}
|
|
508
|
+
const basePattern = new URLPattern({ pathname });
|
|
509
|
+
return {
|
|
510
|
+
fetch: async (request, env, ctx) => {
|
|
511
|
+
const corsResponse = handleCORS(request, corsOptions);
|
|
512
|
+
if (corsResponse) {
|
|
513
|
+
return corsResponse;
|
|
514
|
+
}
|
|
515
|
+
const url = new URL(request.url);
|
|
516
|
+
const namespace = env[binding];
|
|
517
|
+
if (request.method === "POST" && basePattern.test(url)) {
|
|
518
|
+
const acceptHeader = request.headers.get("accept");
|
|
519
|
+
if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
|
|
520
|
+
const body2 = JSON.stringify({
|
|
521
|
+
jsonrpc: "2.0",
|
|
522
|
+
error: {
|
|
523
|
+
code: -32e3,
|
|
524
|
+
message: "Not Acceptable: Client must accept both application/json and text/event-stream"
|
|
525
|
+
},
|
|
526
|
+
id: null
|
|
527
|
+
});
|
|
528
|
+
return new Response(body2, { status: 406 });
|
|
529
|
+
}
|
|
530
|
+
const ct = request.headers.get("content-type");
|
|
531
|
+
if (!ct || !ct.includes("application/json")) {
|
|
532
|
+
const body2 = JSON.stringify({
|
|
533
|
+
jsonrpc: "2.0",
|
|
534
|
+
error: {
|
|
535
|
+
code: -32e3,
|
|
536
|
+
message: "Unsupported Media Type: Content-Type must be application/json"
|
|
537
|
+
},
|
|
538
|
+
id: null
|
|
539
|
+
});
|
|
540
|
+
return new Response(body2, { status: 415 });
|
|
541
|
+
}
|
|
542
|
+
const contentLength = Number.parseInt(
|
|
543
|
+
request.headers.get("content-length") ?? "0",
|
|
544
|
+
10
|
|
545
|
+
);
|
|
546
|
+
if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
|
|
547
|
+
const body2 = JSON.stringify({
|
|
548
|
+
jsonrpc: "2.0",
|
|
549
|
+
error: {
|
|
550
|
+
code: -32e3,
|
|
551
|
+
message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
|
|
552
|
+
},
|
|
553
|
+
id: null
|
|
554
|
+
});
|
|
555
|
+
return new Response(body2, { status: 413 });
|
|
556
|
+
}
|
|
557
|
+
let sessionId = request.headers.get("mcp-session-id");
|
|
558
|
+
let rawMessage;
|
|
559
|
+
try {
|
|
560
|
+
rawMessage = await request.json();
|
|
561
|
+
} catch (error) {
|
|
562
|
+
const body2 = JSON.stringify({
|
|
563
|
+
jsonrpc: "2.0",
|
|
564
|
+
error: {
|
|
565
|
+
code: -32700,
|
|
566
|
+
message: "Parse error: Invalid JSON"
|
|
567
|
+
},
|
|
568
|
+
id: null
|
|
569
|
+
});
|
|
570
|
+
return new Response(body2, { status: 400 });
|
|
571
|
+
}
|
|
572
|
+
let arrayMessage;
|
|
573
|
+
if (Array.isArray(rawMessage)) {
|
|
574
|
+
arrayMessage = rawMessage;
|
|
575
|
+
} else {
|
|
576
|
+
arrayMessage = [rawMessage];
|
|
577
|
+
}
|
|
578
|
+
let messages = [];
|
|
579
|
+
for (const msg of arrayMessage) {
|
|
580
|
+
if (!JSONRPCMessageSchema.safeParse(msg).success) {
|
|
581
|
+
const body2 = JSON.stringify({
|
|
582
|
+
jsonrpc: "2.0",
|
|
583
|
+
error: {
|
|
584
|
+
code: -32700,
|
|
585
|
+
message: "Parse error: Invalid JSON-RPC message"
|
|
586
|
+
},
|
|
587
|
+
id: null
|
|
588
|
+
});
|
|
589
|
+
return new Response(body2, { status: 400 });
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
|
|
593
|
+
const isInitializationRequest = messages.some(
|
|
594
|
+
(msg) => InitializeRequestSchema.safeParse(msg).success
|
|
595
|
+
);
|
|
596
|
+
if (isInitializationRequest && sessionId) {
|
|
597
|
+
const body2 = JSON.stringify({
|
|
598
|
+
jsonrpc: "2.0",
|
|
599
|
+
error: {
|
|
600
|
+
code: -32600,
|
|
601
|
+
message: "Invalid Request: Initialization requests must not include a sessionId"
|
|
602
|
+
},
|
|
603
|
+
id: null
|
|
604
|
+
});
|
|
605
|
+
return new Response(body2, { status: 400 });
|
|
606
|
+
}
|
|
607
|
+
if (isInitializationRequest && messages.length > 1) {
|
|
608
|
+
const body2 = JSON.stringify({
|
|
609
|
+
jsonrpc: "2.0",
|
|
610
|
+
error: {
|
|
611
|
+
code: -32600,
|
|
612
|
+
message: "Invalid Request: Only one initialization request is allowed"
|
|
613
|
+
},
|
|
614
|
+
id: null
|
|
615
|
+
});
|
|
616
|
+
return new Response(body2, { status: 400 });
|
|
617
|
+
}
|
|
618
|
+
if (!isInitializationRequest && !sessionId) {
|
|
619
|
+
const body2 = JSON.stringify({
|
|
620
|
+
jsonrpc: "2.0",
|
|
621
|
+
error: {
|
|
622
|
+
code: -32e3,
|
|
623
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
624
|
+
},
|
|
625
|
+
id: null
|
|
626
|
+
});
|
|
627
|
+
return new Response(body2, { status: 400 });
|
|
628
|
+
}
|
|
629
|
+
sessionId = sessionId ?? namespace.newUniqueId().toString();
|
|
630
|
+
const id = namespace.idFromName(`streamable-http:${sessionId}`);
|
|
631
|
+
const doStub = namespace.get(id);
|
|
632
|
+
const isInitialized = await doStub.isInitialized();
|
|
633
|
+
if (isInitializationRequest) {
|
|
634
|
+
await doStub.setInitialized();
|
|
635
|
+
} else if (!isInitialized) {
|
|
636
|
+
const body2 = JSON.stringify({
|
|
637
|
+
jsonrpc: "2.0",
|
|
638
|
+
error: {
|
|
639
|
+
code: -32001,
|
|
640
|
+
message: "Session not found"
|
|
641
|
+
},
|
|
642
|
+
id: null
|
|
643
|
+
});
|
|
644
|
+
return new Response(body2, { status: 404 });
|
|
645
|
+
}
|
|
646
|
+
const { readable, writable } = new TransformStream();
|
|
647
|
+
const writer = writable.getWriter();
|
|
648
|
+
const encoder = new TextEncoder();
|
|
649
|
+
const upgradeUrl = new URL(request.url);
|
|
650
|
+
upgradeUrl.pathname = "/streamable-http";
|
|
651
|
+
const response = await doStub.fetch(
|
|
652
|
+
new Request(upgradeUrl, {
|
|
653
|
+
headers: {
|
|
654
|
+
Upgrade: "websocket",
|
|
655
|
+
// Required by PartyServer
|
|
656
|
+
"x-partykit-room": sessionId
|
|
657
|
+
}
|
|
658
|
+
})
|
|
659
|
+
);
|
|
660
|
+
const ws = response.webSocket;
|
|
661
|
+
if (!ws) {
|
|
662
|
+
console.error("Failed to establish WebSocket connection");
|
|
663
|
+
await writer.close();
|
|
664
|
+
const body2 = JSON.stringify({
|
|
665
|
+
jsonrpc: "2.0",
|
|
666
|
+
error: {
|
|
667
|
+
code: -32001,
|
|
668
|
+
message: "Failed to establish WebSocket connection"
|
|
669
|
+
},
|
|
670
|
+
id: null
|
|
671
|
+
});
|
|
672
|
+
return new Response(body2, { status: 500 });
|
|
673
|
+
}
|
|
674
|
+
const requestIds = /* @__PURE__ */ new Set();
|
|
675
|
+
ws.accept();
|
|
676
|
+
ws.addEventListener("message", (event) => {
|
|
677
|
+
async function onMessage(event2) {
|
|
678
|
+
try {
|
|
679
|
+
const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
|
|
680
|
+
const message = JSON.parse(data);
|
|
681
|
+
const result = JSONRPCMessageSchema.safeParse(message);
|
|
682
|
+
if (!result.success) {
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
|
|
686
|
+
requestIds.delete(result.data.id);
|
|
687
|
+
}
|
|
688
|
+
const messageText = `event: message
|
|
689
|
+
data: ${JSON.stringify(result.data)}
|
|
690
|
+
|
|
691
|
+
`;
|
|
692
|
+
await writer.write(encoder.encode(messageText));
|
|
693
|
+
if (requestIds.size === 0) {
|
|
694
|
+
ws.close();
|
|
695
|
+
}
|
|
696
|
+
} catch (error) {
|
|
697
|
+
console.error("Error forwarding message to SSE:", error);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
onMessage(event).catch(console.error);
|
|
701
|
+
});
|
|
702
|
+
ws.addEventListener("error", (error) => {
|
|
703
|
+
async function onError(error2) {
|
|
704
|
+
try {
|
|
705
|
+
await writer.close();
|
|
706
|
+
} catch (e) {
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
onError(error).catch(console.error);
|
|
710
|
+
});
|
|
711
|
+
ws.addEventListener("close", () => {
|
|
712
|
+
async function onClose() {
|
|
713
|
+
try {
|
|
714
|
+
await writer.close();
|
|
715
|
+
} catch (error) {
|
|
716
|
+
console.error("Error closing SSE connection:", error);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
onClose().catch(console.error);
|
|
720
|
+
});
|
|
721
|
+
const hasOnlyNotificationsOrResponses = messages.every(
|
|
722
|
+
(msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
|
|
723
|
+
);
|
|
724
|
+
if (hasOnlyNotificationsOrResponses) {
|
|
725
|
+
for (const message of messages) {
|
|
726
|
+
ws.send(JSON.stringify(message));
|
|
727
|
+
}
|
|
728
|
+
ws.close();
|
|
729
|
+
return new Response(null, { status: 202 });
|
|
730
|
+
}
|
|
731
|
+
for (const message of messages) {
|
|
732
|
+
if (isJSONRPCRequest(message)) {
|
|
733
|
+
requestIds.add(message.id);
|
|
734
|
+
}
|
|
735
|
+
ws.send(JSON.stringify(message));
|
|
736
|
+
}
|
|
737
|
+
return new Response(readable, {
|
|
738
|
+
headers: {
|
|
739
|
+
"Content-Type": "text/event-stream",
|
|
740
|
+
"Cache-Control": "no-cache",
|
|
741
|
+
Connection: "keep-alive",
|
|
742
|
+
"mcp-session-id": sessionId,
|
|
743
|
+
"Access-Control-Allow-Origin": corsOptions?.origin || "*"
|
|
744
|
+
},
|
|
745
|
+
status: 200
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
const body = JSON.stringify({
|
|
749
|
+
jsonrpc: "2.0",
|
|
750
|
+
error: {
|
|
751
|
+
code: -32e3,
|
|
752
|
+
message: "Method not allowed"
|
|
753
|
+
},
|
|
754
|
+
id: null
|
|
755
|
+
});
|
|
756
|
+
return new Response(body, { status: 405 });
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
}
|
|
333
760
|
};
|
|
334
761
|
_status = new WeakMap();
|
|
335
762
|
_transport = new WeakMap();
|
|
336
|
-
|
|
763
|
+
_transportType = new WeakMap();
|
|
764
|
+
_requestIdToConnectionId = new WeakMap();
|
|
337
765
|
_agent = new WeakMap();
|
|
338
766
|
_McpAgent_instances = new WeakSet();
|
|
339
767
|
initialize_fn = async function() {
|
|
@@ -343,6 +771,7 @@ initialize_fn = async function() {
|
|
|
343
771
|
__privateSet(this, _status, "started");
|
|
344
772
|
});
|
|
345
773
|
};
|
|
774
|
+
var McpAgent = _McpAgent;
|
|
346
775
|
export {
|
|
347
776
|
McpAgent
|
|
348
777
|
};
|