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