Elffuss BraidHub

kikocis/continue public

0cbdfa622ced · 6.0 KiBRawPermalink
1import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
3import {
4 MCPOptions,
5 MCPServerStatus,
6 StdioOptions,
7 TransportOptions,
8} from "../..";
9import MCPConnection, { MCPExtras } from "./MCPConnection";
10
11export class MCPManagerSingleton {
12 private static instance: MCPManagerSingleton;
13
14 public onConnectionsRefreshed?: () => void;
15 public connections: Map<string, MCPConnection> = new Map();
16 private disconnectedServers: string[] = [];
17
18 private abortController: AbortController = new AbortController();
19
20 private constructor() {}
21
22 public static getInstance(): MCPManagerSingleton {
23 if (!MCPManagerSingleton.instance) {
24 MCPManagerSingleton.instance = new MCPManagerSingleton();
25 }
26 return MCPManagerSingleton.instance;
27 }
28
29 addDisconnectedServer(serverId: string) {
30 this.disconnectedServers.push(serverId);
31 }
32 removeDisconnectedServer(serverId: string) {
33 this.disconnectedServers = this.disconnectedServers.filter(
34 (server) => server !== serverId,
35 );
36 }
37 getDisconnectedServers() {
38 return this.disconnectedServers;
39 }
40
41 createConnection(id: string, options: MCPOptions): MCPConnection {
42 if (this.connections.has(id)) {
43 return this.connections.get(id)!;
44 } else {
45 const connection = new MCPConnection(options);
46 this.connections.set(id, connection);
47 return connection;
48 }
49 }
50
51 getConnection(id: string) {
52 return this.connections.get(id);
53 }
54
55 async removeConnection(id: string) {
56 const connection = this.connections.get(id);
57 if (connection) {
58 await connection.client.close();
59 }
60
61 this.connections.delete(id);
62 }
63
64 async shutdown() {
65 if (this.connections.size > 0) {
66 await Promise.allSettled(
67 Array.from(this.connections.entries()).map(([id, connection]) => {
68 try {
69 connection.abortController.abort();
70 void connection.client.close();
71 } finally {
72 this.connections.delete(id);
73 }
74 }),
75 );
76 }
77 }
78
79 setConnections(
80 servers: MCPOptions[],
81 forceRefresh: boolean,
82 extras?: MCPExtras,
83 ) {
84 let refresh = false;
85
86 // Remove any connections that are no longer in config
87 Array.from(this.connections.entries()).forEach(([id, connection]) => {
88 if (
89 !servers.find(
90 // Refresh the connection if TransportOptions changed
91 (s) =>
92 s.id === id &&
93 this.compareTransportOptions(
94 connection.options.transport,
95 s.transport,
96 ),
97 )
98 ) {
99 refresh = true;
100 connection.abortController.abort();
101 void connection.client.close();
102 this.connections.delete(id);
103 }
104 });
105
106 // Add any connections that are not yet in manager
107 servers.forEach((server) => {
108 if (this.connections.has(server.id)) {
109 const conn = this.connections.get(server.id);
110 if (conn) {
111 // We need to update it. Some attributes may have changed, such as name, faviconUrl, etc.
112 conn.options = server;
113 }
114 } else {
115 refresh = true;
116 this.connections.set(server.id, new MCPConnection(server, extras));
117 }
118 });
119
120 // NOTE the id is made by stringifying the options
121 if (refresh) {
122 void this.refreshConnections(forceRefresh);
123 }
124 }
125
126 private compareTransportOptions(
127 a: TransportOptions,
128 b: TransportOptions,
129 ): boolean {
130 if (a.type !== b.type) {
131 return false;
132 }
133 if (a.type === "stdio" && b.type === "stdio") {
134 return (
135 a.command === b.command &&
136 JSON.stringify(a.args) === JSON.stringify(b.args) &&
137 this.compareEnv(a, b)
138 );
139 } else if (a.type !== "stdio" && b.type !== "stdio") {
140 return a.url === b.url;
141 }
142 return false;
143 }
144
145 private compareEnv(a: StdioOptions, b: StdioOptions): boolean {
146 const aEnv = a.env ?? {};
147 const bEnv = b.env ?? {};
148 const aKeys = Object.keys(aEnv);
149 const bKeys = Object.keys(bEnv);
150
151 return (
152 aKeys.length === bKeys.length &&
153 aKeys.every((key) => aEnv[key] === bEnv[key])
154 );
155 }
156
157 async refreshConnection(serverId: string) {
158 const connection = this.connections.get(serverId);
159 if (!connection) {
160 throw new Error(`MCP Connection ${serverId} not found`);
161 }
162 await connection.connectClient(true, this.abortController.signal);
163 if (this.onConnectionsRefreshed) {
164 this.onConnectionsRefreshed();
165 }
166 }
167
168 async refreshConnections(force: boolean) {
169 this.abortController.abort();
170 this.abortController = new AbortController();
171 await Promise.race([
172 new Promise((resolve) => {
173 this.abortController.signal.addEventListener("abort", () => {
174 resolve(undefined);
175 });
176 }),
177 (async () => {
178 await Promise.all(
179 Array.from(this.connections.values())
180 .filter(
181 (connection) =>
182 !this.disconnectedServers.some(
183 (s) => s === connection.options.id,
184 ),
185 )
186 .map(async (connection) => {
187 await connection.connectClient(
188 force,
189 this.abortController.signal,
190 );
191 }),
192 );
193 if (this.onConnectionsRefreshed) {
194 this.onConnectionsRefreshed();
195 }
196 })(),
197 ]);
198 }
199
200 getStatuses(): (MCPServerStatus & { client: Client })[] {
201 return Array.from(this.connections.values()).map((connection) => ({
202 ...connection.getStatus(),
203 client: connection.client,
204 }));
205 }
206
207 setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) {
208 this.connections.get(server.id)!.status = status;
209 }
210
211 async getPrompt(
212 serverName: string,
213 promptName: string,
214 args: Record<string, string> = {},
215 ) {
216 const connection = this.connections.get(serverName);
217 if (!connection) {
218 throw new Error(
219 `Error getting prompt: MCP Connection ${serverName} not found`,
220 );
221 }
222 return await connection.client.getPrompt({
223 name: promptName,
224 arguments: args,
225 });
226 }
227}