Elffuss BraidHub

kikocis/continue public

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