MCP session refcount grows on repeated acquisition by the same context
Bug Description
MCPSessionManager.get_session() increments a pooled session's reference count every time an already-mapped context_id asks for that same healthy session. MCP clients call this path repeatedly (for example while listing tools and before each tool invocation), but disconnect() releases a context only once.
The context mapping is overwritten with the same (server_key, session_id) pair while the reference count keeps increasing. After disconnect, the mapping is gone but the refcount remains positive, so the HTTP connection or stdio subprocess cannot be released through that context and can remain alive until idle cleanup.
This affects both stdio and Streamable HTTP transports on release-1.13.0.
Reproduction
- Create an
MCPSessionManagerwith a mocked live transport task. - Call
get_session("same-context", params, transport)several times. - Observe one physical session but a refcount equal to the number of calls.
- Call
_cleanup_session("same-context")once. - Observe that the context mapping is removed while the session still has a positive refcount and remains allocated.
A focused regression assertion is:
first = await manager.get_session("ctx", params, "streamable_http")
second = await manager.get_session("ctx", params, "streamable_http")
assert first is second
assert manager._session_refcount[pair] == 1 # currently 2
await manager._cleanup_session("ctx")
assert pair not in manager._session_refcountThe existing session-caching test asserts object reuse and creation count, but does not assert reference ownership.
Expected behavior
A context should acquire a given pooled session at most once. Repeated access by the same context should update last_used and return the session without increasing its refcount. One disconnect should release that context's single ownership.
Environment
- Branch:
release-1.13.0 - Commit checked:
05b6498e8b54c2d89042afc2e2a96c452dd12002 - OS: Windows 11 (logic is platform-independent)
- Python: 3.12
Source: langflow-ai/langflow