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 3 days 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

Thanks for your contribution!

This PR doesn't have a linked issue. All PRs must reference an existing issue.

Please:

  1. Open an issue describing the bug/feature (if one doesn't exist)
  2. Add Fixes #<number> or Closes #<number> to this PR description

See CONTRIBUTING.md for details.

github-actions[bot] avatar Jan 17 '26 23:01 github-actions[bot]

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:

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.

github-actions[bot] avatar Jan 17 '26 23:01 github-actions[bot]