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