Elffuss BraidHub

kikocis/continue public

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