opencode icon indicating copy to clipboard operation
opencode copied to clipboard

fix(mcp): Fix memory leaks in OAuth transport and process cleanup

Open sauerdaniel opened this issue 18 hours ago • 2 comments

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:

  1. OAuth retry - A new transport is created for the same server, orphaning the previous one
  2. OAuth cancellation - removeAuth() deletes the map entry but doesn't close the transport
  3. 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.

sauerdaniel avatar Jan 17 '26 23:01 sauerdaniel