Elffuss BraidHub

kikocis/continue public

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