opencode
opencode copied to clipboard
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.