Elffuss BraidHub

kikocis/continue public

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