Skip to content

Conversation

@certainly-param
Copy link

Fixes #1450

I found that HTTP responses don't get closed properly when SSE streaming fails with exceptions in the streamable HTTP client.

The Problem:
When the async for loop in _handle_sse_response and _handle_resumption_request throws an exception (malformed JSON, network error, etc.), the response is never closed because response.aclose() is only called in the success path.

Impact:
This can cause connection pool exhaustion in long-running clients, eventually causing new requests to hang or fail.

What I Added:

  • test_resource_leak_reproduction.py - Standalone script that demonstrates the issue
  • tests/client/test_streamable_http_resource_leak.py - Pytest tests that verify the resource leak and show how the fix should work

Both test files show that when SSE parsing fails, the response doesn't get closed, confirming the resource leak.

The Fix:
The methods need finally blocks to ensure response.aclose() is always called:

try:
    # ... existing code ...
except Exception as e:
    # ... existing exception handling ...
finally:
    await response.aclose()

This ensures resources are properly cleaned up regardless of whether exceptions occur.

Fixes modelcontextprotocol#1450 - HTTP responses don't get closed properly when SSE streaming fails
with exceptions in _handle_sse_response and _handle_resumption_request.

The issue: when the async for loop throws an exception, response.aclose()
never gets called because it's only in the success path.

Added reproduction script and pytest tests to demonstrate the problem.
The fix requires adding finally blocks to ensure response.aclose() always gets called.
@certainly-param certainly-param force-pushed the fix-streamable-http-resource-leak branch from 1b4bf1e to d2f7de8 Compare October 17, 2025 15:57
@felixweinberger felixweinberger added bug Something isn't working needs maintainer action Potentially serious issue - needs proactive fix and maintainer attention P0 Broken core functionality, security issues, critical missing feature labels Oct 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working needs maintainer action Potentially serious issue - needs proactive fix and maintainer attention P0 Broken core functionality, security issues, critical missing feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Response leak in SSE handlers

2 participants