Skip to content

Conversation

@quuu
Copy link
Collaborator

@quuu quuu commented Aug 13, 2025

This pull request addresses a memory leak issue in the SSE (Server-Sent Events) handling logic of the MCP API handler by introducing robust resource cleanup and tracking mechanisms. The main improvements include using a WeakMap to track server metadata, implementing comprehensive cleanup routines for SSE connections, and ensuring all Redis subscriptions and timers are properly released. These changes help prevent resource leaks and improve the stability and reliability of the SSE endpoints.

Memory leak prevention and resource management:

  • Introduced a WeakMap (serverMetadata) to track metadata for each McpServer instance, allowing for automatic garbage collection when servers are no longer referenced.
  • Added a periodic cleanup interval that scans for and removes stale or orphaned servers every 30 seconds, closing their resources and cleaning up metadata.
  • Refactored the SSE connection lifecycle by implementing a comprehensive cleanup function that handles timer clearing, Redis unsubscription, event detachment, and memory release for each connection. This function is now invoked on multiple events (connection close, error, abort, or timeout). [1] [2] [3]
  • Ensured that all Redis subscriptions are unsubscribed and timers are cleared for both /sse and /message endpoints, even in error or timeout scenarios, preventing resource leaks. [1] [2]

Bug fix:

  • Fixed a memory leak when using SSE connections, as documented in the changeset.

@quuu quuu mentioned this pull request Aug 13, 2025
@quuu quuu merged commit 956dc11 into main Aug 25, 2025
1 check passed
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.

2 participants