-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Description
Initial Checks
- I confirm that I'm using the latest version of MCP Python SDK
- I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
Description
There appears to be a memory leak in the session management code. The _server_instances
dictionary grows as new sessions are created, but entries are only removed if a session crashes. When a session is terminated normally, its transport instance remains in the dictionary and is never cleaned up. Over time, this can lead to unbounded memory usage.
Expected behavior:
Session entries in _server_instances
should eventually be removed if they are no longer active or being reused, to avoid memory leaks.
Steps to reproduce:
- Start the server and create multiple sessions.
- Allow sessions to become idle (no further requests sent).
- Observe that
_server_instances
retains references to all idle sessions indefinitely, even after reasonable inactivity.
Clarification:
It is not correct to simply remove a session from the dictionary when an HTTP request terminates normally, because the same session may be reused by subsequent requests. The issue is that if no further requests ever come for that session, the idle session remains in memory.
Suggested fix:
Implement a session timeout or idle cleanup mechanism so that sessions which haven't received any activity for a configurable period are automatically cleaned up and removed from _server_instances
.
Additional notes:
This is not related to any specific Python version. The problem is seen on the current master branch. I am aware that session timeout/cleanup logic is needed to prevent accumulation of idle sessions and associated transports.
See the relevant code in streamable_http_manager.py
— this is currently the only place where a HTTP transport is ever removed from the _server_instances
dict (specifically, when a session crashes).
Example Code
No code sample provided, but the issue can be traced to the session lifecycle management in `StreamableHTTPSessionManager` (see `_handle_stateful_request`).
See code: https://github.com/modelcontextprotocol/python-sdk/blob/d1ac8d68eb2d7ed139bdc2608b8b4e2ec4265be5/src/mcp/server/streamable_http_manager.py
Python & MCP Python SDK
This issue is not related to a specific Python version. The problem is observed on the current master branch of the repository.