Elffuss BraidHub

kikocis/continue public

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