Elffuss BraidHub

kikocis/continue public

9d8db5fc402e · 8.1 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
19class MCPConnection {
20 public client: Client;
21 private transport: Transport;
22
23 private connectionPromise: Promise<unknown> | null = null;
24 public abortController: AbortController;
25
26 public status: MCPConnectionStatus = "not-connected";
27 public errors: string[] = [];
28
29 public prompts: MCPPrompt[] = [];
30 public tools: MCPTool[] = [];
31 public resources: MCPResource[] = [];
32
33 constructor(public options: MCPOptions) {
34 this.transport = this.constructTransport(options);
35
36 this.client = new Client(
37 {
38 name: "continue-client",
39 version: "1.0.0",
40 },
41 {
42 capabilities: {},
43 },
44 );
45
46 this.abortController = new AbortController();
47 }
48
49 async disconnect() {
50 this.abortController.abort();
51 await this.client.close();
52 await this.transport.close();
53 }
54
55 private constructTransport(options: MCPOptions): Transport {
56 switch (options.transport.type) {
57 case "stdio":
58 const env: Record<string, string> = options.transport.env
59 ? { ...options.transport.env }
60 : {};
61 if (process.env.PATH !== undefined) {
62 env.PATH = process.env.PATH;
63 }
64 return new StdioClientTransport({
65 command: options.transport.command,
66 args: options.transport.args,
67 env,
68 });
69 case "websocket":
70 return new WebSocketClientTransport(new URL(options.transport.url));
71 case "sse":
72 return new SSEClientTransport(new URL(options.transport.url), {
73 eventSourceInit: {
74 fetch: (input, init) =>
75 fetch(input, {
76 ...init,
77 headers: {
78 ...init?.headers,
79 ...(options.transport.requestOptions?.headers as Record<string, string> | undefined),
80 }
81 }),
82 },
83 requestInit: { headers: options.transport.requestOptions?.headers }
84 });
85 default:
86 throw new Error(
87 `Unsupported transport type: ${(options.transport as any).type}`,
88 );
89 }
90 }
91
92 getStatus(): MCPServerStatus {
93 return {
94 ...this.options,
95 errors: this.errors,
96 prompts: this.prompts,
97 resources: this.resources,
98 tools: this.tools,
99 status: this.status,
100 };
101 }
102
103 async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) {
104 if (!forceRefresh) {
105 // Already connected
106 if (this.status === "connected") {
107 return;
108 }
109
110 // Connection is already in progress; wait for it to complete
111 if (this.connectionPromise) {
112 await this.connectionPromise;
113 return;
114 }
115 }
116
117 this.status = "connecting";
118 this.tools = [];
119 this.prompts = [];
120 this.resources = [];
121 this.errors = [];
122
123 this.abortController.abort();
124 this.abortController = new AbortController();
125
126 this.connectionPromise = Promise.race([
127 // If aborted by a refresh or other, cancel and don't do anything
128 new Promise((resolve) => {
129 externalSignal.addEventListener("abort", () => {
130 resolve(undefined);
131 });
132 }),
133 new Promise((resolve) => {
134 this.abortController.signal.addEventListener("abort", () => {
135 resolve(undefined);
136 });
137 }),
138 (async () => {
139 const timeoutController = new AbortController();
140 const connectionTimeout = setTimeout(
141 () => timeoutController.abort(),
142 this.options.timeout ?? DEFAULT_MCP_TIMEOUT,
143 );
144
145 try {
146 await Promise.race([
147 new Promise((_, reject) => {
148 timeoutController.signal.addEventListener("abort", () => {
149 reject(new Error("Connection timed out"));
150 });
151 }),
152 (async () => {
153 this.transport = this.constructTransport(this.options);
154 try {
155 await this.client.connect(this.transport);
156 } catch (error) {
157 // Allow the case where for whatever reason is already connected
158 if (
159 error instanceof Error &&
160 error.message.startsWith(
161 "StdioClientTransport already started",
162 )
163 ) {
164 await this.client.close();
165 await this.client.connect(this.transport);
166 } else {
167 throw error;
168 }
169 }
170
171 // TODO register server notification handlers
172 // this.client.transport?.onmessage(msg => console.log())
173 // this.client.setNotificationHandler(, notification => {
174 // console.log(notification)
175 // })
176
177 const capabilities = this.client.getServerCapabilities();
178
179 // Resources <—> Context Provider
180 if (capabilities?.resources) {
181 try {
182 const { resources } = await this.client.listResources(
183 {},
184 { signal: timeoutController.signal },
185 );
186 this.resources = resources;
187 } catch (e) {
188 let errorMessage = `Error loading resources for MCP Server ${this.options.name}`;
189 if (e instanceof Error) {
190 errorMessage += `: ${e.message}`;
191 }
192 this.errors.push(errorMessage);
193 }
194 }
195
196 // Tools <—> Tools
197 if (capabilities?.tools) {
198 try {
199 const { tools } = await this.client.listTools(
200 {},
201 { signal: timeoutController.signal },
202 );
203 this.tools = tools;
204 } catch (e) {
205 let errorMessage = `Error loading tools for MCP Server ${this.options.name}`;
206 if (e instanceof Error) {
207 errorMessage += `: ${e.message}`;
208 }
209 this.errors.push(errorMessage);
210 }
211 }
212
213 // Prompts <—> Slash commands
214 if (capabilities?.prompts) {
215 try {
216 const { prompts } = await this.client.listPrompts(
217 {},
218 { signal: timeoutController.signal },
219 );
220 this.prompts = prompts;
221 } catch (e) {
222 let errorMessage = `Error loading prompts for MCP Server ${this.options.name}`;
223 if (e instanceof Error) {
224 errorMessage += `: ${e.message}`;
225 }
226 this.errors.push(errorMessage);
227 }
228 }
229
230 this.status = "connected";
231 })(),
232 ]);
233 } catch (error) {
234 // Otherwise it's a connection error
235 let errorMessage = `Failed to connect to MCP server ${this.options.name}`;
236 if (error instanceof Error) {
237 const msg = error.message.toLowerCase();
238 if (msg.includes("spawn") && msg.includes("enoent")) {
239 const command = msg.split(" ")[1];
240 errorMessage += `command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
241 } else {
242 errorMessage += ": " + error.message;
243 }
244 }
245
246 this.status = "error";
247 this.errors.push(errorMessage);
248 } finally {
249 this.connectionPromise = null;
250 clearTimeout(connectionTimeout);
251 }
252 })(),
253 ]);
254
255 await this.connectionPromise;
256 }
257}
258
259export default MCPConnection;