agents
Version:
A home for your AI agents
723 lines (721 loc) • 25.8 kB
JavaScript
import { tryN } from "../retries.js";
import { a as Emitter, i as DisposableStore, n as MCPConnectionState, r as toErrorMessage, t as MCPClientConnection } from "../client-connection-CGMuV62J.js";
import { DurableObjectOAuthClientProvider } from "./do-oauth-client-provider.js";
import { nanoid } from "nanoid";
import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker-provider.js";
//#region src/mcp/client.ts
const defaultClientOptions = { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() };
/**
* Utility class that aggregates multiple MCP clients into one
*/
var MCPClientManager = class {
/**
* @param _name Name of the MCP client
* @param _version Version of the MCP Client
* @param options Storage adapter for persisting MCP server state
*/
constructor(_name, _version, options) {
this._name = _name;
this._version = _version;
this.mcpConnections = {};
this._didWarnAboutUnstableGetAITools = false;
this._connectionDisposables = /* @__PURE__ */ new Map();
this._isRestored = false;
this._onObservabilityEvent = new Emitter();
this.onObservabilityEvent = this._onObservabilityEvent.event;
this._onServerStateChanged = new Emitter();
this.onServerStateChanged = this._onServerStateChanged.event;
if (!options.storage) throw new Error("MCPClientManager requires a valid DurableObjectStorage instance");
this._storage = options.storage;
this._createAuthProviderFn = options.createAuthProvider;
}
sql(query, ...bindings) {
return [...this._storage.sql.exec(query, ...bindings)];
}
saveServerToStorage(server) {
this.sql(`INSERT OR REPLACE INTO cf_agents_mcp_servers (
id, name, server_url, client_id, auth_url, callback_url, server_options
) VALUES (?, ?, ?, ?, ?, ?, ?)`, server.id, server.name, server.server_url, server.client_id ?? null, server.auth_url ?? null, server.callback_url, server.server_options ?? null);
}
removeServerFromStorage(serverId) {
this.sql("DELETE FROM cf_agents_mcp_servers WHERE id = ?", serverId);
}
getServersFromStorage() {
return this.sql("SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers");
}
/**
* Get the retry options for a server from stored server_options
*/
getServerRetryOptions(serverId) {
const rows = this.sql("SELECT server_options FROM cf_agents_mcp_servers WHERE id = ?", serverId);
if (!rows.length || !rows[0].server_options) return void 0;
return JSON.parse(rows[0].server_options).retry;
}
clearServerAuthUrl(serverId) {
this.sql("UPDATE cf_agents_mcp_servers SET auth_url = NULL WHERE id = ?", serverId);
}
failConnection(serverId, error) {
this.clearServerAuthUrl(serverId);
if (this.mcpConnections[serverId]) {
this.mcpConnections[serverId].connectionState = MCPConnectionState.FAILED;
this.mcpConnections[serverId].connectionError = error;
}
this._onServerStateChanged.fire();
return {
serverId,
authSuccess: false,
authError: error
};
}
/**
* Create an auth provider for a server
* @internal
*/
createAuthProvider(serverId, callbackUrl, clientName, clientId) {
if (!this._storage) throw new Error("Cannot create auth provider: storage is not initialized");
const authProvider = new DurableObjectOAuthClientProvider(this._storage, clientName, callbackUrl);
authProvider.serverId = serverId;
if (clientId) authProvider.clientId = clientId;
return authProvider;
}
/**
* Restore MCP server connections from storage
* This method is called on Agent initialization to restore previously connected servers
*
* @param clientName Name to use for OAuth client (typically the agent instance name)
*/
async restoreConnectionsFromStorage(clientName) {
if (this._isRestored) return;
const servers = this.getServersFromStorage();
if (!servers || servers.length === 0) {
this._isRestored = true;
return;
}
for (const server of servers) {
const existingConn = this.mcpConnections[server.id];
if (existingConn) {
if (existingConn.connectionState === MCPConnectionState.READY) {
console.warn(`[MCPClientManager] Server ${server.id} already has a ready connection. Skipping recreation.`);
continue;
}
if (existingConn.connectionState === MCPConnectionState.AUTHENTICATING || existingConn.connectionState === MCPConnectionState.CONNECTING || existingConn.connectionState === MCPConnectionState.DISCOVERING) continue;
if (existingConn.connectionState === MCPConnectionState.FAILED) {
try {
await existingConn.client.close();
} catch (error) {
console.warn(`[MCPClientManager] Error closing failed connection ${server.id}:`, error);
}
delete this.mcpConnections[server.id];
this._connectionDisposables.get(server.id)?.dispose();
this._connectionDisposables.delete(server.id);
}
}
const parsedOptions = server.server_options ? JSON.parse(server.server_options) : null;
const authProvider = this._createAuthProviderFn ? this._createAuthProviderFn(server.callback_url) : this.createAuthProvider(server.id, server.callback_url, clientName, server.client_id ?? void 0);
authProvider.serverId = server.id;
if (server.client_id) authProvider.clientId = server.client_id;
const conn = this.createConnection(server.id, server.server_url, {
client: parsedOptions?.client ?? {},
transport: {
...parsedOptions?.transport ?? {},
type: parsedOptions?.transport?.type ?? "auto",
authProvider
}
});
if (server.auth_url) {
conn.connectionState = MCPConnectionState.AUTHENTICATING;
continue;
}
this._restoreServer(server.id, parsedOptions?.retry);
}
this._isRestored = true;
}
/**
* Internal method to restore a single server connection and discovery
*/
async _restoreServer(serverId, retry) {
const maxAttempts = retry?.maxAttempts ?? 3;
if ((await tryN(maxAttempts, async () => this.connectToServer(serverId), {
baseDelayMs: retry?.baseDelayMs ?? 500,
maxDelayMs: retry?.maxDelayMs ?? 5e3
}).catch((error) => {
console.error(`Error connecting to ${serverId} after ${maxAttempts} attempts:`, error);
return null;
}))?.state === MCPConnectionState.CONNECTED) {
const discoverResult = await this.discoverIfConnected(serverId);
if (discoverResult && !discoverResult.success) console.error(`Error discovering ${serverId}:`, discoverResult.error);
}
}
/**
* Connect to and register an MCP server
*
* @deprecated This method is maintained for backward compatibility.
* For new code, use registerServer() and connectToServer() separately.
*
* @param url Server URL
* @param options Connection options
* @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)
*/
async connect(url, options = {}) {
/**
* We need to delay loading ai sdk, because putting it in module scope is
* causing issues with startup time.
* The only place it's used is in getAITools, which only matters after
* .connect() is called on at least one server.
* So it's safe to delay loading it until .connect() is called.
*/
await this.ensureJsonSchema();
const id = options.reconnect?.id ?? nanoid(8);
if (options.transport?.authProvider) {
options.transport.authProvider.serverId = id;
if (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
}
if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {
const normalizedTransport = {
...options.transport,
type: options.transport?.type ?? "auto"
};
this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
name: this._name,
version: this._version
}, {
client: options.client ?? {},
transport: normalizedTransport
});
const store = new DisposableStore();
const existing = this._connectionDisposables.get(id);
if (existing) existing.dispose();
this._connectionDisposables.set(id, store);
store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
this._onObservabilityEvent.fire(event);
}));
}
await this.mcpConnections[id].init();
if (options.reconnect?.oauthCode) try {
await this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);
await this.mcpConnections[id].init();
} catch (error) {
this._onObservabilityEvent.fire({
type: "mcp:client:connect",
displayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,
payload: {
url,
transport: options.transport?.type ?? "auto",
state: this.mcpConnections[id].connectionState,
error: toErrorMessage(error)
},
timestamp: Date.now(),
id
});
throw error;
}
const authUrl = options.transport?.authProvider?.authUrl;
if (this.mcpConnections[id].connectionState === MCPConnectionState.AUTHENTICATING && authUrl && options.transport?.authProvider?.redirectUrl) return {
authUrl,
clientId: options.transport?.authProvider?.clientId,
id
};
const discoverResult = await this.discoverIfConnected(id);
if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover server capabilities: ${discoverResult.error}`);
return { id };
}
/**
* Create an in-memory connection object and set up observability
* Does NOT save to storage - use registerServer() for that
* @returns The connection object (existing or newly created)
*/
createConnection(id, url, options) {
if (this.mcpConnections[id]) return this.mcpConnections[id];
const normalizedTransport = {
...options.transport,
type: options.transport?.type ?? "auto"
};
this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
name: this._name,
version: this._version
}, {
client: {
...defaultClientOptions,
...options.client
},
transport: normalizedTransport
});
const store = new DisposableStore();
const existing = this._connectionDisposables.get(id);
if (existing) existing.dispose();
this._connectionDisposables.set(id, store);
store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
this._onObservabilityEvent.fire(event);
}));
return this.mcpConnections[id];
}
/**
* Register an MCP server connection without connecting
* Creates the connection object, sets up observability, and saves to storage
*
* @param id Server ID
* @param options Registration options including URL, name, callback URL, and connection config
* @returns Server ID
*/
async registerServer(id, options) {
this.createConnection(id, options.url, {
client: options.client,
transport: {
...options.transport,
type: options.transport?.type ?? "auto"
}
});
const { authProvider: _, ...transportWithoutAuth } = options.transport ?? {};
this.saveServerToStorage({
id,
name: options.name,
server_url: options.url,
callback_url: options.callbackUrl,
client_id: options.clientId ?? null,
auth_url: options.authUrl ?? null,
server_options: JSON.stringify({
client: options.client,
transport: transportWithoutAuth,
retry: options.retry
})
});
this._onServerStateChanged.fire();
return id;
}
/**
* Connect to an already registered MCP server and initialize the connection.
*
* For OAuth servers, returns `{ state: "authenticating", authUrl, clientId? }`.
* The user must complete the OAuth flow via the authUrl, which triggers a
* callback handled by `handleCallbackRequest()`.
*
* For non-OAuth servers, establishes the transport connection and returns
* `{ state: "connected" }`. Call `discoverIfConnected()` afterwards to
* discover capabilities and transition to "ready" state.
*
* @param id Server ID (must be registered first via registerServer())
* @returns Connection result with current state and OAuth info (if applicable)
*/
async connectToServer(id) {
const conn = this.mcpConnections[id];
if (!conn) throw new Error(`Server ${id} is not registered. Call registerServer() first.`);
const error = await conn.init();
this._onServerStateChanged.fire();
switch (conn.connectionState) {
case MCPConnectionState.FAILED: return {
state: conn.connectionState,
error: error ?? "Unknown connection error"
};
case MCPConnectionState.AUTHENTICATING: {
const authUrl = conn.options.transport.authProvider?.authUrl;
const redirectUrl = conn.options.transport.authProvider?.redirectUrl;
if (!authUrl || !redirectUrl) return {
state: MCPConnectionState.FAILED,
error: `OAuth configuration incomplete: missing ${!authUrl ? "authUrl" : "redirectUrl"}`
};
const clientId = conn.options.transport.authProvider?.clientId;
const serverRow = this.getServersFromStorage().find((s) => s.id === id);
if (serverRow) {
this.saveServerToStorage({
...serverRow,
auth_url: authUrl,
client_id: clientId ?? null
});
this._onServerStateChanged.fire();
}
return {
state: conn.connectionState,
authUrl,
clientId
};
}
case MCPConnectionState.CONNECTED: return { state: conn.connectionState };
default: return {
state: MCPConnectionState.FAILED,
error: `Unexpected connection state after init: ${conn.connectionState}`
};
}
}
extractServerIdFromState(state) {
if (!state) return null;
const parts = state.split(".");
return parts.length === 2 ? parts[1] : null;
}
isCallbackRequest(req) {
if (req.method !== "GET") return false;
const url = new URL(req.url);
const state = url.searchParams.get("state");
const serverId = this.extractServerIdFromState(state);
if (!serverId) return false;
return this.getServersFromStorage().some((server) => {
if (server.id !== serverId) return false;
try {
const storedUrl = new URL(server.callback_url);
return storedUrl.origin === url.origin && storedUrl.pathname === url.pathname;
} catch {
return false;
}
});
}
validateCallbackRequest(req) {
const url = new URL(req.url);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const error = url.searchParams.get("error");
const errorDescription = url.searchParams.get("error_description");
if (!state) return {
valid: false,
error: "Unauthorized: no state provided"
};
const serverId = this.extractServerIdFromState(state);
if (!serverId) return {
valid: false,
error: "No serverId found in state parameter. Expected format: {nonce}.{serverId}"
};
if (error) return {
serverId,
valid: false,
error: errorDescription || error
};
if (!code) return {
serverId,
valid: false,
error: "Unauthorized: no code provided"
};
if (!this.getServersFromStorage().some((server) => server.id === serverId)) return {
serverId,
valid: false,
error: `No server found with id "${serverId}". Was the request matched with \`isCallbackRequest()\`?`
};
if (this.mcpConnections[serverId] === void 0) return {
serverId,
valid: false,
error: `No connection found for serverId "${serverId}".`
};
return {
valid: true,
serverId,
code,
state
};
}
async handleCallbackRequest(req) {
const validation = this.validateCallbackRequest(req);
if (!validation.valid) {
if (validation.serverId && this.mcpConnections[validation.serverId]) return this.failConnection(validation.serverId, validation.error);
return {
serverId: validation.serverId,
authSuccess: false,
authError: validation.error
};
}
const { serverId, code, state } = validation;
const conn = this.mcpConnections[serverId];
try {
if (!conn.options.transport.authProvider) throw new Error("Trying to finalize authentication for a server connection without an authProvider");
const authProvider = conn.options.transport.authProvider;
authProvider.serverId = serverId;
const stateValidation = await authProvider.checkState(state);
if (!stateValidation.valid) throw new Error(stateValidation.error || "Invalid state");
if (conn.connectionState === MCPConnectionState.READY || conn.connectionState === MCPConnectionState.CONNECTED) {
this.clearServerAuthUrl(serverId);
return {
serverId,
authSuccess: true
};
}
if (conn.connectionState !== MCPConnectionState.AUTHENTICATING) throw new Error(`Failed to authenticate: the client is in "${conn.connectionState}" state, expected "authenticating"`);
await authProvider.consumeState(state);
await conn.completeAuthorization(code);
await authProvider.deleteCodeVerifier();
this.clearServerAuthUrl(serverId);
conn.connectionError = null;
this._onServerStateChanged.fire();
return {
serverId,
authSuccess: true
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return this.failConnection(serverId, message);
}
}
/**
* Discover server capabilities if connection is in CONNECTED or READY state.
* Transitions to DISCOVERING then READY (or CONNECTED on error).
* Can be called to refresh server capabilities (e.g., from a UI refresh button).
*
* If called while a previous discovery is in-flight for the same server,
* the previous discovery will be aborted.
*
* @param serverId The server ID to discover
* @param options Optional configuration
* @param options.timeoutMs Timeout in milliseconds (default: 30000)
* @returns Result with current state and optional error, or undefined if connection not found
*/
async discoverIfConnected(serverId, options = {}) {
const conn = this.mcpConnections[serverId];
if (!conn) {
this._onObservabilityEvent.fire({
type: "mcp:client:discover",
displayMessage: `Connection not found for ${serverId}`,
payload: {},
timestamp: Date.now(),
id: nanoid()
});
return;
}
const result = await conn.discover(options);
this._onServerStateChanged.fire();
return {
...result,
state: conn.connectionState
};
}
/**
* Establish connection in the background after OAuth completion
* This method connects to the server and discovers its capabilities
* @param serverId The server ID to establish connection for
*/
async establishConnection(serverId) {
const conn = this.mcpConnections[serverId];
if (!conn) {
this._onObservabilityEvent.fire({
type: "mcp:client:preconnect",
displayMessage: `Connection not found for serverId: ${serverId}`,
payload: { serverId },
timestamp: Date.now(),
id: nanoid()
});
return;
}
if (conn.connectionState === MCPConnectionState.DISCOVERING || conn.connectionState === MCPConnectionState.READY) {
this._onObservabilityEvent.fire({
type: "mcp:client:connect",
displayMessage: `establishConnection skipped for ${serverId}, already in ${conn.connectionState} state`,
payload: {
url: conn.url.toString(),
transport: conn.options.transport.type || "unknown",
state: conn.connectionState
},
timestamp: Date.now(),
id: nanoid()
});
return;
}
const retry = this.getServerRetryOptions(serverId);
const connectResult = await tryN(retry?.maxAttempts ?? 3, async () => this.connectToServer(serverId), {
baseDelayMs: retry?.baseDelayMs ?? 500,
maxDelayMs: retry?.maxDelayMs ?? 5e3
});
this._onServerStateChanged.fire();
if (connectResult.state === MCPConnectionState.CONNECTED) await this.discoverIfConnected(serverId);
this._onObservabilityEvent.fire({
type: "mcp:client:connect",
displayMessage: `establishConnection completed for ${serverId}, final state: ${conn.connectionState}`,
payload: {
url: conn.url.toString(),
transport: conn.options.transport.type || "unknown",
state: conn.connectionState
},
timestamp: Date.now(),
id: nanoid()
});
}
/**
* Configure OAuth callback handling
* @param config OAuth callback configuration
*/
configureOAuthCallback(config) {
this._oauthCallbackConfig = config;
}
/**
* Get the current OAuth callback configuration
* @returns The current OAuth callback configuration
*/
getOAuthCallbackConfig() {
return this._oauthCallbackConfig;
}
/**
* @returns namespaced list of tools
*/
listTools() {
return getNamespacedData(this.mcpConnections, "tools");
}
/**
* Lazy-loads the jsonSchema function from the AI SDK.
*
* This defers importing the "ai" package until it's actually needed, which helps reduce
* initial bundle size and startup time. The jsonSchema function is required for converting
* MCP tools into AI SDK tool definitions via getAITools().
*
* @internal This method is for internal use only. It's automatically called before operations
* that need jsonSchema (like getAITools() or OAuth flows). External consumers should not need
* to call this directly.
*/
async ensureJsonSchema() {
if (!this.jsonSchema) {
const { jsonSchema } = await import("ai");
this.jsonSchema = jsonSchema;
}
}
/**
* @returns a set of tools that you can use with the AI SDK
*/
getAITools() {
if (!this.jsonSchema) throw new Error("jsonSchema not initialized.");
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.`);
return Object.fromEntries(getNamespacedData(this.mcpConnections, "tools").map((tool) => {
return [`tool_${tool.serverId.replace(/-/g, "")}_${tool.name}`, {
description: tool.description,
execute: async (args) => {
const result = await this.callTool({
arguments: args,
name: tool.name,
serverId: tool.serverId
});
if (result.isError) {
const textContent = result.content?.[0];
const message = textContent?.type === "text" && textContent.text ? textContent.text : "Tool call failed";
throw new Error(message);
}
return result;
},
inputSchema: this.jsonSchema(tool.inputSchema),
outputSchema: tool.outputSchema ? this.jsonSchema(tool.outputSchema) : void 0
}];
}));
}
/**
* @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
* @returns a set of tools that you can use with the AI SDK
*/
unstable_getAITools() {
if (!this._didWarnAboutUnstableGetAITools) {
this._didWarnAboutUnstableGetAITools = true;
console.warn("unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.");
}
return this.getAITools();
}
/**
* Closes all active in-memory connections to MCP servers.
*
* Note: This only closes the transport connections - it does NOT remove
* servers from storage. Servers will still be listed and their callback
* URLs will still match incoming OAuth requests.
*
* Use removeServer() instead if you want to fully clean up a server
* (closes connection AND removes from storage).
*/
async closeAllConnections() {
const ids = Object.keys(this.mcpConnections);
for (const id of ids) this.mcpConnections[id].cancelDiscovery();
await Promise.all(ids.map(async (id) => {
await this.mcpConnections[id].client.close();
}));
for (const id of ids) {
const store = this._connectionDisposables.get(id);
if (store) store.dispose();
this._connectionDisposables.delete(id);
delete this.mcpConnections[id];
}
}
/**
* Closes a connection to an MCP server
* @param id The id of the connection to close
*/
async closeConnection(id) {
if (!this.mcpConnections[id]) throw new Error(`Connection with id "${id}" does not exist.`);
this.mcpConnections[id].cancelDiscovery();
await this.mcpConnections[id].client.close();
delete this.mcpConnections[id];
const store = this._connectionDisposables.get(id);
if (store) store.dispose();
this._connectionDisposables.delete(id);
}
/**
* Remove an MCP server - closes connection if active and removes from storage.
*/
async removeServer(serverId) {
if (this.mcpConnections[serverId]) try {
await this.closeConnection(serverId);
} catch (_e) {}
this.removeServerFromStorage(serverId);
this._onServerStateChanged.fire();
}
/**
* List all MCP servers from storage
*/
listServers() {
return this.getServersFromStorage();
}
/**
* Dispose the manager and all resources.
*/
async dispose() {
try {
await this.closeAllConnections();
} finally {
this._onServerStateChanged.dispose();
this._onObservabilityEvent.dispose();
}
}
/**
* @returns namespaced list of prompts
*/
listPrompts() {
return getNamespacedData(this.mcpConnections, "prompts");
}
/**
* @returns namespaced list of tools
*/
listResources() {
return getNamespacedData(this.mcpConnections, "resources");
}
/**
* @returns namespaced list of resource templates
*/
listResourceTemplates() {
return getNamespacedData(this.mcpConnections, "resourceTemplates");
}
/**
* Namespaced version of callTool
*/
async callTool(params, resultSchema, options) {
const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
return this.mcpConnections[params.serverId].client.callTool({
...params,
name: unqualifiedName
}, resultSchema, options);
}
/**
* Namespaced version of readResource
*/
readResource(params, options) {
return this.mcpConnections[params.serverId].client.readResource(params, options);
}
/**
* Namespaced version of getPrompt
*/
getPrompt(params, options) {
return this.mcpConnections[params.serverId].client.getPrompt(params, options);
}
};
function getNamespacedData(mcpClients, type) {
return Object.entries(mcpClients).map(([name, conn]) => {
return {
data: conn[type],
name
};
}).flatMap(({ name: serverId, data }) => {
return data.map((item) => {
return {
...item,
serverId
};
});
});
}
//#endregion
export { MCPClientManager, getNamespacedData };
//# sourceMappingURL=client.js.map