mcp-language-server icon indicating copy to clipboard operation
mcp-language-server copied to clipboard

Shut down the LSP child reliably when the server is orphaned

Open briiiqtt opened this issue 5 months ago • 0 comments

Summary

When the host that launched this MCP server goes away, the spawned LSP child process must not be left running. This change makes teardown reliable, concurrency-safe, and bounded across the shutdown paths.

main.go

  • Trigger shutdown on stdin EOF (the primary, cross-platform signal) and on a getppid() reparent-to-PID-1 backstop for the pty/held-pipe case where stdio stays open. The poll is conservative (only the PID-1 reparent case) to avoid killing the child when an intermediate process in a wrapper/subreaper chain exits mid-session; its known gap under a Linux PR_SET_CHILD_SUBREAPER ancestor is documented.
  • Run cleanup once (cleanupOnce) and bound it with a 5s backstop run in a goroutine so a wedged Close() / Cmd.Wait() can never block process exit, including the orphan case where ServeStdio never returns.
  • Normalize mcp-go's context.Canceled (its own signal handler) to nil so an intentional shutdown exits 0, while preserving genuine start() failures as exit 1.
  • Resolve the init-time orphan race with an lspClientMu + shuttingDown handshake so exactly one path owns closing the freshly spawned child.

internal/lsp/client.go, transport.go

  • Make teardown concurrency-safe: closeOnce serializes the full teardown (CloseAllFiles → shutdown/exit → stdin close → Cmd.Wait), with a bounded force-kill backstop and a single-close killDone.
  • Serialize all stdin writes under stdinMu; close stdin outside the lock so a writer parked on a full pipe is unblocked.
  • Signal a closed channel so an in-flight Call no longer parks forever. It is signalled both by Close() and by handleMessages on read-loop exit (LSP server death: stdout EOF or crash); a dedicated closedOnce guards the close so both paths are safe against a double-close panic.

🤖 Generated with Claude Code

briiiqtt avatar Jun 05 '26 13:06 briiiqtt