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