Elffuss BraidHub

kikocis/continue public

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