@@ -746,8 +746,8 @@ class MCPConnectionManager:
746746 def __init__ (self , server_info : MCPServerInfo , connection_timeout : float ):
747747 self .server_info = server_info
748748 self .connection_timeout = connection_timeout
749- self ._client = None
750- self ._worker = None
749+ self ._client : MCPClient | None = None
750+ self ._worker : "_MCPClientSessionManager | None" = None
751751
752752 def connect_and_discover_tools (self ) -> list [Tool ]:
753753 """
@@ -794,6 +794,9 @@ def invoke_tool(**kwargs) -> str:
794794
795795 async def invoke ():
796796 logger .debug (f"Inside invoke coroutine for '{ tool_name } '" )
797+ if self ._client is None :
798+ message = "MCP client is not connected"
799+ raise MCPConnectionError (message = message , operation = "invoke" )
797800 result = await asyncio .wait_for (
798801 self ._client .call_tool (tool_name , kwargs ), timeout = invocation_timeout
799802 )
@@ -816,7 +819,7 @@ async def invoke():
816819
817820 return invoke_tool
818821
819- def get_client (self ):
822+ def get_client (self ) -> MCPClient | None :
820823 """Allow direct access to client for MCPTool's async method access"""
821824 return self ._client
822825
@@ -961,6 +964,9 @@ async def ainvoke(self, **kwargs: Any) -> str:
961964 """
962965 try :
963966 client = self ._connection_manager .get_client ()
967+ if client is None :
968+ message = "MCP client is not connected"
969+ raise MCPConnectionError (message = message , operation = "ainvoke" )
964970 return await asyncio .wait_for (client .call_tool (self .name , kwargs ), timeout = self ._invocation_timeout )
965971 except asyncio .TimeoutError as e :
966972 message = f"Tool invocation timed out after { self ._invocation_timeout } seconds"
0 commit comments