Skip to content

Commit c4b8ebe

Browse files
authored
fix(mcp): ensure database and memory manager sync across server instances (#229)
…ction and disconnection handling
1 parent 35d62e0 commit c4b8ebe

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

src/app/api/mcp/list/route.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,26 @@ export async function GET() {
1212
memoryClients.map(({ id, client }) => [id, client] as const),
1313
);
1414

15+
const addTargets = servers.filter((server) => !memoryMap.has(server.id));
16+
17+
const serverIds = new Set(servers.map((s) => s.id));
18+
const removeTargets = memoryClients.filter(({ id }) => !serverIds.has(id));
19+
20+
if (addTargets.length > 0) {
21+
// no need to wait for this
22+
Promise.allSettled(
23+
addTargets.map((server) => mcpClientsManager.refreshClient(server.id)),
24+
);
25+
}
26+
if (removeTargets.length > 0) {
27+
// no need to wait for this
28+
Promise.allSettled(
29+
removeTargets.map((client) =>
30+
mcpClientsManager.disconnectClient(client.id),
31+
),
32+
);
33+
}
34+
1535
const result = servers.map((server) => {
1636
const mem = memoryMap.get(server.id);
1737
const info = mem?.getInfo();

src/lib/ai/mcp/create-mcp-clients-manager.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,13 +185,16 @@ export class MCPClientsManager {
185185
* Removes a client by name, disposing resources and removing from storage
186186
*/
187187
async removeClient(id: string) {
188-
const client = this.clients.get(id);
189-
190188
if (this.storage) {
191189
if (await this.storage.has(id)) {
192190
await this.storage.delete(id);
193191
}
194192
}
193+
this.disconnectClient(id);
194+
}
195+
196+
async disconnectClient(id: string) {
197+
const client = this.clients.get(id);
195198
this.clients.delete(id);
196199
if (client) {
197200
void client.client.disconnect();

0 commit comments

Comments
 (0)