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