Elffuss BraidHub

kikocis/continue public

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