agents 0.0.0-de168a2 → 0.0.0-df52d4b
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 +128 -22
- package/dist/ai-chat-agent.d.ts +49 -4
- package/dist/ai-chat-agent.js +158 -68
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +21 -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-DQJFYHG3.js +1290 -0
- package/dist/chunk-DQJFYHG3.js.map +1 -0
- package/dist/chunk-EM3J4KV7.js +598 -0
- package/dist/chunk-EM3J4KV7.js.map +1 -0
- package/dist/chunk-KUH345EY.js +116 -0
- package/dist/chunk-KUH345EY.js.map +1 -0
- package/dist/chunk-PVQZBKN7.js +106 -0
- package/dist/chunk-PVQZBKN7.js.map +1 -0
- package/dist/client-DgyzBU_8.d.ts +4601 -0
- package/dist/client.d.ts +16 -2
- package/dist/client.js +6 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +263 -18
- package/dist/index.js +14 -6
- package/dist/mcp/client.d.ts +9 -761
- 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 +73 -6
- package/dist/mcp/index.js +768 -162
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.d.ts +46 -0
- package/dist/observability/index.js +10 -0
- package/dist/react.d.ts +88 -5
- package/dist/react.js +20 -8
- 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 +79 -56
- package/src/index.ts +1147 -139
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-XG52S6YY.js +0 -591
- package/dist/chunk-XG52S6YY.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
package/dist/mcp/index.js
CHANGED
|
@@ -1,48 +1,62 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Agent
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-DQJFYHG3.js";
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
SSEEdgeClientTransport,
|
|
6
|
+
StreamableHTTPEdgeClientTransport
|
|
7
|
+
} from "../chunk-EM3J4KV7.js";
|
|
8
|
+
import "../chunk-PVQZBKN7.js";
|
|
9
|
+
import "../chunk-KUH345EY.js";
|
|
10
10
|
|
|
11
11
|
// src/mcp/index.ts
|
|
12
12
|
import { DurableObject } from "cloudflare:workers";
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
13
|
+
import {
|
|
14
|
+
InitializeRequestSchema,
|
|
15
|
+
JSONRPCMessageSchema,
|
|
16
|
+
isJSONRPCError,
|
|
17
|
+
isJSONRPCNotification,
|
|
18
|
+
isJSONRPCRequest,
|
|
19
|
+
isJSONRPCResponse
|
|
20
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
21
|
+
import {
|
|
22
|
+
ElicitRequestSchema
|
|
23
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
24
|
+
var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
|
|
25
|
+
function corsHeaders(_request, corsOptions = {}) {
|
|
26
|
+
const origin = "*";
|
|
27
|
+
return {
|
|
28
|
+
"Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id, mcp-protocol-version",
|
|
29
|
+
"Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, OPTIONS",
|
|
30
|
+
"Access-Control-Allow-Origin": corsOptions.origin || origin,
|
|
31
|
+
"Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
|
|
32
|
+
"Access-Control-Max-Age": (corsOptions.maxAge || 86400).toString()
|
|
22
33
|
};
|
|
34
|
+
}
|
|
35
|
+
function isDurableObjectNamespace(namespace) {
|
|
36
|
+
return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
|
|
37
|
+
}
|
|
38
|
+
function handleCORS(request, corsOptions) {
|
|
23
39
|
if (request.method === "OPTIONS") {
|
|
24
|
-
return new Response(null, { headers: corsHeaders });
|
|
40
|
+
return new Response(null, { headers: corsHeaders(request, corsOptions) });
|
|
25
41
|
}
|
|
26
42
|
return null;
|
|
27
43
|
}
|
|
28
|
-
var
|
|
29
|
-
var McpTransport = class {
|
|
44
|
+
var McpSSETransport = class {
|
|
30
45
|
constructor(getWebSocket) {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
__privateSet(this, _getWebSocket, getWebSocket);
|
|
46
|
+
this._started = false;
|
|
47
|
+
this._getWebSocket = getWebSocket;
|
|
34
48
|
}
|
|
35
49
|
async start() {
|
|
36
|
-
if (
|
|
50
|
+
if (this._started) {
|
|
37
51
|
throw new Error("Transport already started");
|
|
38
52
|
}
|
|
39
|
-
|
|
53
|
+
this._started = true;
|
|
40
54
|
}
|
|
41
55
|
async send(message) {
|
|
42
|
-
if (!
|
|
56
|
+
if (!this._started) {
|
|
43
57
|
throw new Error("Transport not started");
|
|
44
58
|
}
|
|
45
|
-
const websocket =
|
|
59
|
+
const websocket = this._getWebSocket();
|
|
46
60
|
if (!websocket) {
|
|
47
61
|
throw new Error("WebSocket not connected");
|
|
48
62
|
}
|
|
@@ -57,48 +71,128 @@ var McpTransport = class {
|
|
|
57
71
|
this.onclose?.();
|
|
58
72
|
}
|
|
59
73
|
};
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
74
|
+
var McpStreamableHttpTransport = class {
|
|
75
|
+
constructor(getWebSocketForMessageID, notifyResponseIdSent) {
|
|
76
|
+
this._started = false;
|
|
77
|
+
this._getWebSocketForMessageID = getWebSocketForMessageID;
|
|
78
|
+
this._notifyResponseIdSent = notifyResponseIdSent;
|
|
79
|
+
this._getWebSocketForGetRequest = () => null;
|
|
80
|
+
}
|
|
81
|
+
async start() {
|
|
82
|
+
if (this._started) {
|
|
83
|
+
throw new Error("Transport already started");
|
|
84
|
+
}
|
|
85
|
+
this._started = true;
|
|
86
|
+
}
|
|
87
|
+
async send(message) {
|
|
88
|
+
if (!this._started) {
|
|
89
|
+
throw new Error("Transport not started");
|
|
90
|
+
}
|
|
91
|
+
let websocket = null;
|
|
92
|
+
if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
|
|
93
|
+
websocket = this._getWebSocketForMessageID(message.id.toString());
|
|
94
|
+
if (!websocket) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`Could not find WebSocket for message id: ${message.id}`
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
} else if (isJSONRPCRequest(message)) {
|
|
100
|
+
websocket = this._getWebSocketForGetRequest();
|
|
101
|
+
} else if (isJSONRPCNotification(message)) {
|
|
102
|
+
websocket = null;
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
websocket?.send(JSON.stringify(message));
|
|
106
|
+
if (isJSONRPCResponse(message)) {
|
|
107
|
+
this._notifyResponseIdSent(message.id.toString());
|
|
108
|
+
}
|
|
109
|
+
} catch (error) {
|
|
110
|
+
this.onerror?.(error);
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async close() {
|
|
115
|
+
this.onclose?.();
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
var McpAgent = class _McpAgent extends DurableObject {
|
|
64
119
|
constructor(ctx, env) {
|
|
65
120
|
var _a;
|
|
66
121
|
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);
|
|
122
|
+
this._status = "zero";
|
|
123
|
+
this._transportType = "unset";
|
|
124
|
+
this._requestIdToConnectionId = /* @__PURE__ */ new Map();
|
|
77
125
|
this.initRun = false;
|
|
78
126
|
const self = this;
|
|
79
|
-
|
|
127
|
+
this._agent = new (_a = class extends Agent {
|
|
80
128
|
onStateUpdate(state, source) {
|
|
81
129
|
return self.onStateUpdate(state, source);
|
|
82
130
|
}
|
|
131
|
+
async onMessage(connection, message) {
|
|
132
|
+
return self.onMessage(connection, message);
|
|
133
|
+
}
|
|
83
134
|
}, _a.options = {
|
|
84
135
|
hibernate: true
|
|
85
|
-
}, _a)(ctx, env)
|
|
136
|
+
}, _a)(ctx, env);
|
|
137
|
+
}
|
|
138
|
+
get mcp() {
|
|
139
|
+
return this._agent.mcp;
|
|
86
140
|
}
|
|
87
141
|
get state() {
|
|
88
|
-
return
|
|
142
|
+
return this._agent.state;
|
|
89
143
|
}
|
|
90
144
|
sql(strings, ...values) {
|
|
91
|
-
return
|
|
145
|
+
return this._agent.sql(strings, ...values);
|
|
92
146
|
}
|
|
93
147
|
setState(state) {
|
|
94
|
-
return
|
|
148
|
+
return this._agent.setState(state);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Elicit user input with a message and schema
|
|
152
|
+
*/
|
|
153
|
+
async elicitInput(params) {
|
|
154
|
+
const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
|
|
155
|
+
await this.ctx.storage.put(`elicitation:${requestId}`, {
|
|
156
|
+
message: params.message,
|
|
157
|
+
requestedSchema: params.requestedSchema,
|
|
158
|
+
timestamp: Date.now()
|
|
159
|
+
});
|
|
160
|
+
const elicitRequest = {
|
|
161
|
+
jsonrpc: "2.0",
|
|
162
|
+
id: requestId,
|
|
163
|
+
method: "elicitation/create",
|
|
164
|
+
params: {
|
|
165
|
+
message: params.message,
|
|
166
|
+
requestedSchema: params.requestedSchema
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
if (this._transport) {
|
|
170
|
+
await this._transport.send(elicitRequest);
|
|
171
|
+
} else {
|
|
172
|
+
const connections = this._agent?.getConnections();
|
|
173
|
+
if (!connections || Array.from(connections).length === 0) {
|
|
174
|
+
await this.ctx.storage.delete(`elicitation:${requestId}`);
|
|
175
|
+
throw new Error("No active connections available for elicitation");
|
|
176
|
+
}
|
|
177
|
+
const connectionList = Array.from(connections);
|
|
178
|
+
for (const connection of connectionList) {
|
|
179
|
+
try {
|
|
180
|
+
connection.send(JSON.stringify(elicitRequest));
|
|
181
|
+
} catch (error) {
|
|
182
|
+
console.error("Failed to send elicitation request:", error);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return this._waitForElicitationResponse(requestId);
|
|
95
187
|
}
|
|
188
|
+
// we leave the variables as unused for autocomplete purposes
|
|
189
|
+
// biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
|
|
96
190
|
onStateUpdate(state, source) {
|
|
97
191
|
}
|
|
98
192
|
async onStart() {
|
|
99
193
|
var _a;
|
|
100
194
|
const self = this;
|
|
101
|
-
|
|
195
|
+
this._agent = new (_a = class extends Agent {
|
|
102
196
|
constructor() {
|
|
103
197
|
super(...arguments);
|
|
104
198
|
this.initialState = self.initialState;
|
|
@@ -106,26 +200,78 @@ var McpAgent = class extends DurableObject {
|
|
|
106
200
|
onStateUpdate(state, source) {
|
|
107
201
|
return self.onStateUpdate(state, source);
|
|
108
202
|
}
|
|
203
|
+
async onMessage(connection, event) {
|
|
204
|
+
return self.onMessage(connection, event);
|
|
205
|
+
}
|
|
109
206
|
}, _a.options = {
|
|
110
207
|
hibernate: true
|
|
111
|
-
}, _a)(this.ctx, this.env)
|
|
208
|
+
}, _a)(this.ctx, this.env);
|
|
112
209
|
this.props = await this.ctx.storage.get("props");
|
|
113
|
-
this.
|
|
114
|
-
|
|
115
|
-
|
|
210
|
+
this._transportType = await this.ctx.storage.get(
|
|
211
|
+
"transportType"
|
|
212
|
+
);
|
|
213
|
+
await this._init(this.props);
|
|
214
|
+
const server = await this.server;
|
|
215
|
+
if (this._transportType === "sse") {
|
|
216
|
+
this._transport = new McpSSETransport(() => this.getWebSocket());
|
|
217
|
+
await server.connect(this._transport);
|
|
218
|
+
} else if (this._transportType === "streamable-http") {
|
|
219
|
+
this._transport = new McpStreamableHttpTransport(
|
|
220
|
+
(id) => this.getWebSocketForResponseID(id),
|
|
221
|
+
(id) => this._requestIdToConnectionId.delete(id)
|
|
222
|
+
);
|
|
223
|
+
await server.connect(this._transport);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Handle errors that occur during initialization or operation.
|
|
228
|
+
* Override this method to provide custom error handling.
|
|
229
|
+
* @param error - The error that occurred
|
|
230
|
+
* @returns An error response object with status code and message
|
|
231
|
+
*/
|
|
232
|
+
onError(error) {
|
|
233
|
+
console.error("McpAgent error:", error);
|
|
234
|
+
return {
|
|
235
|
+
status: 500,
|
|
236
|
+
message: error.message || "An unexpected error occurred during initialization"
|
|
237
|
+
};
|
|
116
238
|
}
|
|
117
239
|
async _init(props) {
|
|
118
|
-
await this.
|
|
119
|
-
this.
|
|
240
|
+
await this.updateProps(props);
|
|
241
|
+
if (!this.ctx.storage.get("transportType")) {
|
|
242
|
+
await this.ctx.storage.put("transportType", "unset");
|
|
243
|
+
}
|
|
120
244
|
if (!this.initRun) {
|
|
121
245
|
this.initRun = true;
|
|
122
|
-
|
|
246
|
+
try {
|
|
247
|
+
await this.init();
|
|
248
|
+
} catch (error) {
|
|
249
|
+
const errorResponse = this.onError(error);
|
|
250
|
+
throw new Error(`Initialization failed: ${errorResponse.message}`);
|
|
251
|
+
}
|
|
123
252
|
}
|
|
124
253
|
}
|
|
254
|
+
async setInitialized() {
|
|
255
|
+
await this.ctx.storage.put("initialized", true);
|
|
256
|
+
}
|
|
257
|
+
async isInitialized() {
|
|
258
|
+
return await this.ctx.storage.get("initialized") === true;
|
|
259
|
+
}
|
|
260
|
+
async updateProps(props) {
|
|
261
|
+
await this.ctx.storage.put("props", props ?? {});
|
|
262
|
+
this.props = props;
|
|
263
|
+
}
|
|
264
|
+
async _initialize() {
|
|
265
|
+
await this.ctx.blockConcurrencyWhile(async () => {
|
|
266
|
+
this._status = "starting";
|
|
267
|
+
await this.onStart();
|
|
268
|
+
this._status = "started";
|
|
269
|
+
});
|
|
270
|
+
}
|
|
125
271
|
// Allow the worker to fetch a websocket connection to the agent
|
|
126
272
|
async fetch(request) {
|
|
127
|
-
if (
|
|
128
|
-
await
|
|
273
|
+
if (this._status !== "started") {
|
|
274
|
+
await this._initialize();
|
|
129
275
|
}
|
|
130
276
|
if (request.headers.get("Upgrade") !== "websocket") {
|
|
131
277
|
return new Response("Expected WebSocket Upgrade request", {
|
|
@@ -133,18 +279,42 @@ var McpAgent = class extends DurableObject {
|
|
|
133
279
|
});
|
|
134
280
|
}
|
|
135
281
|
const url = new URL(request.url);
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
282
|
+
const path = url.pathname;
|
|
283
|
+
const server = await this.server;
|
|
284
|
+
switch (path) {
|
|
285
|
+
case "/sse": {
|
|
286
|
+
const websockets = this.ctx.getWebSockets();
|
|
287
|
+
if (websockets.length > 0) {
|
|
288
|
+
return new Response("Websocket already connected", { status: 400 });
|
|
289
|
+
}
|
|
290
|
+
await this.ctx.storage.put("transportType", "sse");
|
|
291
|
+
this._transportType = "sse";
|
|
292
|
+
if (!this._transport) {
|
|
293
|
+
this._transport = new McpSSETransport(() => this.getWebSocket());
|
|
294
|
+
await server.connect(this._transport);
|
|
295
|
+
}
|
|
296
|
+
return this._agent.fetch(request);
|
|
297
|
+
}
|
|
298
|
+
case "/streamable-http": {
|
|
299
|
+
if (!this._transport) {
|
|
300
|
+
this._transport = new McpStreamableHttpTransport(
|
|
301
|
+
(id) => this.getWebSocketForResponseID(id),
|
|
302
|
+
(id) => this._requestIdToConnectionId.delete(id)
|
|
303
|
+
);
|
|
304
|
+
await server.connect(this._transport);
|
|
305
|
+
}
|
|
306
|
+
await this.ctx.storage.put("transportType", "streamable-http");
|
|
307
|
+
this._transportType = "streamable-http";
|
|
308
|
+
return this._agent.fetch(request);
|
|
309
|
+
}
|
|
310
|
+
default:
|
|
311
|
+
return new Response(
|
|
312
|
+
"Internal Server Error: Expected /sse or /streamable-http path",
|
|
313
|
+
{
|
|
314
|
+
status: 500
|
|
315
|
+
}
|
|
316
|
+
);
|
|
142
317
|
}
|
|
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
318
|
}
|
|
149
319
|
getWebSocket() {
|
|
150
320
|
const websockets = this.ctx.getWebSockets();
|
|
@@ -153,73 +323,156 @@ var McpAgent = class extends DurableObject {
|
|
|
153
323
|
}
|
|
154
324
|
return websockets[0];
|
|
155
325
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
326
|
+
getWebSocketForResponseID(id) {
|
|
327
|
+
const connectionId = this._requestIdToConnectionId.get(id);
|
|
328
|
+
if (connectionId === void 0) {
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
return this._agent.getConnection(connectionId) ?? null;
|
|
332
|
+
}
|
|
333
|
+
// All messages received here. This is currently never called
|
|
334
|
+
async onMessage(connection, event) {
|
|
335
|
+
if (this._transportType !== "streamable-http") {
|
|
336
|
+
const err = new Error(
|
|
337
|
+
"Internal Server Error: Expected streamable-http protocol"
|
|
338
|
+
);
|
|
339
|
+
this._transport?.onerror?.(err);
|
|
340
|
+
return;
|
|
159
341
|
}
|
|
342
|
+
let message;
|
|
160
343
|
try {
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
344
|
+
const data = typeof event === "string" ? event : new TextDecoder().decode(event);
|
|
345
|
+
message = JSONRPCMessageSchema.parse(JSON.parse(data));
|
|
346
|
+
} catch (error) {
|
|
347
|
+
this._transport?.onerror?.(error);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
if (await this._handleElicitationResponse(message)) {
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
if (isJSONRPCRequest(message)) {
|
|
354
|
+
this._requestIdToConnectionId.set(message.id.toString(), connection.id);
|
|
355
|
+
}
|
|
356
|
+
this._transport?.onmessage?.(message);
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Wait for elicitation response through storage polling
|
|
360
|
+
*/
|
|
361
|
+
async _waitForElicitationResponse(requestId) {
|
|
362
|
+
const startTime = Date.now();
|
|
363
|
+
const timeout = 6e4;
|
|
364
|
+
try {
|
|
365
|
+
while (Date.now() - startTime < timeout) {
|
|
366
|
+
const response = await this.ctx.storage.get(
|
|
367
|
+
`elicitation:response:${requestId}`
|
|
368
|
+
);
|
|
369
|
+
if (response) {
|
|
370
|
+
await this.ctx.storage.delete(`elicitation:${requestId}`);
|
|
371
|
+
await this.ctx.storage.delete(`elicitation:response:${requestId}`);
|
|
372
|
+
return response;
|
|
373
|
+
}
|
|
374
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
166
375
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
376
|
+
throw new Error("Elicitation request timed out");
|
|
377
|
+
} finally {
|
|
378
|
+
await this.ctx.storage.delete(`elicitation:${requestId}`);
|
|
379
|
+
await this.ctx.storage.delete(`elicitation:response:${requestId}`);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Handle elicitation responses */
|
|
384
|
+
async _handleElicitationResponse(message) {
|
|
385
|
+
if (isJSONRPCResponse(message) && message.result) {
|
|
386
|
+
const requestId = message.id?.toString();
|
|
387
|
+
if (!requestId || !requestId.startsWith("elicit_")) return false;
|
|
388
|
+
const pendingRequest = await this.ctx.storage.get(
|
|
389
|
+
`elicitation:${requestId}`
|
|
170
390
|
);
|
|
171
|
-
if (
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
391
|
+
if (!pendingRequest) return false;
|
|
392
|
+
await this.ctx.storage.put(
|
|
393
|
+
`elicitation:response:${requestId}`,
|
|
394
|
+
message.result
|
|
395
|
+
);
|
|
396
|
+
return true;
|
|
397
|
+
}
|
|
398
|
+
if (isJSONRPCError(message)) {
|
|
399
|
+
const requestId = message.id?.toString();
|
|
400
|
+
if (!requestId || !requestId.startsWith("elicit_")) return false;
|
|
401
|
+
const pendingRequest = await this.ctx.storage.get(
|
|
402
|
+
`elicitation:${requestId}`
|
|
403
|
+
);
|
|
404
|
+
if (!pendingRequest) return false;
|
|
405
|
+
const errorResult = {
|
|
406
|
+
action: "cancel",
|
|
407
|
+
content: {
|
|
408
|
+
error: message.error.message || "Elicitation request failed"
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
await this.ctx.storage.put(
|
|
412
|
+
`elicitation:response:${requestId}`,
|
|
413
|
+
errorResult
|
|
414
|
+
);
|
|
415
|
+
return true;
|
|
416
|
+
}
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
419
|
+
// All messages received over SSE after the initial connection has been established
|
|
420
|
+
// will be passed here
|
|
421
|
+
async onSSEMcpMessage(_sessionId, messageBody) {
|
|
422
|
+
if (this._status !== "started") {
|
|
423
|
+
await this._initialize();
|
|
424
|
+
}
|
|
425
|
+
if (this._transportType !== "sse") {
|
|
426
|
+
return new Error("Internal Server Error: Expected SSE protocol");
|
|
427
|
+
}
|
|
428
|
+
try {
|
|
177
429
|
let parsedMessage;
|
|
178
430
|
try {
|
|
179
|
-
parsedMessage = JSONRPCMessageSchema.parse(
|
|
431
|
+
parsedMessage = JSONRPCMessageSchema.parse(messageBody);
|
|
180
432
|
} catch (error) {
|
|
181
|
-
|
|
433
|
+
this._transport?.onerror?.(error);
|
|
182
434
|
throw error;
|
|
183
435
|
}
|
|
184
|
-
|
|
185
|
-
|
|
436
|
+
if (await this._handleElicitationResponse(parsedMessage)) {
|
|
437
|
+
return null;
|
|
438
|
+
}
|
|
439
|
+
this._transport?.onmessage?.(parsedMessage);
|
|
440
|
+
return null;
|
|
186
441
|
} catch (error) {
|
|
187
|
-
|
|
188
|
-
|
|
442
|
+
console.error("Error forwarding message to SSE:", error);
|
|
443
|
+
this._transport?.onerror?.(error);
|
|
444
|
+
return error;
|
|
189
445
|
}
|
|
190
446
|
}
|
|
191
|
-
//
|
|
447
|
+
// Delegate all websocket events to the underlying agent
|
|
192
448
|
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);
|
|
449
|
+
if (this._status !== "started") {
|
|
450
|
+
await this._initialize();
|
|
203
451
|
}
|
|
204
|
-
|
|
452
|
+
return await this._agent.webSocketMessage(ws, event);
|
|
205
453
|
}
|
|
206
454
|
// WebSocket event handlers for hibernation support
|
|
207
455
|
async webSocketError(ws, error) {
|
|
208
|
-
if (
|
|
209
|
-
await
|
|
456
|
+
if (this._status !== "started") {
|
|
457
|
+
await this._initialize();
|
|
210
458
|
}
|
|
211
|
-
|
|
459
|
+
return await this._agent.webSocketError(ws, error);
|
|
212
460
|
}
|
|
213
461
|
async webSocketClose(ws, code, reason, wasClean) {
|
|
214
|
-
if (
|
|
215
|
-
await
|
|
462
|
+
if (this._status !== "started") {
|
|
463
|
+
await this._initialize();
|
|
216
464
|
}
|
|
217
|
-
|
|
218
|
-
__privateSet(this, _connected, false);
|
|
465
|
+
return await this._agent.webSocketClose(ws, code, reason, wasClean);
|
|
219
466
|
}
|
|
220
467
|
static mount(path, {
|
|
221
468
|
binding = "MCP_OBJECT",
|
|
222
469
|
corsOptions
|
|
470
|
+
} = {}) {
|
|
471
|
+
return _McpAgent.serveSSE(path, { binding, corsOptions });
|
|
472
|
+
}
|
|
473
|
+
static serveSSE(path, {
|
|
474
|
+
binding = "MCP_OBJECT",
|
|
475
|
+
corsOptions
|
|
223
476
|
} = {}) {
|
|
224
477
|
let pathname = path;
|
|
225
478
|
if (path === "/") {
|
|
@@ -228,29 +481,57 @@ var McpAgent = class extends DurableObject {
|
|
|
228
481
|
const basePattern = new URLPattern({ pathname });
|
|
229
482
|
const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
|
|
230
483
|
return {
|
|
231
|
-
|
|
484
|
+
async fetch(request, env, ctx) {
|
|
232
485
|
const corsResponse = handleCORS(request, corsOptions);
|
|
233
486
|
if (corsResponse) return corsResponse;
|
|
234
487
|
const url = new URL(request.url);
|
|
235
|
-
const
|
|
488
|
+
const bindingValue = env[binding];
|
|
489
|
+
if (bindingValue == null || typeof bindingValue !== "object") {
|
|
490
|
+
console.error(
|
|
491
|
+
`Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
|
|
492
|
+
);
|
|
493
|
+
return new Response("Invalid binding", { status: 500 });
|
|
494
|
+
}
|
|
495
|
+
if (!isDurableObjectNamespace(bindingValue)) {
|
|
496
|
+
return new Response("Invalid binding", { status: 500 });
|
|
497
|
+
}
|
|
498
|
+
const namespace = bindingValue;
|
|
236
499
|
if (request.method === "GET" && basePattern.test(url)) {
|
|
237
500
|
const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
|
|
238
501
|
const { readable, writable } = new TransformStream();
|
|
239
502
|
const writer = writable.getWriter();
|
|
240
503
|
const encoder = new TextEncoder();
|
|
504
|
+
const endpointUrl = new URL(request.url);
|
|
505
|
+
endpointUrl.pathname = encodeURI(`${pathname}/message`);
|
|
506
|
+
endpointUrl.searchParams.set("sessionId", sessionId);
|
|
507
|
+
const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash;
|
|
241
508
|
const endpointMessage = `event: endpoint
|
|
242
|
-
data: ${
|
|
509
|
+
data: ${relativeUrlWithSession}
|
|
243
510
|
|
|
244
511
|
`;
|
|
245
512
|
writer.write(encoder.encode(endpointMessage));
|
|
246
|
-
const id = namespace.
|
|
513
|
+
const id = namespace.idFromName(`sse:${sessionId}`);
|
|
247
514
|
const doStub = namespace.get(id);
|
|
248
|
-
|
|
515
|
+
try {
|
|
516
|
+
await doStub._init(ctx.props);
|
|
517
|
+
} catch (error) {
|
|
518
|
+
console.error("Failed to initialize McpAgent:", error);
|
|
519
|
+
await writer.close();
|
|
520
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
521
|
+
return new Response(`Initialization failed: ${errorMessage}`, {
|
|
522
|
+
status: 500
|
|
523
|
+
});
|
|
524
|
+
}
|
|
249
525
|
const upgradeUrl = new URL(request.url);
|
|
250
|
-
upgradeUrl.
|
|
526
|
+
upgradeUrl.pathname = "/sse";
|
|
527
|
+
const existingHeaders = {};
|
|
528
|
+
request.headers.forEach((value, key) => {
|
|
529
|
+
existingHeaders[key] = value;
|
|
530
|
+
});
|
|
251
531
|
const response = await doStub.fetch(
|
|
252
532
|
new Request(upgradeUrl, {
|
|
253
533
|
headers: {
|
|
534
|
+
...existingHeaders,
|
|
254
535
|
Upgrade: "websocket",
|
|
255
536
|
// Required by PartyServer
|
|
256
537
|
"x-partykit-room": sessionId
|
|
@@ -261,44 +542,55 @@ data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
|
|
|
261
542
|
if (!ws) {
|
|
262
543
|
console.error("Failed to establish WebSocket connection");
|
|
263
544
|
await writer.close();
|
|
264
|
-
return
|
|
545
|
+
return new Response("Failed to establish WebSocket connection", {
|
|
546
|
+
status: 500
|
|
547
|
+
});
|
|
265
548
|
}
|
|
266
549
|
ws.accept();
|
|
267
|
-
ws.addEventListener("message",
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
550
|
+
ws.addEventListener("message", (event) => {
|
|
551
|
+
async function onMessage(event2) {
|
|
552
|
+
try {
|
|
553
|
+
const message = JSON.parse(event2.data);
|
|
554
|
+
const result = JSONRPCMessageSchema.safeParse(message);
|
|
555
|
+
if (!result.success) {
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
const messageText = `event: message
|
|
275
559
|
data: ${JSON.stringify(result.data)}
|
|
276
560
|
|
|
277
561
|
`;
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
562
|
+
await writer.write(encoder.encode(messageText));
|
|
563
|
+
} catch (error) {
|
|
564
|
+
console.error("Error forwarding message to SSE:", error);
|
|
565
|
+
}
|
|
281
566
|
}
|
|
567
|
+
onMessage(event).catch(console.error);
|
|
282
568
|
});
|
|
283
|
-
ws.addEventListener("error",
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
569
|
+
ws.addEventListener("error", (error) => {
|
|
570
|
+
async function onError(_error) {
|
|
571
|
+
try {
|
|
572
|
+
await writer.close();
|
|
573
|
+
} catch (_e) {
|
|
574
|
+
}
|
|
287
575
|
}
|
|
576
|
+
onError(error).catch(console.error);
|
|
288
577
|
});
|
|
289
|
-
ws.addEventListener("close",
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
578
|
+
ws.addEventListener("close", () => {
|
|
579
|
+
async function onClose() {
|
|
580
|
+
try {
|
|
581
|
+
await writer.close();
|
|
582
|
+
} catch (error) {
|
|
583
|
+
console.error("Error closing SSE connection:", error);
|
|
584
|
+
}
|
|
294
585
|
}
|
|
586
|
+
onClose().catch(console.error);
|
|
295
587
|
});
|
|
296
588
|
return new Response(readable, {
|
|
297
589
|
headers: {
|
|
298
|
-
"Content-Type": "text/event-stream",
|
|
299
590
|
"Cache-Control": "no-cache",
|
|
300
591
|
Connection: "keep-alive",
|
|
301
|
-
"
|
|
592
|
+
"Content-Type": "text/event-stream",
|
|
593
|
+
...corsHeaders(request, corsOptions)
|
|
302
594
|
}
|
|
303
595
|
});
|
|
304
596
|
}
|
|
@@ -310,40 +602,354 @@ data: ${JSON.stringify(result.data)}
|
|
|
310
602
|
{ status: 400 }
|
|
311
603
|
);
|
|
312
604
|
}
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
"
|
|
321
|
-
|
|
605
|
+
const contentType = request.headers.get("content-type") || "";
|
|
606
|
+
if (!contentType.includes("application/json")) {
|
|
607
|
+
return new Response(`Unsupported content-type: ${contentType}`, {
|
|
608
|
+
status: 400
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
const contentLength = Number.parseInt(
|
|
612
|
+
request.headers.get("content-length") || "0",
|
|
613
|
+
10
|
|
322
614
|
);
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
615
|
+
if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
|
|
616
|
+
return new Response(
|
|
617
|
+
`Request body too large: ${contentLength} bytes`,
|
|
618
|
+
{
|
|
619
|
+
status: 400
|
|
620
|
+
}
|
|
621
|
+
);
|
|
622
|
+
}
|
|
623
|
+
const id = namespace.idFromName(`sse:${sessionId}`);
|
|
624
|
+
const doStub = namespace.get(id);
|
|
625
|
+
const messageBody = await request.json();
|
|
626
|
+
await doStub.updateProps(ctx.props);
|
|
627
|
+
const error = await doStub.onSSEMcpMessage(sessionId, messageBody);
|
|
628
|
+
if (error) {
|
|
629
|
+
return new Response(error.message, {
|
|
630
|
+
headers: {
|
|
631
|
+
"Cache-Control": "no-cache",
|
|
632
|
+
Connection: "keep-alive",
|
|
633
|
+
"Content-Type": "text/event-stream",
|
|
634
|
+
...corsHeaders(request, corsOptions)
|
|
635
|
+
},
|
|
636
|
+
status: 400
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
return new Response("Accepted", {
|
|
640
|
+
headers: {
|
|
641
|
+
"Cache-Control": "no-cache",
|
|
642
|
+
Connection: "keep-alive",
|
|
643
|
+
"Content-Type": "text/event-stream",
|
|
644
|
+
...corsHeaders(request, corsOptions)
|
|
645
|
+
},
|
|
646
|
+
status: 202
|
|
327
647
|
});
|
|
328
648
|
}
|
|
329
649
|
return new Response("Not Found", { status: 404 });
|
|
330
650
|
}
|
|
331
651
|
};
|
|
332
652
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
653
|
+
static serve(path, {
|
|
654
|
+
binding = "MCP_OBJECT",
|
|
655
|
+
corsOptions
|
|
656
|
+
} = {}) {
|
|
657
|
+
let pathname = path;
|
|
658
|
+
if (path === "/") {
|
|
659
|
+
pathname = "/*";
|
|
660
|
+
}
|
|
661
|
+
const basePattern = new URLPattern({ pathname });
|
|
662
|
+
return {
|
|
663
|
+
async fetch(request, env, ctx) {
|
|
664
|
+
const corsResponse = handleCORS(request, corsOptions);
|
|
665
|
+
if (corsResponse) {
|
|
666
|
+
return corsResponse;
|
|
667
|
+
}
|
|
668
|
+
const url = new URL(request.url);
|
|
669
|
+
const bindingValue = env[binding];
|
|
670
|
+
if (bindingValue == null || typeof bindingValue !== "object") {
|
|
671
|
+
console.error(
|
|
672
|
+
`Could not find McpAgent binding for ${binding}. Did you update your wrangler configuration?`
|
|
673
|
+
);
|
|
674
|
+
return new Response("Invalid binding", { status: 500 });
|
|
675
|
+
}
|
|
676
|
+
if (!isDurableObjectNamespace(bindingValue)) {
|
|
677
|
+
return new Response("Invalid binding", { status: 500 });
|
|
678
|
+
}
|
|
679
|
+
const namespace = bindingValue;
|
|
680
|
+
if (request.method === "POST" && basePattern.test(url)) {
|
|
681
|
+
const acceptHeader = request.headers.get("accept");
|
|
682
|
+
if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
|
|
683
|
+
const body2 = JSON.stringify({
|
|
684
|
+
error: {
|
|
685
|
+
code: -32e3,
|
|
686
|
+
message: "Not Acceptable: Client must accept both application/json and text/event-stream"
|
|
687
|
+
},
|
|
688
|
+
id: null,
|
|
689
|
+
jsonrpc: "2.0"
|
|
690
|
+
});
|
|
691
|
+
return new Response(body2, { status: 406 });
|
|
692
|
+
}
|
|
693
|
+
const ct = request.headers.get("content-type");
|
|
694
|
+
if (!ct || !ct.includes("application/json")) {
|
|
695
|
+
const body2 = JSON.stringify({
|
|
696
|
+
error: {
|
|
697
|
+
code: -32e3,
|
|
698
|
+
message: "Unsupported Media Type: Content-Type must be application/json"
|
|
699
|
+
},
|
|
700
|
+
id: null,
|
|
701
|
+
jsonrpc: "2.0"
|
|
702
|
+
});
|
|
703
|
+
return new Response(body2, { status: 415 });
|
|
704
|
+
}
|
|
705
|
+
const contentLength = Number.parseInt(
|
|
706
|
+
request.headers.get("content-length") ?? "0",
|
|
707
|
+
10
|
|
708
|
+
);
|
|
709
|
+
if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
|
|
710
|
+
const body2 = JSON.stringify({
|
|
711
|
+
error: {
|
|
712
|
+
code: -32e3,
|
|
713
|
+
message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
|
|
714
|
+
},
|
|
715
|
+
id: null,
|
|
716
|
+
jsonrpc: "2.0"
|
|
717
|
+
});
|
|
718
|
+
return new Response(body2, { status: 413 });
|
|
719
|
+
}
|
|
720
|
+
let sessionId = request.headers.get("mcp-session-id");
|
|
721
|
+
let rawMessage;
|
|
722
|
+
try {
|
|
723
|
+
rawMessage = await request.json();
|
|
724
|
+
} catch (_error) {
|
|
725
|
+
const body2 = JSON.stringify({
|
|
726
|
+
error: {
|
|
727
|
+
code: -32700,
|
|
728
|
+
message: "Parse error: Invalid JSON"
|
|
729
|
+
},
|
|
730
|
+
id: null,
|
|
731
|
+
jsonrpc: "2.0"
|
|
732
|
+
});
|
|
733
|
+
return new Response(body2, { status: 400 });
|
|
734
|
+
}
|
|
735
|
+
let arrayMessage;
|
|
736
|
+
if (Array.isArray(rawMessage)) {
|
|
737
|
+
arrayMessage = rawMessage;
|
|
738
|
+
} else {
|
|
739
|
+
arrayMessage = [rawMessage];
|
|
740
|
+
}
|
|
741
|
+
let messages = [];
|
|
742
|
+
for (const msg of arrayMessage) {
|
|
743
|
+
if (!JSONRPCMessageSchema.safeParse(msg).success) {
|
|
744
|
+
const body2 = JSON.stringify({
|
|
745
|
+
error: {
|
|
746
|
+
code: -32700,
|
|
747
|
+
message: "Parse error: Invalid JSON-RPC message"
|
|
748
|
+
},
|
|
749
|
+
id: null,
|
|
750
|
+
jsonrpc: "2.0"
|
|
751
|
+
});
|
|
752
|
+
return new Response(body2, { status: 400 });
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
|
|
756
|
+
const isInitializationRequest = messages.some(
|
|
757
|
+
(msg) => InitializeRequestSchema.safeParse(msg).success
|
|
758
|
+
);
|
|
759
|
+
if (isInitializationRequest && sessionId) {
|
|
760
|
+
const body2 = JSON.stringify({
|
|
761
|
+
error: {
|
|
762
|
+
code: -32600,
|
|
763
|
+
message: "Invalid Request: Initialization requests must not include a sessionId"
|
|
764
|
+
},
|
|
765
|
+
id: null,
|
|
766
|
+
jsonrpc: "2.0"
|
|
767
|
+
});
|
|
768
|
+
return new Response(body2, { status: 400 });
|
|
769
|
+
}
|
|
770
|
+
if (isInitializationRequest && messages.length > 1) {
|
|
771
|
+
const body2 = JSON.stringify({
|
|
772
|
+
error: {
|
|
773
|
+
code: -32600,
|
|
774
|
+
message: "Invalid Request: Only one initialization request is allowed"
|
|
775
|
+
},
|
|
776
|
+
id: null,
|
|
777
|
+
jsonrpc: "2.0"
|
|
778
|
+
});
|
|
779
|
+
return new Response(body2, { status: 400 });
|
|
780
|
+
}
|
|
781
|
+
if (!isInitializationRequest && !sessionId) {
|
|
782
|
+
const body2 = JSON.stringify({
|
|
783
|
+
error: {
|
|
784
|
+
code: -32e3,
|
|
785
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
786
|
+
},
|
|
787
|
+
id: null,
|
|
788
|
+
jsonrpc: "2.0"
|
|
789
|
+
});
|
|
790
|
+
return new Response(body2, { status: 400 });
|
|
791
|
+
}
|
|
792
|
+
sessionId = sessionId ?? namespace.newUniqueId().toString();
|
|
793
|
+
const id = namespace.idFromName(`streamable-http:${sessionId}`);
|
|
794
|
+
const doStub = namespace.get(id);
|
|
795
|
+
const isInitialized = await doStub.isInitialized();
|
|
796
|
+
if (isInitializationRequest) {
|
|
797
|
+
try {
|
|
798
|
+
await doStub._init(ctx.props);
|
|
799
|
+
await doStub.setInitialized();
|
|
800
|
+
} catch (error) {
|
|
801
|
+
console.error("Failed to initialize McpAgent:", error);
|
|
802
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
803
|
+
const body2 = JSON.stringify({
|
|
804
|
+
error: {
|
|
805
|
+
code: -32001,
|
|
806
|
+
message: `Initialization failed: ${errorMessage}`
|
|
807
|
+
},
|
|
808
|
+
id: null,
|
|
809
|
+
jsonrpc: "2.0"
|
|
810
|
+
});
|
|
811
|
+
return new Response(body2, { status: 500 });
|
|
812
|
+
}
|
|
813
|
+
} else if (!isInitialized) {
|
|
814
|
+
const body2 = JSON.stringify({
|
|
815
|
+
error: {
|
|
816
|
+
code: -32001,
|
|
817
|
+
message: "Session not found"
|
|
818
|
+
},
|
|
819
|
+
id: null,
|
|
820
|
+
jsonrpc: "2.0"
|
|
821
|
+
});
|
|
822
|
+
return new Response(body2, { status: 404 });
|
|
823
|
+
} else {
|
|
824
|
+
await doStub.updateProps(ctx.props);
|
|
825
|
+
}
|
|
826
|
+
const { readable, writable } = new TransformStream();
|
|
827
|
+
const writer = writable.getWriter();
|
|
828
|
+
const encoder = new TextEncoder();
|
|
829
|
+
const upgradeUrl = new URL(request.url);
|
|
830
|
+
upgradeUrl.pathname = "/streamable-http";
|
|
831
|
+
const existingHeaders = {};
|
|
832
|
+
request.headers.forEach((value, key) => {
|
|
833
|
+
existingHeaders[key] = value;
|
|
834
|
+
});
|
|
835
|
+
const response = await doStub.fetch(
|
|
836
|
+
new Request(upgradeUrl, {
|
|
837
|
+
headers: {
|
|
838
|
+
...existingHeaders,
|
|
839
|
+
Upgrade: "websocket",
|
|
840
|
+
// Required by PartyServer
|
|
841
|
+
"x-partykit-room": sessionId
|
|
842
|
+
}
|
|
843
|
+
})
|
|
844
|
+
);
|
|
845
|
+
const ws = response.webSocket;
|
|
846
|
+
if (!ws) {
|
|
847
|
+
console.error("Failed to establish WebSocket connection");
|
|
848
|
+
await writer.close();
|
|
849
|
+
const body2 = JSON.stringify({
|
|
850
|
+
error: {
|
|
851
|
+
code: -32001,
|
|
852
|
+
message: "Failed to establish WebSocket connection"
|
|
853
|
+
},
|
|
854
|
+
id: null,
|
|
855
|
+
jsonrpc: "2.0"
|
|
856
|
+
});
|
|
857
|
+
return new Response(body2, { status: 500 });
|
|
858
|
+
}
|
|
859
|
+
const requestIds = /* @__PURE__ */ new Set();
|
|
860
|
+
ws.accept();
|
|
861
|
+
ws.addEventListener("message", (event) => {
|
|
862
|
+
async function onMessage(event2) {
|
|
863
|
+
try {
|
|
864
|
+
const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
|
|
865
|
+
const message = JSON.parse(data);
|
|
866
|
+
const result = JSONRPCMessageSchema.safeParse(message);
|
|
867
|
+
if (!result.success) {
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
|
|
871
|
+
requestIds.delete(result.data.id);
|
|
872
|
+
}
|
|
873
|
+
const messageText = `event: message
|
|
874
|
+
data: ${JSON.stringify(result.data)}
|
|
875
|
+
|
|
876
|
+
`;
|
|
877
|
+
await writer.write(encoder.encode(messageText));
|
|
878
|
+
if (requestIds.size === 0) {
|
|
879
|
+
ws.close();
|
|
880
|
+
}
|
|
881
|
+
} catch (error) {
|
|
882
|
+
console.error("Error forwarding message to SSE:", error);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
onMessage(event).catch(console.error);
|
|
886
|
+
});
|
|
887
|
+
ws.addEventListener("error", (error) => {
|
|
888
|
+
async function onError(_error) {
|
|
889
|
+
try {
|
|
890
|
+
await writer.close();
|
|
891
|
+
} catch (_e) {
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
onError(error).catch(console.error);
|
|
895
|
+
});
|
|
896
|
+
ws.addEventListener("close", () => {
|
|
897
|
+
async function onClose() {
|
|
898
|
+
try {
|
|
899
|
+
await writer.close();
|
|
900
|
+
} catch (error) {
|
|
901
|
+
console.error("Error closing SSE connection:", error);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
onClose().catch(console.error);
|
|
905
|
+
});
|
|
906
|
+
const hasOnlyNotificationsOrResponses = messages.every(
|
|
907
|
+
(msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
|
|
908
|
+
);
|
|
909
|
+
if (hasOnlyNotificationsOrResponses) {
|
|
910
|
+
for (const message of messages) {
|
|
911
|
+
ws.send(JSON.stringify(message));
|
|
912
|
+
}
|
|
913
|
+
ws.close();
|
|
914
|
+
return new Response(null, {
|
|
915
|
+
headers: corsHeaders(request, corsOptions),
|
|
916
|
+
status: 202
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
for (const message of messages) {
|
|
920
|
+
if (isJSONRPCRequest(message)) {
|
|
921
|
+
requestIds.add(message.id);
|
|
922
|
+
}
|
|
923
|
+
ws.send(JSON.stringify(message));
|
|
924
|
+
}
|
|
925
|
+
return new Response(readable, {
|
|
926
|
+
headers: {
|
|
927
|
+
"Cache-Control": "no-cache",
|
|
928
|
+
Connection: "keep-alive",
|
|
929
|
+
"Content-Type": "text/event-stream",
|
|
930
|
+
"mcp-session-id": sessionId,
|
|
931
|
+
...corsHeaders(request, corsOptions)
|
|
932
|
+
},
|
|
933
|
+
status: 200
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
const body = JSON.stringify({
|
|
937
|
+
error: {
|
|
938
|
+
code: -32e3,
|
|
939
|
+
message: "Method not allowed"
|
|
940
|
+
},
|
|
941
|
+
id: null,
|
|
942
|
+
jsonrpc: "2.0"
|
|
943
|
+
});
|
|
944
|
+
return new Response(body, { status: 405 });
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
}
|
|
345
948
|
};
|
|
346
949
|
export {
|
|
347
|
-
|
|
950
|
+
ElicitRequestSchema,
|
|
951
|
+
McpAgent,
|
|
952
|
+
SSEEdgeClientTransport,
|
|
953
|
+
StreamableHTTPEdgeClientTransport
|
|
348
954
|
};
|
|
349
955
|
//# sourceMappingURL=index.js.map
|