mcp: suppress subprocess exit error during graceful close
Summary
Fixes #855. When ClientSession.Close() initiates graceful shutdown by closing stdin, the subprocess may exit with a non-zero status. This exit error propagated through pipeRWC.Close() as closeErr, causing spurious errors from ClientSession.Close().
This matches the analysis by @adonovan in golang/go#77336:
"a bug in mcp causing a race between the active part of Close (which breaks the connection and terminates the child process) and the waiting part of close (which seems to observe an error from the terminated child without realizing that close itself was responsible)"
Root cause
The error path traced by @adonovan:
ClientSession.Close()callsconn.Close(), which setsconnClosing = trueupdateInFlightsees idle + closing, callss.closer.Close()(pipeRWC.Close)pipeRWC.Close()closes stdin, then waits forcmd.Wait()- The subprocess (e.g. gopls) sees EOF on stdin, treats it as fatal, exits with code 2
cmd.Wait()returns*exec.ExitError, stored ascloseErrconn.wait(false)returnscloseErrto the caller
The subprocess exited because the client told it to (by closing stdin). The exit code is not meaningful for the client.
Fix
In pipeRWC.Close(), after closing stdin and waiting for the subprocess to exit, suppress *exec.ExitError. Errors from the SIGTERM/SIGKILL fallback paths are still propagated, as those indicate the subprocess did not respond to graceful shutdown.
The fix is at the transport layer (not the jsonrpc2 layer) because only the stdio transport has the semantic knowledge that "I closed stdin, so the subprocess exiting is expected."
Test plan
- Added
TestCmdTransportNonZeroExit: connects to a server that exits with code 2 on shutdown, verifiessession.Close()returns nil - Confirmed the test fails without the fix (
exit status 2) and passes with it - Full test suite passes:
GOWORK=off go test ./... -count=1
cc: @findleyr