Elffuss BraidHub

kikocis/continue public

bdbad06b302d · 10.8 KiBRawPermalink
1import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
3
4import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
5import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
6import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
7
8import {
9 MCPConnectionStatus,
10 MCPOptions,
11 MCPPrompt,
12 MCPResource,
13 MCPServerStatus,
14 MCPTool,
15} from "../..";
16import { getEnvPathFromUserShell } from "../../util/shellPath";
17
18const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
19
20// Commands that are batch scripts on Windows and need cmd.exe to execute
21const WINDOWS_BATCH_COMMANDS = [
22 "npx",
23 "uv",
24 "uvx",
25 "pnpx",
26 "dlx",
27 "nx",
28 "bunx",
29];
30
31class MCPConnection {
32 public client: Client;
33 public abortController: AbortController;
34 public status: MCPConnectionStatus = "not-connected";
35 public errors: string[] = [];
36 public prompts: MCPPrompt[] = [];
37 public tools: MCPTool[] = [];
38 public resources: MCPResource[] = [];
39 private transport: Transport;
40 private connectionPromise: Promise<unknown> | null = null;
41 private stdioOutput: { stdout: string; stderr: string } = {
42 stdout: "",
43 stderr: "",
44 };
45
46 constructor(public options: MCPOptions) {
47 this.transport = this.constructTransport(options);
48
49 this.client = new Client(
50 {
51 name: "continue-client",
52 version: "1.0.0",
53 },
54 {
55 capabilities: {},
56 },
57 );
58
59 this.abortController = new AbortController();
60 }
61
62 async disconnect() {
63 this.abortController.abort();
64 await this.client.close();
65 await this.transport.close();
66 }
67
68 getStatus(): MCPServerStatus {
69 return {
70 ...this.options,
71 errors: this.errors,
72 prompts: this.prompts,
73 resources: this.resources,
74 tools: this.tools,
75 status: this.status,
76 };
77 }
78
79 async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) {
80 if (!forceRefresh) {
81 // Already connected
82 if (this.status === "connected") {
83 return;
84 }
85
86 // Connection is already in progress; wait for it to complete
87 if (this.connectionPromise) {
88 await this.connectionPromise;
89 return;
90 }
91 }
92
93 this.status = "connecting";
94 this.tools = [];
95 this.prompts = [];
96 this.resources = [];
97 this.errors = [];
98 this.stdioOutput = { stdout: "", stderr: "" };
99
100 this.abortController.abort();
101 this.abortController = new AbortController();
102
103 this.connectionPromise = Promise.race([
104 // If aborted by a refresh or other, cancel and don't do anything
105 new Promise((resolve) => {
106 externalSignal.addEventListener("abort", () => {
107 resolve(undefined);
108 });
109 }),
110 new Promise((resolve) => {
111 this.abortController.signal.addEventListener("abort", () => {
112 resolve(undefined);
113 });
114 }),
115 (async () => {
116 const timeoutController = new AbortController();
117 const connectionTimeout = setTimeout(
118 () => timeoutController.abort(),
119 this.options.timeout ?? DEFAULT_MCP_TIMEOUT,
120 );
121
122 try {
123 await Promise.race([
124 new Promise((_, reject) => {
125 timeoutController.signal.addEventListener("abort", () => {
126 reject(new Error("Connection timed out"));
127 });
128 }),
129 (async () => {
130 this.transport = this.constructTransport(this.options);
131 try {
132 await this.client.connect(this.transport);
133 } catch (error) {
134 // Allow the case where for whatever reason is already connected
135 if (
136 error instanceof Error &&
137 error.message.startsWith(
138 "StdioClientTransport already started",
139 )
140 ) {
141 await this.client.close();
142 await this.client.connect(this.transport);
143 } else {
144 throw error;
145 }
146 }
147
148 // TODO register server notification handlers
149 // this.client.transport?.onmessage(msg => console.log())
150 // this.client.setNotificationHandler(, notification => {
151 // console.log(notification)
152 // })
153
154 const capabilities = this.client.getServerCapabilities();
155
156 // Resources <—> Context Provider
157 if (capabilities?.resources) {
158 try {
159 const { resources } = await this.client.listResources(
160 {},
161 { signal: timeoutController.signal },
162 );
163 this.resources = resources;
164 } catch (e) {
165 let errorMessage = `Error loading resources for MCP Server ${this.options.name}`;
166 if (e instanceof Error) {
167 errorMessage += `: ${e.message}`;
168 }
169 this.errors.push(errorMessage);
170 }
171 }
172
173 // Tools <—> Tools
174 if (capabilities?.tools) {
175 try {
176 const { tools } = await this.client.listTools(
177 {},
178 { signal: timeoutController.signal },
179 );
180 this.tools = tools;
181 } catch (e) {
182 let errorMessage = `Error loading tools for MCP Server ${this.options.name}`;
183 if (e instanceof Error) {
184 errorMessage += `: ${e.message}`;
185 }
186 this.errors.push(errorMessage);
187 }
188 }
189
190 // Prompts <—> Slash commands
191 if (capabilities?.prompts) {
192 try {
193 const { prompts } = await this.client.listPrompts(
194 {},
195 { signal: timeoutController.signal },
196 );
197 this.prompts = prompts;
198 } catch (e) {
199 let errorMessage = `Error loading prompts for MCP Server ${this.options.name}`;
200 if (e instanceof Error) {
201 errorMessage += `: ${e.message}`;
202 }
203 this.errors.push(errorMessage);
204 }
205 }
206
207 this.status = "connected";
208 })(),
209 ]);
210 } catch (error) {
211 // Otherwise it's a connection error
212 let errorMessage = `Failed to connect to "${this.options.name}"\n`;
213 if (error instanceof Error) {
214 const msg = error.message.toLowerCase();
215 if (msg.includes("spawn") && msg.includes("enoent")) {
216 const command = msg.split(" ")[1];
217 errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
218 } else {
219 errorMessage += "Error: " + error.message;
220 }
221 }
222
223 // Include stdio output if available for stdio transport
224 if (
225 this.options.transport.type === "stdio" &&
226 (this.stdioOutput.stdout || this.stdioOutput.stderr)
227 ) {
228 errorMessage += "\n\nProcess output:";
229 if (this.stdioOutput.stdout) {
230 errorMessage += `\nSTDOUT:\n${this.stdioOutput.stdout}`;
231 }
232 if (this.stdioOutput.stderr) {
233 errorMessage += `\nSTDERR:\n${this.stdioOutput.stderr}`;
234 }
235 }
236
237 this.status = "error";
238 this.errors.push(errorMessage);
239 } finally {
240 this.connectionPromise = null;
241 clearTimeout(connectionTimeout);
242 }
243 })(),
244 ]);
245
246 await this.connectionPromise;
247 }
248
249 /**
250 * Resolves the command and arguments for the current platform
251 * On Windows, batch script commands need to be executed via cmd.exe
252 * @param originalCommand The original command
253 * @param originalArgs The original command arguments
254 * @returns An object with the resolved command and arguments
255 */
256 private resolveCommandForPlatform(
257 originalCommand: string,
258 originalArgs: string[],
259 ): { command: string; args: string[] } {
260 // If not on Windows or not a batch command, return as-is
261 if (
262 process.platform !== "win32" ||
263 !WINDOWS_BATCH_COMMANDS.includes(originalCommand)
264 ) {
265 return { command: originalCommand, args: originalArgs };
266 }
267
268 // On Windows, we need to execute batch commands via cmd.exe
269 // Format: cmd.exe /c command [args]
270 return {
271 command: "cmd.exe",
272 args: ["/c", originalCommand, ...originalArgs],
273 };
274 }
275
276 private constructTransport(options: MCPOptions): Transport {
277 switch (options.transport.type) {
278 case "stdio":
279 const env: Record<string, string> = options.transport.env
280 ? { ...options.transport.env }
281 : {};
282
283 if (process.env.PATH !== undefined) {
284 // Set the initial PATH from process.env
285 env.PATH = process.env.PATH;
286
287 // For non-Windows platforms, try to get the PATH from user shell
288 if (process.platform !== "win32") {
289 try {
290 const shellEnvPath = getEnvPathFromUserShell();
291 if (shellEnvPath && shellEnvPath !== process.env.PATH) {
292 env.PATH = shellEnvPath;
293 }
294 } catch (err) {
295 console.error("Error getting PATH:", err);
296 }
297 }
298 }
299
300 // Resolve the command and args for the current platform
301 const { command, args } = this.resolveCommandForPlatform(
302 options.transport.command,
303 options.transport.args || [],
304 );
305
306 const transport = new StdioClientTransport({
307 command,
308 args,
309 env,
310 stderr: "pipe",
311 });
312
313 // Capture stdio output for better error reporting
314
315 transport.stderr?.on("data", (data: Buffer) => {
316 this.stdioOutput.stderr += data.toString();
317 });
318
319 return transport;
320 case "websocket":
321 return new WebSocketClientTransport(new URL(options.transport.url));
322 case "sse":
323 return new SSEClientTransport(new URL(options.transport.url), {
324 eventSourceInit: {
325 fetch: (input, init) =>
326 fetch(input, {
327 ...init,
328 headers: {
329 ...init?.headers,
330 ...(options.transport.requestOptions?.headers as
331 | Record<string, string>
332 | undefined),
333 },
334 }),
335 },
336 requestInit: { headers: options.transport.requestOptions?.headers },
337 });
338 default:
339 throw new Error(
340 `Unsupported transport type: ${(options.transport as any).type}`,
341 );
342 }
343 }
344}
345
346export default MCPConnection;