Elffuss BraidHub

kikocis/continue public

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