Skip to content

Commit 90af4b2

Browse files
refactor: Simplify StreamableHTTPTransport to respect client configuration
Implements "principle of least surprise" by making the httpx client the single source of truth for HTTP configuration (headers, timeout, auth). Changes: - StreamableHTTPTransport constructor now only takes url parameter - Transport reads configuration from client when making requests - Removed redundant config extraction and storage - Removed headers and sse_read_timeout from RequestContext - Removed MCP_DEFAULT_TIMEOUT and MCP_DEFAULT_SSE_READ_TIMEOUT from _httpx_utils public API (__all__) This addresses PR feedback about awkward config extraction when client is provided. The transport now only adds protocol requirements (MCP headers, session headers) on top of the client's configuration rather than extracting and overriding it. All tests pass, no type errors.
1 parent 7a49c97 commit 90af4b2

File tree

2 files changed

+28
-47
lines changed

2 files changed

+28
-47
lines changed

src/mcp/client/streamable_http.py

Lines changed: 27 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,7 @@
2020
from httpx_sse import EventSource, ServerSentEvent, aconnect_sse
2121
from typing_extensions import deprecated
2222

23-
from mcp.shared._httpx_utils import (
24-
MCP_DEFAULT_SSE_READ_TIMEOUT,
25-
MCP_DEFAULT_TIMEOUT,
26-
McpHttpClientFactory,
27-
create_mcp_http_client,
28-
)
23+
from mcp.shared._httpx_utils import McpHttpClientFactory, create_mcp_http_client
2924
from mcp.shared.message import ClientMessageMetadata, SessionMessage
3025
from mcp.types import (
3126
ErrorData,
@@ -70,12 +65,10 @@ class RequestContext:
7065
"""Context for a request operation."""
7166

7267
client: httpx.AsyncClient
73-
headers: dict[str, str]
7468
session_id: str | None
7569
session_message: SessionMessage
7670
metadata: ClientMessageMetadata | None
7771
read_stream_writer: StreamWriter
78-
sse_read_timeout: float
7972

8073

8174
class StreamableHTTPTransport:
@@ -93,29 +86,31 @@ def __init__(
9386
9487
Args:
9588
url: The endpoint URL.
96-
headers: Optional headers to include in requests.
97-
timeout: HTTP timeout for regular operations.
98-
sse_read_timeout: Timeout for SSE read operations.
99-
auth: Optional HTTPX authentication handler.
89+
headers: DEPRECATED - Ignored. Configure headers on the httpx.AsyncClient instead.
90+
timeout: DEPRECATED - Ignored. Configure timeout on the httpx.AsyncClient instead.
91+
sse_read_timeout: DEPRECATED - Ignored. Configure read timeout on the httpx.AsyncClient instead.
92+
auth: DEPRECATED - Ignored. Configure auth on the httpx.AsyncClient instead.
10093
"""
10194
self.url = url
102-
self.headers = headers or {}
103-
self.timeout = timeout.total_seconds() if isinstance(timeout, timedelta) else timeout
104-
self.sse_read_timeout = (
105-
sse_read_timeout.total_seconds() if isinstance(sse_read_timeout, timedelta) else sse_read_timeout
106-
)
107-
self.auth = auth
10895
self.session_id = None
10996
self.protocol_version = None
110-
self.request_headers = {
111-
**self.headers,
112-
ACCEPT: f"{JSON}, {SSE}",
113-
CONTENT_TYPE: JSON,
114-
}
115-
116-
def _prepare_request_headers(self, base_headers: dict[str, str]) -> dict[str, str]:
117-
"""Update headers with session ID and protocol version if available."""
118-
headers = base_headers.copy()
97+
98+
def _prepare_headers(self, client: httpx.AsyncClient) -> dict[str, str]:
99+
"""Build request headers from client config and protocol requirements.
100+
101+
Merges the client's default headers with MCP protocol headers and session headers.
102+
103+
Args:
104+
client: The httpx client whose headers to use as base.
105+
106+
Returns:
107+
Complete headers dict with client headers, protocol headers, and session headers.
108+
"""
109+
headers = dict(client.headers) if client.headers else {}
110+
# Add MCP protocol headers
111+
headers[ACCEPT] = f"{JSON}, {SSE}"
112+
headers[CONTENT_TYPE] = JSON
113+
# Add session headers if available
119114
if self.session_id:
120115
headers[MCP_SESSION_ID] = self.session_id
121116
if self.protocol_version:
@@ -206,14 +201,13 @@ async def handle_get_stream(
206201
if not self.session_id:
207202
return
208203

209-
headers = self._prepare_request_headers(self.request_headers)
204+
headers = self._prepare_headers(client)
210205

211206
async with aconnect_sse(
212207
client,
213208
"GET",
214209
self.url,
215210
headers=headers,
216-
timeout=httpx.Timeout(self.timeout, read=self.sse_read_timeout),
217211
) as event_source:
218212
event_source.response.raise_for_status()
219213
logger.debug("GET SSE connection established")
@@ -226,7 +220,7 @@ async def handle_get_stream(
226220

227221
async def _handle_resumption_request(self, ctx: RequestContext) -> None:
228222
"""Handle a resumption request using GET with SSE."""
229-
headers = self._prepare_request_headers(ctx.headers)
223+
headers = self._prepare_headers(ctx.client)
230224
if ctx.metadata and ctx.metadata.resumption_token:
231225
headers[LAST_EVENT_ID] = ctx.metadata.resumption_token
232226
else:
@@ -242,7 +236,6 @@ async def _handle_resumption_request(self, ctx: RequestContext) -> None:
242236
"GET",
243237
self.url,
244238
headers=headers,
245-
timeout=httpx.Timeout(self.timeout, read=self.sse_read_timeout),
246239
) as event_source:
247240
event_source.response.raise_for_status()
248241
logger.debug("Resumption GET SSE connection established")
@@ -260,7 +253,7 @@ async def _handle_resumption_request(self, ctx: RequestContext) -> None:
260253

261254
async def _handle_post_request(self, ctx: RequestContext) -> None:
262255
"""Handle a POST request with response processing."""
263-
headers = self._prepare_request_headers(ctx.headers)
256+
headers = self._prepare_headers(ctx.client)
264257
message = ctx.session_message.message
265258
is_initialization = self._is_initialization_request(message)
266259

@@ -401,12 +394,10 @@ async def post_writer(
401394

402395
ctx = RequestContext(
403396
client=client,
404-
headers=self.request_headers,
405397
session_id=self.session_id,
406398
session_message=session_message,
407399
metadata=metadata,
408400
read_stream_writer=read_stream_writer,
409-
sse_read_timeout=self.sse_read_timeout,
410401
)
411402

412403
async def handle_request_async():
@@ -433,7 +424,7 @@ async def terminate_session(self, client: httpx.AsyncClient) -> None:
433424
return
434425

435426
try:
436-
headers = self._prepare_request_headers(self.request_headers)
427+
headers = self._prepare_headers(client)
437428
response = await client.delete(self.url, headers=headers)
438429

439430
if response.status_code == 405:
@@ -488,21 +479,11 @@ async def streamable_http_client(
488479
# Determine if we need to create and manage the client
489480
client_provided = http_client is not None
490481
client = http_client
491-
492482
if client is None:
493483
# Create default client with recommended MCP timeouts
494484
client = create_mcp_http_client()
495485

496-
# Extract configuration from the client to pass to transport
497-
headers_dict = dict(client.headers) if client.headers else None
498-
timeout = client.timeout.connect if (client.timeout and client.timeout.connect is not None) else MCP_DEFAULT_TIMEOUT
499-
sse_read_timeout = (
500-
client.timeout.read if (client.timeout and client.timeout.read is not None) else MCP_DEFAULT_SSE_READ_TIMEOUT
501-
)
502-
auth = client.auth
503-
504-
# Create transport with extracted configuration
505-
transport = StreamableHTTPTransport(url, headers_dict, timeout, sse_read_timeout, auth)
486+
transport = StreamableHTTPTransport(url)
506487

507488
async with anyio.create_task_group() as tg:
508489
try:

src/mcp/shared/_httpx_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import httpx
66

7-
__all__ = ["create_mcp_http_client", "MCP_DEFAULT_TIMEOUT", "MCP_DEFAULT_SSE_READ_TIMEOUT"]
7+
__all__ = ["create_mcp_http_client"]
88

99
# Default MCP timeout configuration
1010
MCP_DEFAULT_TIMEOUT = 30.0 # General operations (seconds)

0 commit comments

Comments
 (0)