@@ -63,17 +63,23 @@ class MCPClient:
63
63
from MCP tools, it will be returned as the last item in the content array of the ToolResult.
64
64
"""
65
65
66
- def __init__ (self , transport_callable : Callable [[], MCPTransport ]):
66
+ def __init__ (self , transport_callable : Callable [[], MCPTransport ], * , startup_timeout : int = 30 ):
67
67
"""Initialize a new MCP Server connection.
68
68
69
69
Args:
70
70
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.
71
73
"""
74
+ self ._startup_timeout = startup_timeout
75
+
72
76
mcp_instrumentation ()
73
77
self ._session_id = uuid .uuid4 ()
74
78
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 ()
77
83
self ._transport_callable = transport_callable
78
84
79
85
self ._background_thread : threading .Thread | None = None
@@ -109,7 +115,7 @@ def start(self) -> "MCPClient":
109
115
self ._log_debug_with_thread ("background thread started, waiting for ready event" )
110
116
try :
111
117
# 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 )
113
119
self ._log_debug_with_thread ("the client initialization was successful" )
114
120
except futures .TimeoutError as e :
115
121
raise MCPClientInitializationError ("background thread did not start in 30 seconds" ) from e
@@ -347,7 +353,8 @@ async def _async_background_thread(self) -> None:
347
353
self ._log_debug_with_thread ("session initialized successfully" )
348
354
# Store the session for use while we await the close event
349
355
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 )
351
358
352
359
self ._log_debug_with_thread ("waiting for close signal" )
353
360
# Keep background thread running until signaled to close.
0 commit comments