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