Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: Increase timeouts and catch errors in MCP endpoints (#1329)
Matthew Zhou57e463f53b11
diff --git a/letta/functions/mcp_client/base_client.py b/letta/functions/mcp_client/base_client.pyindex 20ea92645..851c3d302 100644--- a/letta/functions/mcp_client/base_client.py+++ b/letta/functions/mcp_client/base_client.py@@ -1,9 +1,10 @@import asynciofrom typing import List, Optional, Tuple-from mcp import ClientSession, Tool+from mcp import ClientSession-from letta.functions.mcp_client.types import BaseServerConfig+from letta.functions.mcp_client.exceptions import MCPTimeoutError+from letta.functions.mcp_client.types import BaseServerConfig, MCPToolfrom letta.log import get_loggerfrom letta.settings import tool_settings@@ -31,9 +32,7 @@ class BaseMCPClient:)self.initialized = Trueexcept asyncio.TimeoutError:- raise RuntimeError(- f"Timed out while initializing session for MCP server {self.server_config.server_name} (timeout={tool_settings.mcp_connect_to_server_timeout}s)."- )+ raise MCPTimeoutError("initializing session", self.server_config.server_name, tool_settings.mcp_connect_to_server_timeout)else:raise RuntimeError(f"Connecting to MCP server failed. Please review your server config: {self.server_config.model_dump_json(indent=4)}"@@ -42,7 +41,7 @@ class BaseMCPClient:def _initialize_connection(self, server_config: BaseServerConfig, timeout: float) -> bool:raise NotImplementedError("Subclasses must implement _initialize_connection")- def list_tools(self) -> List[Tool]:+ def list_tools(self) -> List[MCPTool]:self._check_initialized()try:response = self.loop.run_until_complete(@@ -50,11 +49,10 @@ class BaseMCPClient:)return response.toolsexcept asyncio.TimeoutError:- # Could log, throw a custom exception, etc.logger.error(f"Timed out while listing tools for MCP server {self.server_config.server_name} (timeout={tool_settings.mcp_list_tools_timeout}s).")- return []+ raise MCPTimeoutError("listing tools", self.server_config.server_name, tool_settings.mcp_list_tools_timeout)def execute_tool(self, tool_name: str, tool_args: dict) -> Tuple[str, bool]:self._check_initialized()@@ -67,7 +65,7 @@ class BaseMCPClient:logger.error(f"Timed out while executing tool '{tool_name}' for MCP server {self.server_config.server_name} (timeout={tool_settings.mcp_execute_tool_timeout}s).")- return "", True+ raise MCPTimeoutError(f"executing tool '{tool_name}'", self.server_config.server_name, tool_settings.mcp_execute_tool_timeout)def _check_initialized(self):if not self.initialized:diff --git a/letta/functions/mcp_client/exceptions.py b/letta/functions/mcp_client/exceptions.pynew file mode 100644index 000000000..94bf164c8--- /dev/null+++ b/letta/functions/mcp_client/exceptions.py@@ -0,0 +1,6 @@+class MCPTimeoutError(RuntimeError):+ """Custom exception raised when an MCP operation times out."""++ def __init__(self, operation: str, server_name: str, timeout: float):+ message = f"Timed out while {operation} for MCP server {server_name} (timeout={timeout}s)."+ super().__init__(message)diff --git a/letta/server/rest_api/routers/v1/tools.py b/letta/server/rest_api/routers/v1/tools.pyindex f197e449e..b1d953863 100644--- a/letta/server/rest_api/routers/v1/tools.py+++ b/letta/server/rest_api/routers/v1/tools.py@@ -12,6 +12,7 @@ from composio.exceptions import (from fastapi import APIRouter, Body, Depends, Header, HTTPExceptionfrom letta.errors import LettaToolCreateError+from letta.functions.mcp_client.exceptions import MCPTimeoutErrorfrom letta.functions.mcp_client.types import MCPTool, SSEServerConfig, StdioServerConfigfrom letta.helpers.composio_helpers import get_composio_api_keyfrom letta.log import get_logger@@ -367,6 +368,15 @@ def list_mcp_tools_by_server("mcp_server_name": mcp_server_name,},)+ except MCPTimeoutError as e:+ raise HTTPException(+ status_code=408, # Timeout+ detail={+ "code": "MCPTimeoutError",+ "message": str(e),+ "mcp_server_name": mcp_server_name,+ },+ )@router.post("/mcp/servers/{mcp_server_name}/{mcp_tool_name}", response_model=Tool, operation_id="add_mcp_tool")@@ -381,8 +391,29 @@ def add_mcp_tool("""actor = server.user_manager.get_user_or_default(user_id=actor_id)- available_tools = server.get_tools_from_mcp_server(mcp_server_name=mcp_server_name)- # See if the tool is in the avaialable list+ try:+ available_tools = server.get_tools_from_mcp_server(mcp_server_name=mcp_server_name)+ except ValueError as e:+ # ValueError means that the MCP server name doesn't exist+ raise HTTPException(+ status_code=400, # Bad Request+ detail={+ "code": "MCPServerNotFoundError",+ "message": str(e),+ "mcp_server_name": mcp_server_name,+ },+ )+ except MCPTimeoutError as e:+ raise HTTPException(+ status_code=408, # Timeout+ detail={+ "code": "MCPTimeoutError",+ "message": str(e),+ "mcp_server_name": mcp_server_name,+ },+ )++ # See if the tool is in the available listmcp_tool = Nonefor tool in available_tools:if tool.name == mcp_tool_name:diff --git a/letta/settings.py b/letta/settings.pyindex f6ade17ec..52edde9b3 100644--- a/letta/settings.py+++ b/letta/settings.py@@ -19,8 +19,8 @@ class ToolSettings(BaseSettings):local_sandbox_dir: Optional[str] = None# MCP settings- mcp_connect_to_server_timeout: float = 15.0- mcp_list_tools_timeout: float = 10.0+ mcp_connect_to_server_timeout: float = 30.0+ mcp_list_tools_timeout: float = 30.0mcp_execute_tool_timeout: float = 60.0mcp_read_from_config: bool = True # if False, will throw if attempting to read/write from file