fix(mcp): Fix memory leaks in OAuth transport and process cleanup
Summary
Add proper cleanup for MCP (Model Context Protocol) OAuth transports and process lifecycle management to prevent resource leaks.
Fixes #9153 Relates to #5363
Problem
When MCP OAuth flows are initiated, transports stored in pendingOAuthTransports Map are never closed when:
- OAuth retry - A new transport is created for the same server, orphaning the previous one
- OAuth cancellation -
removeAuth()deletes the map entry but doesn't close the transport - Process exit - MCP server processes may continue running as orphans
Solution
Add proper transport lifecycle management:
- Add
closeTransport()helper function to properly close transports - Add
setPendingOAuthTransport()that closes old transports before setting new ones - Close transport in
removeAuth()before deletion - Add signal handlers for SIGINT/SIGTERM to dispose instances on exit
- Wrap main CLI in proper cleanup handlers
Changes
-
packages/opencode/src/mcp/index.ts- Add transport cleanup helpers and update OAuth flow -
packages/opencode/src/index.ts- Add signal handlers and main() wrapper with cleanup
Testing
- [x] TypeScript compilation passes (
bun turbo typecheck) - [x] Unit tests pass (725 tests, 0 failures)
- [x] MCP header tests pass
Note: Manual MCP OAuth flow and process cleanup testing was not performed.
Thanks for your contribution!
This PR doesn't have a linked issue. All PRs must reference an existing issue.
Please:
- Open an issue describing the bug/feature (if one doesn't exist)
- Add
Fixes #<number>orCloses #<number>to this PR description
See CONTRIBUTING.md for details.
The following comment was made by an LLM, it may be inaccurate:
Based on my search, I found one potentially related PR that addresses similar concerns:
Related PR Found:
-
#7424: fix: force kill MCP server processes on dispose to prevent orphan processes
- This PR also addresses orphaned MCP processes, which is one of the two main issues in PR #9145. However, this appears to be a different approach using force kill on dispose rather than graceful shutdown with exit handlers.
The searches did not reveal any other open PRs that directly duplicate the work in PR #9145. The current PR (#9145) appears to be the first to comprehensively address both OAuth transport leaks and orphaned process cleanup together through the mechanisms described.