-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Add streamable_http_client
and deprecate old usage
#869
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,6 +7,7 @@ | |
""" | ||
|
||
import logging | ||
import warnings | ||
from collections.abc import AsyncGenerator, Awaitable, Callable | ||
from contextlib import asynccontextmanager | ||
from dataclasses import dataclass | ||
|
@@ -71,7 +72,7 @@ class RequestContext: | |
session_message: SessionMessage | ||
metadata: ClientMessageMetadata | None | ||
read_stream_writer: StreamWriter | ||
sse_read_timeout: timedelta | ||
sse_read_timeout: float | ||
|
||
|
||
class StreamableHTTPTransport: | ||
|
@@ -81,8 +82,8 @@ def __init__( | |
self, | ||
url: str, | ||
headers: dict[str, Any] | None = None, | ||
timeout: timedelta = timedelta(seconds=30), | ||
sse_read_timeout: timedelta = timedelta(seconds=60 * 5), | ||
timeout: float | timedelta = 30, | ||
sse_read_timeout: float | timedelta = 60 * 5, | ||
Comment on lines
+85
to
+86
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is backwards compatible. |
||
auth: httpx.Auth | None = None, | ||
) -> None: | ||
"""Initialize the StreamableHTTP transport. | ||
|
@@ -96,8 +97,25 @@ def __init__( | |
""" | ||
self.url = url | ||
self.headers = headers or {} | ||
|
||
if isinstance(timeout, timedelta): | ||
warnings.warn( | ||
"`timeout` as `timedelta` is deprecated. Use `float` instead.", | ||
DeprecationWarning, | ||
stacklevel=2, | ||
) | ||
timeout = timeout.total_seconds() | ||
self.timeout = timeout | ||
|
||
if isinstance(sse_read_timeout, timedelta): | ||
warnings.warn( | ||
"`sse_read_timeout` as `timedelta` is deprecated. Use `float` instead.", | ||
DeprecationWarning, | ||
stacklevel=2, | ||
) | ||
sse_read_timeout = sse_read_timeout.total_seconds() | ||
self.sse_read_timeout = sse_read_timeout | ||
|
||
self.auth = auth | ||
self.session_id: str | None = None | ||
self.request_headers = { | ||
|
@@ -194,9 +212,7 @@ async def handle_get_stream( | |
"GET", | ||
self.url, | ||
headers=headers, | ||
timeout=httpx.Timeout( | ||
self.timeout.seconds, read=self.sse_read_timeout.seconds | ||
), | ||
timeout=httpx.Timeout(self.timeout, read=self.sse_read_timeout), | ||
) as event_source: | ||
event_source.response.raise_for_status() | ||
logger.debug("GET SSE connection established") | ||
|
@@ -225,9 +241,7 @@ async def _handle_resumption_request(self, ctx: RequestContext) -> None: | |
"GET", | ||
self.url, | ||
headers=headers, | ||
timeout=httpx.Timeout( | ||
self.timeout.seconds, read=ctx.sse_read_timeout.seconds | ||
), | ||
timeout=httpx.Timeout(self.timeout, read=ctx.sse_read_timeout), | ||
) as event_source: | ||
event_source.response.raise_for_status() | ||
logger.debug("Resumption GET SSE connection established") | ||
|
@@ -446,6 +460,52 @@ async def streamablehttp_client( | |
`sse_read_timeout` determines how long (in seconds) the client will wait for a new | ||
event before disconnecting. All other HTTP operations are controlled by `timeout`. | ||
|
||
Yields: | ||
Tuple containing: | ||
- read_stream: Stream for reading messages from the server | ||
- write_stream: Stream for sending messages to the server | ||
- get_session_id_callback: Function to retrieve the current session ID | ||
""" | ||
warnings.warn( | ||
"`streamablehttp_client` is deprecated. Use `streamable_http_client` instead.", | ||
DeprecationWarning, | ||
stacklevel=2, | ||
) | ||
async with streamable_http_client( | ||
url, | ||
headers, | ||
timeout.total_seconds(), | ||
sse_read_timeout.total_seconds(), | ||
Comment on lines
+477
to
+478
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should use |
||
terminate_on_close, | ||
httpx_client_factory, | ||
auth, | ||
) as (read_stream, write_stream, get_session_id): | ||
yield (read_stream, write_stream, get_session_id) | ||
|
||
|
||
@asynccontextmanager | ||
async def streamable_http_client( | ||
url: str, | ||
headers: dict[str, Any] | None = None, | ||
timeout: float = 30, | ||
sse_read_timeout: float = 60 * 5, | ||
terminate_on_close: bool = True, | ||
httpx_client_factory: McpHttpClientFactory = create_mcp_http_client, | ||
auth: httpx.Auth | None = None, | ||
) -> AsyncGenerator[ | ||
tuple[ | ||
MemoryObjectReceiveStream[SessionMessage | Exception], | ||
MemoryObjectSendStream[SessionMessage], | ||
GetSessionIdCallback, | ||
], | ||
None, | ||
]: | ||
""" | ||
Client transport for StreamableHTTP. | ||
|
||
`sse_read_timeout` determines how long (in seconds) the client will wait for a new | ||
event before disconnecting. All other HTTP operations are controlled by `timeout`. | ||
|
||
Yields: | ||
Tuple containing: | ||
- read_stream: Stream for reading messages from the server | ||
|
@@ -468,7 +528,7 @@ async def streamablehttp_client( | |
async with httpx_client_factory( | ||
headers=transport.request_headers, | ||
timeout=httpx.Timeout( | ||
transport.timeout.seconds, read=transport.sse_read_timeout.seconds | ||
transport.timeout, read=transport.sse_read_timeout | ||
), | ||
auth=transport.auth, | ||
) as client: | ||
|
@@ -489,11 +549,7 @@ def start_get_stream() -> None: | |
) | ||
|
||
try: | ||
yield ( | ||
read_stream, | ||
write_stream, | ||
transport.get_session_id, | ||
) | ||
yield (read_stream, write_stream, transport.get_session_id) | ||
finally: | ||
if transport.session_id and terminate_on_close: | ||
await transport.terminate_session(client) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,6 +7,7 @@ | |
from mcp import types | ||
from mcp.client.session_group import ( | ||
ClientSessionGroup, | ||
ServerParameters, | ||
SseServerParameters, | ||
StreamableHttpParameters, | ||
) | ||
|
@@ -279,45 +280,42 @@ async def test_disconnect_non_existent_server(self): | |
await group.disconnect_from_server(session) | ||
|
||
@pytest.mark.parametrize( | ||
"server_params_instance, client_type_name, patch_target_for_client_func", | ||
"server_params_instance, patch_target_for_client_func", | ||
[ | ||
( | ||
StdioServerParameters(command="test_stdio_cmd"), | ||
"stdio", | ||
"mcp.client.session_group.mcp.stdio_client", | ||
), | ||
( | ||
SseServerParameters(url="http://test.com/sse", timeout=10), | ||
"sse", | ||
"mcp.client.session_group.sse_client", | ||
), # url, headers, timeout, sse_read_timeout | ||
( | ||
StreamableHttpParameters( | ||
url="http://test.com/stream", terminate_on_close=False | ||
), | ||
"streamablehttp", | ||
"mcp.client.session_group.streamablehttp_client", | ||
"mcp.client.session_group.streamable_http_client", | ||
), # url, headers, timeout, sse_read_timeout, terminate_on_close | ||
], | ||
) | ||
async def test_establish_session_parameterized( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've added type hints, and simplified this test. This test shouldn't exist as is, it's very confusing, and full of mocking, but I just adapted it for the sake of my changes. |
||
self, | ||
server_params_instance, | ||
client_type_name, # Just for clarity or conditional logic if needed | ||
patch_target_for_client_func, | ||
server_params_instance: ServerParameters, | ||
patch_target_for_client_func: str, | ||
): | ||
with mock.patch( | ||
"mcp.client.session_group.mcp.ClientSession" | ||
) as mock_ClientSession_class: | ||
with mock.patch(patch_target_for_client_func) as mock_specific_client_func: | ||
client_type_name = server_params_instance.__class__.__name__ | ||
mock_client_cm_instance = mock.AsyncMock( | ||
name=f"{client_type_name}ClientCM" | ||
) | ||
mock_read_stream = mock.AsyncMock(name=f"{client_type_name}Read") | ||
mock_write_stream = mock.AsyncMock(name=f"{client_type_name}Write") | ||
|
||
# streamablehttp_client's __aenter__ returns three values | ||
if client_type_name == "streamablehttp": | ||
# streamable_http_client's __aenter__ returns three values | ||
if isinstance(server_params_instance, StreamableHttpParameters): | ||
mock_extra_stream_val = mock.AsyncMock(name="StreamableExtra") | ||
mock_client_cm_instance.__aenter__.return_value = ( | ||
mock_read_stream, | ||
|
@@ -363,23 +361,23 @@ async def test_establish_session_parameterized( | |
|
||
# --- Assertions --- | ||
# 1. Assert the correct specific client function was called | ||
if client_type_name == "stdio": | ||
if isinstance(server_params_instance, StdioServerParameters): | ||
mock_specific_client_func.assert_called_once_with( | ||
server_params_instance | ||
) | ||
elif client_type_name == "sse": | ||
elif isinstance(server_params_instance, SseServerParameters): | ||
mock_specific_client_func.assert_called_once_with( | ||
url=server_params_instance.url, | ||
headers=server_params_instance.headers, | ||
timeout=server_params_instance.timeout, | ||
sse_read_timeout=server_params_instance.sse_read_timeout, | ||
) | ||
elif client_type_name == "streamablehttp": | ||
else: | ||
mock_specific_client_func.assert_called_once_with( | ||
url=server_params_instance.url, | ||
headers=server_params_instance.headers, | ||
timeout=server_params_instance.timeout, | ||
sse_read_timeout=server_params_instance.sse_read_timeout, | ||
timeout=server_params_instance.timeout.total_seconds(), | ||
sse_read_timeout=server_params_instance.sse_read_timeout.total_seconds(), | ||
terminate_on_close=server_params_instance.terminate_on_close, | ||
) | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My IDE added those... Which seems correct.