Skip to content

Conversation

@sauerdaniel
Copy link
Contributor

@sauerdaniel sauerdaniel commented Jan 17, 2026

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

  • TypeScript compilation passes (bun turbo typecheck)
  • Unit tests pass (725 tests, 0 failures)
  • MCP header tests pass

Note: Manual MCP OAuth flow and process cleanup testing was not performed.

Close existing client before reassigning to prevent transport layer
memory leaks. Add proper cleanup in MCP client lifecycle.
Register process exit handler to properly clean up MCP server connections
when the main process terminates, preventing orphaned child processes.
@github-actions
Copy link
Contributor

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
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Memory leak: MCP OAuth transports not closed on retry or cancellation

1 participant