2626
2727import asyncio
2828import hashlib
29+ import inspect
2930import json
3031import sys
3132from contextlib import AsyncExitStack
33+ from contextlib import asynccontextmanager
3234from datetime import timedelta
3335from typing import Dict
3436from typing import Optional
3537from typing import Union
3638
39+ # cSpell:ignore streamable
40+
41+ import httpx
3742from mcp import ClientSession
3843from mcp .client .sse import sse_client
3944from mcp .client .stdio import stdio_client
40- from mcp .client .streamable_http import streamablehttp_client
45+ try :
46+ from mcp .client .streamable_http import streamable_http_client
47+ except ImportError : # pragma: no cover - compatibility with older mcp versions
48+ from mcp .client .streamable_http import streamablehttp_client as streamable_http_client
49+
50+ _STREAMABLE_HTTP_CLIENT_SUPPORTS_HTTP_CLIENT = "http_client" in inspect .signature (streamable_http_client ).parameters
4151
4252from trpc_agent_sdk .log import logger
4353
@@ -161,7 +171,7 @@ def _create_client(self, merged_headers: Optional[Dict[str, str]] = None):
161171 if isinstance (self ._connection_params , StdioConnectionParams ):
162172 client = stdio_client (
163173 server = self ._connection_params .server_params ,
164- errlog = sys .stderr ,
174+ errlog = sys .stderr , # cSpell:ignore errlog
165175 )
166176 elif isinstance (self ._connection_params , SseConnectionParams ):
167177 client = sse_client (
@@ -171,18 +181,46 @@ def _create_client(self, merged_headers: Optional[Dict[str, str]] = None):
171181 sse_read_timeout = self ._connection_params .sse_read_timeout ,
172182 )
173183 elif isinstance (self ._connection_params , StreamableHTTPConnectionParams ):
174- client = streamablehttp_client (
184+ client = self ._create_streamable_http_client (merged_headers )
185+ else :
186+ raise ValueError ('Unable to initialize connection. Connection should be'
187+ ' StdioConnectionParams or SseConnectionParams or StreamableHTTPConnectionParams, but got'
188+ f' { type (self ._connection_params )} ' )
189+ return client
190+
191+ def _create_streamable_http_client (self , merged_headers : Optional [Dict [str , str ]] = None ):
192+ """Creates a Streamable HTTP client with compatibility for MCP SDK versions."""
193+ if not _STREAMABLE_HTTP_CLIENT_SUPPORTS_HTTP_CLIENT :
194+ return streamable_http_client (
175195 url = self ._connection_params .url ,
176196 headers = merged_headers ,
177197 timeout = self ._connection_params .timeout ,
178198 sse_read_timeout = self ._connection_params .sse_read_timeout ,
179199 terminate_on_close = self ._connection_params .terminate_on_close ,
180200 )
181- else :
182- raise ValueError ('Unable to initialize connection. Connection should be'
183- ' StdioConnectionParams or SseConnectionParams or StreamableHTTPConnectionParams, but got'
184- f' { type (self ._connection_params )} ' )
185- return client
201+
202+ return self ._create_streamable_http_client_with_httpx (merged_headers )
203+
204+ @asynccontextmanager
205+ async def _create_streamable_http_client_with_httpx (self , merged_headers : Optional [Dict [str , str ]] = None ):
206+ """Creates a new-style Streamable HTTP client and owns its httpx client."""
207+ timeout_seconds = self ._connection_params .timeout
208+ if isinstance (timeout_seconds , timedelta ):
209+ timeout_seconds = timeout_seconds .total_seconds ()
210+ sse_read_timeout_seconds = self ._connection_params .sse_read_timeout
211+ if isinstance (sse_read_timeout_seconds , timedelta ):
212+ sse_read_timeout_seconds = sse_read_timeout_seconds .total_seconds ()
213+
214+ async with httpx .AsyncClient (
215+ headers = merged_headers ,
216+ timeout = httpx .Timeout (timeout_seconds , read = sse_read_timeout_seconds ),
217+ ) as http_client :
218+ async with streamable_http_client (
219+ url = self ._connection_params .url ,
220+ http_client = http_client ,
221+ terminate_on_close = self ._connection_params .terminate_on_close ,
222+ ) as transports :
223+ yield transports
186224
187225 async def create_session (self , headers : Optional [Dict [str , str ]] = None ) -> ClientSession | None :
188226 """Creates and initializes an MCP client session.
0 commit comments