A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix(mcp): disconnect server fix and tests (#5877)
Joaquin Coromina075de8441330
diff --git a/marimo/_server/ai/mcp.py b/marimo/_server/ai/mcp.pyindex b4d8e7b4f1..262920aa3f 100644--- a/marimo/_server/ai/mcp.py+++ b/marimo/_server/ai/mcp.py@@ -250,6 +250,11 @@ class MCPServerConnection:write_stream: Optional[MemoryObjectSendStream[SessionMessage]] = Noneexit_stack: Optional[AsyncExitStack] = None+ # Minimal additions for task-per-connection fix+ connection_task: Optional[asyncio.Task[None]] = None+ disconnect_event: Optional[asyncio.Event] = None+ connection_event: Optional[asyncio.Event] = None+class MCPClient:"""Client for managing connections to multiple MCP servers."""@@ -300,11 +305,95 @@ class MCPClient:)# Note: Server with invalid configuration is not added to self.servers- async def connect_to_server(self, server_name: str) -> bool:- """Connect to an MCP server using the appropriate transport."""- # Import common MCP SDK components+ async def _connection_lifecycle(self, server_name: str) -> None:+ """Minimal wrapper to run existing connection and disconnection logic in task-owned AsyncExitStack."""from mcp import ClientSession+ connection = self.connections.get(server_name)+ if not connection:+ return++ server_def = connection.definition++ try:+ # Task-owned AsyncExitStack - same task creates and closes it+ # If a different task tries to close it, it will raise an exception+ async with AsyncExitStack() as exit_stack:+ connection.exit_stack = exit_stack++ # All existing connection logic unchanged+ LOGGER.info(+ f"Connecting to MCP server: {server_name} (transport: {server_def.transport})"+ )++ transport_connector = self.transport_registry.get_connector(+ server_def.transport+ )+ read, write, *_ = await transport_connector.connect(+ server_def, exit_stack+ )++ connection.read_stream = read+ connection.write_stream = write++ connection.session = await exit_stack.enter_async_context(+ ClientSession(read, write)+ )++ if connection.session is None:+ raise RuntimeError("Session was not properly created")+ await connection.session.initialize()++ self._update_server_status(+ server_name, MCPServerStatus.CONNECTED+ )+ await self._discover_tools(connection)++ if server_name not in self.health_check_tasks:+ self.health_check_tasks[server_name] = asyncio.create_task(+ self._monitor_server_health(server_name)+ )++ # Signal that connection is established+ if connection.connection_event:+ connection.connection_event.set()++ LOGGER.info(+ f"Successfully connected to MCP server: {server_name} (transport: {server_def.transport})"+ )++ # Wait for disconnect signal+ if connection.disconnect_event:+ await connection.disconnect_event.wait()++ # Cancel health monitoring+ await self._cancel_health_monitoring(server_name)++ # AsyncExitStack cleans up automatically here in same task++ except Exception as e:+ error_msg = f"Failed to connect to MCP server {server_name} (transport: {server_def.transport}): {str(e)}"+ LOGGER.error(error_msg)+ self._update_server_status(+ server_name, MCPServerStatus.ERROR, error_msg+ )++ # Signal connection event so connect_to_server doesn't wait unnecessarily+ if connection and connection.connection_event:+ connection.connection_event.set()+ finally:+ # Clean up connection state+ self._remove_server_tools(server_name)+ self._update_server_status(+ server_name, MCPServerStatus.DISCONNECTED+ )+ connection.session = None+ connection.read_stream = None+ connection.write_stream = None+ connection.exit_stack = None++ async def connect_to_server(self, server_name: str) -> bool:+ """Connect to an MCP server using the appropriate transport."""if server_name not in self.servers:LOGGER.error(f"Server {server_name} not found in configuration")return False@@ -313,81 +402,50 @@ class MCPClient:# Check if already connectedif server_name in self.connections:- # Use public API to check statuscurrent_status = self.get_server_status(server_name)if current_status == MCPServerStatus.CONNECTED:return Truetry:- # Create connection- connection = MCPServerConnection(definition=server_def)+ # Create connection with minimal task-per-connection additions+ disconnect_event = asyncio.Event()+ connection_event = asyncio.Event()+ connection = MCPServerConnection(+ definition=server_def,+ disconnect_event=disconnect_event,+ connection_event=connection_event,+ )self.connections[server_name] = connectionself._update_server_status(server_name, MCPServerStatus.CONNECTING)-- # Clean up old tools before discovering new ones (handles server updates/restarts)self._remove_server_tools(server_name)- # Create exit stack for proper resource management- connection.exit_stack = AsyncExitStack()-- LOGGER.info(- f"Connecting to MCP server: {server_name} (transport: {server_def.transport})"+ # Create task to run existing connection logic+ connection_task = asyncio.create_task(+ self._connection_lifecycle(server_name))+ connection.connection_task = connection_task- # Get the appropriate transport connector and establish connection- transport_connector = self.transport_registry.get_connector(- server_def.transport- )- read, write, *_ = await transport_connector.connect(- server_def, connection.exit_stack- )-- connection.read_stream = read- connection.write_stream = write-- # Create and initialize session- connection.session = (- await connection.exit_stack.enter_async_context(- ClientSession(read, write)+ # Wait for connection to establish with proper timeout+ try:+ await asyncio.wait_for(+ connection_event.wait(), timeout=server_def.timeout)- )-- # Initialize the session- if connection.session is None:- raise RuntimeError("Session was not properly created")- await connection.session.initialize()-- self._update_server_status(server_name, MCPServerStatus.CONNECTED)-- await self._discover_tools(connection)-- # Start health monitoring for this server- if server_name not in self.health_check_tasks:- self.health_check_tasks[server_name] = asyncio.create_task(- self._monitor_server_health(server_name)+ # Event was set, but check if it was success or error+ current_status = self.get_server_status(server_name)+ return current_status == MCPServerStatus.CONNECTED+ except asyncio.TimeoutError:+ # Connection timed out, but keep task running in background+ LOGGER.warning(+ f"Connection to {server_name} is taking longer than {server_def.timeout}s, continuing in background")-- LOGGER.info(- f"Successfully connected to MCP server: {server_name} (transport: {server_def.transport})"- )- return True+ # Return True if still connecting, False if error occurred+ current_status = self.get_server_status(server_name)+ return current_status == MCPServerStatus.CONNECTINGexcept Exception as e:error_msg = f"Failed to connect to MCP server {server_name} (transport: {server_def.transport}): {str(e)}"LOGGER.error(error_msg)-- # Clean up exit_stack if connection was created but failedif server_name in self.connections:- connection = self.connections[server_name]- if connection.exit_stack:- try:- await connection.exit_stack.aclose()- except Exception as cleanup_error:- LOGGER.warning(- f"Error during cleanup for {server_name}: {cleanup_error}"- )- connection.exit_stack = None-self._update_server_status(server_name, MCPServerStatus.ERROR, error_msg)@@ -844,28 +902,23 @@ class MCPClient:return Truetry:- # Cancel health monitoring task- await self._cancel_health_monitoring(server_name)+ # Signal the connection task to shutdown+ if connection.disconnect_event:+ connection.disconnect_event.set()- # Close exit stack which will properly close the session and streams- if connection.exit_stack:- await connection.exit_stack.aclose()-- # Remove tools from registry- self._remove_server_tools(server_name)-- self._update_server_status(- server_name, MCPServerStatus.DISCONNECTED- )- connection.session = None- connection.read_stream = None- connection.write_stream = None- connection.exit_stack = None+ # Wait for the connection task to complete its cleanup+ if (+ connection.connection_task+ and not connection.connection_task.done()+ ):+ await connection.connection_taskLOGGER.info(f"Disconnected from MCP server: {server_name}")return Trueexcept Exception as e:+ # No retry or forced cleanup - disconnection failures are logged but not blocking.+ # Local state cleanup happens in _connection_lifecycle finally block regardless.LOGGER.error(f"Error disconnecting from server {server_name}: {str(e)}")diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.pyindex 48d3e01c3a..f9cf2e225a 100644--- a/marimo/_server/api/lifespans.py+++ b/marimo/_server/api/lifespans.py@@ -55,13 +55,17 @@ async def mcp(app: Starlette) -> AsyncIterator[None]:"mcp_docs", False)+ mcp_client = None # Track MCP client for cleanup+# Only start MCP servers in Edit modeif session_mgr.mode == SessionMode.EDIT and mcp_docs_enabled:- # add MCP server here after it is implementedtry:from marimo._server.ai.mcp import get_mcp_clientmcp_client = get_mcp_client()+ LOGGER.warning(+ "MCP servers are experimental and may not work as expected"+ )if mcp_client and mcp_client.servers:LOGGER.debug(f"Starting MCP servers: {list(mcp_client.servers.keys())}"@@ -77,6 +81,17 @@ async def mcp(app: Starlette) -> AsyncIterator[None]:yield+ # Clean up MCP connections on shutdown+ if mcp_client:+ try:+ LOGGER.info(+ f"About to disconnect from all MCP servers in task: {id(asyncio.current_task())}"+ )+ await mcp_client.disconnect_from_all_servers()+ LOGGER.info("Successfully disconnected from all MCP servers")+ except Exception as e:+ LOGGER.error(f"Error during MCP cleanup: {e}")+@contextlib.asynccontextmanagerasync def open_browser(app: Starlette) -> AsyncIterator[None]:diff --git a/tests/_server/ai/test_mcp.py b/tests/_server/ai/test_mcp.pyindex 4e74270bba..70f68f7987 100644--- a/tests/_server/ai/test_mcp.py+++ b/tests/_server/ai/test_mcp.py@@ -851,15 +851,10 @@ class TestMCPClientConnectionManagement:# Mock AsyncExitStackwith patch(- "marimo._server.ai.mcp.AsyncExitStack"- ) as mock_exit_stack_class:- mock_exit_stack = AsyncMock()- mock_exit_stack.enter_async_context = AsyncMock()- mock_exit_stack.enter_async_context.side_effect = [- (mock_read, mock_write), # First call for stdio_client- mock_session, # Second call for ClientSession- ]- mock_exit_stack_class.return_value = mock_exit_stack+ "marimo._server.ai.mcp.StdioTransportConnector.connect"+ ) as mock_connector_connect:+ # Mock connector.connect to return the expected streams+ mock_connector_connect.return_value = (mock_read, mock_write)# Create client with test configconfig = MCPConfig(@@ -929,44 +924,275 @@ class TestMCPClientConnectionManagement:mock_session_class.return_value = mock_session_contextwith patch(- "marimo._server.ai.mcp.AsyncExitStack"- ) as mock_exit_stack_class:- mock_exit_stack = AsyncMock()- mock_exit_stack.enter_async_context = AsyncMock()+ "marimo._server.ai.mcp.StdioTransportConnector.connect"+ ) as mock_connector_connect:# Simulate success for server1, failure for server2- mock_exit_stack.enter_async_context.side_effect = [- (AsyncMock(), AsyncMock()), # server1 stdio success- mock_session, # server1 session success+ mock_connector_connect.side_effect = [+ (AsyncMock(), AsyncMock()), # server1 successException("Connection failed"), # server2 failure]- mock_exit_stack_class.return_value = mock_exit_stack- with patch("mcp.client.stdio.stdio_client") as mock_stdio_client:- mock_stdio_context = AsyncMock()- mock_stdio_context.__aenter__ = AsyncMock(- return_value=(AsyncMock(), AsyncMock())- )- mock_stdio_context.__aexit__ = AsyncMock(return_value=None)- mock_stdio_client.return_value = mock_stdio_context-- config = MCPConfig(- mcpServers={- "server1": MCPServerStdioConfig(- command="python", args=["test1.py"]- ),- "server2": MCPServerStdioConfig(- command="python", args=["test2.py"]- ),- }- )- client = MCPClient(config)+ config = MCPConfig(+ mcpServers={+ "server1": MCPServerStdioConfig(+ command="python", args=["test1.py"]+ ),+ "server2": MCPServerStdioConfig(+ command="python", args=["test2.py"]+ ),+ }+ )+ client = MCPClient(config)++ results = await client.connect_to_all_servers()++ # Verify mixed results+ assert len(results) == 2+ assert results["server1"] is True+ assert results["server2"] is False+++ not DependencyManager.mcp.has(), reason="MCP SDK not available"+)+class TestMCPClientDisconnectionManagement:+ """Test cases for MCPClient disconnection functionality."""++ async def test_disconnect_from_server_success(self):+ """Test successful disconnection from a connected server."""+ client = MCPClient(MCPConfig(mcpServers={}))++ # Setup a connected server using existing patterns+ connection = create_test_server_connection(+ name="test_server",+ status=MCPServerStatus.CONNECTED,+ session=AsyncMock(),+ )++ # Create mock task that simulates running connection task+ mock_task = AsyncMock()+ mock_task.done.return_value = False # Task is still running+ disconnect_event = asyncio.Event()++ connection.connection_task = mock_task+ connection.disconnect_event = disconnect_event+ client.connections["test_server"] = connection++ # Call actual disconnect method+ result = await client.disconnect_from_server("test_server")++ # Verify successful disconnection+ assert result is True+ assert disconnect_event.is_set() # Event was signaled+ # Note: mock_task should be awaited since done() returns False++ async def test_disconnect_from_server_already_disconnected(self):+ """Test disconnection from server that's already disconnected."""+ client = MCPClient(MCPConfig(mcpServers={}))++ # Call disconnect on non-existent server+ result = await client.disconnect_from_server("nonexistent_server")++ # Should return True (idempotent operation)+ assert result is True++ async def test_disconnect_from_server_with_exception(self):+ """Test disconnection failure handling (validates our new comment)."""+ client = MCPClient(MCPConfig(mcpServers={}))++ # Setup connection with task that will raise exception when awaited+ connection = create_test_server_connection(+ name="test_server", status=MCPServerStatus.CONNECTED+ )++ # Create event to signal when task has started+ task_started = asyncio.Event()++ # Create a long-running task that will fail when awaited+ async def blocking_failing_task():+ task_started.set() # Signal task has started+ await asyncio.sleep(0.1) # Simulate work+ raise RuntimeError("Simulated disconnection failure")++ # Start the task+ failing_task = asyncio.create_task(blocking_failing_task())+ # Wait for task to actually start (deterministic)+ await asyncio.wait_for(task_started.wait(), timeout=1.0)++ connection.connection_task = failing_task+ connection.disconnect_event = asyncio.Event()+ client.connections["test_server"] = connection++ # Call disconnect - should handle exception gracefully+ result = await client.disconnect_from_server("test_server")++ # Should return False but not raise exception (non-blocking behavior)+ assert result is False++ async def test_disconnect_from_server_cleanup_verification(self):+ """Test that disconnection properly cleans up server state."""+ client = MCPClient(MCPConfig(mcpServers={}))- results = await client.connect_to_all_servers()+ # Setup connected server with tools and monitoring+ connection = create_test_server_connection(+ name="test_server",+ status=MCPServerStatus.CONNECTED,+ session=AsyncMock(),+ )++ # Add tools to verify they get cleaned up+ mock_tools = [+ create_test_tool(name="tool1", server_name="test_server"),+ create_test_tool(name="tool2", server_name="test_server"),+ ]++ for i, tool in enumerate(mock_tools):+ if tool:+ namespaced_name = f"mcp_test_server_tool{i + 1}"+ client.tool_registry[namespaced_name] = tool+ connection.tools.append(tool)++ # Add health monitoring task+ health_task = AsyncMock()+ client.health_check_tasks["test_server"] = health_task++ # Setup connection task+ connection.connection_task = AsyncMock()+ connection.connection_task.done.return_value = True # Already done+ connection.disconnect_event = asyncio.Event()+ client.connections["test_server"] = connection++ # Disconnect+ result = await client.disconnect_from_server("test_server")++ # Verify cleanup happens in _connection_lifecycle finally block+ assert result is True+ # Note: Tool cleanup happens in _connection_lifecycle finally block,+ # not directly in disconnect_from_server++ @pytest.mark.parametrize(+ "server_setups",+ [+ pytest.param(+ [+ {"name": "server1", "should_succeed": True},+ {"name": "server2", "should_succeed": True},+ ],+ id="all_succeed",+ ),+ pytest.param(+ [+ {"name": "server1", "should_succeed": True},+ {"name": "server2", "should_succeed": False},+ ],+ id="mixed_results",+ ),+ pytest.param(+ [+ {"name": "server1", "should_succeed": False},+ {"name": "server2", "should_succeed": False},+ ],+ id="all_fail",+ ),+ ],+ )+ async def test_disconnect_from_all_servers_scenarios(self, server_setups):+ """Test disconnect_from_all_servers with various success/failure combinations."""+ client = MCPClient(MCPConfig(mcpServers={}))++ # Setup connections based on test parameters+ for setup in server_setups:+ connection = create_test_server_connection(+ name=setup["name"], status=MCPServerStatus.CONNECTED+ )++ # Setup task behavior based on should_succeed+ if setup["should_succeed"]:+ mock_task = AsyncMock()+ mock_task.done.return_value = False+ else:+ mock_task = AsyncMock()+ mock_task.done.return_value = False+ mock_task.side_effect = Exception("Simulated failure")++ connection.connection_task = mock_task+ connection.disconnect_event = asyncio.Event()+ client.connections[setup["name"]] = connection++ # Call actual disconnect_from_all_servers method+ await client.disconnect_from_all_servers()++ # Verify disconnect events were set (disconnect_from_all_servers doesn't return results)+ for setup in server_setups:+ connection = client.connections[setup["name"]]+ # Event should be set regardless of success/failure (signal was sent)+ assert connection.disconnect_event.is_set()++ async def test_disconnect_from_all_servers_with_health_monitoring(self):+ """Test that disconnect_from_all_servers cancels health monitoring first."""+ client = MCPClient(MCPConfig(mcpServers={}))++ # Setup connections with health monitoring tasks+ server_names = ["server1", "server2"]+ for name in server_names:+ # Create connection+ connection = create_test_server_connection(+ name=name, status=MCPServerStatus.CONNECTED+ )+ connection.connection_task = AsyncMock()+ connection.connection_task.done.return_value = True+ connection.disconnect_event = asyncio.Event()+ client.connections[name] = connection++ # Create health monitoring task+ health_task = AsyncMock()+ health_task.cancel = AsyncMock()+ client.health_check_tasks[name] = health_task++ # Mock _cancel_health_monitoring to verify it's called+ with patch.object(+ client, "_cancel_health_monitoring", new_callable=AsyncMock+ ) as mock_cancel:+ await client.disconnect_from_all_servers()++ # Verify health monitoring was cancelled first+ mock_cancel.assert_called_once_with()++ async def test_disconnect_cross_task_scenario(self):+ """Test disconnection in cross-task scenarios (like server shutdown)."""+ client = MCPClient(MCPConfig(mcpServers={}))++ # Setup connection that simulates cross-task issues+ connection = create_test_server_connection(+ name="test_server", status=MCPServerStatus.CONNECTED+ )++ # Create event to signal when task has started+ task_started = asyncio.Event()++ # Create a task that simulates cross-task lifecycle issues+ async def cross_task_error():+ task_started.set() # Signal task has started+ await asyncio.sleep(0.1) # Simulate work+ raise RuntimeError("Task was destroyed but it is pending!")++ # Start the task+ cross_task = asyncio.create_task(cross_task_error())+ # Wait for task to actually start (deterministic)+ await asyncio.wait_for(task_started.wait(), timeout=1.0)++ connection.connection_task = cross_task+ connection.disconnect_event = asyncio.Event()+ client.connections["test_server"] = connection++ # This should handle the cross-task error gracefully (non-blocking)+ result = await client.disconnect_from_server("test_server")++ # Should return False (failure) but not raise exception+ assert result is False- # Verify mixed results- assert len(results) == 2- assert results["server1"] is True- assert results["server2"] is False+ # Event should still be signaled to attempt cleanup+ assert connection.disconnect_event.is_set()class TestMCPClientHealthMonitoring: