fix: close existing MCP client before spawning replacement in connect()

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().
This commit is contained in:
Alex Alecu
2026-02-25 13:17:31 +02:00
parent 5d22ab6368
commit bc63efdd81
+10 -7
View File
@@ -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
}
}