| 1 | import { type AssistantConfig } from "@continuedev/sdk"; |
| 2 | import { Client } from "@modelcontextprotocol/sdk/client/index.js"; |
| 3 | import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; |
| 4 | import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; |
| 5 | import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; |
| 6 | import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; |
| 7 | |
| 8 | import { getErrorString } from "../util/error.js"; |
| 9 | import { logger } from "../util/logger.js"; |
| 10 | |
| 11 | import { BaseService, ServiceWithDependencies } from "./BaseService.js"; |
| 12 | import { serviceContainer } from "./ServiceContainer.js"; |
| 13 | import { |
| 14 | MCPConnectionInfo, |
| 15 | MCPServerConfig, |
| 16 | MCPServiceState, |
| 17 | SERVICE_NAMES, |
| 18 | } from "./types.js"; |
| 19 | |
| 20 | interface ServerConnection extends MCPConnectionInfo { |
| 21 | client: Client | null; |
| 22 | } |
| 23 | |
| 24 | export const EMPTY_MCP_STATE: MCPServiceState = { |
| 25 | mcpService: null, |
| 26 | connections: [], |
| 27 | tools: [], |
| 28 | prompts: [], |
| 29 | }; |
| 30 | |
| 31 | export class MCPService |
| 32 | extends BaseService<MCPServiceState> |
| 33 | implements ServiceWithDependencies |
| 34 | { |
| 35 | private connections: Map<string, ServerConnection> = new Map(); |
| 36 | private assistant: AssistantConfig | null = null; |
| 37 | private isShuttingDown = false; |
| 38 | |
| 39 | getDependencies(): string[] { |
| 40 | return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.CONFIG]; |
| 41 | } |
| 42 | constructor() { |
| 43 | super("MCPService", { |
| 44 | ...EMPTY_MCP_STATE, |
| 45 | }); |
| 46 | |
| 47 | // Register shutdown handler |
| 48 | process.on("exit", () => this.cleanup()); |
| 49 | process.on("SIGINT", () => this.cleanup()); |
| 50 | process.on("SIGTERM", () => this.cleanup()); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Initialize the MCP service |
| 55 | */ |
| 56 | async doInitialize( |
| 57 | assistant: AssistantConfig, |
| 58 | waitForConnections = false, |
| 59 | ): Promise<MCPServiceState> { |
| 60 | logger.debug("Initializing MCPService", { |
| 61 | configName: assistant.name, |
| 62 | serverCount: assistant.mcpServers?.length || 0, |
| 63 | }); |
| 64 | |
| 65 | await this.shutdownConnections(); |
| 66 | |
| 67 | this.assistant = assistant; |
| 68 | this.connections.clear(); |
| 69 | |
| 70 | if (assistant.mcpServers?.length) { |
| 71 | logger.debug("Starting MCP server connections", { |
| 72 | serverCount: assistant.mcpServers.length, |
| 73 | }); |
| 74 | } |
| 75 | const connectionPromises = assistant.mcpServers?.map(async (config) => { |
| 76 | if (config) { |
| 77 | return await this.connectServer(config); |
| 78 | } |
| 79 | }); |
| 80 | |
| 81 | const connectionInit = Promise.all(connectionPromises ?? []).then( |
| 82 | (connections) => { |
| 83 | logger.debug("MCP connections established", { |
| 84 | connectionCount: connections.length, |
| 85 | }); |
| 86 | this.updateState(); |
| 87 | }, |
| 88 | ); |
| 89 | if (waitForConnections) { |
| 90 | await connectionInit; |
| 91 | } else { |
| 92 | this.updateState(); |
| 93 | } |
| 94 | |
| 95 | return this.currentState; |
| 96 | } |
| 97 | |
| 98 | /** |
| 99 | * Update internal state based on current connections |
| 100 | */ |
| 101 | private updateState() { |
| 102 | const connections: MCPConnectionInfo[] = Array.from( |
| 103 | this.connections.values(), |
| 104 | ).map(({ client: _, ...rest }) => rest); |
| 105 | const connectedServers = connections.filter( |
| 106 | (c) => c.status === "connected", |
| 107 | ); |
| 108 | const tools = connectedServers.flatMap((s) => s.tools); |
| 109 | const prompts = connectedServers.flatMap((s) => s.prompts); |
| 110 | |
| 111 | const newState: MCPServiceState = { |
| 112 | mcpService: this, |
| 113 | connections, |
| 114 | tools, |
| 115 | prompts, |
| 116 | }; |
| 117 | this.setState(newState); |
| 118 | serviceContainer.set(SERVICE_NAMES.MCP, newState); |
| 119 | } |
| 120 | |
| 121 | /** |
| 122 | * Get current MCP service state |
| 123 | */ |
| 124 | getState(): MCPServiceState { |
| 125 | return { ...this.currentState }; |
| 126 | } |
| 127 | |
| 128 | /** |
| 129 | * Get overall status for UI indicator |
| 130 | */ |
| 131 | getOverallStatus(): { |
| 132 | status: "idle" | "connecting" | "connected" | "error"; |
| 133 | hasWarnings: boolean; |
| 134 | } { |
| 135 | const connections = Array.from(this.connections.values()); |
| 136 | const hasWarnings = connections.some((c) => c.warnings.length > 0); |
| 137 | |
| 138 | if (connections.some((c) => c.status === "connecting")) { |
| 139 | return { status: "connecting", hasWarnings }; |
| 140 | } |
| 141 | if (connections.some((c) => c.status === "error")) { |
| 142 | return { status: "error", hasWarnings }; |
| 143 | } |
| 144 | if (connections.some((c) => c.status === "connected")) { |
| 145 | return { status: "connected", hasWarnings }; |
| 146 | } |
| 147 | |
| 148 | return { status: "idle", hasWarnings }; |
| 149 | } |
| 150 | |
| 151 | /** |
| 152 | * Run a tool by name |
| 153 | */ |
| 154 | public async runTool(name: string, args: Record<string, any>) { |
| 155 | for (const connection of this.connections.values()) { |
| 156 | if (connection.status === "connected" && connection.client) { |
| 157 | const tool = connection.tools.find((t) => t.name === name); |
| 158 | if (tool) { |
| 159 | return await connection.client.callTool({ |
| 160 | name, |
| 161 | arguments: args, |
| 162 | }); |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | throw new Error(`Tool ${name} not found`); |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Restart all servers |
| 171 | */ |
| 172 | public async restartAllServers(): Promise<void> { |
| 173 | if (!this.assistant) return; |
| 174 | |
| 175 | logger.debug("Restarting all MCP servers"); |
| 176 | await this.shutdownConnections(); |
| 177 | await this.initialize(this.assistant); |
| 178 | } |
| 179 | |
| 180 | /** |
| 181 | * Restart a specific server |
| 182 | */ |
| 183 | public async restartServer(serverName: string): Promise<void> { |
| 184 | if (!this.assistant || !this.assistant.mcpServers) return; |
| 185 | |
| 186 | const serverConfig = this.assistant.mcpServers.find( |
| 187 | (s, index) => s && (s.name || `server-${index}`) === serverName, |
| 188 | ); |
| 189 | |
| 190 | if (!serverConfig) { |
| 191 | throw new Error(`Server ${serverName} not found in configuration`); |
| 192 | } |
| 193 | |
| 194 | logger.debug("Restarting MCP server", { name: serverName }); |
| 195 | |
| 196 | const existingConnection = this.connections.get(serverName); |
| 197 | if (existingConnection) { |
| 198 | if (existingConnection.status === "connected") { |
| 199 | await this.shutdownConnection(existingConnection); |
| 200 | } |
| 201 | this.connections.delete(serverName); |
| 202 | } |
| 203 | await this.connectServer(serverConfig); |
| 204 | } |
| 205 | |
| 206 | private async connectServer(serverConfig: MCPServerConfig) { |
| 207 | const connection: ServerConnection = { |
| 208 | config: serverConfig, |
| 209 | client: null, |
| 210 | prompts: [], |
| 211 | tools: [], |
| 212 | status: "connecting", |
| 213 | warnings: [], |
| 214 | }; |
| 215 | const serverName = serverConfig.name; |
| 216 | this.connections.set(serverName, connection); |
| 217 | this.updateState(); |
| 218 | |
| 219 | try { |
| 220 | const client = new Client( |
| 221 | { name: "continue-cli-client", version: "1.0.0" }, |
| 222 | { capabilities: {} }, |
| 223 | ); |
| 224 | |
| 225 | const transport = await this.constructTransport(serverConfig); |
| 226 | |
| 227 | logger.debug("Connecting to MCP server", { |
| 228 | name: serverName, |
| 229 | command: serverConfig.command, |
| 230 | }); |
| 231 | |
| 232 | await client.connect(transport, {}); |
| 233 | |
| 234 | connection.client = client; |
| 235 | connection.status = "connected"; |
| 236 | this.updateState(); |
| 237 | |
| 238 | const capabilities = client.getServerCapabilities(); |
| 239 | logger.debug("MCP server capabilities", { |
| 240 | name: serverName, |
| 241 | hasPrompts: !!capabilities?.prompts, |
| 242 | hasTools: !!capabilities?.tools, |
| 243 | }); |
| 244 | |
| 245 | if (capabilities?.prompts) { |
| 246 | try { |
| 247 | connection.prompts = (await client.listPrompts()).prompts; |
| 248 | logger.debug("Loaded MCP prompts", { |
| 249 | name: serverName, |
| 250 | count: connection.prompts.length, |
| 251 | }); |
| 252 | } catch (error) { |
| 253 | const errorMessage = getErrorString(error); |
| 254 | connection.warnings.push(`Failed to load prompts: ${errorMessage}`); |
| 255 | logger.warn("Failed to load MCP prompts", { |
| 256 | name: serverName, |
| 257 | error: errorMessage, |
| 258 | }); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | if (capabilities?.tools) { |
| 263 | try { |
| 264 | connection.tools = (await client.listTools()).tools; |
| 265 | logger.debug("Loaded MCP tools", { |
| 266 | name: serverName, |
| 267 | count: connection.tools.length, |
| 268 | }); |
| 269 | } catch (error) { |
| 270 | const errorMessage = getErrorString(error); |
| 271 | connection.warnings.push(`Failed to load tools: ${errorMessage}`); |
| 272 | logger.warn("Failed to load MCP tools", { |
| 273 | name: serverName, |
| 274 | error: errorMessage, |
| 275 | }); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | logger.debug("MCP server restarted successfully", { name: serverName }); |
| 280 | } catch (error) { |
| 281 | const errorMessage = getErrorString(error); |
| 282 | connection.status = "error"; |
| 283 | connection.error = errorMessage; |
| 284 | logger.error("Failed to restart MCP server", { |
| 285 | name: serverName, |
| 286 | error: errorMessage, |
| 287 | }); |
| 288 | } |
| 289 | |
| 290 | this.updateState(); |
| 291 | } |
| 292 | |
| 293 | /** |
| 294 | * Stop a specific server |
| 295 | */ |
| 296 | public async stopServer(serverName: string): Promise<void> { |
| 297 | logger.debug("Stopping MCP server", { name: serverName }); |
| 298 | |
| 299 | const connection = this.connections.get(serverName); |
| 300 | if (connection) { |
| 301 | await this.shutdownConnection(connection); |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /** |
| 306 | * Shutdown all connections |
| 307 | */ |
| 308 | public async shutdownConnections(): Promise<void> { |
| 309 | const shutdownPromises = Array.from(this.connections.values()).map( |
| 310 | (connection) => this.shutdownConnection(connection), |
| 311 | ); |
| 312 | await Promise.all(shutdownPromises); |
| 313 | this.updateState(); |
| 314 | } |
| 315 | |
| 316 | /** |
| 317 | * Shutdown a single connection |
| 318 | */ |
| 319 | private async shutdownConnection( |
| 320 | connection: ServerConnection, |
| 321 | ): Promise<void> { |
| 322 | try { |
| 323 | if (connection.client) { |
| 324 | await connection.client.close(); |
| 325 | } |
| 326 | connection.status = "idle"; |
| 327 | connection.warnings = []; |
| 328 | connection.client = null; |
| 329 | connection.tools = []; |
| 330 | connection.prompts = []; |
| 331 | connection.error = undefined; |
| 332 | this.updateState(); |
| 333 | } catch (error) { |
| 334 | const errorMessage = getErrorString(error); |
| 335 | logger.warn("Error shutting down MCP connection", { |
| 336 | name: connection.config?.name, |
| 337 | error: errorMessage, |
| 338 | }); |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | public async cleanup(): Promise<void> { |
| 343 | if (this.isShuttingDown) return; |
| 344 | this.isShuttingDown = true; |
| 345 | |
| 346 | this.removeAllListeners(); |
| 347 | logger.debug("Shutting down MCPService"); |
| 348 | await this.shutdownConnections(); |
| 349 | } |
| 350 | |
| 351 | /** |
| 352 | * Construct transport based on server configuration |
| 353 | */ |
| 354 | private async constructTransport( |
| 355 | serverConfig: MCPServerConfig, |
| 356 | ): Promise<Transport> { |
| 357 | const transportType = serverConfig.type || "stdio"; |
| 358 | |
| 359 | switch (transportType) { |
| 360 | case "stdio": |
| 361 | if (!serverConfig.command) { |
| 362 | throw new Error( |
| 363 | "MCP server command is not specified for stdio transport", |
| 364 | ); |
| 365 | } |
| 366 | |
| 367 | const env: Record<string, string> = serverConfig.env || {}; |
| 368 | if (process.env.PATH !== undefined) { |
| 369 | env.PATH = process.env.PATH; |
| 370 | } |
| 371 | |
| 372 | return new StdioClientTransport({ |
| 373 | command: serverConfig.command, |
| 374 | args: serverConfig.args || [], |
| 375 | env, |
| 376 | cwd: serverConfig.cwd, |
| 377 | stderr: "ignore", |
| 378 | }); |
| 379 | |
| 380 | case "sse": |
| 381 | if (!serverConfig.url) { |
| 382 | throw new Error("MCP server URL is not specified for SSE transport"); |
| 383 | } |
| 384 | return new SSEClientTransport(new URL(serverConfig.url), { |
| 385 | eventSourceInit: { |
| 386 | fetch: (input, init) => |
| 387 | fetch(input, { |
| 388 | ...init, |
| 389 | headers: { |
| 390 | ...init?.headers, |
| 391 | ...(serverConfig.requestOptions?.headers as |
| 392 | | Record<string, string> |
| 393 | | undefined), |
| 394 | }, |
| 395 | }), |
| 396 | }, |
| 397 | requestInit: { headers: serverConfig.requestOptions?.headers }, |
| 398 | }); |
| 399 | |
| 400 | case "streamable-http": |
| 401 | if (!serverConfig.url) { |
| 402 | throw new Error( |
| 403 | "MCP server URL is not specified for streamable-http transport", |
| 404 | ); |
| 405 | } |
| 406 | return new StreamableHTTPClientTransport(new URL(serverConfig.url), { |
| 407 | requestInit: { headers: serverConfig.requestOptions?.headers }, |
| 408 | }); |
| 409 | |
| 410 | default: |
| 411 | throw new Error(`Unsupported transport type: ${transportType}`); |
| 412 | } |
| 413 | } |
| 414 | } |