Skip to content

Commit c37a8f0

Browse files
Julia Iliukhinaclaude
authored andcommitted
fix: use non-deprecated streamable_http_client to prevent connection pool corruption
The deprecated streamablehttp_client has a hidden 5-minute SSE read timeout that causes httpx connection pool corruption when tool handlers return quickly (inline 200 OK response path). This manifests as hangs after ~4 repeated calls. Solution: - Add mcp_compose/http_client.py with streamable_http_client_compat() helper - Helper wraps non-deprecated streamable_http_client with explicit httpx.AsyncClient - Update cli.py, agent.py, and client.py to use the common helper Fixes connection pool corruption issue documented in: - modelcontextprotocol/python-sdk#1941 - modelcontextprotocol/python-sdk#1811 Co-Authored-By: Claude Opus 4.5 <[email protected]>
1 parent 606e714 commit c37a8f0

4 files changed

Lines changed: 112 additions & 68 deletions

File tree

‎examples/anaconda-token/agent.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -236,15 +236,15 @@ async def list_tools(access_token: str | None):
236236
try:
237237
# Import MCP SDK client for streamable HTTP
238238
from mcp import ClientSession
239-
from mcp.client.streamable_http import streamablehttp_client
240-
239+
from mcp_compose.http_client import streamable_http_client_compat
240+
241241
# Build headers - only add Authorization if we have a token
242242
headers = {}
243243
if access_token:
244244
headers["Authorization"] = f"Bearer {access_token}"
245-
246-
# Connect using Streamable HTTP client
247-
async with streamablehttp_client(
245+
246+
# Connect using Streamable HTTP client (non-deprecated)
247+
async with streamable_http_client_compat(
248248
"http://localhost:8080/mcp",
249249
headers=headers if headers else None
250250
) as (read, write, _):

‎mcp_compose/cli.py‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
logger = logging.getLogger(__name__)
2626

2727

28+
from .http_client import streamable_http_client_compat
29+
30+
2831
def setup_logging(verbose: bool = False) -> None:
2932
"""Set up logging configuration."""
3033
level = logging.DEBUG if verbose else logging.INFO
@@ -783,8 +786,7 @@ async def sse_tool_proxy(**kwargs):
783786
)
784787

785788
if protocol_value == "streamable-http":
786-
# Use native MCP streamablehttp_client
787-
from mcp.client.streamable_http import streamablehttp_client
789+
# Use non-deprecated streamable_http_client via helper
788790

789791
# Build headers for authentication
790792
headers = {}
@@ -800,7 +802,7 @@ async def sse_tool_proxy(**kwargs):
800802
else:
801803
headers["Authorization"] = server_config.auth_token
802804

803-
async with streamablehttp_client(
805+
async with streamable_http_client_compat(
804806
url=server_config.url,
805807
headers=headers if headers else None,
806808
timeout=float(server_config.timeout),
@@ -841,9 +843,6 @@ def make_streamable_http_proxy(
841843
async def streamable_http_tool_proxy(**kwargs):
842844
"""Proxy function for streamable HTTP tool."""
843845
from mcp import ClientSession
844-
from mcp.client.streamable_http import (
845-
streamablehttp_client,
846-
)
847846

848847
# Build headers for authentication
849848
hdrs = {}
@@ -866,7 +865,7 @@ async def streamable_http_tool_proxy(**kwargs):
866865
http_config.auth_token
867866
)
868867

869-
async with streamablehttp_client(
868+
async with streamable_http_client_compat(
870869
url=http_config.url,
871870
headers=hdrs if hdrs else None,
872871
timeout=float(http_config.timeout),
@@ -1077,7 +1076,6 @@ async def http_tool_proxy(**kwargs):
10771076
import time
10781077

10791078
from mcp import ClientSession
1080-
from mcp.client.streamable_http import streamablehttp_client
10811079

10821080
from .config import StreamableHttpProxiedServerConfig
10831081

@@ -1131,7 +1129,7 @@ async def http_tool_proxy(**kwargs):
11311129
else:
11321130
headers["Authorization"] = server_config.auth_token
11331131

1134-
async with streamablehttp_client(
1132+
async with streamable_http_client_compat(
11351133
url=server_config.url,
11361134
headers=headers if headers else None,
11371135
timeout=float(server_config.timeout),
@@ -1182,9 +1180,6 @@ def make_streamable_http_proxy(
11821180
async def streamable_http_tool_proxy(**kwargs):
11831181
"""Proxy function for streamable HTTP tool."""
11841182
from mcp import ClientSession
1185-
from mcp.client.streamable_http import (
1186-
streamablehttp_client,
1187-
)
11881183

11891184
# Build headers for authentication
11901185
hdrs = {}
@@ -1200,7 +1195,7 @@ async def streamable_http_tool_proxy(**kwargs):
12001195
else:
12011196
hdrs["Authorization"] = http_config.auth_token
12021197

1203-
async with streamablehttp_client(
1198+
async with streamable_http_client_compat(
12041199
url=http_config.url,
12051200
headers=hdrs if hdrs else None,
12061201
timeout=float(http_config.timeout),

‎mcp_compose/http_client.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Copyright (c) 2025-2026 Datalayer, Inc.
2+
# Distributed under the terms of the Modified BSD License.
3+
4+
"""
5+
HTTP client utilities for MCP Compose.
6+
7+
Provides compatibility wrapper for the MCP SDK's streamable HTTP client.
8+
"""
9+
10+
import httpx
11+
from contextlib import asynccontextmanager
12+
from mcp.client.streamable_http import streamable_http_client
13+
14+
15+
def streamable_http_client_compat(url, headers=None, timeout=30, verify=True):
16+
"""
17+
Compatibility wrapper that provides the same interface as the deprecated
18+
streamablehttp_client but uses the non-deprecated streamable_http_client.
19+
20+
This avoids the 5-minute SSE read timeout issue that causes connection pool
21+
corruption when tool handlers return quickly (inline 200 OK response path).
22+
23+
See: https://github.com/modelcontextprotocol/python-sdk/issues/1941
24+
25+
Args:
26+
url: The MCP server URL (e.g., "http://localhost:8080/mcp")
27+
headers: Optional dict of HTTP headers (e.g., {"Authorization": "Bearer ..."})
28+
timeout: Request timeout in seconds (default: 30)
29+
verify: SSL certificate verification (default: True). Set to False for localhost dev.
30+
31+
Returns:
32+
Async context manager yielding (read_stream, write_stream, get_session_id)
33+
34+
Usage:
35+
async with streamable_http_client_compat(
36+
url="http://localhost:8080/mcp",
37+
headers={"Authorization": "Bearer token"},
38+
timeout=30,
39+
) as (read_stream, write_stream, get_session_id):
40+
async with ClientSession(read_stream, write_stream) as session:
41+
await session.initialize()
42+
result = await session.call_tool("tool_name", {"arg": "value"})
43+
"""
44+
45+
@asynccontextmanager
46+
async def _context():
47+
async with httpx.AsyncClient(
48+
headers=headers,
49+
timeout=httpx.Timeout(float(timeout)),
50+
verify=verify,
51+
) as http_client:
52+
async with streamable_http_client(
53+
url=url,
54+
http_client=http_client,
55+
) as streams:
56+
yield streams
57+
58+
return _context()

‎references/oauth/mcp_oauth_example/client.py‎

Lines changed: 41 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@
3030
# MCP client imports
3131
try:
3232
from mcp import ClientSession
33-
from mcp.client.streamable_http import streamablehttp_client
34-
import httpx
33+
from mcp_compose.http_client import streamable_http_client_compat
3534
HAS_MCP = True
3635
except ImportError:
3736
HAS_MCP = False
@@ -91,22 +90,18 @@ async def _list_tools():
9190
# Disable SSL verification for localhost (development with mkcert)
9291
server_url = self.oauth.get_server_url()
9392
verify_ssl = not server_url.startswith("https://localhost")
94-
95-
# Create HTTP client with auth headers
96-
async with httpx.AsyncClient(
93+
94+
# Connect using non-deprecated streamable HTTP client
95+
async with streamable_http_client_compat(
96+
f"{self.oauth.get_server_url()}/mcp",
9797
headers={"Authorization": f"Bearer {self.access_token}"},
9898
timeout=30.0,
99-
verify=verify_ssl
100-
) as http_client:
101-
# Connect using MCP SDK's streamable HTTP client
102-
async with streamablehttp_client(
103-
f"{self.oauth.get_server_url()}/mcp",
104-
http_client=http_client
105-
) as (read_stream, write_stream):
106-
async with ClientSession(read_stream, write_stream) as session:
107-
await session.initialize()
108-
tools_list = await session.list_tools()
109-
return tools_list
99+
verify=verify_ssl,
100+
) as (read_stream, write_stream, _):
101+
async with ClientSession(read_stream, write_stream) as session:
102+
await session.initialize()
103+
tools_list = await session.list_tools()
104+
return tools_list
110105

111106
# Run async function
112107
tools_list = asyncio.run(_list_tools())
@@ -153,44 +148,40 @@ async def invoke_tool_mcp(self, tool_name: str, arguments: Dict[str, Any]) -> Op
153148
# Disable SSL verification for localhost (development with mkcert)
154149
server_url = self.oauth.get_server_url()
155150
verify_ssl = not server_url.startswith("https://localhost")
156-
157-
# Create HTTP client with auth headers
158-
async with httpx.AsyncClient(
151+
152+
# Connect using non-deprecated streamable HTTP client
153+
async with streamable_http_client_compat(
154+
f"{self.oauth.get_server_url()}/mcp",
159155
headers={"Authorization": f"Bearer {self.access_token}"},
160156
timeout=30.0,
161-
verify=verify_ssl
162-
) as http_client:
163-
# Connect to MCP server via HTTP streaming
164-
async with streamablehttp_client(
165-
f"{self.oauth.get_server_url()}/mcp",
166-
http_client=http_client
167-
) as (read_stream, write_stream):
168-
async with ClientSession(read_stream, write_stream) as session:
169-
# Initialize the session
170-
await session.initialize()
171-
172-
# Call the tool
173-
result = await session.call_tool(tool_name, arguments)
174-
175-
# Extract content from result
176-
if hasattr(result, 'content'):
177-
content = result.content
178-
if isinstance(content, list) and len(content) > 0:
179-
# Get the text content from the first item
180-
first_content = content[0]
181-
if hasattr(first_content, 'text'):
182-
result_text = first_content.text
183-
else:
184-
result_text = str(first_content)
157+
verify=verify_ssl,
158+
) as (read_stream, write_stream, _):
159+
async with ClientSession(read_stream, write_stream) as session:
160+
# Initialize the session
161+
await session.initialize()
162+
163+
# Call the tool
164+
result = await session.call_tool(tool_name, arguments)
165+
166+
# Extract content from result
167+
if hasattr(result, 'content'):
168+
content = result.content
169+
if isinstance(content, list) and len(content) > 0:
170+
# Get the text content from the first item
171+
first_content = content[0]
172+
if hasattr(first_content, 'text'):
173+
result_text = first_content.text
185174
else:
186-
result_text = str(content)
175+
result_text = str(first_content)
187176
else:
188-
result_text = str(result)
189-
190-
print(f"✅ Tool invoked successfully")
191-
print(f" Result: {result_text}")
192-
193-
return result
177+
result_text = str(content)
178+
else:
179+
result_text = str(result)
180+
181+
print(f"✅ Tool invoked successfully")
182+
print(f" Result: {result_text}")
183+
184+
return result
194185

195186
except Exception as e:
196187
print(f"❌ Error invoking tool: {e}")

0 commit comments

Comments
 (0)