From bc63efdd8130790690fad620c5c2f9b26eb5e612 Mon Sep 17 00:00:00 2001 From: Alex Alecu Date: Wed, 25 Feb 2026 13:17:31 +0200 Subject: [PATCH] fix: close existing MCP client before spawning replacement in connect() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously, connect() called create() (which spawns a new child process and writes processes[key]) before closing the existing client. The old client's close handler would then delete processes[key], removing the *new* process entry from the map — losing track of the new child. Move the existing client close to before create(), matching the pattern already used in add(). --- packages/opencode/src/mcp/index.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index d561600e87d..d2d2a6e4c93 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -595,6 +595,16 @@ export namespace MCP { } const s = await state() + // kilocode_change start — close existing client *before* creating a new one to prevent + // process map corruption (old close could delete the new process entry) + const existingClient = s.clients[name] + if (existingClient) { + await existingClient.close().catch((error) => { + log.error("Failed to close existing MCP client", { name, error }) + }) + delete s.clients[name] + } + // kilocode_change end const result = await create(name, { ...mcp, enabled: true }, s.processes) // kilocode_change — pass processes if (!result) { @@ -606,13 +616,6 @@ export namespace MCP { } 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 } }