Elffuss BraidHub

kikocis/continue public

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