@@ -63,17 +63,23 @@ class MCPClient:
6363 from MCP tools, it will be returned as the last item in the content array of the ToolResult.
6464 """
6565
66- def __init__ (self , transport_callable : Callable [[], MCPTransport ]):
66+ def __init__ (self , transport_callable : Callable [[], MCPTransport ], * , startup_timeout : int = 30 ):
6767 """Initialize a new MCP Server connection.
6868
6969 Args:
7070 transport_callable: A callable that returns an MCPTransport (read_stream, write_stream) tuple
71+ startup_timeout: Timeout after which MCP server initialization should be cancelled
72+ Defaults to 30.
7173 """
74+ self ._startup_timeout = startup_timeout
75+
7276 mcp_instrumentation ()
7377 self ._session_id = uuid .uuid4 ()
7478 self ._log_debug_with_thread ("initializing MCPClient connection" )
75- self ._init_future : futures .Future [None ] = futures .Future () # Main thread blocks until future completes
76- self ._close_event = asyncio .Event () # Do not want to block other threads while close event is false
79+ # Main thread blocks until future completesock
80+ self ._init_future : futures .Future [None ] = futures .Future ()
81+ # Do not want to block other threads while close event is false
82+ self ._close_event = asyncio .Event ()
7783 self ._transport_callable = transport_callable
7884
7985 self ._background_thread : threading .Thread | None = None
@@ -109,7 +115,7 @@ def start(self) -> "MCPClient":
109115 self ._log_debug_with_thread ("background thread started, waiting for ready event" )
110116 try :
111117 # Blocking main thread until session is initialized in other thread or if the thread stops
112- self ._init_future .result (timeout = 30 )
118+ self ._init_future .result (timeout = self . _startup_timeout )
113119 self ._log_debug_with_thread ("the client initialization was successful" )
114120 except futures .TimeoutError as e :
115121 raise MCPClientInitializationError ("background thread did not start in 30 seconds" ) from e
@@ -347,7 +353,8 @@ async def _async_background_thread(self) -> None:
347353 self ._log_debug_with_thread ("session initialized successfully" )
348354 # Store the session for use while we await the close event
349355 self ._background_thread_session = session
350- self ._init_future .set_result (None ) # Signal that the session has been created and is ready for use
356+ # Signal that the session has been created and is ready for use
357+ self ._init_future .set_result (None )
351358
352359 self ._log_debug_with_thread ("waiting for close signal" )
353360 # Keep background thread running until signaled to close.
0 commit comments