Elffuss BraidHub

kikocis/continue public

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