Elffuss BraidHub

kikocis/continue public

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