Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/app/script/e2e-local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ try {
Object.assign(process.env, serverEnv)
process.env.AGENT = "1"
process.env.OPENCODE = "1"
process.env.OPENCODE_PID = String(process.pid)

const log = await import("../../opencode/src/util/log")
const install = await import("../../opencode/src/installation")
Expand Down
1 change: 1 addition & 0 deletions packages/opencode/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ let cli = yargs(hideBin(process.argv))

process.env.AGENT = "1"
process.env.OPENCODE = "1"
process.env.OPENCODE_PID = String(process.pid)

Log.Default.info("opencode", {
version: Installation.VERSION,
Expand Down
37 changes: 37 additions & 0 deletions packages/opencode/src/mcp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,28 @@ export namespace MCP {
return typeof entry === "object" && entry !== null && "type" in entry
}

async function descendants(pid: number): Promise<number[]> {
if (process.platform === "win32") return []
const pids: number[] = []
const queue = [pid]
while (queue.length > 0) {
const current = queue.shift()!
const proc = Bun.spawn(["pgrep", "-P", String(current)], { stdout: "pipe", stderr: "pipe" })
const [code, out] = await Promise.all([proc.exited, new Response(proc.stdout).text()]).catch(
() => [-1, ""] as const,
)
if (code !== 0) continue
for (const tok of out.trim().split(/\s+/)) {
const cpid = parseInt(tok, 10)
if (!isNaN(cpid) && pids.indexOf(cpid) === -1) {
pids.push(cpid)
queue.push(cpid)
}
}
}
return pids
}

const state = Instance.state(
async () => {
const cfg = await Config.get()
Expand Down Expand Up @@ -196,6 +218,21 @@ export namespace MCP {
}
},
async (state) => {
// The MCP SDK only signals the direct child process on close.
// Servers like chrome-devtools-mcp spawn grandchild processes
// (e.g. Chrome) that the SDK never reaches, leaving them orphaned.
// Kill the full descendant tree first so the server exits promptly
// and no processes are left behind.
for (const client of Object.values(state.clients)) {
const pid = (client.transport as any)?.pid
if (typeof pid !== "number") continue
for (const dpid of await descendants(pid)) {
try {
process.kill(dpid, "SIGTERM")
} catch {}
}
}

await Promise.all(
Object.values(state.clients).map((client) =>
client.close().catch((error) => {
Expand Down
Loading