[PR #9145] fix(mcp): Fix memory leaks in OAuth transport and process cleanup #13002

Open
opened 2026-02-16 18:17:53 -05:00 by yindo · 0 comments
Owner

Original Pull Request: https://github.com/anomalyco/opencode/pull/9145

State: open
Merged: No


Summary

Fix memory leaks in MCP OAuth transport management and add process exit cleanup to prevent orphaned MCP server processes.

Fixes #9153
Relates to #5363

Problem

  1. OAuth transport leaks: When MCP OAuth flows retry, a new transport is created for the same server but the previous transport is never closed. Similarly, removeAuth() deletes the map entry without closing the transport.
  2. Orphan processes: MCP server child processes continue running after the main process exits because there is no cleanup handler.

Solution

Transport Cleanup (mcp/index.ts)

  • Add closeTransport() helper that safely calls .close() on a transport
  • Add setPendingOAuthTransport() that closes old transports before replacing them
  • Close transport in removeAuth() before deleting the map entry

Process Exit Cleanup (index.ts)

  • Register SIGINT/SIGTERM handlers that call Instance.disposeAll() before exit
  • Call cleanup in the existing finally block for normal exit paths
  • Guard against duplicate cleanup with a cleanupDone flag

Testing

  • TypeScript compilation passes (bun turbo typecheck)
  • Unit tests pass

AI-Assisted

Yes

**Original Pull Request:** https://github.com/anomalyco/opencode/pull/9145 **State:** open **Merged:** No --- ## Summary Fix memory leaks in MCP OAuth transport management and add process exit cleanup to prevent orphaned MCP server processes. Fixes #9153 Relates to #5363 ## Problem 1. **OAuth transport leaks**: When MCP OAuth flows retry, a new transport is created for the same server but the previous transport is never closed. Similarly, `removeAuth()` deletes the map entry without closing the transport. 2. **Orphan processes**: MCP server child processes continue running after the main process exits because there is no cleanup handler. ## Solution ### Transport Cleanup (`mcp/index.ts`) - Add `closeTransport()` helper that safely calls `.close()` on a transport - Add `setPendingOAuthTransport()` that closes old transports before replacing them - Close transport in `removeAuth()` before deleting the map entry ### Process Exit Cleanup (`index.ts`) - Register `SIGINT`/`SIGTERM` handlers that call `Instance.disposeAll()` before exit - Call cleanup in the existing `finally` block for normal exit paths - Guard against duplicate cleanup with a `cleanupDone` flag ## Testing - [x] TypeScript compilation passes (`bun turbo typecheck`) - [x] Unit tests pass ## AI-Assisted Yes
yindo added the pull-request label 2026-02-16 18:17:53 -05:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: anomalyco/opencode#13002