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