Elffuss BraidHub

kikocis/continue public

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