Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: handle async context task cleanup for mcp client [LET-5746] (#5619)
jnjpnge3f794dac557
diff --git a/letta/server/rest_api/routers/v1/tools.py b/letta/server/rest_api/routers/v1/tools.pyindex 937fe24a1..5386ea33a 100644--- a/letta/server/rest_api/routers/v1/tools.py+++ b/letta/server/rest_api/routers/v1/tools.py@@ -37,7 +37,9 @@ from letta.server.server import SyncServerfrom letta.services.mcp.oauth_utils import MCPOAuthSession, drill_down_exception, oauth_stream_eventfrom letta.services.mcp.stdio_client import AsyncStdioMCPClientfrom letta.services.mcp.types import OauthStreamEvent+from letta.services.summarizer.summarizer import tracebackfrom letta.settings import tool_settings+from letta.utils import asynciofrom letta.validators import ToolIdrouter = APIRouter(prefix="/tools", tags=["tools"])@@ -664,7 +666,11 @@ async def connect_mcp_server(detailed_error = drill_down_exception(e)logger.error(f"Error in OAuth stream:\n{detailed_error}")yield oauth_stream_event(OauthStreamEvent.ERROR, message=f"Internal error: {detailed_error}")-+ # TODO: investigate cancelled by cancel scope errors here during oauth exchange flow+ except asyncio.CancelledError as e:+ logger.error(f"CancelledError: {e!r}")+ tb = "".join(traceback.format_stack())+ logger.error(f"Stack trace at cancellation:\n{tb}")finally:if client:try:diff --git a/letta/services/mcp_manager.py b/letta/services/mcp_manager.pyindex 56278fac9..60095e047 100644--- a/letta/services/mcp_manager.py+++ b/letta/services/mcp_manager.py@@ -40,12 +40,13 @@ from letta.schemas.secret import Secretfrom letta.schemas.tool import Tool as PydanticTool, ToolCreate, ToolUpdatefrom letta.schemas.user import User as PydanticUserfrom letta.server.db import db_registry+from letta.services.mcp.base_client import AsyncBaseMCPClientfrom letta.services.mcp.sse_client import MCP_CONFIG_TOPLEVEL_KEY, AsyncSSEMCPClientfrom letta.services.mcp.stdio_client import AsyncStdioMCPClientfrom letta.services.mcp.streamable_http_client import AsyncStreamableHTTPMCPClientfrom letta.services.tool_manager import ToolManagerfrom letta.settings import settings, tool_settings-from letta.utils import enforce_types, printd, safe_create_task+from letta.utils import enforce_types, printd, safe_create_task_with_returnlogger = get_logger(__name__)@@ -1149,12 +1150,26 @@ class MCPManager:# Get authorization URL by triggering OAuth flowtemp_client = Noneconnect_task = None++ async def connect_and_cleanup(client: AsyncBaseMCPClient, ready_queue: asyncio.Queue):+ """Wrap connection and cleanup in the same task to share cancel scope"""+ try:+ await client.connect_to_server()+ # Send client to main task without finishing the task+ await ready_queue.put(client)+ # Now wait for signal to cleanup+ await client._cleanup_event.wait()+ finally:+ await client.cleanup()+try:+ ready_queue = asyncio.Queue()temp_client = await self.get_mcp_client(request, actor, oauth_provider)+ temp_client._cleanup_event = asyncio.Event()# Run connect_to_server in background to avoid blocking# This will trigger the OAuth flow and the redirect_handler will save the authorization URL to database- connect_task = safe_create_task(temp_client.connect_to_server(), label="mcp_oauth_connect")+ connect_task = safe_create_task_with_return(connect_and_cleanup(temp_client, ready_queue), label="mcp_oauth_connect")# Fetch the authorization URL from database and yield state to client to proceed with handling authorization URLauth_session = await self.get_oauth_session_by_id(session_id, actor)@@ -1173,11 +1188,14 @@ class MCPManager:yield oauth_stream_event(OauthStreamEvent.WAITING_FOR_AUTH, message="Waiting for user authorization...")# Callback handler will poll for authorization code and state and update the OAuth session- await connect_task-+ # Get the client from the queue+ temp_client = await ready_queue.get()tools = await temp_client.list_tools(serialize=True)yield oauth_stream_event(OauthStreamEvent.SUCCESS, tools=tools)+ # Signal the background task to cleanup in its own task+ temp_client._cleanup_event.set()+ await connect_task # now it finishes safelyexcept Exception as e:logger.error(f"Error triggering OAuth flow: {e}")yield oauth_stream_event(OauthStreamEvent.ERROR, message=f"Failed to trigger OAuth: {str(e)}")@@ -1190,8 +1208,3 @@ class MCPManager:await connect_taskexcept asyncio.CancelledError:pass- if temp_client:- try:- await temp_client.cleanup()- except Exception as cleanup_error:- logger.warning(f"Error during temp MCP client cleanup: {cleanup_error}")diff --git a/letta/utils.py b/letta/utils.pyindex 5bba2e2d4..b5b619e55 100644--- a/letta/utils.py+++ b/letta/utils.py@@ -1129,6 +1129,29 @@ def safe_create_task(coro, label: str = "background task"):return task+@trace_method+def safe_create_task_with_return(coro, label: str = "background task"):+ async def wrapper():+ try:+ return await coro+ except Exception as e:+ logger.exception(f"{label} failed with {type(e).__name__}: {e}")+ raise++ task = asyncio.create_task(wrapper())++ # Add task to the set to maintain strong reference+ _background_tasks.add(task)++ # Log task count to trace+ log_attributes({"total_background_task_count": get_background_task_count()})++ # Remove task from set when done to prevent memory leaks+ task.add_done_callback(_background_tasks.discard)++ return task++def safe_create_shielded_task(coro, label: str = "shielded background task"):"""Create a shielded background task that cannot be cancelled externally.