Skip to content

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.

feat: add mcp backend client side integration (#5736)

Joaquin Coromina364905967ae6
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index d25010d7fc..face4da902 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -440,6 +440,54 @@ class MarimoConfig(TypedDict):
snippets: NotRequired[SnippetsConfig]
datasources: NotRequired[DatasourcesConfig]
sharing: NotRequired[SharingConfig]
+ # We don't support configuring MCP servers yet
+ # mcp: NotRequired[MCPConfig]
+
+
+@mddoc
+@dataclass
+class MCPServerStdioConfig(TypedDict):
+ """Configuration for STDIO transport MCP servers"""
+
+ command: str
+ args: NotRequired[Optional[list[str]]]
+ env: NotRequired[Optional[dict[str, str]]]
+ disabled: NotRequired[Optional[bool]]
+
+
+@mddoc
+@dataclass
+class MCPServerStreamableHttpConfig(TypedDict):
+ """Configuration for Streamable HTTP transport MCP servers"""
+
+ url: str
+ headers: NotRequired[Optional[dict[str, str]]]
+ timeout: NotRequired[Optional[float]]
+ env: NotRequired[Optional[dict[str, str]]]
+ disabled: NotRequired[Optional[bool]]
+
+
+MCPServerConfig = Union[MCPServerStdioConfig, MCPServerStreamableHttpConfig]
+
+
+@mddoc
+@dataclass
+class MCPConfig(TypedDict):
+ """
+ Configuration for MCP servers
+
+ Note: the field name `mcpServers` is camelCased to match MCP server
+ config conventions used by popular AI applications (e.g. Cursor, Claude Desktop, etc.)
+ """
+
+ mcpServers: dict[str, MCPServerConfig]
+
+
+DEFAULT_MCP_CONFIG: MCPConfig = MCPConfig(
+ mcpServers={
+ # TODO(bjoaquinc): add Marimo MCP server here after it is implemented
+ }
+)
@mddoc
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 895055f93c..e7d822e77e 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -235,6 +235,7 @@ class DependencyManager:
boto3 = Dependency("boto3")
litellm = Dependency("litellm")
redshift_connector = Dependency("redshift_connector")
+ mcp = Dependency("mcp")
# Version requirements to properly support the new superfences introduced in
# pymdown#2470
diff --git a/marimo/_server/ai/mcp.py b/marimo/_server/ai/mcp.py
new file mode 100644
index 0000000000..b4d8e7b4f1
--- /dev/null
+++ b/marimo/_server/ai/mcp.py
@@ -0,0 +1,909 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import asyncio
+import os
+import time
+from abc import ABC, abstractmethod
+from contextlib import AsyncExitStack
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import TYPE_CHECKING, Any, Optional, Union, cast
+
+from marimo import _loggers
+from marimo._config.config import (
+ DEFAULT_MCP_CONFIG,
+ MCPConfig,
+ MCPServerConfig,
+ MCPServerStdioConfig,
+ MCPServerStreamableHttpConfig,
+)
+from marimo._dependencies.dependencies import DependencyManager
+
+if TYPE_CHECKING:
+ from typing import Protocol, TypedDict
+
+ from anyio.streams.memory import (
+ MemoryObjectReceiveStream,
+ MemoryObjectSendStream,
+ )
+ from mcp import ClientSession # type: ignore[import-not-found]
+ from mcp.shared.message import SessionMessage
+ from mcp.types import ( # type: ignore[import-not-found]
+ CallToolRequestParams,
+ CallToolResult,
+ ListToolsResult,
+ Tool,
+ )
+
+ class MCPToolMeta(TypedDict):
+ """Metadata that marimo adds to MCP tools."""
+
+ server_name: str
+ namespaced_name: str
+
+ class MCPToolWithMeta(Protocol):
+ """MCP Tool with marimo-specific metadata."""
+
+ name: str
+ description: str | None
+ inputSchema: dict[str, Any]
+ meta: MCPToolMeta
+
+
+# Type alias that matches the MCP SDK's CallToolRequestParams.arguments type
+MCPToolArgs = Optional[dict[str, Any]]
+
+# Type alias for MCP transport connection streams
+TransportConnectorResponse = tuple[
+ "MemoryObjectReceiveStream[Union[SessionMessage, Exception]]",
+ "MemoryObjectSendStream[SessionMessage]",
+]
+
+LOGGER = _loggers.marimo_logger()
+
+
+class MCPTransportType(str, Enum):
+ """Supported MCP transport types."""
+
+ # based on https://modelcontextprotocol.io/docs/concepts/transports
+ STDIO = "stdio"
+ STREAMABLE_HTTP = "streamable_http"
+
+
+class MCPServerStatus(Enum):
+ """Status of an MCP server connection."""
+
+ DISCONNECTED = "disconnected"
+ CONNECTING = "connecting"
+ CONNECTED = "connected"
+ ERROR = "error"
+
+
+@dataclass
+class MCPServerDefinition:
+ """Runtime server definition wrapping config with computed fields."""
+
+ name: str
+ transport: MCPTransportType
+ config: MCPServerConfig
+ timeout: float = 30.0
+
+
+class MCPServerDefinitionFactory:
+ """Factory for creating transport-specific server definitions."""
+
+ @classmethod
+ def from_config(
+ cls, name: str, config: MCPServerConfig
+ ) -> MCPServerDefinition:
+ """Create server definition with automatic transport detection.
+
+ Args:
+ name: Server name
+ config: Server configuration from config file
+
+ Returns:
+ Server definition with detected transport type
+
+ Raises:
+ ValueError: If configuration type is not supported
+ """
+ # Import here to avoid circular imports
+
+ if "command" in config:
+ return MCPServerDefinition(
+ name=name,
+ transport=MCPTransportType.STDIO,
+ config=config,
+ timeout=30.0, # default timeout for STDIO
+ )
+ elif "url" in config:
+ return MCPServerDefinition(
+ name=name,
+ transport=MCPTransportType.STREAMABLE_HTTP,
+ config=config,
+ timeout=config.get("timeout") or 30.0,
+ )
+ else:
+ raise ValueError(f"Unsupported config type: {type(config)}")
+
+
+class MCPTransportConnector(ABC):
+ """Abstract base class for MCP transport connectors."""
+
+ @abstractmethod
+ async def connect(
+ self, server_def: MCPServerDefinition, exit_stack: AsyncExitStack
+ ) -> TransportConnectorResponse:
+ """Connect to the MCP server and return read/write streams.
+
+ Args:
+ server_def: Server definition with transport-specific parameters
+ exit_stack: Async exit stack for resource management
+
+ Returns:
+ Tuple of (read_stream, write_stream) for the ClientSession
+ """
+ pass
+
+
+class StdioTransportConnector(MCPTransportConnector):
+ """STDIO transport connector for process-based MCP servers."""
+
+ async def connect(
+ self, server_def: MCPServerDefinition, exit_stack: AsyncExitStack
+ ) -> TransportConnectorResponse:
+ # Import MCP SDK components for stdio transport
+ from mcp import StdioServerParameters
+ from mcp.client.stdio import stdio_client
+
+ # Type narrowing for mypy
+ assert "command" in server_def.config
+ config = cast(MCPServerStdioConfig, server_def.config)
+
+ # Set up environment variables for the server process
+ env = os.environ.copy()
+ env.update(config.get("env") or {})
+
+ # Configure server parameters
+ server_params = StdioServerParameters(
+ command=config["command"],
+ args=config.get("args") or [],
+ env=env,
+ )
+
+ # Establish connection with proper resource management
+ read, write, *_ = await exit_stack.enter_async_context(
+ stdio_client(server_params)
+ )
+
+ return read, write
+
+
+class StreamableHTTPTransportConnector(MCPTransportConnector):
+ """Streamable HTTP transport connector for modern HTTP-based MCP servers."""
+
+ async def connect(
+ self, server_def: MCPServerDefinition, exit_stack: AsyncExitStack
+ ) -> TransportConnectorResponse:
+ # Import MCP SDK components for streamable HTTP transport
+ from mcp.client.streamable_http import streamablehttp_client
+
+ # Type narrowing for mypy
+ assert "url" in server_def.config
+ config = cast(MCPServerStreamableHttpConfig, server_def.config)
+
+ # Establish streamable HTTP connection
+ read, write, *_ = await exit_stack.enter_async_context(
+ streamablehttp_client(
+ config["url"],
+ headers=config.get("headers") or {},
+ timeout=server_def.timeout,
+ )
+ )
+
+ return read, write
+
+
+class MCPTransportRegistry:
+ """Registry for MCP transport connectors."""
+
+ def __init__(self) -> None:
+ self._connectors: dict[MCPTransportType, MCPTransportConnector] = {
+ MCPTransportType.STDIO: StdioTransportConnector(),
+ MCPTransportType.STREAMABLE_HTTP: StreamableHTTPTransportConnector(),
+ }
+
+ def get_connector(
+ self, transport_type: MCPTransportType
+ ) -> MCPTransportConnector:
+ """Get the appropriate transport connector for the given transport type.
+
+ Args:
+ transport_type: The type of transport to connect with
+
+ Returns:
+ Transport connector instance
+
+ Raises:
+ ValueError: If transport type is not supported
+ """
+ if transport_type not in self._connectors:
+ raise ValueError(f"Unsupported transport type: {transport_type}")
+ return self._connectors[transport_type]
+
+
+@dataclass
+class MCPServerConnection:
+ """Represents a connection to an MCP server."""
+
+ definition: MCPServerDefinition
+ session: Optional[ClientSession] = None
+ status: MCPServerStatus = MCPServerStatus.DISCONNECTED
+ tools: list[Tool] = field(default_factory=list)
+ last_health_check: float = 0
+ error_message: Optional[str] = None
+ read_stream: Optional[
+ MemoryObjectReceiveStream[Union[SessionMessage, Exception]]
+ ] = None
+ write_stream: Optional[MemoryObjectSendStream[SessionMessage]] = None
+ exit_stack: Optional[AsyncExitStack] = None
+
+
+class MCPClient:
+ """Client for managing connections to multiple MCP servers."""
+
+ def __init__(self, config: Optional[MCPConfig] = None):
+ """Initialize MCP client with server configuration."""
+ self.config: MCPConfig = config or MCPConfig(mcpServers={})
+ self.servers: dict[str, MCPServerDefinition] = {}
+ self.connections: dict[str, MCPServerConnection] = {}
+ self.tool_registry: dict[str, Tool] = {}
+ self.server_counters: dict[
+ str, int
+ ] = {} # For handling naming conflicts
+ self.transport_registry = MCPTransportRegistry()
+ self.health_check_tasks: dict[str, asyncio.Task[None]] = {}
+ self.health_check_interval: float = 30.0 # seconds
+ self.health_check_timeout: float = (
+ 5.0 # seconds - shorter timeout for health checks
+ )
+ self._parse_config()
+
+ def _parse_config(self) -> None:
+ """Parse MCP server configuration.
+
+ Note: Servers with invalid configurations are logged but excluded from self.servers,
+ making them unavailable for connection attempts.
+ """
+ mcp_servers = self.config.get("mcpServers", {})
+
+ for server_name, server_config in mcp_servers.items():
+ try:
+ server_def = MCPServerDefinitionFactory.from_config(
+ server_name, server_config
+ )
+
+ self.servers[server_name] = server_def
+ LOGGER.debug(
+ f"Registered MCP server: {server_name} (transport: {server_def.transport})"
+ )
+ except KeyError as e:
+ LOGGER.error(
+ f"Invalid configuration for server {server_name}: missing {e}"
+ )
+ # Note: Server with invalid configuration is not added to self.servers
+ except ValueError as e:
+ LOGGER.error(
+ f"Invalid configuration for server {server_name}: {e}"
+ )
+ # 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
+ from mcp import ClientSession
+
+ if server_name not in self.servers:
+ LOGGER.error(f"Server {server_name} not found in configuration")
+ return False
+
+ server_def = self.servers[server_name]
+
+ # Check if already connected
+ if server_name in self.connections:
+ # Use public API to check status
+ current_status = self.get_server_status(server_name)
+ if current_status == MCPServerStatus.CONNECTED:
+ return True
+
+ try:
+ # Create connection
+ connection = MCPServerConnection(definition=server_def)
+ self.connections[server_name] = connection
+ self._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})"
+ )
+
+ # 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)
+ )
+ )
+
+ # 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)
+ )
+
+ LOGGER.info(
+ f"Successfully connected to MCP server: {server_name} (transport: {server_def.transport})"
+ )
+ return True
+
+ 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)
+
+ # Clean up exit_stack if connection was created but failed
+ if 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
+ )
+ return False
+
+ async def _discover_tools(self, connection: MCPServerConnection) -> None:
+ """Discover tools from an MCP server."""
+ try:
+ LOGGER.info(
+ f"Discovering tools for server: {connection.definition.name}"
+ )
+
+ if not connection.session:
+ raise RuntimeError("No active session for tool discovery")
+
+ # Use the MCP SDK to discover tools
+ tools_response: ListToolsResult = (
+ await connection.session.list_tools()
+ )
+
+ # Add discovered tools
+ self._add_server_tools(connection, tools_response.tools)
+
+ LOGGER.info(
+ f"Discovered {len(connection.tools)} tools from {connection.definition.name}"
+ )
+
+ except Exception as e:
+ LOGGER.error(
+ f"Tool discovery failed for {connection.definition.name}: {str(e)}"
+ )
+
+ def _create_namespaced_tool_name(
+ self, server_name: str, tool_name: str
+ ) -> str:
+ """Create a namespaced tool name with conflict resolution."""
+ base_name = f"mcp_{server_name}_{tool_name}"
+
+ # Check for conflicts
+ if base_name not in self.tool_registry:
+ return base_name
+
+ # Handle naming conflicts - add readable counter to group tools from the same server
+ # The existing tool keeps the base name, current tool gets a numbered name
+ # e.g. mcp_server_name_tool_name, mcp_server_name1_tool_name, mcp_server_name2_tool_name, ...
+ # Based on the vscode MCP tool naming strategy:
+ # https://github.com/microsoft/vscode/issues/244644#issuecomment-2932206637
+ counter = self.server_counters.get(server_name, 0) + 1
+ self.server_counters[server_name] = counter
+ return f"mcp_{server_name}{counter}_{tool_name}"
+
+ async def connect_to_all_servers(self) -> dict[str, bool]:
+ """Connect to all configured MCP servers."""
+ results = {}
+
+ # Connect to servers concurrently
+ tasks = [
+ self.connect_to_server(server_name)
+ for server_name in self.servers.keys()
+ ]
+
+ connection_results = await asyncio.gather(
+ *tasks, return_exceptions=True
+ )
+
+ for server_name, result in zip(
+ self.servers.keys(), connection_results
+ ):
+ if isinstance(result, Exception):
+ LOGGER.error(f"Failed to connect to {server_name}: {result}")
+ results[server_name] = False
+ else:
+ results[server_name] = bool(result)
+
+ return results
+
+ def _create_error_result(self, error_message: str) -> CallToolResult:
+ """Create a properly formatted error CallToolResult
+
+ Args:
+ error_message: The error message to include
+
+ Returns:
+ CallToolResult with isError=True and the error message
+ """
+ # Based on the MCP SDK error handling:
+ # https://modelcontextprotocol.io/docs/concepts/tools#error-handling
+ from mcp.types import CallToolResult, TextContent
+
+ return CallToolResult(
+ isError=True,
+ content=[TextContent(type="text", text=error_message)],
+ )
+
+ def is_error_result(self, result: CallToolResult) -> bool:
+ """Check if a CallToolResult represents an error."""
+ return hasattr(result, "isError") and result.isError is True
+
+ async def invoke_tool(
+ self, namespaced_tool_name: str, params: CallToolRequestParams
+ ) -> CallToolResult:
+ """Invoke an MCP tool using properly typed CallToolRequestParams."""
+ tool = self.tool_registry.get(namespaced_tool_name)
+ if not tool:
+ # Return validation error as CallToolResult instead of raising
+ return self._create_error_result(
+ f"Tool '{namespaced_tool_name}' not found"
+ )
+
+ # Validate that the params tool name matches the resolved tool name
+ if params.name != tool.name:
+ return self._create_error_result(
+ f"Internal error: Parameter tool name '{params.name}' does not match resolved tool name '{tool.name}'"
+ )
+
+ # Get server_name from meta field
+ server_name = tool.meta.get("server_name") if tool.meta else None
+ if not server_name:
+ return self._create_error_result(
+ f"Internal error: Tool '{namespaced_tool_name}' missing server information"
+ )
+
+ if self.get_server_status(server_name) != MCPServerStatus.CONNECTED:
+ return self._create_error_result(
+ f"Server '{server_name}' is not connected"
+ )
+
+ connection = self.connections.get(server_name)
+ if not connection or not connection.session:
+ return self._create_error_result(
+ f"Internal error: No active session for server '{server_name}'"
+ )
+
+ try:
+ LOGGER.debug(
+ f"Invoking MCP tool with params: {namespaced_tool_name}"
+ )
+
+ # Use asyncio.wait_for for timeout handling
+ timeout = connection.definition.timeout
+ result = await asyncio.wait_for(
+ connection.session.call_tool(params.name, params.arguments),
+ timeout=timeout,
+ )
+
+ # Validate the result
+ if not result:
+ LOGGER.warning(
+ f"Tool {namespaced_tool_name} returned empty result"
+ )
+ return self._create_error_result("Tool returned empty result")
+
+ # Return the MCP SDK result directly (may already have isError=True)
+ return result
+
+ except asyncio.TimeoutError:
+ error_msg = f"Tool {namespaced_tool_name} timed out after {connection.definition.timeout} seconds"
+ LOGGER.error(error_msg)
+
+ return self._create_error_result(
+ f"Tool execution timed out after {connection.definition.timeout} seconds"
+ )
+
+ except Exception as e:
+ LOGGER.error(
+ f"Failed to invoke tool {namespaced_tool_name} with params: {str(e)}"
+ )
+
+ return self._create_error_result(
+ f"Tool execution failed: {str(e)}"
+ )
+
+ def create_tool_params(
+ self, namespaced_tool_name: str, arguments: MCPToolArgs = None
+ ) -> CallToolRequestParams:
+ """Create properly typed CallToolRequestParams for a tool."""
+ from mcp.types import CallToolRequestParams
+
+ tool = self.tool_registry.get(namespaced_tool_name)
+ if not tool:
+ raise ValueError(f"Tool '{namespaced_tool_name}' not found")
+
+ return CallToolRequestParams(name=tool.name, arguments=arguments)
+
+ def extract_text_content(self, result: CallToolResult) -> list[str]:
+ """Extract text content from a CallToolResult, handling both success and error cases."""
+ # Import TextContent at runtime for isinstance check
+ from mcp.types import TextContent
+
+ if not hasattr(result, "content") or not result.content:
+ LOGGER.warning("CallToolResult has no content")
+ return []
+
+ text_contents: list[str] = []
+
+ for content_item in result.content:
+ # Use isinstance with the actual TextContent type for proper type checking
+ if isinstance(content_item, TextContent):
+ text_contents.append(content_item.text)
+ else:
+ # Log unexpected content types for debugging
+ LOGGER.debug(
+ f"Unexpected content type in CallToolResult. We only support TextContent: {type(content_item)}"
+ )
+
+ # Log if this was an error result (for debugging purposes)
+ if hasattr(result, "isError") and result.isError:
+ LOGGER.debug(
+ f"Extracted text content from error result: {len(text_contents)} items"
+ )
+
+ return text_contents
+
+ def get_all_tools(self) -> list[Tool]:
+ """Get all registered MCP tools."""
+ return list(self.tool_registry.values())
+
+ def get_tools_by_server(self, server_name: str) -> list[Tool]:
+ """Get tools from a specific server."""
+ return [
+ tool
+ for tool in self.tool_registry.values()
+ if tool.meta and tool.meta.get("server_name") == server_name
+ ]
+
+ def get_server_status(self, server_name: str) -> Optional[MCPServerStatus]:
+ """Get the status of a specific server."""
+ connection = self.connections.get(server_name)
+ return connection.status if connection else None
+
+ def get_all_server_statuses(self) -> dict[str, MCPServerStatus]:
+ """Get the status of all servers."""
+ return {name: conn.status for name, conn in self.connections.items()}
+
+ async def _monitor_server_health(self, server_name: str) -> None:
+ """Continuously monitor server health."""
+ try:
+ while True:
+ try:
+ await asyncio.sleep(self.health_check_interval)
+
+ # Use the public API to check server status
+ current_status = self.get_server_status(server_name)
+ if current_status != MCPServerStatus.CONNECTED:
+ continue
+
+ # Perform health check
+ health_check_passed = await self._perform_health_check(
+ server_name
+ )
+
+ if health_check_passed:
+ # Handle successful health check
+ LOGGER.debug(f"Health check passed for {server_name}")
+ connection = self.connections.get(server_name)
+ if connection:
+ # Update last health check time
+ connection.last_health_check = time.time()
+ else:
+ # Handle failed health check
+ LOGGER.warning(
+ f"Health check failed for {server_name}, marking as ERROR and removing from monitoring"
+ )
+
+ # Determine the appropriate error message based on connection state
+ connection = self.connections.get(server_name)
+ if connection and not connection.session:
+ error_msg = "No active session"
+ else:
+ error_msg = "Health check failed"
+
+ # Update server status and remove tools
+ self._update_server_status(
+ server_name, MCPServerStatus.ERROR, error_msg
+ )
+ self._remove_server_tools(server_name)
+ break # Exit monitoring loop on failure
+
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ LOGGER.error(
+ f"Health monitoring error for {server_name}: {e}"
+ )
+ break # Exit monitoring loop on unexpected error
+ finally:
+ # Clean up the monitoring task from the registry
+ # Note: Don't cancel here since the task is already exiting
+ if server_name in self.health_check_tasks:
+ del self.health_check_tasks[server_name]
+ LOGGER.debug(
+ f"Removed health monitoring task for {server_name}"
+ )
+
+ async def _perform_health_check(self, server_name: str) -> bool:
+ """Perform health check for a server and update its status"""
+ connection = self.connections.get(server_name)
+ if not connection:
+ return False
+
+ try:
+ if not connection.session:
+ return False
+
+ # Use official MCP ping method for health check
+ # https://modelcontextprotocol.io/specification/2025-03-26/basic/utilities/ping
+ await asyncio.wait_for(
+ connection.session.send_ping(),
+ timeout=self.health_check_timeout,
+ )
+
+ return True
+
+ except asyncio.TimeoutError:
+ LOGGER.warning(
+ f"Health check ping timed out after {self.health_check_timeout} seconds for {server_name}"
+ )
+ return False
+ except Exception as e:
+ LOGGER.warning(f"Health check failed for {server_name}: {e}")
+ return False
+
+ def _update_server_status(
+ self,
+ server_name: str,
+ status: MCPServerStatus,
+ error_message: Optional[str] = None,
+ ) -> None:
+ """Centralized method to update server status.
+
+ Args:
+ server_name: Name of the server
+ status: New status to set
+ error_message: Optional error message for ERROR status
+ """
+ connection = self.connections.get(server_name)
+ if not connection:
+ return
+
+ connection.status = status
+ connection.error_message = error_message
+
+ def _add_server_tools(
+ self, connection: MCPServerConnection, tools: list[Tool]
+ ) -> None:
+ """Add tools from a server to the registry and connection.
+
+ Args:
+ connection: Server connection to add tools to
+ tools: List of raw MCP tools to add
+ """
+ from mcp.types import Tool # type: ignore[import-not-found]
+
+ server_name = connection.definition.name
+
+ for tool in tools:
+ namespaced_name = self._create_namespaced_tool_name(
+ server_name, tool.name
+ )
+
+ # Create MCP tool with metadata
+ # Note: MCP SDK Tool constructor uses _meta parameter (with underscore)
+ # but exposes the data as .meta attribute (without underscore) after creation
+ mcp_tool = Tool(
+ name=tool.name,
+ description=tool.description,
+ inputSchema=tool.inputSchema,
+ _meta={
+ "server_name": server_name,
+ "namespaced_name": namespaced_name,
+ },
+ )
+
+ # Add to connection and registry
+ connection.tools.append(mcp_tool)
+ self.tool_registry[namespaced_name] = mcp_tool
+
+ LOGGER.debug(f"Added {len(tools)} tools from {server_name}")
+
+ def _remove_server_tools(self, server_name: str) -> None:
+ """Remove all tools from a server from the registry and clear connection tools.
+
+ Args:
+ server_name: Server name to remove tools for.
+ """
+ tools_to_remove = [
+ name
+ for name, tool in self.tool_registry.items()
+ if tool.meta and tool.meta.get("server_name") == server_name
+ ]
+
+ if tools_to_remove:
+ for tool_name in tools_to_remove:
+ del self.tool_registry[tool_name]
+ LOGGER.debug(
+ f"Removed {len(tools_to_remove)} tools from {server_name}"
+ )
+
+ # Also clear tools from the connection object if it exists
+ connection = self.connections.get(server_name)
+ if connection:
+ connection.tools.clear()
+
+ # Reset the server counter so reconnection starts with clean tool names
+ self._reset_server_counter(server_name)
+
+ def _reset_server_counter(self, server_name: str) -> None:
+ """Reset the naming counter for a server to allow clean reconnection.
+
+ Args:
+ server_name: Server name to reset counter for.
+ """
+ if server_name in self.server_counters:
+ del self.server_counters[server_name]
+ LOGGER.debug(f"Reset naming counter for {server_name}")
+
+ async def _cancel_health_monitoring(
+ self, server_name: Optional[str] = None
+ ) -> None:
+ """Cancel health monitoring for a specific server or all servers.
+
+ Args:
+ server_name: Server name to cancel monitoring for. If None, cancels all.
+ """
+ if server_name is not None:
+ # Cancel single server monitoring
+ if server_name in self.health_check_tasks:
+ task = self.health_check_tasks[server_name]
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ del self.health_check_tasks[server_name]
+ LOGGER.debug(f"Cancelled health monitoring for {server_name}")
+ else:
+ # Cancel all server monitoring
+ if self.health_check_tasks:
+ # Cancel all tasks
+ for task in self.health_check_tasks.values():
+ task.cancel()
+
+ # Wait for all tasks to complete
+ await asyncio.gather(
+ *self.health_check_tasks.values(), return_exceptions=True
+ )
+ self.health_check_tasks.clear()
+ LOGGER.debug("Cancelled all health monitoring tasks")
+
+ async def disconnect_from_server(self, server_name: str) -> bool:
+ """Disconnect from a specific MCP server."""
+ connection = self.connections.get(server_name)
+ if not connection:
+ return True
+
+ try:
+ # Cancel health monitoring task
+ await self._cancel_health_monitoring(server_name)
+
+ # 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
+
+ LOGGER.info(f"Disconnected from MCP server: {server_name}")
+ return True
+
+ except Exception as e:
+ LOGGER.error(
+ f"Error disconnecting from server {server_name}: {str(e)}"
+ )
+ return False
+
+ async def disconnect_from_all_servers(self) -> None:
+ """Disconnect from all MCP servers."""
+ # Cancel all health monitoring tasks first
+ await self._cancel_health_monitoring()
+
+ # Disconnect from all servers
+ tasks = [
+ self.disconnect_from_server(server_name)
+ for server_name in list(self.connections.keys())
+ ]
+
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+
+# Global MCP client instance using lazy initialization
+_MCP_CLIENT: Optional[MCPClient] = None
+
+
+def get_mcp_client(config: Optional[MCPConfig] = None) -> MCPClient:
+ """Get the global MCP client instance, initializing it if needed."""
+ global _MCP_CLIENT
+ if _MCP_CLIENT is None:
+ try:
+ DependencyManager.mcp.require(why="for MCP server connections")
+ except ModuleNotFoundError as e:
+ LOGGER.info(f"MCP SDK not available: {str(e)}")
+ raise
+
+ _MCP_CLIENT = MCPClient(config or _get_default_config())
+ LOGGER.info("MCP client initialized")
+ return _MCP_CLIENT
+
+
+def _get_default_config() -> MCPConfig:
+ """Get default MCP configuration."""
+ return DEFAULT_MCP_CONFIG
diff --git a/marimo/_server/ai/tools.py b/marimo/_server/ai/tools.py
index 6a82ad8a1e..ad763808df 100644
--- a/marimo/_server/ai/tools.py
+++ b/marimo/_server/ai/tools.py
@@ -2,11 +2,17 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any, Callable, Literal, Optional
+from typing import TYPE_CHECKING, Any, Callable, Literal, Optional
from marimo import _loggers
from marimo._config.config import CopilotMode
+if TYPE_CHECKING:
+ from mcp.types import ( # type: ignore[import-not-found]
+ CallToolResult,
+ Tool as MCPRawTool,
+ )
+
LOGGER = _loggers.marimo_logger()
# Type aliases for tool system
@@ -37,7 +43,7 @@ class ToolResult:
class ToolManager:
- """Centralized manager for all tools (mcp, backend, frontend)."""
+ """Centralized manager for backend and frontend tools, with dynamic MCP tool access."""
def __init__(self) -> None:
"""Initialize the tool manager."""
@@ -75,21 +81,47 @@ class ToolManager:
self._tools[tool.name] = tool
LOGGER.debug(f"Registered frontend tool: {tool.name}")
- def register_mcp_tool(self, tool: Tool) -> None:
- """Register an MCP tool (no local handler needed)."""
- if tool.source != "mcp":
- raise ValueError("Tool source must be 'mcp'")
-
- self._tools[tool.name] = tool
- LOGGER.debug(f"Registered MCP tool: {tool.name}")
+ def get_all_tools(self) -> list[Tool]:
+ """Get all available frontend, backend, and MCP tools."""
+ local_tools = list(self._tools.values())
+ mcp_tools = self.list_mcp_tools()
+ all_tools = local_tools + mcp_tools
+ return all_tools
def get_tools_for_mode(self, mode: CopilotMode) -> list[Tool]:
"""Get all tools available for a specific mode."""
- return [tool for tool in self._tools.values() if mode in tool.mode]
+ all_tools = self.get_all_tools()
+ return [tool for tool in all_tools if mode in tool.mode]
- def get_tool(self, name: str) -> Optional[Tool]:
+ def get_tool(
+ self, name: str, source: Optional[ToolSource] = None
+ ) -> Optional[Tool]:
"""Get tool definition by name."""
- return self._tools.get(name)
+ if source:
+ if source == "backend":
+ # Check if it's a backend tool
+ tool = self._tools.get(name)
+ if tool and tool.source == "backend":
+ return tool
+ elif source == "frontend":
+ # Check if it's a frontend tool
+ tool = self._tools.get(name)
+ if tool and tool.source == "frontend":
+ return tool
+ elif source == "mcp":
+ # Check MCP tools
+ mcp_tools = self.list_mcp_tools()
+ for mcp_tool in mcp_tools:
+ if mcp_tool.name == name:
+ return mcp_tool
+ return None
+ else:
+ # No source specified, check all sources
+ all_tools = self.get_all_tools()
+ for tool in all_tools:
+ if tool.name == name:
+ return tool
+ return None
def validate_backend_tool_arguments(
self, tool_name: str, arguments: FunctionArgs
@@ -128,9 +160,36 @@ class ToolManager:
return True, ""
- def create_system_llm_error(self, error_message: str) -> str:
- """Create an LLM error message for a tool."""
- return f"{error_message} Please file a GitHub issue if this problem persists."
+ def list_mcp_tools(self) -> list[Tool]:
+ """Get all MCP tools from the MCP client."""
+ try:
+ from marimo._server.ai.mcp import get_mcp_client
+
+ mcp_client = get_mcp_client()
+ mcp_tools = mcp_client.get_all_tools()
+ return [self.convert_mcp_tool(tool) for tool in mcp_tools]
+
+ except Exception as e:
+ LOGGER.error(f"Failed to get MCP tools: {str(e)}")
+ return []
+
+ def convert_mcp_tool(self, mcp_tool: MCPRawTool) -> Tool:
+ """Convert an MCP tool to marimo Tool format."""
+ # Get namespaced name from meta field (meta is dict[str, Any] | None)
+ meta = mcp_tool.meta or {}
+ namespaced_name = (
+ meta.get("namespaced_name") if isinstance(meta, dict) else None
+ )
+
+ # Convert to marimo Tool format
+ return Tool(
+ name=namespaced_name or mcp_tool.name,
+ description=mcp_tool.description or "No description available",
+ parameters=mcp_tool.inputSchema,
+ source="mcp",
+ mode=["ask"], # MCP tools available in ask mode for now
+ # TODO(bjoaquinc): change default mode to "agent" when we add agent mode
+ )
async def invoke_tool(
self, tool_name: str, arguments: FunctionArgs
@@ -139,11 +198,10 @@ class ToolManager:
tool = self.get_tool(tool_name)
if not tool:
- available_tools = list(self._tools.keys())
return ToolResult(
tool_name=tool_name,
result=None,
- error=f"Tool '{tool_name}' not found. Available tools: {', '.join(available_tools)}",
+ error=f"Internal error: Tool '{tool_name}' not found.",
)
if tool.source == "frontend":
@@ -152,26 +210,21 @@ class ToolManager:
return ToolResult(
tool_name=tool_name,
result=None,
- error=self.create_system_llm_error(
- f"Tool '{tool_name}' is a frontend tool and cannot be executed on the server."
- ),
+ error=f"Internal error: Tool '{tool_name}' is a frontend tool and cannot be executed on the server.",
)
- # Validate arguments for backend tools
- if tool.source == "backend":
- is_valid, validation_error = self.validate_backend_tool_arguments(
- tool_name, arguments
- )
- if not is_valid:
- return ToolResult(
- tool_name=tool_name,
- result=None,
- error=f"Invalid arguments for tool '{tool_name}': {validation_error}",
- )
-
try:
if tool.source == "backend":
# Handle backend tools
+ is_valid, validation_error = (
+ self.validate_backend_tool_arguments(tool_name, arguments)
+ )
+ if not is_valid:
+ return ToolResult(
+ tool_name=tool_name,
+ result=None,
+ error=f"Invalid arguments for tool '{tool_name}': {validation_error}",
+ )
handler = self._backend_handlers.get(tool_name)
if not handler:
system_error = (
@@ -181,15 +234,49 @@ class ToolManager:
return ToolResult(
tool_name=tool_name,
result=None,
- error=self.create_system_llm_error(
- f"Tool '{tool_name}' cannot be invoked."
- ),
+ error=f"Internal error: Tool '{tool_name}' cannot be invoked.",
)
result = await self._call_handler(handler, arguments)
+ return ToolResult(
+ tool_name=tool_name, result=result, error=None
+ )
elif tool.source == "mcp":
# Handle MCP tools
- result = await self._invoke_mcp_tool(tool_name, arguments)
+ call_result = await self._invoke_mcp_tool(tool_name, arguments)
+
+ # Check if the result indicates an error using the MCP client
+ from marimo._server.ai.mcp import get_mcp_client
+
+ mcp_client = get_mcp_client()
+
+ if mcp_client.is_error_result(call_result):
+ # Extract error message from the result content
+ error_messages = mcp_client.extract_text_content(
+ call_result
+ )
+ error_text = (
+ " ".join(error_messages)
+ if error_messages
+ else "Unknown MCP tool error"
+ )
+ LOGGER.error(
+ f"MCP tool '{tool_name}' returned error: {error_text}"
+ )
+ return ToolResult(
+ tool_name=tool_name, result=None, error=error_text
+ )
+
+ # For successful results, extract text content from CallToolResult
+ success_messages = mcp_client.extract_text_content(call_result)
+ result_text = (
+ " ".join(success_messages)
+ if success_messages
+ else "MCP tool completed successfully with no text output"
+ )
+ return ToolResult(
+ tool_name=tool_name, result=result_text, error=None
+ )
else:
# Unknown tool source
@@ -198,13 +285,9 @@ class ToolManager:
return ToolResult(
tool_name=tool_name,
result=None,
- error=self.create_system_llm_error(
- f"Tool configuration error for tool {tool_name}."
- ),
+ error=f"Internal error: Tool configuration error for tool {tool_name}.",
)
- return ToolResult(tool_name=tool_name, result=result, error=None)
-
except Exception as e:
error_message = f"Error invoking tool '{tool_name}': {str(e)}"
LOGGER.error(error_message)
@@ -231,16 +314,20 @@ class ToolManager:
async def _invoke_mcp_tool(
self, tool_name: str, arguments: FunctionArgs
- ) -> Any:
+ ) -> CallToolResult:
"""Invoke an MCP tool via the MCP client."""
- # TODO: Implement MCP tool invocation
- # This would interact with the MCP client to call the tool
- LOGGER.warning(
- f"MCP tool invocation not yet implemented for '{tool_name}'"
- )
- return {
- "message": f"MCP tool '{tool_name}' called with args: {arguments}"
- }
+ from marimo._server.ai.mcp import get_mcp_client
+
+ mcp_client = get_mcp_client()
+
+ # Create properly typed parameters for the MCP tool
+ params = mcp_client.create_tool_params(tool_name, arguments)
+
+ # Invoke the tool
+ call_result = await mcp_client.invoke_tool(tool_name, params)
+
+ # Return the CallToolResult directly - let invoke_tool handle error checking
+ return call_result
def _register_builtin_tools(self) -> None:
"""Register built-in backend tools."""
@@ -249,12 +336,6 @@ class ToolManager:
register_all_backend_tools()
- def _discover_mcp_tools(self) -> None:
- """Discover and register MCP tools."""
- # TODO: Implement MCP tool discovery
- # This would connect to MCP servers and get their available tools
- LOGGER.debug("MCP tool discovery not yet implemented")
-
# Global tool manager instance using lazy initialization to avoid circular imports
_TOOL_MANAGER: Optional[ToolManager] = None
@@ -267,8 +348,7 @@ def get_tool_manager() -> ToolManager:
_TOOL_MANAGER = ToolManager()
# Register tools after the manager is created to avoid circular imports
_TOOL_MANAGER._register_builtin_tools()
- _TOOL_MANAGER._discover_mcp_tools()
LOGGER.info(
- f"ToolManager initialized with {len(_TOOL_MANAGER._tools)} tools"
+ f"ToolManager initialized with {len(_TOOL_MANAGER._tools)} backend/frontend tools"
)
return _TOOL_MANAGER
diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.py
index 5d2c851928..2fa85fe9ee 100644
--- a/marimo/_server/api/lifespans.py
+++ b/marimo/_server/api/lifespans.py
@@ -46,6 +46,19 @@ async def lsp(app: Starlette) -> AsyncIterator[None]:
yield
+async def mcp(app: Starlette) -> AsyncIterator[None]:
+ state = AppState.from_app(app)
+ session_mgr = state.session_manager
+
+ # Only start MCP servers in Edit mode
+ if session_mgr.mode == SessionMode.EDIT:
+ # add MCP server here after it is implemented
+ ...
+
+ yield
+
+
@contextlib.asynccontextmanager
async def open_browser(app: Starlette) -> AsyncIterator[None]:
state = AppState.from_app(app)
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index 57611a4a17..8f6cace71d 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -168,6 +168,7 @@ def start(
lifespan=Lifespans(
[
lifespans.lsp,
+ lifespans.mcp,
lifespans.etc,
lifespans.signal_handler,
lifespans.logging,
diff --git a/pyproject.toml b/pyproject.toml
index 12279e9c78..1a5a1fefbe 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -202,6 +202,7 @@ dependencies = [
"types-redis~=4.6.0.20241004",
"types-Markdown~=3.6.0.20240316",
"types-PyYAML~=6.0.12.20240808",
+ "mcp>=1.0.0; python_version >= '3.10'",
]
[tool.hatch.envs.typecheck.scripts]
@@ -287,6 +288,7 @@ extra-dependencies = [
"jax>=0.4.0; python_version == '3.12'",
"torch>=2.4.0; python_version == '3.12'",
"scikit-bio>=0.6.3; python_version == '3.12'",
+ "mcp>=1.0.0; python_version >= '3.10'",
]
[[tool.hatch.envs.test-optional.matrix]]
diff --git a/tests/_server/ai/test_mcp.py b/tests/_server/ai/test_mcp.py
new file mode 100644
index 0000000000..4e74270bba
--- /dev/null
+++ b/tests/_server/ai/test_mcp.py
@@ -0,0 +1,1122 @@
+# Copyright 2024 Marimo. All rights reserved.
+import asyncio
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from marimo._config.config import (
+ MCPConfig,
+ MCPServerStdioConfig,
+ MCPServerStreamableHttpConfig,
+)
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._server.ai.mcp import (
+ MCPClient,
+ MCPServerConnection,
+ MCPServerDefinition,
+ MCPServerDefinitionFactory,
+ MCPServerStatus,
+ MCPTransportRegistry,
+ MCPTransportType,
+ StdioTransportConnector,
+ StreamableHTTPTransportConnector,
+ get_mcp_client,
+)
+
+# test fixtures and helpers
+
+
+def mock_session_setup():
+ """Create a properly configured mock session with async context manager behavior."""
+
+ def _create_mock_session(additional_methods=None, side_effects=None):
+ mock_session = AsyncMock()
+ mock_session.initialize = AsyncMock()
+ mock_session.list_tools = AsyncMock()
+ mock_session.list_tools.return_value.tools = []
+
+ # Add any additional methods specified
+ if additional_methods:
+ for method_name, method_mock in additional_methods.items():
+ setattr(mock_session, method_name, method_mock)
+
+ # Apply any side effects
+ if side_effects:
+ for method_name, side_effect in side_effects.items():
+ getattr(mock_session, method_name).side_effect = side_effect
+
+ mock_session_context = AsyncMock()
+ mock_session_context.__aenter__ = AsyncMock(return_value=mock_session)
+ mock_session_context.__aexit__ = AsyncMock(return_value=None)
+
+ return mock_session, mock_session_context
+
+ return _create_mock_session
+
+
+def mock_stdio_setup():
+ """Create a properly configured mock stdio client with async context manager behavior."""
+
+ def _create_mock_stdio():
+ mock_read = AsyncMock()
+ mock_write = AsyncMock()
+ mock_stdio_context = AsyncMock()
+ mock_stdio_context.__aenter__ = AsyncMock(
+ return_value=(mock_read, mock_write)
+ )
+ mock_stdio_context.__aexit__ = AsyncMock(return_value=None)
+
+ return mock_read, mock_write, mock_stdio_context
+
+ return _create_mock_stdio
+
+
+def create_test_server_definition(
+ name: str = "test_server",
+ command: str = "test",
+ args: list = None,
+ env: dict = None,
+ timeout: float = None,
+) -> MCPServerDefinition:
+ """Create a test server definition with sensible defaults."""
+ if args is None:
+ args = []
+ if env is None:
+ env = {}
+
+ config = MCPServerStdioConfig(command=command, args=args, env=env)
+ server_def = MCPServerDefinitionFactory.from_config(name, config)
+
+ if timeout is not None:
+ server_def.timeout = timeout
+
+ return server_def
+
+
+def create_test_server_connection(
+ name: str = "test_server",
+ command: str = "test",
+ args: list = None,
+ env: dict = None,
+ status: MCPServerStatus = MCPServerStatus.DISCONNECTED,
+ session=None,
+ timeout: float = None,
+) -> MCPServerConnection:
+ """Create a test server connection with sensible defaults."""
+ server_def = create_test_server_definition(
+ name, command, args, env, timeout
+ )
+ connection = MCPServerConnection(definition=server_def)
+ connection.status = status
+ connection.session = session
+ return connection
+
+
+def create_test_tool(
+ name: str = "test_tool",
+ description: str = "Test tool",
+ server_name: str = "test_server",
+ namespaced_name: str = None,
+ input_schema: dict = None,
+):
+ """Create a test tool with sensible defaults."""
+ if DependencyManager.mcp.has():
+ from mcp.types import Tool
+
+ if input_schema is None:
+ input_schema = {"type": "object"}
+ if namespaced_name is None:
+ namespaced_name = f"mcp_{server_name}_{name}"
+
+ return Tool(
+ name=name,
+ description=description,
+ inputSchema=input_schema,
+ _meta={
+ "server_name": server_name,
+ "namespaced_name": namespaced_name,
+ },
+ )
+ return None
+
+
+# tests
+
+
+class TestMCPServerDefinition:
+ """Test cases for MCPServerDefinition class."""
+
+ @pytest.mark.parametrize(
+ ("config_type", "expected_transport", "config_kwargs"),
+ [
+ pytest.param(
+ MCPServerStdioConfig,
+ MCPTransportType.STDIO,
+ {
+ "command": "python",
+ "args": ["server.py"],
+ "env": {"API_KEY": "test"},
+ },
+ id="stdio_transport",
+ ),
+ pytest.param(
+ MCPServerStreamableHttpConfig,
+ MCPTransportType.STREAMABLE_HTTP,
+ {
+ "url": "https://api.example.com/mcp",
+ "headers": {"Auth": "Bearer token"},
+ "timeout": 45.0,
+ },
+ id="http_transport",
+ ),
+ ],
+ )
+ def test_from_config_transport_detection(
+ self, config_type, expected_transport, config_kwargs
+ ):
+ """Test that transport types are correctly auto-detected from configuration."""
+ config = config_type(**config_kwargs)
+ server_def = MCPServerDefinitionFactory.from_config(
+ "test_server", config
+ )
+
+ assert server_def.name == "test_server"
+ assert server_def.transport == expected_transport
+ assert server_def.config == config
+
+ # Verify transport-specific attributes are available from config
+ if expected_transport == MCPTransportType.STDIO:
+ assert server_def.config["command"] == config_kwargs["command"]
+ assert server_def.config.get("args") == config_kwargs["args"]
+ assert server_def.config.get("env") == config_kwargs["env"]
+ elif expected_transport == MCPTransportType.STREAMABLE_HTTP:
+ assert server_def.config["url"] == config_kwargs["url"]
+ assert server_def.config.get("headers") == config_kwargs["headers"]
+ assert server_def.timeout == config_kwargs["timeout"]
+
+
+class TestMCPTransportConnectors:
+ """Test cases for transport connector classes."""
+
+ def test_transport_registry_functionality(self):
+ """Test that the transport registry properly handles all transport types."""
+ registry = MCPTransportRegistry()
+
+ # Test that all transport types are supported
+ for transport_type in MCPTransportType:
+ connector = registry.get_connector(transport_type)
+ assert connector is not None
+
+ # Test unsupported transport type
+ with pytest.raises(ValueError, match="Unsupported transport type"):
+ registry.get_connector("unsupported_transport") # type: ignore
+
+ @pytest.mark.skipif(
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+ )
+ @patch("mcp.client.stdio.stdio_client")
+ async def test_stdio_connector_connect(self, mock_stdio_client):
+ """Test STDIO transport connector connection."""
+ # Setup mocks
+ mock_read = AsyncMock()
+ mock_write = AsyncMock()
+ mock_context = AsyncMock()
+ mock_context.__aenter__ = AsyncMock(
+ return_value=(mock_read, mock_write)
+ )
+ mock_context.__aexit__ = AsyncMock(return_value=None)
+ mock_stdio_client.return_value = mock_context
+
+ # Create connector and test connection
+ connector = StdioTransportConnector()
+ config = MCPServerStdioConfig(
+ command="python", args=["server.py"], env={"TEST_VAR": "value"}
+ )
+ server_def = MCPServerDefinition(
+ name="test", transport=MCPTransportType.STDIO, config=config
+ )
+
+ from contextlib import AsyncExitStack
+
+ async with AsyncExitStack() as exit_stack:
+ read, write = await connector.connect(server_def, exit_stack)
+ assert read == mock_read
+ assert write == mock_write
+
+ @pytest.mark.skipif(
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+ )
+ @patch("mcp.client.streamable_http.streamablehttp_client")
+ async def test_http_connector_connect(self, mock_http_client):
+ """Test HTTP transport connector connection."""
+ # Setup mocks
+ mock_read = AsyncMock()
+ mock_write = AsyncMock()
+ mock_context = AsyncMock()
+ mock_context.__aenter__ = AsyncMock(
+ return_value=(mock_read, mock_write)
+ )
+ mock_context.__aexit__ = AsyncMock(return_value=None)
+ mock_http_client.return_value = mock_context
+
+ # Create connector and test connection
+ connector = StreamableHTTPTransportConnector()
+ config = MCPServerStreamableHttpConfig(
+ url="https://api.example.com/mcp",
+ headers={"Authorization": "Bearer token"},
+ timeout=30.0,
+ )
+ server_def = MCPServerDefinition(
+ name="test",
+ transport=MCPTransportType.STREAMABLE_HTTP,
+ config=config,
+ timeout=30.0,
+ )
+
+ from contextlib import AsyncExitStack
+
+ async with AsyncExitStack() as exit_stack:
+ read, write = await connector.connect(server_def, exit_stack)
+ assert read == mock_read
+ assert write == mock_write
+
+
+class TestMCPClientConfiguration:
+ """Test cases for MCPClient configuration parsing and initialization."""
+
+ def test_init_with_empty_config(self):
+ """Test MCPClient initialization with empty config."""
+ config = MCPConfig(mcpServers={})
+ client = MCPClient(config)
+ assert client.servers == {}
+ assert client.connections == {}
+ assert client.tool_registry == {}
+
+ @pytest.mark.parametrize(
+ ("server_configs", "expected_servers"),
+ [
+ pytest.param(
+ {
+ "stdio_server": MCPServerStdioConfig(
+ command="python",
+ args=["test.py"],
+ env={"TEST": "value"},
+ ),
+ },
+ ["stdio_server"],
+ id="single_stdio_server",
+ ),
+ pytest.param(
+ {
+ "http_server": MCPServerStreamableHttpConfig(
+ url="https://api.example.com/mcp",
+ headers={"Auth": "Bearer token"},
+ ),
+ },
+ ["http_server"],
+ id="single_http_server",
+ ),
+ pytest.param(
+ {
+ "stdio_server": MCPServerStdioConfig(
+ command="python", args=["test.py"]
+ ),
+ "http_server": MCPServerStreamableHttpConfig(
+ url="https://api.example.com/mcp"
+ ),
+ },
+ ["stdio_server", "http_server"],
+ id="mixed_servers",
+ ),
+ ],
+ )
+ def test_parse_config_valid_servers(
+ self, server_configs, expected_servers
+ ):
+ """Test parsing valid server configurations."""
+ config = MCPConfig(mcpServers=server_configs)
+ client = MCPClient(config)
+
+ assert len(client.servers) == len(expected_servers)
+ for server_name in expected_servers:
+ assert server_name in client.servers
+ server_def = client.servers[server_name]
+ assert server_def.name == server_name
+
+
+class TestMCPClientToolManagement:
+ """Test cases for MCPClient tool management functionality."""
+
+ def test_create_namespaced_tool_name_no_conflict(self):
+ """Test creating namespaced tool name without conflicts."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+ name = client._create_namespaced_tool_name("github", "create_issue")
+ assert name == "mcp_github_create_issue"
+
+ @pytest.mark.skipif(
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+ )
+ def test_create_namespaced_tool_name_with_conflicts(self):
+ """Test creating namespaced tool name with conflicts and counter resolution."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+
+ from mcp.types import Tool
+
+ # Create first tool - should get base name
+ name1 = client._create_namespaced_tool_name("github", "create_issue")
+ assert name1 == "mcp_github_create_issue"
+
+ # Add it to registry
+ tool1 = Tool(
+ name="create_issue",
+ description="Test tool",
+ inputSchema={},
+ _meta={"server_name": "github", "namespaced_name": name1},
+ )
+ client.tool_registry[name1] = tool1
+
+ # Create second tool with same name - should get numbered suffix
+ name2 = client._create_namespaced_tool_name("github", "create_issue")
+ assert name2 == "mcp_github1_create_issue"
+
+ # Create third tool - should get next counter
+ name3 = client._create_namespaced_tool_name("github", "create_issue")
+ assert name3 == "mcp_github2_create_issue"
+
+ # All names should be unique
+ assert len({name1, name2, name3}) == 3
+
+ @pytest.mark.skipif(
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+ )
+ def test_add_server_tools(self):
+ """Test adding tools from a server to registry and connection."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+ from mcp.types import Tool
+
+ # Create server connection
+ connection = create_test_server_connection()
+
+ # Create raw tools to add
+ raw_tools = [
+ Tool(
+ name="tool1",
+ description="Test tool 1",
+ inputSchema={"type": "object"},
+ ),
+ Tool(
+ name="tool2",
+ description="Test tool 2",
+ inputSchema={"type": "object"},
+ ),
+ ]
+
+ # Add tools
+ client._add_server_tools(connection, raw_tools)
+
+ # Verify tools are added to connection
+ assert len(connection.tools) == 2
+
+ # Verify tools are added to registry with proper namespacing
+ assert "mcp_test_server_tool1" in client.tool_registry
+ assert "mcp_test_server_tool2" in client.tool_registry
+
+ # Verify tool metadata
+ tool1 = client.tool_registry["mcp_test_server_tool1"]
+ assert tool1.meta["server_name"] == "test_server"
+ assert tool1.meta["namespaced_name"] == "mcp_test_server_tool1"
+
+ @pytest.mark.skipif(
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+ )
+ def test_remove_server_tools(self):
+ """Test removing tools from a server."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+ from mcp.types import Tool
+
+ # Create tools from different servers
+ server1_tools = [
+ (
+ "mcp_server1_tool1",
+ Tool(
+ name="tool1",
+ description="Test",
+ inputSchema={},
+ _meta={
+ "server_name": "server1",
+ "namespaced_name": "mcp_server1_tool1",
+ },
+ ),
+ ),
+ (
+ "mcp_server1_tool2",
+ Tool(
+ name="tool2",
+ description="Test",
+ inputSchema={},
+ _meta={
+ "server_name": "server1",
+ "namespaced_name": "mcp_server1_tool2",
+ },
+ ),
+ ),
+ ]
+ server2_tools = [
+ (
+ "mcp_server2_tool3",
+ Tool(
+ name="tool3",
+ description="Test",
+ inputSchema={},
+ _meta={
+ "server_name": "server2",
+ "namespaced_name": "mcp_server2_tool3",
+ },
+ ),
+ )
+ ]
+
+ # Add tools to registry
+ for namespaced_name, tool in server1_tools + server2_tools:
+ client.tool_registry[namespaced_name] = tool
+
+ # Create connection and add tools
+ connection = create_test_server_connection(name="server1")
+ connection.tools = [tool for _, tool in server1_tools]
+ client.connections["server1"] = connection
+
+ # Set a counter for the server
+ client.server_counters["server1"] = 3
+
+ # Remove tools from server1
+ client._remove_server_tools("server1")
+
+ # Verify server1 tools are removed
+ for namespaced_name, _ in server1_tools:
+ assert namespaced_name not in client.tool_registry
+
+ # Verify server2 tools remain
+ for namespaced_name, _ in server2_tools:
+ assert namespaced_name in client.tool_registry
+
+ # Verify connection tools are cleared
+ assert len(connection.tools) == 0
+
+ # Verify counter is reset
+ assert "server1" not in client.server_counters
+
+ @pytest.mark.skipif(
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+ )
+ @pytest.mark.parametrize(
+ ("server_name", "expected_tool_count"),
+ [
+ pytest.param("server1", 2, id="existing_server"),
+ pytest.param("nonexistent", 0, id="nonexistent_server"),
+ ],
+ )
+ def test_get_tools_by_server(self, server_name, expected_tool_count):
+ """Test getting tools by server name."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+ from mcp.types import Tool
+
+ # Add tools from different servers
+ tools_data = [
+ ("mcp_server1_tool1", "server1"),
+ ("mcp_server1_tool2", "server1"),
+ ("mcp_server2_tool3", "server2"),
+ ]
+
+ for namespaced_name, server in tools_data:
+ tool = Tool(
+ name=namespaced_name.split("_")[-1],
+ description="Test",
+ inputSchema={},
+ _meta={
+ "server_name": server,
+ "namespaced_name": namespaced_name,
+ },
+ )
+ client.tool_registry[namespaced_name] = tool
+
+ # Get tools by server
+ tools = client.get_tools_by_server(server_name)
+ assert len(tools) == expected_tool_count
+
+
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+)
+class TestMCPClientToolExecution:
+ """Test cases for MCPClient tool execution functionality."""
+
+ def test_create_tool_params(self):
+ """Test creating properly typed CallToolRequestParams."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+
+ # Add a mock tool to the registry
+ mock_tool = create_test_tool()
+ client.tool_registry["mcp_test_server_test_tool"] = mock_tool
+
+ # Test creating tool params with arguments
+ params = client.create_tool_params(
+ "mcp_test_server_test_tool", {"arg1": "value1"}
+ )
+ assert params.name == "test_tool"
+ assert params.arguments == {"arg1": "value1"}
+
+ # Test with no arguments
+ params_no_args = client.create_tool_params("mcp_test_server_test_tool")
+ assert params_no_args.name == "test_tool"
+ assert params_no_args.arguments is None
+
+ # Test with non-existent tool
+ with pytest.raises(ValueError, match="Tool 'nonexistent' not found"):
+ client.create_tool_params("nonexistent")
+
+ @pytest.mark.parametrize(
+ ("tool_setup", "connection_setup", "expected_error_pattern"),
+ [
+ pytest.param(
+ None, # No tool setup
+ {"status": MCPServerStatus.CONNECTED, "session": AsyncMock()},
+ "Tool 'nonexistent_tool' not found",
+ id="tool_not_found",
+ ),
+ pytest.param(
+ {"server_name": "test_server"},
+ {"status": MCPServerStatus.DISCONNECTED, "session": None},
+ "Server 'test_server' is not connected",
+ id="server_not_connected",
+ ),
+ pytest.param(
+ {"server_name": "test_server"},
+ {"status": MCPServerStatus.CONNECTED, "session": None},
+ "No active session for server 'test_server'",
+ id="no_active_session",
+ ),
+ ],
+ )
+ async def test_invoke_tool_error_cases(
+ self, tool_setup, connection_setup, expected_error_pattern
+ ):
+ """Test invoke_tool error handling scenarios."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+ from mcp.types import Tool
+
+ # Setup tool if provided
+ if tool_setup:
+ mock_tool = Tool(
+ name="test_tool",
+ description="Test tool",
+ inputSchema={},
+ _meta={
+ "server_name": tool_setup["server_name"],
+ "namespaced_name": "mcp_test_server_test_tool",
+ },
+ )
+ client.tool_registry["mcp_test_server_test_tool"] = mock_tool
+
+ # Setup connection
+ server_def = MCPServerDefinitionFactory.from_config(
+ "test_server", MCPServerStdioConfig(command="test", args=[])
+ )
+ connection = MCPServerConnection(definition=server_def)
+ connection.status = connection_setup["status"]
+ connection.session = connection_setup["session"]
+ client.connections["test_server"] = connection
+
+ # Create params for the tool
+ params = client.create_tool_params(
+ "mcp_test_server_test_tool", {"arg1": "value1"}
+ )
+ tool_name = "mcp_test_server_test_tool"
+ else:
+ # Use non-existent tool
+ from mcp.types import CallToolRequestParams
+
+ params = CallToolRequestParams(
+ name="nonexistent", arguments={"arg1": "value1"}
+ )
+ tool_name = "nonexistent_tool"
+
+ # Test tool invocation
+ result = await client.invoke_tool(tool_name, params)
+
+ # Verify it's an error result
+ assert client.is_error_result(result) is True
+
+ # Verify error message
+ error_messages = client.extract_text_content(result)
+ assert len(error_messages) > 0
+ assert expected_error_pattern in error_messages[0]
+
+ async def test_invoke_tool_success(self):
+ """Test successful tool invocation."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+ from mcp.types import CallToolResult, TextContent
+
+ # Setup tool
+ mock_tool = create_test_tool()
+ client.tool_registry["mcp_test_server_test_tool"] = mock_tool
+
+ # Setup connection with mock session
+ connection = create_test_server_connection(
+ status=MCPServerStatus.CONNECTED, session=AsyncMock()
+ )
+
+ # Mock successful tool result
+ expected_result = CallToolResult(
+ content=[
+ TextContent(type="text", text="Tool executed successfully")
+ ]
+ )
+ connection.session.call_tool = AsyncMock(return_value=expected_result)
+ client.connections["test_server"] = connection
+
+ # Create params and invoke tool
+ params = client.create_tool_params(
+ "mcp_test_server_test_tool", {"arg1": "value1"}
+ )
+ result = await client.invoke_tool("mcp_test_server_test_tool", params)
+
+ # Verify result
+ assert client.is_error_result(result) is False
+ text_contents = client.extract_text_content(result)
+ assert "Tool executed successfully" in text_contents[0]
+
+ # Verify session was called correctly
+ connection.session.call_tool.assert_called_once_with(
+ "test_tool", {"arg1": "value1"}
+ )
+
+ async def test_invoke_tool_timeout(self):
+ """Test tool invocation timeout handling."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+
+ # Setup tool
+ mock_tool = create_test_tool()
+ client.tool_registry["mcp_test_server_test_tool"] = mock_tool
+
+ # Setup connection with timeout
+ connection = create_test_server_connection(
+ timeout=0.1, # Very short timeout
+ status=MCPServerStatus.CONNECTED,
+ session=AsyncMock(),
+ )
+
+ # Mock session to hang longer than timeout
+ async def slow_call_tool(_name, _args):
+ await asyncio.sleep(1) # Longer than timeout
+
+ connection.session.call_tool = AsyncMock(side_effect=slow_call_tool)
+ client.connections["test_server"] = connection
+
+ # Create params and invoke tool
+ params = client.create_tool_params(
+ "mcp_test_server_test_tool", {"arg1": "value1"}
+ )
+ result = await client.invoke_tool("mcp_test_server_test_tool", params)
+
+ # Verify timeout error
+ assert client.is_error_result(result) is True
+ error_messages = client.extract_text_content(result)
+ assert "timed out" in error_messages[0]
+
+ @pytest.mark.parametrize(
+ ("result_content", "expected_is_error", "expected_text_count"),
+ [
+ pytest.param(
+ [{"type": "text", "text": "Success message"}],
+ False,
+ 1,
+ id="success_result",
+ ),
+ pytest.param(
+ [{"type": "text", "text": "Error occurred"}],
+ True,
+ 1,
+ id="error_result",
+ ),
+ pytest.param(
+ [
+ {"type": "text", "text": "First message"},
+ {"type": "text", "text": "Second message"},
+ ],
+ False,
+ 2,
+ id="multiple_text_content",
+ ),
+ ],
+ )
+ def test_result_handling_helpers(
+ self, result_content, expected_is_error, expected_text_count
+ ):
+ """Test CallToolResult helper methods."""
+ from mcp.types import CallToolResult, TextContent
+
+ client = MCPClient(MCPConfig(mcpServers={}))
+
+ # Create result
+ content = [TextContent(**item) for item in result_content]
+ result = CallToolResult(isError=expected_is_error, content=content)
+
+ # Test error detection
+ assert client.is_error_result(result) == expected_is_error
+
+ # Test text extraction
+ text_contents = client.extract_text_content(result)
+ assert len(text_contents) == expected_text_count
+
+ for i, expected_text in enumerate(
+ [item["text"] for item in result_content]
+ ):
+ assert text_contents[i] == expected_text
+
+
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+)
+class TestMCPClientConnectionManagement:
+ """Test cases for MCPClient connection management functionality."""
+
+ async def test_discover_tools_success(self):
+ """Test successful tool discovery from an MCP server."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+ from mcp.types import ListToolsResult, Tool
+
+ # Create mock connection with session
+ mock_session = AsyncMock()
+ connection = create_test_server_connection(session=mock_session)
+
+ # Mock tools response
+ mock_tools = [
+ Tool(
+ name="tool1",
+ description="First tool",
+ inputSchema={"type": "object"},
+ ),
+ Tool(
+ name="tool2",
+ description="Second tool",
+ inputSchema={"type": "object"},
+ ),
+ ]
+ mock_response = ListToolsResult(tools=mock_tools)
+ mock_session.list_tools = AsyncMock(return_value=mock_response)
+
+ # Test tool discovery
+ await client._discover_tools(connection)
+
+ # Verify tools were added
+ assert len(connection.tools) == 2
+ assert "mcp_test_server_tool1" in client.tool_registry
+ assert "mcp_test_server_tool2" in client.tool_registry
+
+ # Verify session was called
+ mock_session.list_tools.assert_called_once()
+
+ async def test_discover_tools_no_session(self):
+ """Test tool discovery with no active session."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+
+ # Create connection without session
+ connection = create_test_server_connection(session=None)
+
+ # Test tool discovery (should handle gracefully)
+ await client._discover_tools(connection)
+
+ # Verify no tools were added
+ assert len(connection.tools) == 0
+ assert len(client.tool_registry) == 0
+
+ @patch("mcp.ClientSession")
+ @patch("mcp.client.stdio.stdio_client")
+ async def test_connect_to_server_success(
+ self,
+ mock_stdio_client,
+ mock_session_class,
+ mock_stdio_setup,
+ mock_session_setup,
+ ):
+ """Test successful server connection with complete flow."""
+ # Setup stdio and session mocks using fixtures
+ mock_read, mock_write, mock_stdio_context = mock_stdio_setup()
+ mock_stdio_client.return_value = mock_stdio_context
+
+ mock_session, mock_session_context = mock_session_setup()
+ mock_session_class.return_value = mock_session_context
+
+ # Mock AsyncExitStack
+ with 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
+
+ # Create client with test config
+ config = MCPConfig(
+ mcpServers={
+ "test_server": MCPServerStdioConfig(
+ command="python", args=["test.py"], env={}
+ )
+ }
+ )
+ client = MCPClient(config)
+
+ # Test connection
+ result = await client.connect_to_server("test_server")
+
+ assert result is True
+ assert "test_server" in client.connections
+ assert (
+ client.connections["test_server"].status
+ == MCPServerStatus.CONNECTED
+ )
+
+ @pytest.mark.parametrize(
+ ("server_exists", "already_connected", "expected_result"),
+ [
+ pytest.param(False, False, False, id="server_not_found"),
+ pytest.param(True, True, True, id="already_connected"),
+ ],
+ )
+ async def test_connect_to_server_edge_cases(
+ self, server_exists, already_connected, expected_result
+ ):
+ """Test server connection edge cases."""
+ config = MCPConfig(mcpServers={})
+ if server_exists:
+ config["mcpServers"]["test_server"] = MCPServerStdioConfig(
+ command="python", args=["test.py"]
+ )
+
+ client = MCPClient(config)
+
+ if already_connected:
+ # Setup existing connection
+ server_def = MCPServerDefinitionFactory.from_config(
+ "test_server", MCPServerStdioConfig(command="test", args=[])
+ )
+ connection = MCPServerConnection(definition=server_def)
+ connection.status = MCPServerStatus.CONNECTED
+ client.connections["test_server"] = connection
+
+ result = await client.connect_to_server("test_server")
+ assert result == expected_result
+
+ @patch("mcp.ClientSession")
+ async def test_connect_to_all_servers_mixed_results(
+ self, mock_session_class
+ ):
+ """Test connecting to multiple servers with mixed success/failure."""
+ # Setup session mock for successful connections
+ mock_session = AsyncMock()
+ mock_session.initialize = AsyncMock()
+ mock_session.list_tools = AsyncMock()
+ mock_session.list_tools.return_value.tools = []
+
+ mock_session_context = AsyncMock()
+ mock_session_context.__aenter__ = AsyncMock(return_value=mock_session)
+ mock_session_context.__aexit__ = AsyncMock(return_value=None)
+ mock_session_class.return_value = mock_session_context
+
+ with patch(
+ "marimo._server.ai.mcp.AsyncExitStack"
+ ) as mock_exit_stack_class:
+ mock_exit_stack = AsyncMock()
+ mock_exit_stack.enter_async_context = AsyncMock()
+ # 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
+ Exception("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)
+
+ results = await client.connect_to_all_servers()
+
+ # Verify mixed results
+ assert len(results) == 2
+ assert results["server1"] is True
+ assert results["server2"] is False
+
+
+class TestMCPClientHealthMonitoring:
+ """Test cases for MCPClient health monitoring functionality."""
+
+ @pytest.mark.skipif(
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+ )
+ async def test_perform_health_check_success(self):
+ """Test successful health check."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+
+ # Create connection with mock session
+ server_def = MCPServerDefinitionFactory.from_config(
+ "test", MCPServerStdioConfig(command="test", args=[])
+ )
+ connection = MCPServerConnection(definition=server_def)
+ connection.session = AsyncMock()
+ connection.session.send_ping = AsyncMock()
+ client.connections["test"] = connection
+
+ result = await client._perform_health_check("test")
+
+ assert result is True
+ connection.session.send_ping.assert_called_once()
+ # Note: last_health_check is updated by the caller (_monitor_server_health), not _perform_health_check
+ assert connection.last_health_check == 0 # Should remain unchanged
+
+ @pytest.mark.parametrize(
+ ("session_setup", "ping_behavior", "expected_result"),
+ [
+ pytest.param(
+ None, # No session
+ None,
+ False,
+ id="no_session",
+ ),
+ pytest.param(
+ AsyncMock(), # Valid session
+ Exception("Ping failed"), # Exception during ping
+ False,
+ id="ping_exception",
+ ),
+ ],
+ )
+ async def test_perform_health_check_failure_cases(
+ self, session_setup, ping_behavior, expected_result
+ ):
+ """Test health check failure scenarios."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+
+ # Create connection
+ server_def = MCPServerDefinitionFactory.from_config(
+ "test", MCPServerStdioConfig(command="test", args=[])
+ )
+ connection = MCPServerConnection(definition=server_def)
+ connection.session = session_setup
+
+ if session_setup and ping_behavior:
+ connection.session.send_ping = AsyncMock(side_effect=ping_behavior)
+
+ client.connections["test"] = connection
+
+ result = await client._perform_health_check("test")
+
+ assert result == expected_result
+ # Note: _perform_health_check doesn't update connection status directly
+ # Status updates happen in the calling code (_monitor_server_health)
+
+ async def test_perform_health_check_timeout(self):
+ """Test health check timeout handling."""
+ client = MCPClient(MCPConfig(mcpServers={}))
+ client.health_check_timeout = 0.1 # Very short timeout
+
+ # Create connection with session that hangs
+ server_def = MCPServerDefinitionFactory.from_config(
+ "test", MCPServerStdioConfig(command="test", args=[])
+ )
+ connection = MCPServerConnection(definition=server_def)
+ connection.session = AsyncMock()
+
+ # Create a coroutine that sleeps longer than timeout
+ async def slow_ping():
+ await asyncio.sleep(1)
+
+ connection.session.send_ping = AsyncMock(side_effect=slow_ping)
+ client.connections["test"] = connection
+
+ result = await client._perform_health_check("test")
+
+ assert result is False
+ # Note: _perform_health_check doesn't update connection status directly
+ # Status updates happen in the calling code (_monitor_server_health)
+
+
+class TestMCPServerConnection:
+ """Test cases for MCPServerConnection class."""
+
+ def test_server_connection_creation(self):
+ """Test creating a server connection with proper defaults."""
+ server_def = MCPServerDefinitionFactory.from_config(
+ "test_server",
+ MCPServerStdioConfig(
+ command="python", args=["test.py"], env={"TEST": "value"}
+ ),
+ )
+
+ connection = MCPServerConnection(definition=server_def)
+
+ assert connection.definition.name == "test_server"
+ assert connection.definition.config["command"] == "python"
+ assert connection.definition.config.get("args") == ["test.py"]
+ assert connection.definition.config.get("env") == {"TEST": "value"}
+ assert connection.status == MCPServerStatus.DISCONNECTED
+ assert connection.session is None
+ assert len(connection.tools) == 0
+ assert connection.last_health_check == 0
+ assert connection.error_message is None
+
+
+class TestMCPUtilities:
+ """Test utility functions and configuration."""
+
+ @pytest.mark.skipif(
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+ )
+ def test_get_mcp_client_singleton(self):
+ """Test that get_mcp_client returns singleton instance."""
+ client1 = get_mcp_client()
+ client2 = get_mcp_client()
+
+ assert client1 is client2
+
+ @pytest.mark.skipif(
+ not DependencyManager.mcp.has(), reason="MCP SDK not available"
+ )
+ def test_get_mcp_client_with_custom_config(self):
+ """Test get_mcp_client with custom configuration."""
+ # Reset global client for this test
+ import marimo._server.ai.mcp as mcp_module
+
+ mcp_module._MCP_CLIENT = None
+
+ custom_config = MCPConfig(
+ mcpServers={
+ "custom_server": MCPServerStdioConfig(
+ command="custom", args=["--test"], env={}
+ )
+ }
+ )
+
+ client = get_mcp_client(custom_config)
+ assert "custom_server" in client.servers