Skip to content

Remove unused MCP connections on config reload #4690

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 15 additions & 16 deletions core/config/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
IdeType,
ILLM,
LLMOptions,
MCPOptions,
ModelDescription,
RerankerDescription,
SerializedContinueConfig,
Expand Down Expand Up @@ -542,40 +543,39 @@ async function intermediateToFinalConfig(

// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
function getMcpId(options: MCPOptions) {
return JSON.stringify(options);
}
if (config.experimental?.modelContextProtocolServers) {
await mcpManager.removeUnusedConnections(
config.experimental.modelContextProtocolServers.map(getMcpId),
);
}

if (config.experimental?.modelContextProtocolServers) {
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
4000,
5000,
);

await Promise.allSettled(
config.experimental.modelContextProtocolServers?.map(
async (server, index) => {
try {
const mcpId = index.toString();
const mcpId = getMcpId(server);
const mcpConnection = mcpManager.createConnection(mcpId, server);
if (!mcpConnection) {
return;
}
const mcpError = await mcpConnection.modifyConfig(
await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
"MCP Server",
server.faviconUrl,
);
if (mcpError) {
errors.push(mcpError);
}
} catch (e) {
let errorMessage = "Failed to load MCP server";
if (e instanceof Error) {
if (e.name === "AbortError") {
errorMessage += ": connection timed out";
} else {
errorMessage += ": " + e.message;
}
errorMessage += ": " + e.message;
}
errors.push({
fatal: false,
Expand Down Expand Up @@ -998,6 +998,5 @@ export {
finalToBrowserConfig,
intermediateToFinalConfig,
loadContinueConfigFromJson,
type BrowserSerializedContinueConfig
type BrowserSerializedContinueConfig,
};

22 changes: 9 additions & 13 deletions core/config/yaml/loadYaml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,12 +369,18 @@ async function configYamlToContinueConfig(

// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
if (config.mcpServers) {
await mcpManager.removeUnusedConnections(
config.mcpServers.map((s) => s.name),
);
}

await Promise.allSettled(
config.mcpServers?.map(async (server) => {
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
4000,
5000,
);

try {
Expand All @@ -386,28 +392,18 @@ async function configYamlToContinueConfig(
...server,
},
});
if (!mcpConnection) {
return;
}

const mcpError = await mcpConnection.modifyConfig(
await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
server.name,
server.faviconUrl,
);
if (mcpError) {
localErrors.push(mcpError);
}
} catch (e) {
let errorMessage = `Failed to load MCP server ${server.name}`;
if (e instanceof Error) {
if (e.name === "AbortError") {
errorMessage += ": connection timed out";
} else {
errorMessage += ": " + e.message;
}
errorMessage += ": " + e.message;
}
localErrors.push({
fatal: false,
Expand Down
41 changes: 27 additions & 14 deletions core/context/mcp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";

import { ConfigValidationError } from "@continuedev/config-yaml";
import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../..";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { encodeMCPToolUri } from "../../tools/callTool";
Expand All @@ -24,13 +23,13 @@ export class MCPManagerSingleton {
return MCPManagerSingleton.instance;
}

createConnection(id: string, options: MCPOptions): MCPConnection | undefined {
createConnection(id: string, options: MCPOptions): MCPConnection {
if (!this.connections.has(id)) {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id);
return this.connections.get(id)!;
}
}

Expand All @@ -46,6 +45,13 @@ export class MCPManagerSingleton {

this.connections.delete(id);
}

async removeUnusedConnections(keepIds: string[]) {
const toRemove = Array.from(this.connections.keys()).filter(
(k) => !keepIds.includes(k),
);
await Promise.all(toRemove.map(this.removeConnection));
}
}

class MCPConnection {
Expand Down Expand Up @@ -123,25 +129,32 @@ class MCPConnection {
signal: AbortSignal,
name: string,
faviconUrl: string | undefined,
): Promise<ConfigValidationError | undefined> {
) {
try {
await Promise.race([
this.connectClient(),
new Promise((_, reject) => {
signal.addEventListener("abort", () =>
reject(new Error("Connection aborted")),
reject(new Error("Connection timed out")),
);
}),
]);
} catch (error: any) {
if (signal.aborted) {
throw new Error("Operation aborted");
}
if (!error.message.startsWith("StdioClientTransport already started")) {
return {
fatal: false,
message: `Failed to connect to MCP: ${error.message}`,
};
} catch (error) {
if (error instanceof Error) {
const msg = error.message.toLowerCase();
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
throw new Error(
`command "${command}" not found. To use this MCP server, install the ${command} CLI.`,
);
} else if (
!error.message.startsWith("StdioClientTransport already started")
) {
// don't throw error if it's just a "server already running" case
throw error;
}
} else {
throw error;
}
}

Expand Down
Loading