hono-agents 0.0.0-9effbce → 0.0.0-9fbb1b6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +862 -514
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,17 +1,22 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1
2
|
import "partysocket";
|
|
2
3
|
import { nanoid } from "nanoid";
|
|
4
|
+
import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker-provider.js";
|
|
3
5
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
4
|
-
import { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
5
6
|
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
6
7
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
7
|
-
import {
|
|
8
|
+
import { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
8
9
|
import { parseCronExpression } from "cron-schedule";
|
|
9
10
|
import "cloudflare:email";
|
|
10
11
|
import { Server, routePartykitRequest } from "partyserver";
|
|
11
12
|
import { env } from "hono/adapter";
|
|
12
13
|
import { createMiddleware } from "hono/factory";
|
|
13
14
|
|
|
14
|
-
//#region ../agents/dist/
|
|
15
|
+
//#region ../agents/dist/context-BkKbAa1R.js
|
|
16
|
+
const agentContext = new AsyncLocalStorage();
|
|
17
|
+
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region ../agents/dist/ai-types-DEtF_8Km.js
|
|
15
20
|
/**
|
|
16
21
|
* Enum for message types to improve type safety and maintainability
|
|
17
22
|
*/
|
|
@@ -21,15 +26,23 @@ let MessageType = /* @__PURE__ */ function(MessageType$1) {
|
|
|
21
26
|
MessageType$1["CF_AGENT_USE_CHAT_RESPONSE"] = "cf_agent_use_chat_response";
|
|
22
27
|
MessageType$1["CF_AGENT_CHAT_CLEAR"] = "cf_agent_chat_clear";
|
|
23
28
|
MessageType$1["CF_AGENT_CHAT_REQUEST_CANCEL"] = "cf_agent_chat_request_cancel";
|
|
29
|
+
/** Sent by server when client connects and there's an active stream to resume */
|
|
30
|
+
MessageType$1["CF_AGENT_STREAM_RESUMING"] = "cf_agent_stream_resuming";
|
|
31
|
+
/** Sent by client to acknowledge stream resuming notification and request chunks */
|
|
32
|
+
MessageType$1["CF_AGENT_STREAM_RESUME_ACK"] = "cf_agent_stream_resume_ack";
|
|
24
33
|
MessageType$1["CF_AGENT_MCP_SERVERS"] = "cf_agent_mcp_servers";
|
|
25
34
|
MessageType$1["CF_MCP_AGENT_EVENT"] = "cf_mcp_agent_event";
|
|
26
35
|
MessageType$1["CF_AGENT_STATE"] = "cf_agent_state";
|
|
27
36
|
MessageType$1["RPC"] = "rpc";
|
|
37
|
+
/** Client sends tool result to server (for client-side tools) */
|
|
38
|
+
MessageType$1["CF_AGENT_TOOL_RESULT"] = "cf_agent_tool_result";
|
|
39
|
+
/** Server notifies client that a message was updated (e.g., tool result applied) */
|
|
40
|
+
MessageType$1["CF_AGENT_MESSAGE_UPDATED"] = "cf_agent_message_updated";
|
|
28
41
|
return MessageType$1;
|
|
29
42
|
}({});
|
|
30
43
|
|
|
31
44
|
//#endregion
|
|
32
|
-
//#region ../agents/dist/client-
|
|
45
|
+
//#region ../agents/dist/client-DjTPRM8-.js
|
|
33
46
|
/**
|
|
34
47
|
* Convert a camelCase string to a kebab-case string
|
|
35
48
|
* @param str The string to convert
|
|
@@ -43,7 +56,158 @@ function camelCaseToKebabCase(str) {
|
|
|
43
56
|
}
|
|
44
57
|
|
|
45
58
|
//#endregion
|
|
46
|
-
//#region ../agents/dist/client-
|
|
59
|
+
//#region ../agents/dist/do-oauth-client-provider-B1fVIshX.js
|
|
60
|
+
const STATE_EXPIRATION_MS = 600 * 1e3;
|
|
61
|
+
var DurableObjectOAuthClientProvider = class {
|
|
62
|
+
constructor(storage, clientName, baseRedirectUrl) {
|
|
63
|
+
this.storage = storage;
|
|
64
|
+
this.clientName = clientName;
|
|
65
|
+
this.baseRedirectUrl = baseRedirectUrl;
|
|
66
|
+
if (!storage) throw new Error("DurableObjectOAuthClientProvider requires a valid DurableObjectStorage instance");
|
|
67
|
+
}
|
|
68
|
+
get clientMetadata() {
|
|
69
|
+
return {
|
|
70
|
+
client_name: this.clientName,
|
|
71
|
+
client_uri: this.clientUri,
|
|
72
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
73
|
+
redirect_uris: [this.redirectUrl],
|
|
74
|
+
response_types: ["code"],
|
|
75
|
+
token_endpoint_auth_method: "none"
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
get clientUri() {
|
|
79
|
+
return new URL(this.redirectUrl).origin;
|
|
80
|
+
}
|
|
81
|
+
get redirectUrl() {
|
|
82
|
+
return this.baseRedirectUrl;
|
|
83
|
+
}
|
|
84
|
+
get clientId() {
|
|
85
|
+
if (!this._clientId_) throw new Error("Trying to access clientId before it was set");
|
|
86
|
+
return this._clientId_;
|
|
87
|
+
}
|
|
88
|
+
set clientId(clientId_) {
|
|
89
|
+
this._clientId_ = clientId_;
|
|
90
|
+
}
|
|
91
|
+
get serverId() {
|
|
92
|
+
if (!this._serverId_) throw new Error("Trying to access serverId before it was set");
|
|
93
|
+
return this._serverId_;
|
|
94
|
+
}
|
|
95
|
+
set serverId(serverId_) {
|
|
96
|
+
this._serverId_ = serverId_;
|
|
97
|
+
}
|
|
98
|
+
keyPrefix(clientId) {
|
|
99
|
+
return `/${this.clientName}/${this.serverId}/${clientId}`;
|
|
100
|
+
}
|
|
101
|
+
clientInfoKey(clientId) {
|
|
102
|
+
return `${this.keyPrefix(clientId)}/client_info/`;
|
|
103
|
+
}
|
|
104
|
+
async clientInformation() {
|
|
105
|
+
if (!this._clientId_) return;
|
|
106
|
+
return await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;
|
|
107
|
+
}
|
|
108
|
+
async saveClientInformation(clientInformation) {
|
|
109
|
+
await this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);
|
|
110
|
+
this.clientId = clientInformation.client_id;
|
|
111
|
+
}
|
|
112
|
+
tokenKey(clientId) {
|
|
113
|
+
return `${this.keyPrefix(clientId)}/token`;
|
|
114
|
+
}
|
|
115
|
+
async tokens() {
|
|
116
|
+
if (!this._clientId_) return;
|
|
117
|
+
return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
|
|
118
|
+
}
|
|
119
|
+
async saveTokens(tokens) {
|
|
120
|
+
await this.storage.put(this.tokenKey(this.clientId), tokens);
|
|
121
|
+
}
|
|
122
|
+
get authUrl() {
|
|
123
|
+
return this._authUrl_;
|
|
124
|
+
}
|
|
125
|
+
stateKey(nonce) {
|
|
126
|
+
return `/${this.clientName}/${this.serverId}/state/${nonce}`;
|
|
127
|
+
}
|
|
128
|
+
async state() {
|
|
129
|
+
const nonce = nanoid();
|
|
130
|
+
const state = `${nonce}.${this.serverId}`;
|
|
131
|
+
const storedState = {
|
|
132
|
+
nonce,
|
|
133
|
+
serverId: this.serverId,
|
|
134
|
+
createdAt: Date.now()
|
|
135
|
+
};
|
|
136
|
+
await this.storage.put(this.stateKey(nonce), storedState);
|
|
137
|
+
return state;
|
|
138
|
+
}
|
|
139
|
+
async checkState(state) {
|
|
140
|
+
const parts = state.split(".");
|
|
141
|
+
if (parts.length !== 2) return {
|
|
142
|
+
valid: false,
|
|
143
|
+
error: "Invalid state format"
|
|
144
|
+
};
|
|
145
|
+
const [nonce, serverId] = parts;
|
|
146
|
+
const key = this.stateKey(nonce);
|
|
147
|
+
const storedState = await this.storage.get(key);
|
|
148
|
+
if (!storedState) return {
|
|
149
|
+
valid: false,
|
|
150
|
+
error: "State not found or already used"
|
|
151
|
+
};
|
|
152
|
+
if (storedState.serverId !== serverId) {
|
|
153
|
+
await this.storage.delete(key);
|
|
154
|
+
return {
|
|
155
|
+
valid: false,
|
|
156
|
+
error: "State serverId mismatch"
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
if (Date.now() - storedState.createdAt > STATE_EXPIRATION_MS) {
|
|
160
|
+
await this.storage.delete(key);
|
|
161
|
+
return {
|
|
162
|
+
valid: false,
|
|
163
|
+
error: "State expired"
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
valid: true,
|
|
168
|
+
serverId
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
async consumeState(state) {
|
|
172
|
+
const parts = state.split(".");
|
|
173
|
+
if (parts.length !== 2) {
|
|
174
|
+
console.warn(`[OAuth] consumeState called with invalid state format: ${state.substring(0, 20)}...`);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const [nonce] = parts;
|
|
178
|
+
await this.storage.delete(this.stateKey(nonce));
|
|
179
|
+
}
|
|
180
|
+
async redirectToAuthorization(authUrl) {
|
|
181
|
+
this._authUrl_ = authUrl.toString();
|
|
182
|
+
}
|
|
183
|
+
async invalidateCredentials(scope) {
|
|
184
|
+
if (!this._clientId_) return;
|
|
185
|
+
const deleteKeys = [];
|
|
186
|
+
if (scope === "all" || scope === "client") deleteKeys.push(this.clientInfoKey(this.clientId));
|
|
187
|
+
if (scope === "all" || scope === "tokens") deleteKeys.push(this.tokenKey(this.clientId));
|
|
188
|
+
if (scope === "all" || scope === "verifier") deleteKeys.push(this.codeVerifierKey(this.clientId));
|
|
189
|
+
if (deleteKeys.length > 0) await this.storage.delete(deleteKeys);
|
|
190
|
+
}
|
|
191
|
+
codeVerifierKey(clientId) {
|
|
192
|
+
return `${this.keyPrefix(clientId)}/code_verifier`;
|
|
193
|
+
}
|
|
194
|
+
async saveCodeVerifier(verifier) {
|
|
195
|
+
const key = this.codeVerifierKey(this.clientId);
|
|
196
|
+
if (await this.storage.get(key)) return;
|
|
197
|
+
await this.storage.put(key, verifier);
|
|
198
|
+
}
|
|
199
|
+
async codeVerifier() {
|
|
200
|
+
const codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));
|
|
201
|
+
if (!codeVerifier) throw new Error("No code verifier found");
|
|
202
|
+
return codeVerifier;
|
|
203
|
+
}
|
|
204
|
+
async deleteCodeVerifier() {
|
|
205
|
+
await this.storage.delete(this.codeVerifierKey(this.clientId));
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
//#endregion
|
|
210
|
+
//#region ../agents/dist/client-QZa2Rq0l.js
|
|
47
211
|
function toDisposable(fn) {
|
|
48
212
|
return { dispose: fn };
|
|
49
213
|
}
|
|
@@ -91,73 +255,21 @@ function isTransportNotImplemented(error) {
|
|
|
91
255
|
const msg = toErrorMessage(error);
|
|
92
256
|
return msg.includes("404") || msg.includes("405") || msg.includes("Not Implemented") || msg.includes("not implemented");
|
|
93
257
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
delete workerOptions.mode;
|
|
110
|
-
return options.eventSourceInit?.fetch?.(fetchUrl, workerOptions) || fetch(fetchUrl, workerOptions);
|
|
111
|
-
};
|
|
112
|
-
super(url, {
|
|
113
|
-
...options,
|
|
114
|
-
eventSourceInit: {
|
|
115
|
-
...options.eventSourceInit,
|
|
116
|
-
fetch: fetchOverride
|
|
117
|
-
}
|
|
118
|
-
});
|
|
119
|
-
this.authProvider = options.authProvider;
|
|
120
|
-
}
|
|
121
|
-
async authHeaders() {
|
|
122
|
-
if (this.authProvider) {
|
|
123
|
-
const tokens = await this.authProvider.tokens();
|
|
124
|
-
if (tokens) return { Authorization: `Bearer ${tokens.access_token}` };
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
};
|
|
128
|
-
var StreamableHTTPEdgeClientTransport = class extends StreamableHTTPClientTransport {
|
|
129
|
-
/**
|
|
130
|
-
* Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment
|
|
131
|
-
*/
|
|
132
|
-
constructor(url, options) {
|
|
133
|
-
const fetchOverride = async (fetchUrl, fetchInit = {}) => {
|
|
134
|
-
const headers = await this.authHeaders();
|
|
135
|
-
const workerOptions = {
|
|
136
|
-
...fetchInit,
|
|
137
|
-
headers: {
|
|
138
|
-
...options.requestInit?.headers,
|
|
139
|
-
...fetchInit?.headers,
|
|
140
|
-
...headers
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
delete workerOptions.mode;
|
|
144
|
-
return options.requestInit?.fetch?.(fetchUrl, workerOptions) || fetch(fetchUrl, workerOptions);
|
|
145
|
-
};
|
|
146
|
-
super(url, {
|
|
147
|
-
...options,
|
|
148
|
-
requestInit: {
|
|
149
|
-
...options.requestInit,
|
|
150
|
-
fetch: fetchOverride
|
|
151
|
-
}
|
|
152
|
-
});
|
|
153
|
-
this.authProvider = options.authProvider;
|
|
154
|
-
}
|
|
155
|
-
async authHeaders() {
|
|
156
|
-
if (this.authProvider) {
|
|
157
|
-
const tokens = await this.authProvider.tokens();
|
|
158
|
-
if (tokens) return { Authorization: `Bearer ${tokens.access_token}` };
|
|
159
|
-
}
|
|
160
|
-
}
|
|
258
|
+
/**
|
|
259
|
+
* Connection state machine for MCP client connections.
|
|
260
|
+
*
|
|
261
|
+
* State transitions:
|
|
262
|
+
* - Non-OAuth: init() → CONNECTING → DISCOVERING → READY
|
|
263
|
+
* - OAuth: init() → AUTHENTICATING → (callback) → CONNECTING → DISCOVERING → READY
|
|
264
|
+
* - Any state can transition to FAILED on error
|
|
265
|
+
*/
|
|
266
|
+
const MCPConnectionState = {
|
|
267
|
+
AUTHENTICATING: "authenticating",
|
|
268
|
+
CONNECTING: "connecting",
|
|
269
|
+
CONNECTED: "connected",
|
|
270
|
+
DISCOVERING: "discovering",
|
|
271
|
+
READY: "ready",
|
|
272
|
+
FAILED: "failed"
|
|
161
273
|
};
|
|
162
274
|
var MCPClientConnection = class {
|
|
163
275
|
constructor(url, info, options = {
|
|
@@ -166,7 +278,7 @@ var MCPClientConnection = class {
|
|
|
166
278
|
}) {
|
|
167
279
|
this.url = url;
|
|
168
280
|
this.options = options;
|
|
169
|
-
this.connectionState =
|
|
281
|
+
this.connectionState = MCPConnectionState.CONNECTING;
|
|
170
282
|
this.tools = [];
|
|
171
283
|
this.prompts = [];
|
|
172
284
|
this.resources = [];
|
|
@@ -182,36 +294,49 @@ var MCPClientConnection = class {
|
|
|
182
294
|
});
|
|
183
295
|
}
|
|
184
296
|
/**
|
|
185
|
-
* Initialize a client connection
|
|
297
|
+
* Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state
|
|
298
|
+
* Sets connection state based on the result and emits observability events
|
|
186
299
|
*
|
|
187
|
-
* @returns
|
|
300
|
+
* @returns Error message if connection failed, undefined otherwise
|
|
188
301
|
*/
|
|
189
302
|
async init() {
|
|
190
303
|
const transportType = this.options.transport.type;
|
|
191
304
|
if (!transportType) throw new Error("Transport type must be specified");
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
this.
|
|
197
|
-
|
|
198
|
-
|
|
305
|
+
const res = await this.tryConnect(transportType);
|
|
306
|
+
this.connectionState = res.state;
|
|
307
|
+
if (res.state === MCPConnectionState.CONNECTED && res.transport) {
|
|
308
|
+
this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
|
|
309
|
+
return await this.handleElicitationRequest(request);
|
|
310
|
+
});
|
|
311
|
+
this.lastConnectedTransport = res.transport;
|
|
312
|
+
this._onObservabilityEvent.fire({
|
|
313
|
+
type: "mcp:client:connect",
|
|
314
|
+
displayMessage: `Connected successfully using ${res.transport} transport for ${this.url.toString()}`,
|
|
315
|
+
payload: {
|
|
316
|
+
url: this.url.toString(),
|
|
317
|
+
transport: res.transport,
|
|
318
|
+
state: this.connectionState
|
|
319
|
+
},
|
|
320
|
+
timestamp: Date.now(),
|
|
321
|
+
id: nanoid()
|
|
322
|
+
});
|
|
323
|
+
return;
|
|
324
|
+
} else if (res.state === MCPConnectionState.FAILED && res.error) {
|
|
325
|
+
const errorMessage = toErrorMessage(res.error);
|
|
199
326
|
this._onObservabilityEvent.fire({
|
|
200
327
|
type: "mcp:client:connect",
|
|
201
|
-
displayMessage: `
|
|
328
|
+
displayMessage: `Failed to connect to ${this.url.toString()}: ${errorMessage}`,
|
|
202
329
|
payload: {
|
|
203
330
|
url: this.url.toString(),
|
|
204
331
|
transport: transportType,
|
|
205
332
|
state: this.connectionState,
|
|
206
|
-
error:
|
|
333
|
+
error: errorMessage
|
|
207
334
|
},
|
|
208
335
|
timestamp: Date.now(),
|
|
209
336
|
id: nanoid()
|
|
210
337
|
});
|
|
211
|
-
|
|
212
|
-
return;
|
|
338
|
+
return errorMessage;
|
|
213
339
|
}
|
|
214
|
-
await this.discoverAndRegister();
|
|
215
340
|
}
|
|
216
341
|
/**
|
|
217
342
|
* Finish OAuth by probing transports based on configured type.
|
|
@@ -243,113 +368,189 @@ var MCPClientConnection = class {
|
|
|
243
368
|
* Complete OAuth authorization
|
|
244
369
|
*/
|
|
245
370
|
async completeAuthorization(code) {
|
|
246
|
-
if (this.connectionState !==
|
|
371
|
+
if (this.connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error("Connection must be in authenticating state to complete authorization");
|
|
247
372
|
try {
|
|
248
373
|
await this.finishAuthProbe(code);
|
|
249
|
-
this.connectionState =
|
|
374
|
+
this.connectionState = MCPConnectionState.CONNECTING;
|
|
250
375
|
} catch (error) {
|
|
251
|
-
this.connectionState =
|
|
376
|
+
this.connectionState = MCPConnectionState.FAILED;
|
|
252
377
|
throw error;
|
|
253
378
|
}
|
|
254
379
|
}
|
|
255
380
|
/**
|
|
256
|
-
*
|
|
381
|
+
* Discover server capabilities and register tools, resources, prompts, and templates.
|
|
382
|
+
* This method does the work but does not manage connection state - that's handled by discover().
|
|
257
383
|
*/
|
|
258
|
-
async
|
|
259
|
-
|
|
384
|
+
async discoverAndRegister() {
|
|
385
|
+
this.serverCapabilities = this.client.getServerCapabilities();
|
|
386
|
+
if (!this.serverCapabilities) throw new Error("The MCP Server failed to return server capabilities");
|
|
387
|
+
const operations = [];
|
|
388
|
+
const operationNames = [];
|
|
389
|
+
operations.push(Promise.resolve(this.client.getInstructions()));
|
|
390
|
+
operationNames.push("instructions");
|
|
391
|
+
if (this.serverCapabilities.tools) {
|
|
392
|
+
operations.push(this.registerTools());
|
|
393
|
+
operationNames.push("tools");
|
|
394
|
+
}
|
|
395
|
+
if (this.serverCapabilities.resources) {
|
|
396
|
+
operations.push(this.registerResources());
|
|
397
|
+
operationNames.push("resources");
|
|
398
|
+
}
|
|
399
|
+
if (this.serverCapabilities.prompts) {
|
|
400
|
+
operations.push(this.registerPrompts());
|
|
401
|
+
operationNames.push("prompts");
|
|
402
|
+
}
|
|
403
|
+
if (this.serverCapabilities.resources) {
|
|
404
|
+
operations.push(this.registerResourceTemplates());
|
|
405
|
+
operationNames.push("resource templates");
|
|
406
|
+
}
|
|
260
407
|
try {
|
|
261
|
-
const
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
408
|
+
const results = await Promise.all(operations);
|
|
409
|
+
for (let i = 0; i < results.length; i++) {
|
|
410
|
+
const result = results[i];
|
|
411
|
+
switch (operationNames[i]) {
|
|
412
|
+
case "instructions":
|
|
413
|
+
this.instructions = result;
|
|
414
|
+
break;
|
|
415
|
+
case "tools":
|
|
416
|
+
this.tools = result;
|
|
417
|
+
break;
|
|
418
|
+
case "resources":
|
|
419
|
+
this.resources = result;
|
|
420
|
+
break;
|
|
421
|
+
case "prompts":
|
|
422
|
+
this.prompts = result;
|
|
423
|
+
break;
|
|
424
|
+
case "resource templates":
|
|
425
|
+
this.resourceTemplates = result;
|
|
426
|
+
break;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
265
429
|
} catch (error) {
|
|
266
|
-
this.
|
|
430
|
+
this._onObservabilityEvent.fire({
|
|
431
|
+
type: "mcp:client:discover",
|
|
432
|
+
displayMessage: `Failed to discover capabilities for ${this.url.toString()}: ${toErrorMessage(error)}`,
|
|
433
|
+
payload: {
|
|
434
|
+
url: this.url.toString(),
|
|
435
|
+
error: toErrorMessage(error)
|
|
436
|
+
},
|
|
437
|
+
timestamp: Date.now(),
|
|
438
|
+
id: nanoid()
|
|
439
|
+
});
|
|
267
440
|
throw error;
|
|
268
441
|
}
|
|
269
442
|
}
|
|
270
443
|
/**
|
|
271
|
-
* Discover server capabilities
|
|
444
|
+
* Discover server capabilities with timeout and cancellation support.
|
|
445
|
+
* If called while a previous discovery is in-flight, the previous discovery will be aborted.
|
|
446
|
+
*
|
|
447
|
+
* @param options Optional configuration
|
|
448
|
+
* @param options.timeoutMs Timeout in milliseconds (default: 15000)
|
|
449
|
+
* @returns Result indicating success/failure with optional error message
|
|
272
450
|
*/
|
|
273
|
-
async
|
|
274
|
-
|
|
275
|
-
this.
|
|
276
|
-
if (!this.serverCapabilities) throw new Error("The MCP Server failed to return server capabilities");
|
|
277
|
-
const [instructionsResult, toolsResult, resourcesResult, promptsResult, resourceTemplatesResult] = await Promise.allSettled([
|
|
278
|
-
this.client.getInstructions(),
|
|
279
|
-
this.registerTools(),
|
|
280
|
-
this.registerResources(),
|
|
281
|
-
this.registerPrompts(),
|
|
282
|
-
this.registerResourceTemplates()
|
|
283
|
-
]);
|
|
284
|
-
const operations = [
|
|
285
|
-
{
|
|
286
|
-
name: "instructions",
|
|
287
|
-
result: instructionsResult
|
|
288
|
-
},
|
|
289
|
-
{
|
|
290
|
-
name: "tools",
|
|
291
|
-
result: toolsResult
|
|
292
|
-
},
|
|
293
|
-
{
|
|
294
|
-
name: "resources",
|
|
295
|
-
result: resourcesResult
|
|
296
|
-
},
|
|
297
|
-
{
|
|
298
|
-
name: "prompts",
|
|
299
|
-
result: promptsResult
|
|
300
|
-
},
|
|
301
|
-
{
|
|
302
|
-
name: "resource templates",
|
|
303
|
-
result: resourceTemplatesResult
|
|
304
|
-
}
|
|
305
|
-
];
|
|
306
|
-
for (const { name, result } of operations) if (result.status === "rejected") {
|
|
307
|
-
const url = this.url.toString();
|
|
451
|
+
async discover(options = {}) {
|
|
452
|
+
const { timeoutMs = 15e3 } = options;
|
|
453
|
+
if (this.connectionState !== MCPConnectionState.CONNECTED && this.connectionState !== MCPConnectionState.READY) {
|
|
308
454
|
this._onObservabilityEvent.fire({
|
|
309
455
|
type: "mcp:client:discover",
|
|
310
|
-
displayMessage: `
|
|
456
|
+
displayMessage: `Discovery skipped for ${this.url.toString()}, state is ${this.connectionState}`,
|
|
311
457
|
payload: {
|
|
312
|
-
url,
|
|
313
|
-
|
|
314
|
-
error: result.reason
|
|
458
|
+
url: this.url.toString(),
|
|
459
|
+
state: this.connectionState
|
|
315
460
|
},
|
|
316
461
|
timestamp: Date.now(),
|
|
317
462
|
id: nanoid()
|
|
318
463
|
});
|
|
464
|
+
return {
|
|
465
|
+
success: false,
|
|
466
|
+
error: `Discovery skipped - connection in ${this.connectionState} state`
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
if (this._discoveryAbortController) {
|
|
470
|
+
this._discoveryAbortController.abort();
|
|
471
|
+
this._discoveryAbortController = void 0;
|
|
472
|
+
}
|
|
473
|
+
const abortController = new AbortController();
|
|
474
|
+
this._discoveryAbortController = abortController;
|
|
475
|
+
this.connectionState = MCPConnectionState.DISCOVERING;
|
|
476
|
+
let timeoutId;
|
|
477
|
+
try {
|
|
478
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
479
|
+
timeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Discovery timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
480
|
+
});
|
|
481
|
+
if (abortController.signal.aborted) throw new Error("Discovery was cancelled");
|
|
482
|
+
const abortPromise = new Promise((_, reject) => {
|
|
483
|
+
abortController.signal.addEventListener("abort", () => {
|
|
484
|
+
reject(/* @__PURE__ */ new Error("Discovery was cancelled"));
|
|
485
|
+
});
|
|
486
|
+
});
|
|
487
|
+
await Promise.race([
|
|
488
|
+
this.discoverAndRegister(),
|
|
489
|
+
timeoutPromise,
|
|
490
|
+
abortPromise
|
|
491
|
+
]);
|
|
492
|
+
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
493
|
+
this.connectionState = MCPConnectionState.READY;
|
|
494
|
+
this._onObservabilityEvent.fire({
|
|
495
|
+
type: "mcp:client:discover",
|
|
496
|
+
displayMessage: `Discovery completed for ${this.url.toString()}`,
|
|
497
|
+
payload: { url: this.url.toString() },
|
|
498
|
+
timestamp: Date.now(),
|
|
499
|
+
id: nanoid()
|
|
500
|
+
});
|
|
501
|
+
return { success: true };
|
|
502
|
+
} catch (e) {
|
|
503
|
+
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
504
|
+
this.connectionState = MCPConnectionState.CONNECTED;
|
|
505
|
+
return {
|
|
506
|
+
success: false,
|
|
507
|
+
error: e instanceof Error ? e.message : String(e)
|
|
508
|
+
};
|
|
509
|
+
} finally {
|
|
510
|
+
this._discoveryAbortController = void 0;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Cancel any in-flight discovery operation.
|
|
515
|
+
* Called when closing the connection.
|
|
516
|
+
*/
|
|
517
|
+
cancelDiscovery() {
|
|
518
|
+
if (this._discoveryAbortController) {
|
|
519
|
+
this._discoveryAbortController.abort();
|
|
520
|
+
this._discoveryAbortController = void 0;
|
|
319
521
|
}
|
|
320
|
-
this.instructions = instructionsResult.status === "fulfilled" ? instructionsResult.value : void 0;
|
|
321
|
-
this.tools = toolsResult.status === "fulfilled" ? toolsResult.value : [];
|
|
322
|
-
this.resources = resourcesResult.status === "fulfilled" ? resourcesResult.value : [];
|
|
323
|
-
this.prompts = promptsResult.status === "fulfilled" ? promptsResult.value : [];
|
|
324
|
-
this.resourceTemplates = resourceTemplatesResult.status === "fulfilled" ? resourceTemplatesResult.value : [];
|
|
325
|
-
this.connectionState = "ready";
|
|
326
522
|
}
|
|
327
523
|
/**
|
|
328
|
-
* Notification handler registration
|
|
524
|
+
* Notification handler registration for tools
|
|
525
|
+
* Should only be called if serverCapabilities.tools exists
|
|
329
526
|
*/
|
|
330
527
|
async registerTools() {
|
|
331
|
-
if (
|
|
332
|
-
if (this.serverCapabilities.tools.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {
|
|
528
|
+
if (this.serverCapabilities?.tools?.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {
|
|
333
529
|
this.tools = await this.fetchTools();
|
|
334
530
|
});
|
|
335
531
|
return this.fetchTools();
|
|
336
532
|
}
|
|
533
|
+
/**
|
|
534
|
+
* Notification handler registration for resources
|
|
535
|
+
* Should only be called if serverCapabilities.resources exists
|
|
536
|
+
*/
|
|
337
537
|
async registerResources() {
|
|
338
|
-
if (
|
|
339
|
-
if (this.serverCapabilities.resources.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {
|
|
538
|
+
if (this.serverCapabilities?.resources?.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {
|
|
340
539
|
this.resources = await this.fetchResources();
|
|
341
540
|
});
|
|
342
541
|
return this.fetchResources();
|
|
343
542
|
}
|
|
543
|
+
/**
|
|
544
|
+
* Notification handler registration for prompts
|
|
545
|
+
* Should only be called if serverCapabilities.prompts exists
|
|
546
|
+
*/
|
|
344
547
|
async registerPrompts() {
|
|
345
|
-
if (
|
|
346
|
-
if (this.serverCapabilities.prompts.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {
|
|
548
|
+
if (this.serverCapabilities?.prompts?.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {
|
|
347
549
|
this.prompts = await this.fetchPrompts();
|
|
348
550
|
});
|
|
349
551
|
return this.fetchPrompts();
|
|
350
552
|
}
|
|
351
553
|
async registerResourceTemplates() {
|
|
352
|
-
if (!this.serverCapabilities || !this.serverCapabilities.resources) return [];
|
|
353
554
|
return this.fetchResourceTemplates();
|
|
354
555
|
}
|
|
355
556
|
async fetchTools() {
|
|
@@ -402,8 +603,8 @@ var MCPClientConnection = class {
|
|
|
402
603
|
*/
|
|
403
604
|
getTransport(transportType) {
|
|
404
605
|
switch (transportType) {
|
|
405
|
-
case "streamable-http": return new
|
|
406
|
-
case "sse": return new
|
|
606
|
+
case "streamable-http": return new StreamableHTTPClientTransport(this.url, this.options.transport);
|
|
607
|
+
case "sse": return new SSEClientTransport(this.url, this.options.transport);
|
|
407
608
|
default: throw new Error(`Unsupported transport type: ${transportType}`);
|
|
408
609
|
}
|
|
409
610
|
}
|
|
@@ -415,44 +616,24 @@ var MCPClientConnection = class {
|
|
|
415
616
|
const transport = this.getTransport(currentTransportType);
|
|
416
617
|
try {
|
|
417
618
|
await this.client.connect(transport);
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
displayMessage: `Connected successfully using ${currentTransportType} transport for ${url}`,
|
|
423
|
-
payload: {
|
|
424
|
-
url,
|
|
425
|
-
transport: currentTransportType,
|
|
426
|
-
state: this.connectionState
|
|
427
|
-
},
|
|
428
|
-
timestamp: Date.now(),
|
|
429
|
-
id: nanoid()
|
|
430
|
-
});
|
|
431
|
-
break;
|
|
619
|
+
return {
|
|
620
|
+
state: MCPConnectionState.CONNECTED,
|
|
621
|
+
transport: currentTransportType
|
|
622
|
+
};
|
|
432
623
|
} catch (e) {
|
|
433
624
|
const error = e instanceof Error ? e : new Error(String(e));
|
|
434
|
-
if (isUnauthorized(error))
|
|
435
|
-
if (
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
payload: {
|
|
441
|
-
url,
|
|
442
|
-
transport: currentTransportType,
|
|
443
|
-
state: this.connectionState
|
|
444
|
-
},
|
|
445
|
-
timestamp: Date.now(),
|
|
446
|
-
id: nanoid()
|
|
447
|
-
});
|
|
448
|
-
continue;
|
|
449
|
-
}
|
|
450
|
-
throw e;
|
|
625
|
+
if (isUnauthorized(error)) return { state: MCPConnectionState.AUTHENTICATING };
|
|
626
|
+
if (isTransportNotImplemented(error) && hasFallback) continue;
|
|
627
|
+
return {
|
|
628
|
+
state: MCPConnectionState.FAILED,
|
|
629
|
+
error
|
|
630
|
+
};
|
|
451
631
|
}
|
|
452
632
|
}
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
633
|
+
return {
|
|
634
|
+
state: MCPConnectionState.FAILED,
|
|
635
|
+
error: /* @__PURE__ */ new Error("No transports available")
|
|
636
|
+
};
|
|
456
637
|
}
|
|
457
638
|
_capabilityErrorHandler(empty, method) {
|
|
458
639
|
return (e) => {
|
|
@@ -475,6 +656,7 @@ var MCPClientConnection = class {
|
|
|
475
656
|
};
|
|
476
657
|
}
|
|
477
658
|
};
|
|
659
|
+
const defaultClientOptions = { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() };
|
|
478
660
|
/**
|
|
479
661
|
* Utility class that aggregates multiple MCP clients into one
|
|
480
662
|
*/
|
|
@@ -482,26 +664,121 @@ var MCPClientManager = class {
|
|
|
482
664
|
/**
|
|
483
665
|
* @param _name Name of the MCP client
|
|
484
666
|
* @param _version Version of the MCP Client
|
|
485
|
-
* @param
|
|
667
|
+
* @param options Storage adapter for persisting MCP server state
|
|
486
668
|
*/
|
|
487
|
-
constructor(_name, _version) {
|
|
669
|
+
constructor(_name, _version, options) {
|
|
488
670
|
this._name = _name;
|
|
489
671
|
this._version = _version;
|
|
490
672
|
this.mcpConnections = {};
|
|
491
|
-
this._callbackUrls = [];
|
|
492
673
|
this._didWarnAboutUnstableGetAITools = false;
|
|
493
674
|
this._connectionDisposables = /* @__PURE__ */ new Map();
|
|
675
|
+
this._isRestored = false;
|
|
494
676
|
this._onObservabilityEvent = new Emitter();
|
|
495
677
|
this.onObservabilityEvent = this._onObservabilityEvent.event;
|
|
496
|
-
this.
|
|
497
|
-
this.
|
|
678
|
+
this._onServerStateChanged = new Emitter();
|
|
679
|
+
this.onServerStateChanged = this._onServerStateChanged.event;
|
|
680
|
+
if (!options.storage) throw new Error("MCPClientManager requires a valid DurableObjectStorage instance");
|
|
681
|
+
this._storage = options.storage;
|
|
682
|
+
}
|
|
683
|
+
sql(query, ...bindings) {
|
|
684
|
+
return [...this._storage.sql.exec(query, ...bindings)];
|
|
685
|
+
}
|
|
686
|
+
saveServerToStorage(server) {
|
|
687
|
+
this.sql(`INSERT OR REPLACE INTO cf_agents_mcp_servers (
|
|
688
|
+
id, name, server_url, client_id, auth_url, callback_url, server_options
|
|
689
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?)`, server.id, server.name, server.server_url, server.client_id ?? null, server.auth_url ?? null, server.callback_url, server.server_options ?? null);
|
|
690
|
+
}
|
|
691
|
+
removeServerFromStorage(serverId) {
|
|
692
|
+
this.sql("DELETE FROM cf_agents_mcp_servers WHERE id = ?", serverId);
|
|
693
|
+
}
|
|
694
|
+
getServersFromStorage() {
|
|
695
|
+
return this.sql("SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers");
|
|
696
|
+
}
|
|
697
|
+
clearServerAuthUrl(serverId) {
|
|
698
|
+
this.sql("UPDATE cf_agents_mcp_servers SET auth_url = NULL WHERE id = ?", serverId);
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Create an auth provider for a server
|
|
702
|
+
* @internal
|
|
703
|
+
*/
|
|
704
|
+
createAuthProvider(serverId, callbackUrl, clientName, clientId) {
|
|
705
|
+
if (!this._storage) throw new Error("Cannot create auth provider: storage is not initialized");
|
|
706
|
+
const authProvider = new DurableObjectOAuthClientProvider(this._storage, clientName, callbackUrl);
|
|
707
|
+
authProvider.serverId = serverId;
|
|
708
|
+
if (clientId) authProvider.clientId = clientId;
|
|
709
|
+
return authProvider;
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Restore MCP server connections from storage
|
|
713
|
+
* This method is called on Agent initialization to restore previously connected servers
|
|
714
|
+
*
|
|
715
|
+
* @param clientName Name to use for OAuth client (typically the agent instance name)
|
|
716
|
+
*/
|
|
717
|
+
async restoreConnectionsFromStorage(clientName) {
|
|
718
|
+
if (this._isRestored) return;
|
|
719
|
+
const servers = this.getServersFromStorage();
|
|
720
|
+
if (!servers || servers.length === 0) {
|
|
721
|
+
this._isRestored = true;
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
for (const server of servers) {
|
|
725
|
+
const existingConn = this.mcpConnections[server.id];
|
|
726
|
+
if (existingConn) {
|
|
727
|
+
if (existingConn.connectionState === MCPConnectionState.READY) {
|
|
728
|
+
console.warn(`[MCPClientManager] Server ${server.id} already has a ready connection. Skipping recreation.`);
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
if (existingConn.connectionState === MCPConnectionState.AUTHENTICATING || existingConn.connectionState === MCPConnectionState.CONNECTING || existingConn.connectionState === MCPConnectionState.DISCOVERING) continue;
|
|
732
|
+
if (existingConn.connectionState === MCPConnectionState.FAILED) {
|
|
733
|
+
try {
|
|
734
|
+
await existingConn.client.close();
|
|
735
|
+
} catch (error) {
|
|
736
|
+
console.warn(`[MCPClientManager] Error closing failed connection ${server.id}:`, error);
|
|
737
|
+
}
|
|
738
|
+
delete this.mcpConnections[server.id];
|
|
739
|
+
this._connectionDisposables.get(server.id)?.dispose();
|
|
740
|
+
this._connectionDisposables.delete(server.id);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
const parsedOptions = server.server_options ? JSON.parse(server.server_options) : null;
|
|
744
|
+
const authProvider = this.createAuthProvider(server.id, server.callback_url, clientName, server.client_id ?? void 0);
|
|
745
|
+
const conn = this.createConnection(server.id, server.server_url, {
|
|
746
|
+
client: parsedOptions?.client ?? {},
|
|
747
|
+
transport: {
|
|
748
|
+
...parsedOptions?.transport ?? {},
|
|
749
|
+
type: parsedOptions?.transport?.type ?? "auto",
|
|
750
|
+
authProvider
|
|
751
|
+
}
|
|
752
|
+
});
|
|
753
|
+
if (server.auth_url) {
|
|
754
|
+
conn.connectionState = MCPConnectionState.AUTHENTICATING;
|
|
755
|
+
continue;
|
|
756
|
+
}
|
|
757
|
+
this._restoreServer(server.id);
|
|
758
|
+
}
|
|
759
|
+
this._isRestored = true;
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Internal method to restore a single server connection and discovery
|
|
763
|
+
*/
|
|
764
|
+
async _restoreServer(serverId) {
|
|
765
|
+
if ((await this.connectToServer(serverId).catch((error) => {
|
|
766
|
+
console.error(`Error connecting to ${serverId}:`, error);
|
|
767
|
+
return null;
|
|
768
|
+
}))?.state === MCPConnectionState.CONNECTED) {
|
|
769
|
+
const discoverResult = await this.discoverIfConnected(serverId);
|
|
770
|
+
if (discoverResult && !discoverResult.success) console.error(`Error discovering ${serverId}:`, discoverResult.error);
|
|
771
|
+
}
|
|
498
772
|
}
|
|
499
773
|
/**
|
|
500
774
|
* Connect to and register an MCP server
|
|
501
775
|
*
|
|
502
|
-
* @
|
|
503
|
-
*
|
|
504
|
-
*
|
|
776
|
+
* @deprecated This method is maintained for backward compatibility.
|
|
777
|
+
* For new code, use registerServer() and connectToServer() separately.
|
|
778
|
+
*
|
|
779
|
+
* @param url Server URL
|
|
780
|
+
* @param options Connection options
|
|
781
|
+
* @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)
|
|
505
782
|
*/
|
|
506
783
|
async connect(url, options = {}) {
|
|
507
784
|
/**
|
|
@@ -511,10 +788,7 @@ var MCPClientManager = class {
|
|
|
511
788
|
* .connect() is called on at least one server.
|
|
512
789
|
* So it's safe to delay loading it until .connect() is called.
|
|
513
790
|
*/
|
|
514
|
-
|
|
515
|
-
const { jsonSchema } = await import("ai");
|
|
516
|
-
this.jsonSchema = jsonSchema;
|
|
517
|
-
}
|
|
791
|
+
await this.ensureJsonSchema();
|
|
518
792
|
const id = options.reconnect?.id ?? nanoid(8);
|
|
519
793
|
if (options.transport?.authProvider) {
|
|
520
794
|
options.transport.authProvider.serverId = id;
|
|
@@ -543,7 +817,7 @@ var MCPClientManager = class {
|
|
|
543
817
|
await this.mcpConnections[id].init();
|
|
544
818
|
if (options.reconnect?.oauthCode) try {
|
|
545
819
|
await this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);
|
|
546
|
-
await this.mcpConnections[id].
|
|
820
|
+
await this.mcpConnections[id].init();
|
|
547
821
|
} catch (error) {
|
|
548
822
|
this._onObservabilityEvent.fire({
|
|
549
823
|
type: "mcp:client:connect",
|
|
@@ -560,57 +834,230 @@ var MCPClientManager = class {
|
|
|
560
834
|
throw error;
|
|
561
835
|
}
|
|
562
836
|
const authUrl = options.transport?.authProvider?.authUrl;
|
|
563
|
-
if (this.mcpConnections[id].connectionState ===
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
837
|
+
if (this.mcpConnections[id].connectionState === MCPConnectionState.AUTHENTICATING && authUrl && options.transport?.authProvider?.redirectUrl) return {
|
|
838
|
+
authUrl,
|
|
839
|
+
clientId: options.transport?.authProvider?.clientId,
|
|
840
|
+
id
|
|
841
|
+
};
|
|
842
|
+
const discoverResult = await this.discoverIfConnected(id);
|
|
843
|
+
if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover server capabilities: ${discoverResult.error}`);
|
|
844
|
+
return { id };
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Create an in-memory connection object and set up observability
|
|
848
|
+
* Does NOT save to storage - use registerServer() for that
|
|
849
|
+
* @returns The connection object (existing or newly created)
|
|
850
|
+
*/
|
|
851
|
+
createConnection(id, url, options) {
|
|
852
|
+
if (this.mcpConnections[id]) return this.mcpConnections[id];
|
|
853
|
+
const normalizedTransport = {
|
|
854
|
+
...options.transport,
|
|
855
|
+
type: options.transport?.type ?? "auto"
|
|
856
|
+
};
|
|
857
|
+
this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
|
|
858
|
+
name: this._name,
|
|
859
|
+
version: this._version
|
|
860
|
+
}, {
|
|
861
|
+
client: {
|
|
862
|
+
...defaultClientOptions,
|
|
863
|
+
...options.client
|
|
864
|
+
},
|
|
865
|
+
transport: normalizedTransport
|
|
866
|
+
});
|
|
867
|
+
const store = new DisposableStore();
|
|
868
|
+
const existing = this._connectionDisposables.get(id);
|
|
869
|
+
if (existing) existing.dispose();
|
|
870
|
+
this._connectionDisposables.set(id, store);
|
|
871
|
+
store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
|
|
872
|
+
this._onObservabilityEvent.fire(event);
|
|
873
|
+
}));
|
|
874
|
+
return this.mcpConnections[id];
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* Register an MCP server connection without connecting
|
|
878
|
+
* Creates the connection object, sets up observability, and saves to storage
|
|
879
|
+
*
|
|
880
|
+
* @param id Server ID
|
|
881
|
+
* @param options Registration options including URL, name, callback URL, and connection config
|
|
882
|
+
* @returns Server ID
|
|
883
|
+
*/
|
|
884
|
+
async registerServer(id, options) {
|
|
885
|
+
this.createConnection(id, options.url, {
|
|
886
|
+
client: options.client,
|
|
887
|
+
transport: {
|
|
888
|
+
...options.transport,
|
|
889
|
+
type: options.transport?.type ?? "auto"
|
|
890
|
+
}
|
|
891
|
+
});
|
|
892
|
+
const { authProvider: _, ...transportWithoutAuth } = options.transport ?? {};
|
|
893
|
+
this.saveServerToStorage({
|
|
894
|
+
id,
|
|
895
|
+
name: options.name,
|
|
896
|
+
server_url: options.url,
|
|
897
|
+
callback_url: options.callbackUrl,
|
|
898
|
+
client_id: options.clientId ?? null,
|
|
899
|
+
auth_url: options.authUrl ?? null,
|
|
900
|
+
server_options: JSON.stringify({
|
|
901
|
+
client: options.client,
|
|
902
|
+
transport: transportWithoutAuth
|
|
903
|
+
})
|
|
904
|
+
});
|
|
905
|
+
this._onServerStateChanged.fire();
|
|
906
|
+
return id;
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Connect to an already registered MCP server and initialize the connection.
|
|
910
|
+
*
|
|
911
|
+
* For OAuth servers, returns `{ state: "authenticating", authUrl, clientId? }`.
|
|
912
|
+
* The user must complete the OAuth flow via the authUrl, which triggers a
|
|
913
|
+
* callback handled by `handleCallbackRequest()`.
|
|
914
|
+
*
|
|
915
|
+
* For non-OAuth servers, establishes the transport connection and returns
|
|
916
|
+
* `{ state: "connected" }`. Call `discoverIfConnected()` afterwards to
|
|
917
|
+
* discover capabilities and transition to "ready" state.
|
|
918
|
+
*
|
|
919
|
+
* @param id Server ID (must be registered first via registerServer())
|
|
920
|
+
* @returns Connection result with current state and OAuth info (if applicable)
|
|
921
|
+
*/
|
|
922
|
+
async connectToServer(id) {
|
|
923
|
+
const conn = this.mcpConnections[id];
|
|
924
|
+
if (!conn) throw new Error(`Server ${id} is not registered. Call registerServer() first.`);
|
|
925
|
+
const error = await conn.init();
|
|
926
|
+
this._onServerStateChanged.fire();
|
|
927
|
+
switch (conn.connectionState) {
|
|
928
|
+
case MCPConnectionState.FAILED: return {
|
|
929
|
+
state: conn.connectionState,
|
|
930
|
+
error: error ?? "Unknown connection error"
|
|
931
|
+
};
|
|
932
|
+
case MCPConnectionState.AUTHENTICATING: {
|
|
933
|
+
const authUrl = conn.options.transport.authProvider?.authUrl;
|
|
934
|
+
const redirectUrl = conn.options.transport.authProvider?.redirectUrl;
|
|
935
|
+
if (!authUrl || !redirectUrl) return {
|
|
936
|
+
state: MCPConnectionState.FAILED,
|
|
937
|
+
error: `OAuth configuration incomplete: missing ${!authUrl ? "authUrl" : "redirectUrl"}`
|
|
938
|
+
};
|
|
939
|
+
const clientId = conn.options.transport.authProvider?.clientId;
|
|
940
|
+
const serverRow = this.getServersFromStorage().find((s) => s.id === id);
|
|
941
|
+
if (serverRow) {
|
|
942
|
+
this.saveServerToStorage({
|
|
943
|
+
...serverRow,
|
|
944
|
+
auth_url: authUrl,
|
|
945
|
+
client_id: clientId ?? null
|
|
946
|
+
});
|
|
947
|
+
this._onServerStateChanged.fire();
|
|
948
|
+
}
|
|
949
|
+
return {
|
|
950
|
+
state: conn.connectionState,
|
|
951
|
+
authUrl,
|
|
952
|
+
clientId
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
case MCPConnectionState.CONNECTED: return { state: conn.connectionState };
|
|
956
|
+
default: return {
|
|
957
|
+
state: MCPConnectionState.FAILED,
|
|
958
|
+
error: `Unexpected connection state after init: ${conn.connectionState}`
|
|
569
959
|
};
|
|
570
960
|
}
|
|
571
|
-
|
|
961
|
+
}
|
|
962
|
+
extractServerIdFromState(state) {
|
|
963
|
+
if (!state) return null;
|
|
964
|
+
const parts = state.split(".");
|
|
965
|
+
return parts.length === 2 ? parts[1] : null;
|
|
572
966
|
}
|
|
573
967
|
isCallbackRequest(req) {
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
968
|
+
if (req.method !== "GET") return false;
|
|
969
|
+
if (!req.url.includes("/callback")) return false;
|
|
970
|
+
const state = new URL(req.url).searchParams.get("state");
|
|
971
|
+
const serverId = this.extractServerIdFromState(state);
|
|
972
|
+
if (!serverId) return false;
|
|
973
|
+
return this.getServersFromStorage().some((server) => server.id === serverId);
|
|
577
974
|
}
|
|
578
975
|
async handleCallbackRequest(req) {
|
|
579
976
|
const url = new URL(req.url);
|
|
580
|
-
const urlMatch = this._callbackUrls.find((url$1) => {
|
|
581
|
-
return req.url.startsWith(url$1);
|
|
582
|
-
});
|
|
583
|
-
if (!urlMatch) throw new Error(`No callback URI match found for the request url: ${req.url}. Was the request matched with \`isCallbackRequest()\`?`);
|
|
584
977
|
const code = url.searchParams.get("code");
|
|
585
978
|
const state = url.searchParams.get("state");
|
|
586
|
-
const
|
|
587
|
-
const
|
|
588
|
-
if (!code) throw new Error("Unauthorized: no code provided");
|
|
979
|
+
const error = url.searchParams.get("error");
|
|
980
|
+
const errorDescription = url.searchParams.get("error_description");
|
|
589
981
|
if (!state) throw new Error("Unauthorized: no state provided");
|
|
982
|
+
const serverId = this.extractServerIdFromState(state);
|
|
983
|
+
if (!serverId) throw new Error("No serverId found in state parameter. Expected format: {nonce}.{serverId}");
|
|
984
|
+
if (!this.getServersFromStorage().some((server) => server.id === serverId)) throw new Error(`No server found with id "${serverId}". Was the request matched with \`isCallbackRequest()\`?`);
|
|
590
985
|
if (this.mcpConnections[serverId] === void 0) throw new Error(`Could not find serverId: ${serverId}`);
|
|
591
|
-
if (this.mcpConnections[serverId].connectionState !== "authenticating") throw new Error("Failed to authenticate: the client isn't in the `authenticating` state");
|
|
592
986
|
const conn = this.mcpConnections[serverId];
|
|
593
987
|
if (!conn.options.transport.authProvider) throw new Error("Trying to finalize authentication for a server connection without an authProvider");
|
|
594
|
-
const
|
|
595
|
-
|
|
596
|
-
|
|
988
|
+
const authProvider = conn.options.transport.authProvider;
|
|
989
|
+
authProvider.serverId = serverId;
|
|
990
|
+
const stateValidation = await authProvider.checkState(state);
|
|
991
|
+
if (!stateValidation.valid) throw new Error(`Invalid state: ${stateValidation.error}`);
|
|
992
|
+
if (error) return {
|
|
993
|
+
serverId,
|
|
994
|
+
authSuccess: false,
|
|
995
|
+
authError: errorDescription || error
|
|
996
|
+
};
|
|
997
|
+
if (!code) throw new Error("Unauthorized: no code provided");
|
|
998
|
+
if (this.mcpConnections[serverId].connectionState === MCPConnectionState.READY || this.mcpConnections[serverId].connectionState === MCPConnectionState.CONNECTED) {
|
|
999
|
+
this.clearServerAuthUrl(serverId);
|
|
1000
|
+
return {
|
|
1001
|
+
serverId,
|
|
1002
|
+
authSuccess: true
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
if (this.mcpConnections[serverId].connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error(`Failed to authenticate: the client is in "${this.mcpConnections[serverId].connectionState}" state, expected "authenticating"`);
|
|
597
1006
|
try {
|
|
1007
|
+
await authProvider.consumeState(state);
|
|
598
1008
|
await conn.completeAuthorization(code);
|
|
1009
|
+
await authProvider.deleteCodeVerifier();
|
|
1010
|
+
this.clearServerAuthUrl(serverId);
|
|
1011
|
+
this._onServerStateChanged.fire();
|
|
599
1012
|
return {
|
|
600
1013
|
serverId,
|
|
601
1014
|
authSuccess: true
|
|
602
1015
|
};
|
|
603
|
-
} catch (
|
|
1016
|
+
} catch (authError) {
|
|
1017
|
+
const errorMessage = authError instanceof Error ? authError.message : String(authError);
|
|
1018
|
+
this._onServerStateChanged.fire();
|
|
604
1019
|
return {
|
|
605
1020
|
serverId,
|
|
606
1021
|
authSuccess: false,
|
|
607
|
-
authError:
|
|
1022
|
+
authError: errorMessage
|
|
608
1023
|
};
|
|
609
1024
|
}
|
|
610
1025
|
}
|
|
611
1026
|
/**
|
|
1027
|
+
* Discover server capabilities if connection is in CONNECTED or READY state.
|
|
1028
|
+
* Transitions to DISCOVERING then READY (or CONNECTED on error).
|
|
1029
|
+
* Can be called to refresh server capabilities (e.g., from a UI refresh button).
|
|
1030
|
+
*
|
|
1031
|
+
* If called while a previous discovery is in-flight for the same server,
|
|
1032
|
+
* the previous discovery will be aborted.
|
|
1033
|
+
*
|
|
1034
|
+
* @param serverId The server ID to discover
|
|
1035
|
+
* @param options Optional configuration
|
|
1036
|
+
* @param options.timeoutMs Timeout in milliseconds (default: 30000)
|
|
1037
|
+
* @returns Result with current state and optional error, or undefined if connection not found
|
|
1038
|
+
*/
|
|
1039
|
+
async discoverIfConnected(serverId, options = {}) {
|
|
1040
|
+
const conn = this.mcpConnections[serverId];
|
|
1041
|
+
if (!conn) {
|
|
1042
|
+
this._onObservabilityEvent.fire({
|
|
1043
|
+
type: "mcp:client:discover",
|
|
1044
|
+
displayMessage: `Connection not found for ${serverId}`,
|
|
1045
|
+
payload: {},
|
|
1046
|
+
timestamp: Date.now(),
|
|
1047
|
+
id: nanoid()
|
|
1048
|
+
});
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
const result = await conn.discover(options);
|
|
1052
|
+
this._onServerStateChanged.fire();
|
|
1053
|
+
return {
|
|
1054
|
+
...result,
|
|
1055
|
+
state: conn.connectionState
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
612
1059
|
* Establish connection in the background after OAuth completion
|
|
613
|
-
* This method
|
|
1060
|
+
* This method connects to the server and discovers its capabilities
|
|
614
1061
|
* @param serverId The server ID to establish connection for
|
|
615
1062
|
*/
|
|
616
1063
|
async establishConnection(serverId) {
|
|
@@ -625,38 +1072,34 @@ var MCPClientManager = class {
|
|
|
625
1072
|
});
|
|
626
1073
|
return;
|
|
627
1074
|
}
|
|
628
|
-
|
|
629
|
-
await conn.establishConnection();
|
|
630
|
-
this._onConnected.fire(serverId);
|
|
631
|
-
} catch (error) {
|
|
632
|
-
const url = conn.url.toString();
|
|
1075
|
+
if (conn.connectionState === MCPConnectionState.DISCOVERING || conn.connectionState === MCPConnectionState.READY) {
|
|
633
1076
|
this._onObservabilityEvent.fire({
|
|
634
1077
|
type: "mcp:client:connect",
|
|
635
|
-
displayMessage: `
|
|
1078
|
+
displayMessage: `establishConnection skipped for ${serverId}, already in ${conn.connectionState} state`,
|
|
636
1079
|
payload: {
|
|
637
|
-
url,
|
|
638
|
-
transport: conn.options.transport.type
|
|
639
|
-
state: conn.connectionState
|
|
640
|
-
error: toErrorMessage(error)
|
|
1080
|
+
url: conn.url.toString(),
|
|
1081
|
+
transport: conn.options.transport.type || "unknown",
|
|
1082
|
+
state: conn.connectionState
|
|
641
1083
|
},
|
|
642
1084
|
timestamp: Date.now(),
|
|
643
1085
|
id: nanoid()
|
|
644
1086
|
});
|
|
1087
|
+
return;
|
|
645
1088
|
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
1089
|
+
const connectResult = await this.connectToServer(serverId);
|
|
1090
|
+
this._onServerStateChanged.fire();
|
|
1091
|
+
if (connectResult.state === MCPConnectionState.CONNECTED) await this.discoverIfConnected(serverId);
|
|
1092
|
+
this._onObservabilityEvent.fire({
|
|
1093
|
+
type: "mcp:client:connect",
|
|
1094
|
+
displayMessage: `establishConnection completed for ${serverId}, final state: ${conn.connectionState}`,
|
|
1095
|
+
payload: {
|
|
1096
|
+
url: conn.url.toString(),
|
|
1097
|
+
transport: conn.options.transport.type || "unknown",
|
|
1098
|
+
state: conn.connectionState
|
|
1099
|
+
},
|
|
1100
|
+
timestamp: Date.now(),
|
|
1101
|
+
id: nanoid()
|
|
1102
|
+
});
|
|
660
1103
|
}
|
|
661
1104
|
/**
|
|
662
1105
|
* Configure OAuth callback handling
|
|
@@ -679,9 +1122,28 @@ var MCPClientManager = class {
|
|
|
679
1122
|
return getNamespacedData(this.mcpConnections, "tools");
|
|
680
1123
|
}
|
|
681
1124
|
/**
|
|
1125
|
+
* Lazy-loads the jsonSchema function from the AI SDK.
|
|
1126
|
+
*
|
|
1127
|
+
* This defers importing the "ai" package until it's actually needed, which helps reduce
|
|
1128
|
+
* initial bundle size and startup time. The jsonSchema function is required for converting
|
|
1129
|
+
* MCP tools into AI SDK tool definitions via getAITools().
|
|
1130
|
+
*
|
|
1131
|
+
* @internal This method is for internal use only. It's automatically called before operations
|
|
1132
|
+
* that need jsonSchema (like getAITools() or OAuth flows). External consumers should not need
|
|
1133
|
+
* to call this directly.
|
|
1134
|
+
*/
|
|
1135
|
+
async ensureJsonSchema() {
|
|
1136
|
+
if (!this.jsonSchema) {
|
|
1137
|
+
const { jsonSchema } = await import("ai");
|
|
1138
|
+
this.jsonSchema = jsonSchema;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
682
1142
|
* @returns a set of tools that you can use with the AI SDK
|
|
683
1143
|
*/
|
|
684
1144
|
getAITools() {
|
|
1145
|
+
if (!this.jsonSchema) throw new Error("jsonSchema not initialized.");
|
|
1146
|
+
for (const [id, conn] of Object.entries(this.mcpConnections)) if (conn.connectionState !== MCPConnectionState.READY && conn.connectionState !== MCPConnectionState.AUTHENTICATING) console.warn(`[getAITools] WARNING: Reading tools from connection ${id} in state "${conn.connectionState}". Tools may not be loaded yet.`);
|
|
685
1147
|
return Object.fromEntries(getNamespacedData(this.mcpConnections, "tools").map((tool) => {
|
|
686
1148
|
return [`tool_${tool.serverId.replace(/-/g, "")}_${tool.name}`, {
|
|
687
1149
|
description: tool.description,
|
|
@@ -711,10 +1173,18 @@ var MCPClientManager = class {
|
|
|
711
1173
|
return this.getAITools();
|
|
712
1174
|
}
|
|
713
1175
|
/**
|
|
714
|
-
* Closes all connections to MCP servers
|
|
1176
|
+
* Closes all active in-memory connections to MCP servers.
|
|
1177
|
+
*
|
|
1178
|
+
* Note: This only closes the transport connections - it does NOT remove
|
|
1179
|
+
* servers from storage. Servers will still be listed and their callback
|
|
1180
|
+
* URLs will still match incoming OAuth requests.
|
|
1181
|
+
*
|
|
1182
|
+
* Use removeServer() instead if you want to fully clean up a server
|
|
1183
|
+
* (closes connection AND removes from storage).
|
|
715
1184
|
*/
|
|
716
1185
|
async closeAllConnections() {
|
|
717
1186
|
const ids = Object.keys(this.mcpConnections);
|
|
1187
|
+
for (const id of ids) this.mcpConnections[id].cancelDiscovery();
|
|
718
1188
|
await Promise.all(ids.map(async (id) => {
|
|
719
1189
|
await this.mcpConnections[id].client.close();
|
|
720
1190
|
}));
|
|
@@ -731,6 +1201,7 @@ var MCPClientManager = class {
|
|
|
731
1201
|
*/
|
|
732
1202
|
async closeConnection(id) {
|
|
733
1203
|
if (!this.mcpConnections[id]) throw new Error(`Connection with id "${id}" does not exist.`);
|
|
1204
|
+
this.mcpConnections[id].cancelDiscovery();
|
|
734
1205
|
await this.mcpConnections[id].client.close();
|
|
735
1206
|
delete this.mcpConnections[id];
|
|
736
1207
|
const store = this._connectionDisposables.get(id);
|
|
@@ -738,13 +1209,29 @@ var MCPClientManager = class {
|
|
|
738
1209
|
this._connectionDisposables.delete(id);
|
|
739
1210
|
}
|
|
740
1211
|
/**
|
|
1212
|
+
* Remove an MCP server - closes connection if active and removes from storage.
|
|
1213
|
+
*/
|
|
1214
|
+
async removeServer(serverId) {
|
|
1215
|
+
if (this.mcpConnections[serverId]) try {
|
|
1216
|
+
await this.closeConnection(serverId);
|
|
1217
|
+
} catch (_e) {}
|
|
1218
|
+
this.removeServerFromStorage(serverId);
|
|
1219
|
+
this._onServerStateChanged.fire();
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* List all MCP servers from storage
|
|
1223
|
+
*/
|
|
1224
|
+
listServers() {
|
|
1225
|
+
return this.getServersFromStorage();
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
741
1228
|
* Dispose the manager and all resources.
|
|
742
1229
|
*/
|
|
743
1230
|
async dispose() {
|
|
744
1231
|
try {
|
|
745
1232
|
await this.closeAllConnections();
|
|
746
1233
|
} finally {
|
|
747
|
-
this.
|
|
1234
|
+
this._onServerStateChanged.dispose();
|
|
748
1235
|
this._onObservabilityEvent.dispose();
|
|
749
1236
|
}
|
|
750
1237
|
}
|
|
@@ -806,96 +1293,7 @@ function getNamespacedData(mcpClients, type) {
|
|
|
806
1293
|
}
|
|
807
1294
|
|
|
808
1295
|
//#endregion
|
|
809
|
-
//#region ../agents/dist/
|
|
810
|
-
var DurableObjectOAuthClientProvider = class {
|
|
811
|
-
constructor(storage, clientName, baseRedirectUrl) {
|
|
812
|
-
this.storage = storage;
|
|
813
|
-
this.clientName = clientName;
|
|
814
|
-
this.baseRedirectUrl = baseRedirectUrl;
|
|
815
|
-
}
|
|
816
|
-
get clientMetadata() {
|
|
817
|
-
return {
|
|
818
|
-
client_name: this.clientName,
|
|
819
|
-
client_uri: this.clientUri,
|
|
820
|
-
grant_types: ["authorization_code", "refresh_token"],
|
|
821
|
-
redirect_uris: [this.redirectUrl],
|
|
822
|
-
response_types: ["code"],
|
|
823
|
-
token_endpoint_auth_method: "none"
|
|
824
|
-
};
|
|
825
|
-
}
|
|
826
|
-
get clientUri() {
|
|
827
|
-
return new URL(this.redirectUrl).origin;
|
|
828
|
-
}
|
|
829
|
-
get redirectUrl() {
|
|
830
|
-
return `${this.baseRedirectUrl}/${this.serverId}`;
|
|
831
|
-
}
|
|
832
|
-
get clientId() {
|
|
833
|
-
if (!this._clientId_) throw new Error("Trying to access clientId before it was set");
|
|
834
|
-
return this._clientId_;
|
|
835
|
-
}
|
|
836
|
-
set clientId(clientId_) {
|
|
837
|
-
this._clientId_ = clientId_;
|
|
838
|
-
}
|
|
839
|
-
get serverId() {
|
|
840
|
-
if (!this._serverId_) throw new Error("Trying to access serverId before it was set");
|
|
841
|
-
return this._serverId_;
|
|
842
|
-
}
|
|
843
|
-
set serverId(serverId_) {
|
|
844
|
-
this._serverId_ = serverId_;
|
|
845
|
-
}
|
|
846
|
-
keyPrefix(clientId) {
|
|
847
|
-
return `/${this.clientName}/${this.serverId}/${clientId}`;
|
|
848
|
-
}
|
|
849
|
-
clientInfoKey(clientId) {
|
|
850
|
-
return `${this.keyPrefix(clientId)}/client_info/`;
|
|
851
|
-
}
|
|
852
|
-
async clientInformation() {
|
|
853
|
-
if (!this._clientId_) return;
|
|
854
|
-
return await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;
|
|
855
|
-
}
|
|
856
|
-
async saveClientInformation(clientInformation) {
|
|
857
|
-
await this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);
|
|
858
|
-
this.clientId = clientInformation.client_id;
|
|
859
|
-
}
|
|
860
|
-
tokenKey(clientId) {
|
|
861
|
-
return `${this.keyPrefix(clientId)}/token`;
|
|
862
|
-
}
|
|
863
|
-
async tokens() {
|
|
864
|
-
if (!this._clientId_) return;
|
|
865
|
-
return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
|
|
866
|
-
}
|
|
867
|
-
async saveTokens(tokens) {
|
|
868
|
-
await this.storage.put(this.tokenKey(this.clientId), tokens);
|
|
869
|
-
}
|
|
870
|
-
get authUrl() {
|
|
871
|
-
return this._authUrl_;
|
|
872
|
-
}
|
|
873
|
-
/**
|
|
874
|
-
* Because this operates on the server side (but we need browser auth), we send this url back to the user
|
|
875
|
-
* and require user interact to initiate the redirect flow
|
|
876
|
-
*/
|
|
877
|
-
async redirectToAuthorization(authUrl) {
|
|
878
|
-
const stateToken = nanoid();
|
|
879
|
-
authUrl.searchParams.set("state", stateToken);
|
|
880
|
-
this._authUrl_ = authUrl.toString();
|
|
881
|
-
}
|
|
882
|
-
codeVerifierKey(clientId) {
|
|
883
|
-
return `${this.keyPrefix(clientId)}/code_verifier`;
|
|
884
|
-
}
|
|
885
|
-
async saveCodeVerifier(verifier) {
|
|
886
|
-
const key = this.codeVerifierKey(this.clientId);
|
|
887
|
-
if (await this.storage.get(key)) return;
|
|
888
|
-
await this.storage.put(key, verifier);
|
|
889
|
-
}
|
|
890
|
-
async codeVerifier() {
|
|
891
|
-
const codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));
|
|
892
|
-
if (!codeVerifier) throw new Error("No code verifier found");
|
|
893
|
-
return codeVerifier;
|
|
894
|
-
}
|
|
895
|
-
};
|
|
896
|
-
|
|
897
|
-
//#endregion
|
|
898
|
-
//#region ../agents/dist/src-CTtjSFyX.js
|
|
1296
|
+
//#region ../agents/dist/src-BZDh910Z.js
|
|
899
1297
|
/**
|
|
900
1298
|
* A generic observability implementation that logs events to the console.
|
|
901
1299
|
*/
|
|
@@ -933,7 +1331,6 @@ function getNextCronTime(cron) {
|
|
|
933
1331
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
934
1332
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
935
1333
|
const DEFAULT_STATE = {};
|
|
936
|
-
const agentContext = new AsyncLocalStorage();
|
|
937
1334
|
function getCurrentAgent() {
|
|
938
1335
|
const store = agentContext.getStore();
|
|
939
1336
|
if (!store) return {
|
|
@@ -1014,8 +1411,8 @@ var Agent = class Agent$1 extends Server {
|
|
|
1014
1411
|
super(ctx, env$1);
|
|
1015
1412
|
this._state = DEFAULT_STATE;
|
|
1016
1413
|
this._disposables = new DisposableStore();
|
|
1414
|
+
this._destroyed = false;
|
|
1017
1415
|
this._ParentClass = Object.getPrototypeOf(this).constructor;
|
|
1018
|
-
this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
1019
1416
|
this.initialState = DEFAULT_STATE;
|
|
1020
1417
|
this.observability = genericObservability;
|
|
1021
1418
|
this._flushingQueue = false;
|
|
@@ -1053,27 +1450,37 @@ var Agent = class Agent$1 extends Server {
|
|
|
1053
1450
|
}
|
|
1054
1451
|
});
|
|
1055
1452
|
if (row.type === "cron") {
|
|
1453
|
+
if (this._destroyed) return;
|
|
1056
1454
|
const nextExecutionTime = getNextCronTime(row.cron);
|
|
1057
1455
|
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
1058
1456
|
this.sql`
|
|
1059
1457
|
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
1060
1458
|
`;
|
|
1061
|
-
} else
|
|
1459
|
+
} else {
|
|
1460
|
+
if (this._destroyed) return;
|
|
1461
|
+
this.sql`
|
|
1062
1462
|
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
1063
1463
|
`;
|
|
1464
|
+
}
|
|
1064
1465
|
}
|
|
1466
|
+
if (this._destroyed) return;
|
|
1065
1467
|
await this._scheduleNextAlarm();
|
|
1066
1468
|
};
|
|
1067
1469
|
if (!wrappedClasses.has(this.constructor)) {
|
|
1068
1470
|
this._autoWrapCustomMethods();
|
|
1069
1471
|
wrappedClasses.add(this.constructor);
|
|
1070
1472
|
}
|
|
1071
|
-
this.
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1473
|
+
this.sql`
|
|
1474
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
1475
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1476
|
+
name TEXT NOT NULL,
|
|
1477
|
+
server_url TEXT NOT NULL,
|
|
1478
|
+
callback_url TEXT NOT NULL,
|
|
1479
|
+
client_id TEXT,
|
|
1480
|
+
auth_url TEXT,
|
|
1481
|
+
server_options TEXT
|
|
1482
|
+
)
|
|
1483
|
+
`;
|
|
1077
1484
|
this.sql`
|
|
1078
1485
|
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
1079
1486
|
id TEXT PRIMARY KEY NOT NULL,
|
|
@@ -1088,34 +1495,25 @@ var Agent = class Agent$1 extends Server {
|
|
|
1088
1495
|
created_at INTEGER DEFAULT (unixepoch())
|
|
1089
1496
|
)
|
|
1090
1497
|
`;
|
|
1091
|
-
this.ctx.blockConcurrencyWhile(async () => {
|
|
1092
|
-
return this._tryCatch(async () => {
|
|
1093
|
-
this.sql`
|
|
1094
|
-
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
1095
|
-
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
1096
|
-
callback TEXT,
|
|
1097
|
-
payload TEXT,
|
|
1098
|
-
type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
|
|
1099
|
-
time INTEGER,
|
|
1100
|
-
delayInSeconds INTEGER,
|
|
1101
|
-
cron TEXT,
|
|
1102
|
-
created_at INTEGER DEFAULT (unixepoch())
|
|
1103
|
-
)
|
|
1104
|
-
`;
|
|
1105
|
-
await this.alarm();
|
|
1106
|
-
});
|
|
1107
|
-
});
|
|
1108
1498
|
this.sql`
|
|
1109
|
-
CREATE TABLE IF NOT EXISTS
|
|
1110
|
-
id TEXT PRIMARY KEY NOT NULL,
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1499
|
+
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
1500
|
+
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
1501
|
+
callback TEXT,
|
|
1502
|
+
payload TEXT,
|
|
1503
|
+
type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
|
|
1504
|
+
time INTEGER,
|
|
1505
|
+
delayInSeconds INTEGER,
|
|
1506
|
+
cron TEXT,
|
|
1507
|
+
created_at INTEGER DEFAULT (unixepoch())
|
|
1117
1508
|
)
|
|
1118
1509
|
`;
|
|
1510
|
+
this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1", { storage: this.ctx.storage });
|
|
1511
|
+
this._disposables.add(this.mcp.onServerStateChanged(async () => {
|
|
1512
|
+
this.broadcastMcpServers();
|
|
1513
|
+
}));
|
|
1514
|
+
this._disposables.add(this.mcp.onObservabilityEvent((event) => {
|
|
1515
|
+
this.observability?.emit(event);
|
|
1516
|
+
}));
|
|
1119
1517
|
const _onRequest = this.onRequest.bind(this);
|
|
1120
1518
|
this.onRequest = (request) => {
|
|
1121
1519
|
return agentContext.run({
|
|
@@ -1124,8 +1522,9 @@ var Agent = class Agent$1 extends Server {
|
|
|
1124
1522
|
request,
|
|
1125
1523
|
email: void 0
|
|
1126
1524
|
}, async () => {
|
|
1127
|
-
|
|
1128
|
-
|
|
1525
|
+
await this.mcp.ensureJsonSchema();
|
|
1526
|
+
const oauthResponse = await this.handleMcpOAuthCallback(request);
|
|
1527
|
+
if (oauthResponse) return oauthResponse;
|
|
1129
1528
|
return this._tryCatch(() => _onRequest(request));
|
|
1130
1529
|
});
|
|
1131
1530
|
};
|
|
@@ -1137,6 +1536,7 @@ var Agent = class Agent$1 extends Server {
|
|
|
1137
1536
|
request: void 0,
|
|
1138
1537
|
email: void 0
|
|
1139
1538
|
}, async () => {
|
|
1539
|
+
await this.mcp.ensureJsonSchema();
|
|
1140
1540
|
if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
|
|
1141
1541
|
let parsed;
|
|
1142
1542
|
try {
|
|
@@ -1201,7 +1601,7 @@ var Agent = class Agent$1 extends Server {
|
|
|
1201
1601
|
connection,
|
|
1202
1602
|
request: ctx$1.request,
|
|
1203
1603
|
email: void 0
|
|
1204
|
-
}, () => {
|
|
1604
|
+
}, async () => {
|
|
1205
1605
|
if (this.state) connection.send(JSON.stringify({
|
|
1206
1606
|
state: this.state,
|
|
1207
1607
|
type: MessageType.CF_AGENT_STATE
|
|
@@ -1228,27 +1628,9 @@ var Agent = class Agent$1 extends Server {
|
|
|
1228
1628
|
request: void 0,
|
|
1229
1629
|
email: void 0
|
|
1230
1630
|
}, async () => {
|
|
1231
|
-
await this._tryCatch(() => {
|
|
1232
|
-
|
|
1233
|
-
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1234
|
-
`;
|
|
1631
|
+
await this._tryCatch(async () => {
|
|
1632
|
+
await this.mcp.restoreConnectionsFromStorage(this.name);
|
|
1235
1633
|
this.broadcastMcpServers();
|
|
1236
|
-
if (servers && Array.isArray(servers) && servers.length > 0) {
|
|
1237
|
-
servers.forEach((server) => {
|
|
1238
|
-
if (server.callback_url) this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
|
|
1239
|
-
});
|
|
1240
|
-
servers.forEach((server) => {
|
|
1241
|
-
this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, server.server_options ? JSON.parse(server.server_options) : void 0, {
|
|
1242
|
-
id: server.id,
|
|
1243
|
-
oauthClientId: server.client_id ?? void 0
|
|
1244
|
-
}).then(() => {
|
|
1245
|
-
this.broadcastMcpServers();
|
|
1246
|
-
}).catch((error) => {
|
|
1247
|
-
console.error(`Error connecting to MCP server: ${server.name} (${server.server_url})`, error);
|
|
1248
|
-
this.broadcastMcpServers();
|
|
1249
|
-
});
|
|
1250
|
-
});
|
|
1251
|
-
}
|
|
1252
1634
|
return _onStart(props);
|
|
1253
1635
|
});
|
|
1254
1636
|
});
|
|
@@ -1593,10 +1975,7 @@ var Agent = class Agent$1 extends Server {
|
|
|
1593
1975
|
const result = this.sql`
|
|
1594
1976
|
SELECT * FROM cf_agents_schedules WHERE id = ${id}
|
|
1595
1977
|
`;
|
|
1596
|
-
if (!result)
|
|
1597
|
-
console.error(`schedule ${id} not found`);
|
|
1598
|
-
return;
|
|
1599
|
-
}
|
|
1978
|
+
if (!result || result.length === 0) return;
|
|
1600
1979
|
return {
|
|
1601
1980
|
...result[0],
|
|
1602
1981
|
payload: JSON.parse(result[0].payload)
|
|
@@ -1633,11 +2012,12 @@ var Agent = class Agent$1 extends Server {
|
|
|
1633
2012
|
/**
|
|
1634
2013
|
* Cancel a scheduled task
|
|
1635
2014
|
* @param id ID of the task to cancel
|
|
1636
|
-
* @returns true if the task was cancelled, false
|
|
2015
|
+
* @returns true if the task was cancelled, false if the task was not found
|
|
1637
2016
|
*/
|
|
1638
2017
|
async cancelSchedule(id) {
|
|
1639
2018
|
const schedule = await this.getSchedule(id);
|
|
1640
|
-
if (schedule)
|
|
2019
|
+
if (!schedule) return false;
|
|
2020
|
+
this.observability?.emit({
|
|
1641
2021
|
displayMessage: `Schedule ${id} cancelled`,
|
|
1642
2022
|
id: nanoid(),
|
|
1643
2023
|
payload: {
|
|
@@ -1654,7 +2034,7 @@ var Agent = class Agent$1 extends Server {
|
|
|
1654
2034
|
async _scheduleNextAlarm() {
|
|
1655
2035
|
const result = this.sql`
|
|
1656
2036
|
SELECT time FROM cf_agents_schedules
|
|
1657
|
-
WHERE time
|
|
2037
|
+
WHERE time >= ${Math.floor(Date.now() / 1e3)}
|
|
1658
2038
|
ORDER BY time ASC
|
|
1659
2039
|
LIMIT 1
|
|
1660
2040
|
`;
|
|
@@ -1668,15 +2048,18 @@ var Agent = class Agent$1 extends Server {
|
|
|
1668
2048
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
1669
2049
|
*/
|
|
1670
2050
|
async destroy() {
|
|
2051
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
1671
2052
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
1672
2053
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
1673
|
-
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
1674
2054
|
this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
|
|
1675
2055
|
await this.ctx.storage.deleteAlarm();
|
|
1676
2056
|
await this.ctx.storage.deleteAll();
|
|
1677
2057
|
this._disposables.dispose();
|
|
1678
|
-
await this.mcp.dispose
|
|
1679
|
-
this.
|
|
2058
|
+
await this.mcp.dispose();
|
|
2059
|
+
this._destroyed = true;
|
|
2060
|
+
setTimeout(() => {
|
|
2061
|
+
this.ctx.abort("destroyed");
|
|
2062
|
+
}, 0);
|
|
1680
2063
|
this.observability?.emit({
|
|
1681
2064
|
displayMessage: "Agent destroyed",
|
|
1682
2065
|
id: nanoid(),
|
|
@@ -1700,7 +2083,8 @@ var Agent = class Agent$1 extends Server {
|
|
|
1700
2083
|
* @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
|
|
1701
2084
|
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
1702
2085
|
* @param options MCP client and transport options
|
|
1703
|
-
* @returns authUrl
|
|
2086
|
+
* @returns Server id and state - either "authenticating" with authUrl, or "ready"
|
|
2087
|
+
* @throws If connection or discovery fails
|
|
1704
2088
|
*/
|
|
1705
2089
|
async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
|
|
1706
2090
|
let resolvedCallbackHost = callbackHost;
|
|
@@ -1711,89 +2095,10 @@ var Agent = class Agent$1 extends Server {
|
|
|
1711
2095
|
resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
|
|
1712
2096
|
}
|
|
1713
2097
|
const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1717
|
-
VALUES (
|
|
1718
|
-
${serverId},
|
|
1719
|
-
${serverName},
|
|
1720
|
-
${url},
|
|
1721
|
-
${null},
|
|
1722
|
-
${null},
|
|
1723
|
-
${callbackUrl},
|
|
1724
|
-
${options ? JSON.stringify(options) : null}
|
|
1725
|
-
);
|
|
1726
|
-
`;
|
|
1727
|
-
const result = await this._connectToMcpServerInternal(serverName, url, callbackUrl, options, { id: serverId });
|
|
1728
|
-
if (result.clientId || result.authUrl) this.sql`
|
|
1729
|
-
UPDATE cf_agents_mcp_servers
|
|
1730
|
-
SET client_id = ${result.clientId ?? null}, auth_url = ${result.authUrl ?? null}
|
|
1731
|
-
WHERE id = ${serverId}
|
|
1732
|
-
`;
|
|
1733
|
-
this.broadcastMcpServers();
|
|
1734
|
-
return result;
|
|
1735
|
-
}
|
|
1736
|
-
/**
|
|
1737
|
-
* Handle potential OAuth callback requests after DO hibernation.
|
|
1738
|
-
* Detects OAuth callbacks, restores state from database, and processes the callback.
|
|
1739
|
-
* Returns a Response if this was an OAuth callback, otherwise returns undefined.
|
|
1740
|
-
*/
|
|
1741
|
-
async _handlePotentialOAuthCallback(request) {
|
|
1742
|
-
if (request.method !== "GET") return;
|
|
1743
|
-
const url = new URL(request.url);
|
|
1744
|
-
if (!(url.pathname.includes("/callback/") && url.searchParams.has("code"))) return;
|
|
1745
|
-
const pathParts = url.pathname.split("/");
|
|
1746
|
-
const callbackIndex = pathParts.indexOf("callback");
|
|
1747
|
-
const serverId = callbackIndex !== -1 ? pathParts[callbackIndex + 1] : null;
|
|
1748
|
-
if (!serverId) return new Response("Invalid callback URL: missing serverId", { status: 400 });
|
|
1749
|
-
if (this.mcp.isCallbackRequest(request) && this.mcp.mcpConnections[serverId]) return this._processOAuthCallback(request);
|
|
1750
|
-
try {
|
|
1751
|
-
const server = this.sql`
|
|
1752
|
-
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
|
|
1753
|
-
FROM cf_agents_mcp_servers
|
|
1754
|
-
WHERE id = ${serverId}
|
|
1755
|
-
`.find((s) => s.id === serverId);
|
|
1756
|
-
if (!server) return new Response(`OAuth callback failed: Server ${serverId} not found in database`, { status: 404 });
|
|
1757
|
-
if (!server.callback_url) return new Response(`OAuth callback failed: No callback URL stored for server ${serverId}`, { status: 500 });
|
|
1758
|
-
this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
|
|
1759
|
-
if (!this.mcp.mcpConnections[serverId]) {
|
|
1760
|
-
let parsedOptions;
|
|
1761
|
-
try {
|
|
1762
|
-
parsedOptions = server.server_options ? JSON.parse(server.server_options) : void 0;
|
|
1763
|
-
} catch {
|
|
1764
|
-
return new Response(`OAuth callback failed: Invalid server options in database for ${serverId}`, { status: 500 });
|
|
1765
|
-
}
|
|
1766
|
-
await this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, parsedOptions, {
|
|
1767
|
-
id: server.id,
|
|
1768
|
-
oauthClientId: server.client_id ?? void 0
|
|
1769
|
-
});
|
|
1770
|
-
}
|
|
1771
|
-
return this._processOAuthCallback(request);
|
|
1772
|
-
} catch (error) {
|
|
1773
|
-
const errorMsg = error instanceof Error ? error.message : "Unknown error";
|
|
1774
|
-
console.error(`Failed to restore MCP state for ${serverId}:`, error);
|
|
1775
|
-
return new Response(`OAuth callback failed during state restoration: ${errorMsg}`, { status: 500 });
|
|
1776
|
-
}
|
|
1777
|
-
}
|
|
1778
|
-
/**
|
|
1779
|
-
* Process an OAuth callback request (assumes state is already restored)
|
|
1780
|
-
*/
|
|
1781
|
-
async _processOAuthCallback(request) {
|
|
1782
|
-
const result = await this.mcp.handleCallbackRequest(request);
|
|
1783
|
-
this.broadcastMcpServers();
|
|
1784
|
-
if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
|
|
1785
|
-
console.error("Background connection failed:", error);
|
|
1786
|
-
}).finally(() => {
|
|
1787
|
-
this.broadcastMcpServers();
|
|
1788
|
-
});
|
|
1789
|
-
return this.handleOAuthCallbackResponse(result, request);
|
|
1790
|
-
}
|
|
1791
|
-
async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
|
|
2098
|
+
await this.mcp.ensureJsonSchema();
|
|
2099
|
+
const id = nanoid(8);
|
|
1792
2100
|
const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
|
|
1793
|
-
|
|
1794
|
-
authProvider.serverId = reconnect.id;
|
|
1795
|
-
if (reconnect.oauthClientId) authProvider.clientId = reconnect.oauthClientId;
|
|
1796
|
-
}
|
|
2101
|
+
authProvider.serverId = id;
|
|
1797
2102
|
const transportType = options?.transport?.type ?? "auto";
|
|
1798
2103
|
let headerTransportOpts = {};
|
|
1799
2104
|
if (options?.transport?.headers) headerTransportOpts = {
|
|
@@ -1803,28 +2108,33 @@ var Agent = class Agent$1 extends Server {
|
|
|
1803
2108
|
}) },
|
|
1804
2109
|
requestInit: { headers: options?.transport?.headers }
|
|
1805
2110
|
};
|
|
1806
|
-
|
|
2111
|
+
await this.mcp.registerServer(id, {
|
|
2112
|
+
url,
|
|
2113
|
+
name: serverName,
|
|
2114
|
+
callbackUrl,
|
|
1807
2115
|
client: options?.client,
|
|
1808
|
-
reconnect,
|
|
1809
2116
|
transport: {
|
|
1810
2117
|
...headerTransportOpts,
|
|
1811
2118
|
authProvider,
|
|
1812
2119
|
type: transportType
|
|
1813
2120
|
}
|
|
1814
2121
|
});
|
|
2122
|
+
const result = await this.mcp.connectToServer(id);
|
|
2123
|
+
if (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${url}: ${result.error}`);
|
|
2124
|
+
if (result.state === MCPConnectionState.AUTHENTICATING) return {
|
|
2125
|
+
id,
|
|
2126
|
+
state: result.state,
|
|
2127
|
+
authUrl: result.authUrl
|
|
2128
|
+
};
|
|
2129
|
+
const discoverResult = await this.mcp.discoverIfConnected(id);
|
|
2130
|
+
if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);
|
|
1815
2131
|
return {
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
id
|
|
2132
|
+
id,
|
|
2133
|
+
state: MCPConnectionState.READY
|
|
1819
2134
|
};
|
|
1820
2135
|
}
|
|
1821
2136
|
async removeMcpServer(id) {
|
|
1822
|
-
this.mcp.
|
|
1823
|
-
this.mcp.unregisterCallbackUrl(id);
|
|
1824
|
-
this.sql`
|
|
1825
|
-
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1826
|
-
`;
|
|
1827
|
-
this.broadcastMcpServers();
|
|
2137
|
+
await this.mcp.removeServer(id);
|
|
1828
2138
|
}
|
|
1829
2139
|
getMcpServers() {
|
|
1830
2140
|
const mcpState = {
|
|
@@ -1833,18 +2143,18 @@ var Agent = class Agent$1 extends Server {
|
|
|
1833
2143
|
servers: {},
|
|
1834
2144
|
tools: this.mcp.listTools()
|
|
1835
2145
|
};
|
|
1836
|
-
const servers = this.
|
|
1837
|
-
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1838
|
-
`;
|
|
2146
|
+
const servers = this.mcp.listServers();
|
|
1839
2147
|
if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
|
|
1840
2148
|
const serverConn = this.mcp.mcpConnections[server.id];
|
|
2149
|
+
let defaultState = "not-connected";
|
|
2150
|
+
if (!serverConn && server.auth_url) defaultState = "authenticating";
|
|
1841
2151
|
mcpState.servers[server.id] = {
|
|
1842
2152
|
auth_url: server.auth_url,
|
|
1843
2153
|
capabilities: serverConn?.serverCapabilities ?? null,
|
|
1844
2154
|
instructions: serverConn?.instructions ?? null,
|
|
1845
2155
|
name: server.name,
|
|
1846
2156
|
server_url: server.server_url,
|
|
1847
|
-
state: serverConn?.connectionState ??
|
|
2157
|
+
state: serverConn?.connectionState ?? defaultState
|
|
1848
2158
|
};
|
|
1849
2159
|
}
|
|
1850
2160
|
return mcpState;
|
|
@@ -1856,6 +2166,28 @@ var Agent = class Agent$1 extends Server {
|
|
|
1856
2166
|
}));
|
|
1857
2167
|
}
|
|
1858
2168
|
/**
|
|
2169
|
+
* Handle MCP OAuth callback request if it's an OAuth callback.
|
|
2170
|
+
*
|
|
2171
|
+
* This method encapsulates the entire OAuth callback flow:
|
|
2172
|
+
* 1. Checks if the request is an MCP OAuth callback
|
|
2173
|
+
* 2. Processes the OAuth code exchange
|
|
2174
|
+
* 3. Establishes the connection if successful
|
|
2175
|
+
* 4. Broadcasts MCP server state updates
|
|
2176
|
+
* 5. Returns the appropriate HTTP response
|
|
2177
|
+
*
|
|
2178
|
+
* @param request The incoming HTTP request
|
|
2179
|
+
* @returns Response if this was an OAuth callback, null otherwise
|
|
2180
|
+
*/
|
|
2181
|
+
async handleMcpOAuthCallback(request) {
|
|
2182
|
+
if (!this.mcp.isCallbackRequest(request)) return null;
|
|
2183
|
+
const result = await this.mcp.handleCallbackRequest(request);
|
|
2184
|
+
if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
|
|
2185
|
+
console.error("[Agent handleMcpOAuthCallback] Connection establishment failed:", error);
|
|
2186
|
+
});
|
|
2187
|
+
this.broadcastMcpServers();
|
|
2188
|
+
return this.handleOAuthCallbackResponse(result, request);
|
|
2189
|
+
}
|
|
2190
|
+
/**
|
|
1859
2191
|
* Handle OAuth callback response using MCPClientManager configuration
|
|
1860
2192
|
* @param result OAuth callback result
|
|
1861
2193
|
* @param request The original request (needed for base URL)
|
|
@@ -1864,10 +2196,21 @@ var Agent = class Agent$1 extends Server {
|
|
|
1864
2196
|
handleOAuthCallbackResponse(result, request) {
|
|
1865
2197
|
const config = this.mcp.getOAuthCallbackConfig();
|
|
1866
2198
|
if (config?.customHandler) return config.customHandler(result);
|
|
1867
|
-
|
|
1868
|
-
if (config?.
|
|
1869
|
-
|
|
1870
|
-
|
|
2199
|
+
const baseOrigin = new URL(request.url).origin;
|
|
2200
|
+
if (config?.successRedirect && result.authSuccess) try {
|
|
2201
|
+
return Response.redirect(new URL(config.successRedirect, baseOrigin).href);
|
|
2202
|
+
} catch (e) {
|
|
2203
|
+
console.error("Invalid successRedirect URL:", config.successRedirect, e);
|
|
2204
|
+
return Response.redirect(baseOrigin);
|
|
2205
|
+
}
|
|
2206
|
+
if (config?.errorRedirect && !result.authSuccess) try {
|
|
2207
|
+
const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`;
|
|
2208
|
+
return Response.redirect(new URL(errorUrl, baseOrigin).href);
|
|
2209
|
+
} catch (e) {
|
|
2210
|
+
console.error("Invalid errorRedirect URL:", config.errorRedirect, e);
|
|
2211
|
+
return Response.redirect(baseOrigin);
|
|
2212
|
+
}
|
|
2213
|
+
return Response.redirect(baseOrigin);
|
|
1871
2214
|
}
|
|
1872
2215
|
};
|
|
1873
2216
|
const wrappedClasses = /* @__PURE__ */ new Set();
|
|
@@ -1893,10 +2236,15 @@ async function routeAgentRequest(request, env$1, options) {
|
|
|
1893
2236
|
prefix: "agents",
|
|
1894
2237
|
...options
|
|
1895
2238
|
});
|
|
1896
|
-
if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket")
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
2239
|
+
if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
|
|
2240
|
+
const newHeaders = new Headers(response.headers);
|
|
2241
|
+
for (const [key, value] of Object.entries(corsHeaders)) newHeaders.set(key, value);
|
|
2242
|
+
response = new Response(response.body, {
|
|
2243
|
+
status: response.status,
|
|
2244
|
+
statusText: response.statusText,
|
|
2245
|
+
headers: newHeaders
|
|
2246
|
+
});
|
|
2247
|
+
}
|
|
1900
2248
|
return response;
|
|
1901
2249
|
}
|
|
1902
2250
|
/**
|