Skip to content

Commit 55cef01

Browse files
committed
fix(mcp): register process exit handler to dispose instances and prevent orphan processes
1 parent 679c542 commit 55cef01

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

packages/opencode/src/index.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import { PrCommand } from "./cli/cmd/pr"
2929
import { SessionCommand } from "./cli/cmd/session"
3030
import { DbCommand } from "./cli/cmd/db"
3131
import path from "path"
32+
import { Instance } from "./project/instance"
3233
import { Global } from "./global"
3334
import { JsonMigration } from "./storage/json-migration"
3435
import { Database } from "./storage/db"
@@ -155,6 +156,19 @@ const cli = yargs(hideBin(process.argv))
155156
})
156157
.strict()
157158

159+
// Dispose instances on termination to prevent orphan MCP/LSP processes
160+
let cleanupDone = false
161+
async function cleanup(signal: string) {
162+
if (cleanupDone) return
163+
cleanupDone = true
164+
Log.Default.info("cleanup triggered", { signal })
165+
try {
166+
await Instance.disposeAll()
167+
} catch {}
168+
}
169+
process.on("SIGINT", () => cleanup("SIGINT").then(() => process.exit(130)))
170+
process.on("SIGTERM", () => cleanup("SIGTERM").then(() => process.exit(143)))
171+
158172
try {
159173
await cli.parse()
160174
} catch (e) {
@@ -195,6 +209,7 @@ try {
195209
}
196210
process.exitCode = 1
197211
} finally {
212+
await cleanup("exit")
198213
// Some subprocesses don't react properly to SIGTERM and similar signals.
199214
// Most notably, some docker-container-based MCP servers don't handle such signals unless
200215
// run using `docker run --init`.

0 commit comments

Comments
 (0)