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