From 393b70fc7e8048d36653fa342b6ed2a9f777226a Mon Sep 17 00:00:00 2001 From: mayor Date: Tue, 13 Jan 2026 18:10:43 +0100 Subject: [PATCH] fix(mcp): close existing client before reassignment to prevent leaks When MCP.add() or finishAuth() assigns a new client to s.clients[name], any existing client at that key is orphaned without being closed. This causes connection/resource leaks over time. Add existingClient.close() before reassignment in both locations to properly clean up replaced clients. --- packages/opencode/src/mcp/index.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index aca0c663152..4e0968391f3 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -266,6 +266,13 @@ export namespace MCP { status: s.status, } } + // Close existing client if present to prevent memory leaks + const existingClient = s.clients[name] + if (existingClient) { + await existingClient.close().catch((error) => { + log.error("Failed to close existing MCP client", { name, error }) + }) + } s.clients[name] = result.mcpClient s.status[name] = result.status @@ -523,6 +530,13 @@ export namespace MCP { const s = await state() s.status[name] = result.status if (result.mcpClient) { + // Close existing client if present to prevent memory leaks + const existingClient = s.clients[name] + if (existingClient) { + await existingClient.close().catch((error) => { + log.error("Failed to close existing MCP client", { name, error }) + }) + } s.clients[name] = result.mcpClient } }