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