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