From c570479d32a430b091a184c4f1411d1193d45d6d Mon Sep 17 00:00:00 2001 From: Hoang Tran Date: Thu, 4 Sep 2025 10:57:24 +0000 Subject: [PATCH 01/28] add working mcp integration --- examples/mcp_integration.py | 111 +++++++++++++++++++++ openhands/sdk/__init__.py | 8 ++ openhands/sdk/mcp/__init__.py | 29 ++++++ openhands/sdk/mcp/client.py | 176 ++++++++++++++++++++++++++++++++++ openhands/sdk/mcp/tool.py | 162 +++++++++++++++++++++++++++++++ openhands/sdk/mcp/utils.py | 108 +++++++++++++++++++++ 6 files changed, 594 insertions(+) create mode 100644 examples/mcp_integration.py create mode 100644 openhands/sdk/mcp/__init__.py create mode 100644 openhands/sdk/mcp/client.py create mode 100644 openhands/sdk/mcp/tool.py create mode 100644 openhands/sdk/mcp/utils.py diff --git a/examples/mcp_integration.py b/examples/mcp_integration.py new file mode 100644 index 00000000000..ef761732a76 --- /dev/null +++ b/examples/mcp_integration.py @@ -0,0 +1,111 @@ +"""Example demonstrating MCP (Model Context Protocol) integration with agent-sdk. + +This example shows how to configure MCP servers and use MCP tools with agents. + +Prerequisites: +- Install fastmcp: pip install fastmcp +- Install mcp: pip install mcp +- Have an MCP server running (e.g., `fetch` server) +""" + +import asyncio +import os + +from pydantic import SecretStr + +from openhands.sdk import ( + LLM, + Agent, + Conversation, + EventType, + LLMConfig, + LLMConvertibleEvent, + Message, + TextContent, + Tool, + get_logger, +) +from openhands.sdk.config.mcp_config import MCPConfig, MCPStdioServerConfig +from openhands.sdk.mcp.utils import create_mcp_tools_from_config +from openhands.tools import BashTool, FileEditorTool + + +logger = get_logger(__name__) + +# Configure LLM +api_key = os.getenv("LITELLM_API_KEY") +assert api_key is not None, "LITELLM_API_KEY environment variable is not set." +llm = LLM( + config=LLMConfig( + model="litellm_proxy/anthropic/claude-sonnet-4-20250514", + base_url="https://llm-proxy.eval.all-hands.dev", + api_key=SecretStr(api_key), + ) +) + +# Configure MCP servers +mcp_config = MCPConfig( + stdio_servers=[ + MCPStdioServerConfig( + name="fetch", + command="uvx", + args=["mcp-server-fetch"], + ) + ] +) + +# Tools +cwd = os.getcwd() +tools: list[Tool] = [ + BashTool(working_dir=cwd), + FileEditorTool(), +] + +# Add MCP tools if available +try: + mcp_tools = asyncio.run(create_mcp_tools_from_config(mcp_config, timeout=10.0)) + tools.extend(mcp_tools) + logger.info(f"Added {len(mcp_tools)} MCP tools") + for tool in mcp_tools: + logger.info(f" - {tool.name}: {tool.description}") +except Exception as e: + logger.warning(f"Failed to load MCP tools: {e}") + logger.info("Continuing with standard tools only") + +# Agent +agent = Agent(llm=llm, tools=tools) + +llm_messages = [] # collect raw LLM messages + + +def conversation_callback(event: EventType): + logger.info(f"Found a conversation message: {str(event)[:200]}...") + if isinstance(event, LLMConvertibleEvent): + llm_messages.append(event.to_llm_message()) + + +# Conversation +conversation = Conversation( + agent=agent, + callbacks=[conversation_callback], +) + +# Example message that can use MCP tools if available +message = Message( + role="user", + content=[ + TextContent( + text="Read https://github.com/All-Hands-AI/OpenHands and " + + "write 3 facts about the project into FACTS.txt." + ) + ], +) + +logger.info("Starting conversation with MCP integration...") +response = conversation.send_message(message) +conversation.run() + +print("=" * 100) +print("Conversation finished. Got the following LLM messages:") +for i, message in enumerate(llm_messages): + print(f"Message {i}: {str(message)[:200]}") diff --git a/openhands/sdk/__init__.py b/openhands/sdk/__init__.py index 0adf32a2b82..67ad34ca10c 100644 --- a/openhands/sdk/__init__.py +++ b/openhands/sdk/__init__.py @@ -14,6 +14,11 @@ TextContent, ) from openhands.sdk.logger import get_logger +from openhands.sdk.mcp import ( + MCPClient, + MCPTool, + create_mcp_tools_from_config, +) from openhands.sdk.tool import ActionBase, ObservationBase, Tool @@ -36,6 +41,9 @@ "ObservationBase", "LLMConfig", "MCPConfig", + "MCPClient", + "MCPTool", + "create_mcp_tools_from_config", "get_logger", "Conversation", "ConversationCallbackType", diff --git a/openhands/sdk/mcp/__init__.py b/openhands/sdk/mcp/__init__.py new file mode 100644 index 00000000000..a7c68ed3e0c --- /dev/null +++ b/openhands/sdk/mcp/__init__.py @@ -0,0 +1,29 @@ +"""MCP (Model Context Protocol) integration for agent-sdk.""" + +from openhands.sdk.mcp.client import MCPClient +from openhands.sdk.mcp.tool import ( + MCPTool, + MCPToolAction, + MCPToolExecutor, + MCPToolObservation, + MCPToolRegistry, +) +from openhands.sdk.mcp.utils import ( + create_mcp_client, + create_mcp_tools_from_config, +) + + +__all__ = [ + # Client + "MCPClient", + # Tools + "MCPTool", + "MCPToolAction", + "MCPToolObservation", + "MCPToolExecutor", + "MCPToolRegistry", + # Utilities + "create_mcp_client", + "create_mcp_tools_from_config", +] diff --git a/openhands/sdk/mcp/client.py b/openhands/sdk/mcp/client.py new file mode 100644 index 00000000000..76e574254c6 --- /dev/null +++ b/openhands/sdk/mcp/client.py @@ -0,0 +1,176 @@ +"""MCP Client implementation.""" + +from typing import Optional + +from fastmcp import Client +from fastmcp.client.transports import ( + SSETransport, + StdioTransport, + StreamableHttpTransport, +) +from mcp import McpError +from mcp.types import CallToolResult, Tool as MCPTool +from pydantic import BaseModel, ConfigDict, Field + +from openhands.sdk.config.mcp_config import ( + MCPSHTTPServerConfig, + MCPSSEServerConfig, + MCPStdioServerConfig, +) +from openhands.sdk.logger import get_logger + + +logger = get_logger(__name__) + + +class MCPClient(BaseModel): + """MCP client that connects to servers and manages available tools.""" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + client: Optional[Client] = None + tools: list[MCPTool] = Field(default_factory=list) + tool_map: dict[str, MCPTool] = Field(default_factory=dict) + server_config: ( + MCPSSEServerConfig | MCPSHTTPServerConfig | MCPStdioServerConfig | None + ) = None + + # Connection parameters for client recreation + _timeout: float = 30.0 + _conversation_id: Optional[str] = None + + def _create_stdio_client(self) -> Client: + """Create a new stdio client using stored server config.""" + if not isinstance(self.server_config, MCPStdioServerConfig): + raise RuntimeError("Server config is not for stdio transport") + + transport = StdioTransport( + command=self.server_config.command, + args=self.server_config.args or [], + env=self.server_config.env, + ) + return Client(transport, timeout=self._timeout) + + def _create_http_client(self) -> Client: + """Create a new HTTP client using stored server config.""" + if not isinstance( + self.server_config, (MCPSSEServerConfig, MCPSHTTPServerConfig) + ): + raise RuntimeError("Server config is not for HTTP transport") + + server_url = self.server_config.url + api_key = self.server_config.api_key + + if not server_url: + raise ValueError("Server URL is required.") + + headers = ( + { + "Authorization": f"Bearer {api_key}", + "s": api_key, # For action execution server's MCP Router + "X-Session-API-Key": api_key, # For Remote Runtime + } + if api_key + else {} + ) + + if self._conversation_id: + headers["X-OpenHands-ServerConversation-ID"] = self._conversation_id + + # Instantiate custom transports due to custom headers + if isinstance(self.server_config, MCPSHTTPServerConfig): + transport = StreamableHttpTransport( + url=server_url, + headers=headers if headers else None, + ) + else: + transport = SSETransport( + url=server_url, + headers=headers if headers else None, + ) + + return Client(transport, timeout=self._timeout) + + async def _initialize_and_list_tools(self) -> None: + """Initialize session and populate tool map.""" + if not self.client: + raise RuntimeError("Session not initialized.") + + async with self.client: + tools = await self.client.list_tools() + + # Clear existing tools + self.tools = [] + self.tool_map = {} + + # Store tools directly as MCP Tool objects + for tool in tools: + self.tool_map[tool.name] = tool + self.tools.append(tool) + + logger.info(f"Connected to server with tools: {[tool.name for tool in tools]}") + + async def connect_http( + self, + server: MCPSSEServerConfig | MCPSHTTPServerConfig, + conversation_id: str | None = None, + timeout: float = 30.0, + ): + """Connect to MCP server using SHTTP or SSE transport.""" + server_url = server.url + + if not server_url: + raise ValueError("Server URL is required.") + + try: + # Store connection parameters for recreation + self.server_config = server + self._timeout = timeout + self._conversation_id = conversation_id + + # Create initial client for tool listing + self.client = self._create_http_client() + await self._initialize_and_list_tools() + except McpError as e: + error_msg = f"McpError connecting to {server_url}: {e}" + logger.error(error_msg) + raise + except Exception as e: + error_msg = f"Error connecting to {server_url}: {e}" + logger.error(error_msg) + raise + + async def connect_stdio(self, server: MCPStdioServerConfig, timeout: float = 30.0): + """Connect to MCP server using stdio transport.""" + try: + # Store connection parameters for recreation + self.server_config = server + self._timeout = timeout + + # Create initial client for tool listing + self.client = self._create_stdio_client() + await self._initialize_and_list_tools() + except Exception as e: + server_name = getattr( + server, "name", f"{server.command} {' '.join(server.args or [])}" + ) + error_msg = f"Failed to connect to stdio server {server_name}: {e}" + logger.error(error_msg) + raise + + async def call_tool(self, tool_name: str, args: dict) -> CallToolResult: + """Call a tool on the MCP server.""" + if tool_name not in self.tool_map: + raise ValueError(f"Tool {tool_name} not found.") + + if not self.server_config: + raise RuntimeError("Server config is not available.") + + # Recreate client for each tool call + if isinstance(self.server_config, MCPStdioServerConfig): + fresh_client = self._create_stdio_client() + else: + fresh_client = self._create_http_client() + + async with fresh_client: + return await fresh_client.call_tool_mcp(name=tool_name, arguments=args) diff --git a/openhands/sdk/mcp/tool.py b/openhands/sdk/mcp/tool.py new file mode 100644 index 00000000000..3a7b07b98eb --- /dev/null +++ b/openhands/sdk/mcp/tool.py @@ -0,0 +1,162 @@ +"""MCPTool definition and implementation.""" + +import asyncio +import json +from typing import Any + +from pydantic import Field + +from openhands.sdk.logger import get_logger +from openhands.sdk.mcp.client import MCPClient +from openhands.sdk.tool import ( + ActionBase, + ObservationBase, + Tool, + ToolAnnotations, + ToolExecutor, +) + + +logger = get_logger(__name__) + + +class MCPToolAction(ActionBase): + """Action for calling MCP tools.""" + + tool_name: str = Field(description="Name of the MCP tool to call") + arguments: dict[str, Any] = Field( + default_factory=dict, description="Arguments to pass to the MCP tool" + ) + + +class MCPToolObservation(ObservationBase): + """Observation from MCP tool execution.""" + + content: str = Field(default="", description="Content returned from the MCP tool") + is_error: bool = Field( + default=False, description="Whether the call resulted in an error" + ) + error_message: str | None = Field( + default=None, description="Error message if the call failed" + ) + tool_name: str = Field(description="Name of the tool that was called") + + @property + def agent_observation(self) -> str: + """Format the observation for agent display.""" + if self.is_error: + return f"Error calling tool {self.tool_name}: {self.error_message}" + else: + return ( + f"Tool {self.tool_name} returned: {json.dumps(self.content, indent=2)}" + ) + + +class MCPToolExecutor(ToolExecutor): + """Executor for MCP tools.""" + + def __init__(self, mcp_client: MCPClient): + self.mcp_client = mcp_client + + def __call__(self, action: MCPToolAction) -> MCPToolObservation: + """Execute an MCP tool call.""" + try: + result = asyncio.run( + self.mcp_client.call_tool(action.tool_name, action.arguments) + ) + + return MCPToolObservation( + content=json.dumps(result.model_dump(mode="json")), + is_error=result.isError, + tool_name=action.tool_name, + ) + + except Exception as e: + error_msg = f"Error calling MCP tool {action.tool_name}: {str(e)}" + logger.error(error_msg) + + return MCPToolObservation( + is_error=True, + error_message=error_msg, + tool_name=action.tool_name, + ) + + +class MCPTool(Tool[MCPToolAction, MCPToolObservation]): + """MCP Tool that wraps an MCP client and provides tool functionality.""" + + def __init__(self, mcp_client: MCPClient, tool_name: str): + """Initialize MCPTool with an MCP client and specific tool name. + + Args: + mcp_client: The MCP client to use for tool calls + tool_name: Name of the specific MCP tool to wrap + """ + if tool_name not in mcp_client.tool_map: + raise ValueError(f"Tool {tool_name} not found in MCP client") + + mcp_tool = mcp_client.tool_map[tool_name] + + # Create executor + executor = MCPToolExecutor(mcp_client) + + # Initialize the parent Tool + super().__init__( + name=tool_name, + description=mcp_tool.description or "No description provided", + input_schema=MCPToolAction, + output_schema=MCPToolObservation, + annotations=ToolAnnotations( + title=tool_name, + readOnlyHint=False, # MCP tools can be read-only or not + destructiveHint=True, # Conservative default + idempotentHint=False, # Conservative default + openWorldHint=True, # MCP tools often interact with external systems + ), + executor=executor, + ) + + self.mcp_client = mcp_client + self.mcp_tool = mcp_tool + + def to_mcp_tool(self) -> dict[str, Any]: + """Convert to MCP tool format using the original MCP tool schema.""" + return { + "name": self.mcp_tool.name, + "description": self.mcp_tool.description, + "inputSchema": self.mcp_tool.inputSchema, + } + + +class MCPToolRegistry: + """Registry for managing MCP tools from multiple clients.""" + + def __init__(self): + self.clients: dict[str, MCPClient] = {} + self.tools: dict[str, MCPTool] = {} + + def add_client(self, name: str, client: MCPClient) -> None: + """Add an MCP client to the registry.""" + self.clients[name] = client + + # Create tools for all available tools in the client + for tool_name in client.tool_map: + # Use client_name:tool_name as the key to avoid conflicts + full_tool_name = f"{name}:{tool_name}" + self.tools[full_tool_name] = MCPTool(client, tool_name) + + def get_tool(self, tool_name: str) -> MCPTool | None: + """Get a tool by name.""" + return self.tools.get(tool_name) + + def get_all_tools(self) -> list[MCPTool]: + """Get all registered MCP tools.""" + return list(self.tools.values()) + + def get_tools_for_client(self, client_name: str) -> list[MCPTool]: + """Get all tools for a specific client.""" + return [ + tool + for name, tool in self.tools.items() + if name.startswith(f"{client_name}:") + ] diff --git a/openhands/sdk/mcp/utils.py b/openhands/sdk/mcp/utils.py new file mode 100644 index 00000000000..9385479180f --- /dev/null +++ b/openhands/sdk/mcp/utils.py @@ -0,0 +1,108 @@ +"""Utility functions for MCP integration.""" + +from openhands.sdk.config.mcp_config import ( + MCPConfig, + MCPSHTTPServerConfig, + MCPSSEServerConfig, + MCPStdioServerConfig, +) +from openhands.sdk.logger import get_logger +from openhands.sdk.mcp.client import MCPClient +from openhands.sdk.mcp.tool import MCPToolRegistry +from openhands.sdk.tool import Tool + + +logger = get_logger(__name__) + + +async def create_mcp_client( + server_config: MCPSSEServerConfig | MCPSHTTPServerConfig | MCPStdioServerConfig, + conversation_id: str | None = None, + timeout: float = 30.0, +) -> MCPClient: + """Create and connect an MCP client from server configuration. + + Args: + server_config: MCP server configuration + conversation_id: Optional conversation ID for HTTP-based servers + timeout: Connection timeout in seconds + + Returns: + Connected MCP client + + Raises: + Exception: If connection fails + """ + client = MCPClient() + + if isinstance(server_config, (MCPSSEServerConfig, MCPSHTTPServerConfig)): + await client.connect_http(server_config, conversation_id, timeout) + elif isinstance(server_config, MCPStdioServerConfig): + await client.connect_stdio(server_config, timeout) + else: + raise ValueError(f"Unsupported server config type: {type(server_config)}") + + return client + + +async def create_mcp_tools_from_config( + mcp_config: MCPConfig, + conversation_id: str | None = None, + timeout: float = 30.0, +) -> list[Tool]: + """Create MCP tools from MCP configuration. + + Args: + mcp_config: MCP configuration containing server definitions + conversation_id: Optional conversation ID for HTTP-based servers + timeout: Connection timeout in seconds + + Returns: + List of MCP tools ready to use with agents + + Raises: + Exception: If any server connection fails + """ + tools: list[Tool] = [] + registry = MCPToolRegistry() + + # Process SSE servers + for server_config in mcp_config.sse_servers: + try: + client = await create_mcp_client(server_config, conversation_id, timeout) + server_name = getattr(server_config, "name", server_config.url) + registry.add_client(server_name, client) + logger.info(f"Connected to SSE server: {server_name}") + except Exception as e: + logger.error(f"Failed to connect to SSE server {server_config.url}: {e}") + # Continue with other servers instead of failing completely + + # Process SHTTP servers + for server_config in mcp_config.shttp_servers: + try: + client = await create_mcp_client(server_config, conversation_id, timeout) + server_name = getattr(server_config, "name", server_config.url) + registry.add_client(server_name, client) + logger.info(f"Connected to SHTTP server: {server_name}") + except Exception as e: + logger.error(f"Failed to connect to SHTTP server {server_config.url}: {e}") + # Continue with other servers instead of failing completely + + # Process stdio servers + for server_config in mcp_config.stdio_servers: + try: + client = await create_mcp_client(server_config, conversation_id, timeout) + server_name = getattr(server_config, "name", server_config.command) + registry.add_client(server_name, client) + logger.info(f"Connected to stdio server: {server_name}") + except Exception as e: + logger.error( + f"Failed to connect to stdio server {server_config.command}: {e}" + ) + # Continue with other servers instead of failing completely + + # Convert all MCP tools to agent-sdk tools + tools.extend(registry.get_all_tools()) + + logger.info(f"Created {len(tools)} MCP tools from {len(registry.clients)} servers") + return tools From f91982414f23de1e71bdc5b64401ca4fcdc952a6 Mon Sep 17 00:00:00 2001 From: Hoang Tran Date: Thu, 4 Sep 2025 11:41:50 +0000 Subject: [PATCH 02/28] migrate mcp tests --- examples/mcp_integration.py | 10 - pyproject.toml | 2 + tests/sdk/mcp/__init__.py | 1 + .../mcp/test_mcp_create_clients_timeout.py | 246 ++++++++++++ tests/sdk/mcp/test_mcp_timeout.py | 212 +++++++++++ tests/sdk/mcp/test_tool.py | 356 ++++++++++++++++++ tests/sdk/mcp/test_utils.py | 299 +++++++++++++++ uv.lock | 13 + 8 files changed, 1129 insertions(+), 10 deletions(-) create mode 100644 tests/sdk/mcp/__init__.py create mode 100644 tests/sdk/mcp/test_mcp_create_clients_timeout.py create mode 100644 tests/sdk/mcp/test_mcp_timeout.py create mode 100644 tests/sdk/mcp/test_tool.py create mode 100644 tests/sdk/mcp/test_utils.py diff --git a/examples/mcp_integration.py b/examples/mcp_integration.py index ef761732a76..c54a351a6fc 100644 --- a/examples/mcp_integration.py +++ b/examples/mcp_integration.py @@ -1,13 +1,3 @@ -"""Example demonstrating MCP (Model Context Protocol) integration with agent-sdk. - -This example shows how to configure MCP servers and use MCP tools with agents. - -Prerequisites: -- Install fastmcp: pip install fastmcp -- Install mcp: pip install mcp -- Have an MCP server running (e.g., `fetch` server) -""" - import asyncio import os diff --git a/pyproject.toml b/pyproject.toml index 0c5478d504e..fd0974d885f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,6 +16,7 @@ dev = [ "pytest-cov>=5.0.0", "ruff>=0.12.10", "pycodestyle>=2.12.0", + "pytest-asyncio>=1.1.0", ] # Ruff configuration @@ -45,4 +46,5 @@ python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] addopts = "-v --tb=short" +asyncio_mode = "auto" diff --git a/tests/sdk/mcp/__init__.py b/tests/sdk/mcp/__init__.py new file mode 100644 index 00000000000..2ce101d5396 --- /dev/null +++ b/tests/sdk/mcp/__init__.py @@ -0,0 +1 @@ +"""Tests for MCP (Model Context Protocol) integration.""" diff --git a/tests/sdk/mcp/test_mcp_create_clients_timeout.py b/tests/sdk/mcp/test_mcp_create_clients_timeout.py new file mode 100644 index 00000000000..63a5a9e13bf --- /dev/null +++ b/tests/sdk/mcp/test_mcp_create_clients_timeout.py @@ -0,0 +1,246 @@ +import asyncio +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from openhands.sdk.config.mcp_config import ( + MCPConfig, + MCPSHTTPServerConfig, + MCPSSEServerConfig, + MCPStdioServerConfig, +) +from openhands.sdk.mcp.utils import create_mcp_client, create_mcp_tools_from_config + + +@pytest.mark.asyncio +async def test_create_mcp_client_invalid_url(): + """Test creating MCP client with invalid URL.""" + # Use a valid URL format but mock the connection to fail + server_config = MCPSSEServerConfig(url="http://invalid-url-format") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: + mock_client_instance = AsyncMock() + mock_mcp_client.return_value = mock_client_instance + + # Mock connect_http to fail for invalid URL + mock_client_instance.connect_http = AsyncMock( + side_effect=ValueError("Invalid URL") + ) + + with pytest.raises(ValueError): + await create_mcp_client(server_config) + + +@pytest.mark.asyncio +async def test_create_mcp_client_unreachable_host(): + """Test creating MCP client with unreachable host.""" + server_config = MCPSSEServerConfig(url="http://unreachable-host:8080") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: + mock_client_instance = AsyncMock() + mock_mcp_client.return_value = mock_client_instance + + # Mock connect_http to fail with connection error + mock_client_instance.connect_http = AsyncMock( + side_effect=ConnectionError("Host unreachable") + ) + + with pytest.raises(ConnectionError): + await create_mcp_client(server_config) + + +@pytest.mark.asyncio +async def test_create_mcp_client_stdio_command_not_found(): + """Test creating MCP stdio client with non-existent command.""" + server_config = MCPStdioServerConfig( + name="bad_server", + command="nonexistent_command", + args=["--help"], + ) + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: + mock_client_instance = AsyncMock() + mock_mcp_client.return_value = mock_client_instance + + # Mock connect_stdio to fail for nonexistent command + mock_client_instance.connect_stdio = AsyncMock( + side_effect=FileNotFoundError("Command not found") + ) + + with pytest.raises(FileNotFoundError): + await create_mcp_client(server_config) + + +@pytest.mark.asyncio +async def test_create_mcp_tools_from_config_mixed_failures(): + """Test creating MCP tools with mixed connection failures.""" + config = MCPConfig( + sse_servers=[ + MCPSSEServerConfig(url="http://good-sse:8080"), + MCPSSEServerConfig(url="http://bad-sse:8080"), + ], + stdio_servers=[ + MCPStdioServerConfig( + name="good_stdio", + command="python", + args=["-m", "good_stdio"], + ), + MCPStdioServerConfig( + name="bad_stdio", + command="bad_command", + ), + ], + ) + + # Mock clients - some succeed, some fail + mock_client = AsyncMock() + mock_tool = MagicMock() + mock_tool.name = "tool1" + + def mock_create_client(server_config, conversation_id=None, timeout=None): + if hasattr(server_config, "url") and "bad-sse" in server_config.url: + raise ConnectionError("SSE connection failed") + elif ( + hasattr(server_config, "command") and "bad_command" in server_config.command + ): + raise FileNotFoundError("Stdio command not found") + else: + return mock_client + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client + ): + with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool] + + tools = await create_mcp_tools_from_config(config) + + # Should get tools from successful servers only (2 out of 4) + assert len(tools) == 1 + assert ( + mock_registry.add_client.call_count == 2 + ) # Only successful connections + + +@pytest.mark.asyncio +async def test_create_mcp_tools_from_config_all_timeout(): + """Test creating MCP tools where all connections timeout.""" + config = MCPConfig( + sse_servers=[ + MCPSSEServerConfig(url="http://timeout1:8080"), + MCPSSEServerConfig(url="http://timeout2:8080"), + ], + stdio_servers=[ + MCPStdioServerConfig(name="timeout3", command="timeout_cmd1"), + MCPStdioServerConfig(name="timeout4", command="timeout_cmd2"), + ], + ) + + # Mock all connections to timeout + def mock_create_client(server_config, conversation_id=None, timeout=None): + raise asyncio.TimeoutError("Connection timeout") + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client + ): + with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [] + + tools = await create_mcp_tools_from_config(config) + + # Should get no tools due to all timeouts + assert len(tools) == 0 + assert mock_registry.add_client.call_count == 0 # No successful connections + + +@pytest.mark.asyncio +async def test_create_mcp_client_with_various_timeouts(): + """Test creating MCP client with various timeout scenarios.""" + server_config = MCPSSEServerConfig(url="http://server:8080") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: + mock_client_instance = AsyncMock() + mock_mcp_client.return_value = mock_client_instance + + # Test different timeout values + timeouts = [1.0, 5.0, 10.0, 30.0] + + for timeout_val in timeouts: + mock_client_instance.connect_http = AsyncMock() + await create_mcp_client(server_config, timeout=timeout_val) + + # Verify timeout was passed correctly + mock_client_instance.connect_http.assert_called_with( + server_config, None, timeout_val + ) + + +@pytest.mark.asyncio +async def test_create_mcp_tools_from_config_partial_success(): + """Test creating MCP tools with partial success across different server types.""" + config = MCPConfig( + sse_servers=[ + MCPSSEServerConfig(url="http://working-sse:8080"), + MCPSSEServerConfig(url="http://failing-sse:8080"), + ], + stdio_servers=[ + MCPStdioServerConfig( + name="working_stdio", command="python", args=["-m", "server"] + ), + ], + shttp_servers=[ + MCPSHTTPServerConfig(url="http://working-shttp:8080"), + ], + ) + + # Mock mixed success/failure + mock_client = AsyncMock() + mock_tool1 = MagicMock() + mock_tool1.name = "tool1" + mock_tool2 = MagicMock() + mock_tool2.name = "tool2" + + def mock_create_client(server_config, conversation_id=None, timeout=None): + if hasattr(server_config, "url") and "failing-sse" in server_config.url: + raise ConnectionError("Failed SSE connection") + else: + return mock_client + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client + ): + with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool1, mock_tool2] + + tools = await create_mcp_tools_from_config(config) + + # Should get tools from successful servers (3 out of 4) + assert len(tools) == 2 + assert mock_registry.add_client.call_count == 3 # 3 successful connections + + +@pytest.mark.asyncio +async def test_create_mcp_client_stdio_with_timeout(): + """Test creating MCP stdio client with timeout parameter.""" + server_config = MCPStdioServerConfig( + name="test_server", + command="python", + args=["-m", "test_server"], + ) + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: + mock_client_instance = AsyncMock() + mock_mcp_client.return_value = mock_client_instance + mock_client_instance.connect_stdio = AsyncMock() + + # Test with custom timeout + await create_mcp_client(server_config, timeout=15.0) + + # Verify timeout was passed correctly + mock_client_instance.connect_stdio.assert_called_once_with(server_config, 15.0) diff --git a/tests/sdk/mcp/test_mcp_timeout.py b/tests/sdk/mcp/test_mcp_timeout.py new file mode 100644 index 00000000000..55992a962d5 --- /dev/null +++ b/tests/sdk/mcp/test_mcp_timeout.py @@ -0,0 +1,212 @@ +import asyncio +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from openhands.sdk.config.mcp_config import ( + MCPConfig, + MCPSSEServerConfig, + MCPStdioServerConfig, +) +from openhands.sdk.mcp.utils import create_mcp_client, create_mcp_tools_from_config + + +@pytest.mark.asyncio +async def test_create_mcp_client_sse_connection_timeout(): + """Test SSE connection with timeout.""" + server_config = MCPSSEServerConfig(url="http://unreachable-server:8080") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: + mock_client_instance = AsyncMock() + mock_mcp_client.return_value = mock_client_instance + + # Mock connect_http to timeout + async def mock_connect_timeout(*args, **kwargs): + await asyncio.sleep(0.1) # Small delay to simulate timeout + raise asyncio.TimeoutError("Connection timeout") + + mock_client_instance.connect_http = AsyncMock(side_effect=mock_connect_timeout) + + # Should raise timeout error + with pytest.raises(asyncio.TimeoutError): + await create_mcp_client(server_config) + + +@pytest.mark.asyncio +async def test_create_mcp_client_stdio_connection_timeout(): + """Test stdio connection with timeout.""" + server_config = MCPStdioServerConfig( + name="timeout_server", + command="sleep", + args=["10"], # Command that takes too long + ) + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: + mock_client_instance = AsyncMock() + mock_mcp_client.return_value = mock_client_instance + + # Mock connect_stdio to timeout + async def mock_connect_timeout(*args, **kwargs): + await asyncio.sleep(0.1) # Small delay to simulate timeout + raise asyncio.TimeoutError("Stdio connection timeout") + + mock_client_instance.connect_stdio = AsyncMock(side_effect=mock_connect_timeout) + + # Should raise timeout error + with pytest.raises(asyncio.TimeoutError): + await create_mcp_client(server_config) + + +@pytest.mark.asyncio +async def test_create_mcp_tools_from_config_with_timeout_errors(): + """Test creating MCP tools from configuration with timeout errors.""" + config = MCPConfig( + sse_servers=[ + MCPSSEServerConfig(url="http://good-server:8080"), + MCPSSEServerConfig(url="http://timeout-server:8080"), + ] + ) + + # Mock one successful client and one that times out + mock_good_client = AsyncMock() + mock_tool = MagicMock() + mock_tool.name = "tool1" + + def mock_create_client(server_config, conversation_id=None, timeout=None): + if "timeout-server" in server_config.url: + raise asyncio.TimeoutError("Connection timeout") + else: + return mock_good_client + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client + ): + with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool] + + tools = await create_mcp_tools_from_config(config) + + # Should get tools from the good server only + assert len(tools) == 1 + assert tools[0] == mock_tool + # Should have only added the successful client + mock_registry.add_client.assert_called_once_with( + "http://good-server:8080", mock_good_client + ) + + +@pytest.mark.asyncio +async def test_create_mcp_tools_from_config_mixed_timeout_success(): + """Test creating MCP tools with mixed timeout and success results.""" + config = MCPConfig( + sse_servers=[ + MCPSSEServerConfig(url="http://server1:8080"), + MCPSSEServerConfig(url="http://server2:8080"), + ], + stdio_servers=[ + MCPStdioServerConfig( + name="stdio1", command="python", args=["-m", "server"] + ), + MCPStdioServerConfig(name="stdio2", command="timeout_command"), + ], + ) + + # Mock clients - some succeed, some timeout + mock_client = AsyncMock() + mock_tool = MagicMock() + mock_tool.name = "tool1" + + def mock_create_client(server_config, conversation_id=None, timeout=None): + if hasattr(server_config, "url") and "server2" in server_config.url: + raise asyncio.TimeoutError("HTTP timeout") + elif ( + hasattr(server_config, "command") + and "timeout_command" in server_config.command + ): + raise asyncio.TimeoutError("Stdio timeout") + else: + return mock_client + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client + ): + with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool] + + tools = await create_mcp_tools_from_config(config) + + # Should get tools from successful servers only (2 out of 4) + assert len(tools) == 1 + assert ( + mock_registry.add_client.call_count == 2 + ) # Only successful connections + + +@pytest.mark.asyncio +async def test_create_mcp_client_with_custom_timeout(): + """Test creating MCP client with custom timeout value.""" + server_config = MCPSSEServerConfig(url="http://server:8080") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: + mock_client_instance = AsyncMock() + mock_mcp_client.return_value = mock_client_instance + mock_client_instance.connect_http = AsyncMock() + + # Test with custom timeout + await create_mcp_client(server_config, timeout=5.0) + + # Verify timeout was passed correctly + mock_client_instance.connect_http.assert_called_once_with( + server_config, None, 5.0 + ) + + +@pytest.mark.asyncio +async def test_create_mcp_tools_from_config_with_custom_timeout(): + """Test creating MCP tools with custom timeout value.""" + config = MCPConfig(sse_servers=[MCPSSEServerConfig(url="http://server:8080")]) + + mock_client = AsyncMock() + mock_tool = MagicMock() + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client + ) as mock_create: + with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool] + + # Test with custom timeout + await create_mcp_tools_from_config(config, timeout=10.0) + + # Verify timeout was passed to create_mcp_client + mock_create.assert_called_with(config.sse_servers[0], None, 10.0) + + +@pytest.mark.asyncio +async def test_create_mcp_client_connection_error_vs_timeout(): + """Test distinguishing between connection errors and timeouts.""" + server_config = MCPSSEServerConfig(url="http://server:8080") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: + mock_client_instance = AsyncMock() + mock_mcp_client.return_value = mock_client_instance + + # Test timeout error + mock_client_instance.connect_http = AsyncMock( + side_effect=asyncio.TimeoutError("Timeout") + ) + with pytest.raises(asyncio.TimeoutError): + await create_mcp_client(server_config) + + # Test connection error + mock_client_instance.connect_http = AsyncMock( + side_effect=ConnectionError("Connection failed") + ) + with pytest.raises(ConnectionError): + await create_mcp_client(server_config) diff --git a/tests/sdk/mcp/test_tool.py b/tests/sdk/mcp/test_tool.py new file mode 100644 index 00000000000..bb00e9adcd2 --- /dev/null +++ b/tests/sdk/mcp/test_tool.py @@ -0,0 +1,356 @@ +"""Tests for MCP tool functionality.""" + +from unittest.mock import MagicMock, patch + +from openhands.sdk.mcp.tool import ( + MCPTool, + MCPToolAction, + MCPToolExecutor, + MCPToolObservation, + MCPToolRegistry, +) + + +class TestMCPToolAction: + """Test MCPToolAction data class.""" + + def test_mcp_tool_action_creation(self): + """Test creating an MCP tool action.""" + action = MCPToolAction( + tool_name="test_tool", + arguments={"param1": "value1", "param2": 42}, + ) + + assert action.tool_name == "test_tool" + assert action.arguments == {"param1": "value1", "param2": 42} + + def test_mcp_tool_action_empty_arguments(self): + """Test creating an MCP tool action with empty arguments.""" + action = MCPToolAction(tool_name="test_tool") + + assert action.tool_name == "test_tool" + assert action.arguments == {} + + +class TestMCPToolObservation: + """Test MCPToolObservation data class.""" + + def test_mcp_tool_observation_success(self): + """Test creating a successful MCP tool observation.""" + observation = MCPToolObservation( + tool_name="test_tool", + content="Operation completed successfully", + is_error=False, + ) + + assert observation.tool_name == "test_tool" + assert observation.content == "Operation completed successfully" + assert observation.is_error is False + + def test_mcp_tool_observation_error(self): + """Test creating an error MCP tool observation.""" + observation = MCPToolObservation( + tool_name="test_tool", + content="Operation failed: Invalid parameter", + is_error=True, + error_message="Invalid parameter", + ) + + assert observation.tool_name == "test_tool" + assert observation.content == "Operation failed: Invalid parameter" + assert observation.is_error is True + assert observation.error_message == "Invalid parameter" + + +class TestMCPToolExecutor: + """Test MCPToolExecutor functionality.""" + + def setup_method(self): + """Set up test fixtures.""" + self.mock_client = MagicMock() + self.executor = MCPToolExecutor(mcp_client=self.mock_client) + + def test_execute_success(self): + """Test successful tool execution.""" + # Mock successful MCP call + mock_result = MagicMock() + mock_result.content = [{"text": "Success result"}] + mock_result.isError = False + mock_result.model_dump.return_value = { + "content": [{"text": "Success result"}], + "isError": False, + } + + # Mock asyncio.run to return the mock result + with patch("asyncio.run", return_value=mock_result): + action = MCPToolAction( + tool_name="test_tool", + arguments={"param": "value"}, + ) + + observation = self.executor(action) + + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert ( + observation.content + == '{"content": [{"text": "Success result"}], "isError": false}' + ) + assert observation.is_error is False + + def test_execute_error(self): + """Test tool execution with error.""" + # Mock error MCP call + mock_result = MagicMock() + mock_result.content = [{"text": "Error occurred"}] + mock_result.isError = True + mock_result.model_dump.return_value = { + "content": [{"text": "Error occurred"}], + "isError": True, + } + + with patch("asyncio.run", return_value=mock_result): + action = MCPToolAction( + tool_name="test_tool", + arguments={"param": "value"}, + ) + + observation = self.executor(action) + + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert ( + observation.content + == '{"content": [{"text": "Error occurred"}], "isError": true}' + ) + assert observation.is_error is True + + def test_execute_exception(self): + """Test tool execution with exception.""" + # Mock exception during execution + with patch("asyncio.run", side_effect=Exception("Connection failed")): + action = MCPToolAction( + tool_name="test_tool", + arguments={"param": "value"}, + ) + + observation = self.executor(action) + + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert observation.content == "" + assert observation.is_error is True + assert ( + observation.error_message + and "Connection failed" in observation.error_message + ) + + def test_execute_empty_content(self): + """Test tool execution with empty content.""" + # Mock result with empty content + mock_result = MagicMock() + mock_result.content = [] + mock_result.isError = False + mock_result.model_dump.return_value = {"content": [], "isError": False} + + with patch("asyncio.run", return_value=mock_result): + action = MCPToolAction( + tool_name="test_tool", + arguments={"param": "value"}, + ) + + observation = self.executor(action) + + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert observation.content == '{"content": [], "isError": false}' + assert observation.is_error is False + + +class TestMCPTool: + """Test MCPTool functionality.""" + + def setup_method(self): + """Set up test fixtures.""" + self.mock_client = MagicMock() + + # Mock tool map + mock_tool = MagicMock() + mock_tool.name = "test_tool" + mock_tool.description = "A test tool" + mock_tool.inputSchema = {"type": "object", "properties": {}} + + self.mock_client.tool_map = {"test_tool": mock_tool} + + self.tool = MCPTool(mcp_client=self.mock_client, tool_name="test_tool") + + def test_mcp_tool_creation(self): + """Test creating an MCP tool.""" + assert self.tool.name == "test_tool" + assert self.tool.description == "A test tool" + + def test_create_action(self): + """Test creating an action for the tool.""" + # Create action directly using the action type + action = MCPToolAction(tool_name="test_tool", arguments={"param": "value"}) + + assert isinstance(action, MCPToolAction) + assert action.tool_name == "test_tool" + assert action.arguments == {"param": "value"} + + def test_execute_action(self): + """Test executing an action through the tool.""" + # Mock successful execution + mock_result = MagicMock() + mock_result.content = [{"text": "Success"}] + mock_result.isError = False + mock_result.model_dump.return_value = { + "content": [{"text": "Success"}], + "isError": False, + } + + with patch("asyncio.run", return_value=mock_result): + action = MCPToolAction(tool_name="test_tool", arguments={"param": "value"}) + + observation = self.tool.call(action) + + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert observation.is_error is False + + def test_to_openai_tool(self): + """Test converting to OpenAI tool format.""" + openai_tool = self.tool.to_openai_tool() + + assert openai_tool["type"] == "function" + assert openai_tool["function"]["name"] == "test_tool" + assert ( + "description" in openai_tool["function"] + and openai_tool["function"]["description"] == "A test tool" + ) + + def test_to_mcp_tool(self): + """Test converting to MCP tool format.""" + mcp_tool = self.tool.to_mcp_tool() + + assert mcp_tool["name"] == "test_tool" + assert mcp_tool["description"] == "A test tool" + assert "inputSchema" in mcp_tool + + +class TestMCPToolRegistry: + """Test MCPToolRegistry functionality.""" + + def setup_method(self): + """Set up test fixtures.""" + self.registry = MCPToolRegistry() + + def test_empty_registry(self): + """Test empty registry state.""" + assert len(self.registry.clients) == 0 + assert len(self.registry.tools) == 0 + assert len(self.registry.get_all_tools()) == 0 + + def test_add_client(self): + """Test adding a client to the registry.""" + mock_client = MagicMock() + + # Mock tool map with two tools + mock_tool1 = MagicMock() + mock_tool1.name = "tool1" + mock_tool1.description = "Tool 1" + mock_tool1.inputSchema = {} + + mock_tool2 = MagicMock() + mock_tool2.name = "tool2" + mock_tool2.description = "Tool 2" + mock_tool2.inputSchema = {} + + mock_client.tool_map = {"tool1": mock_tool1, "tool2": mock_tool2} + + self.registry.add_client("test_server", mock_client) + + assert "test_server" in self.registry.clients + assert self.registry.clients["test_server"] == mock_client + + # Should have created tools with prefixed names + assert "test_server:tool1" in self.registry.tools + assert "test_server:tool2" in self.registry.tools + + def test_get_all_tools(self): + """Test getting all tools from registry.""" + mock_client = MagicMock() + + # Mock tool map + mock_tool1 = MagicMock() + mock_tool1.name = "tool1" + mock_tool1.description = "Tool 1" + mock_tool1.inputSchema = {} + + mock_tool2 = MagicMock() + mock_tool2.name = "tool2" + mock_tool2.description = "Tool 2" + mock_tool2.inputSchema = {} + + mock_client.tool_map = {"tool1": mock_tool1, "tool2": mock_tool2} + + self.registry.add_client("test_server", mock_client) + + tools = self.registry.get_all_tools() + assert len(tools) == 2 + + tool_names = [tool.name for tool in tools] + assert "tool1" in tool_names + assert "tool2" in tool_names + + def test_get_tools_for_client(self): + """Test getting tools for a specific client.""" + mock_client1 = MagicMock() + mock_client2 = MagicMock() + + # Mock tool maps + mock_tool1 = MagicMock() + mock_tool1.name = "tool1" + mock_tool1.description = "Tool 1" + mock_tool1.inputSchema = {} + + mock_tool2 = MagicMock() + mock_tool2.name = "tool2" + mock_tool2.description = "Tool 2" + mock_tool2.inputSchema = {} + + mock_client1.tool_map = {"tool1": mock_tool1} + mock_client2.tool_map = {"tool2": mock_tool2} + + self.registry.add_client("server1", mock_client1) + self.registry.add_client("server2", mock_client2) + + server1_tools = self.registry.get_tools_for_client("server1") + server2_tools = self.registry.get_tools_for_client("server2") + + assert len(server1_tools) == 1 + assert len(server2_tools) == 1 + assert server1_tools[0].name == "tool1" + assert server2_tools[0].name == "tool2" + + def test_get_tool(self): + """Test getting a specific tool by name.""" + mock_client = MagicMock() + + mock_tool = MagicMock() + mock_tool.name = "test_tool" + mock_tool.description = "Test Tool" + mock_tool.inputSchema = {} + + mock_client.tool_map = {"test_tool": mock_tool} + + self.registry.add_client("test_server", mock_client) + + # Get tool by full name + tool = self.registry.get_tool("test_server:test_tool") + assert tool is not None + assert tool.name == "test_tool" + + # Non-existent tool should return None + non_existent = self.registry.get_tool("non_existent") + assert non_existent is None diff --git a/tests/sdk/mcp/test_utils.py b/tests/sdk/mcp/test_utils.py new file mode 100644 index 00000000000..c7d2183b46b --- /dev/null +++ b/tests/sdk/mcp/test_utils.py @@ -0,0 +1,299 @@ +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from openhands.sdk.config.mcp_config import ( + MCPConfig, + MCPSHTTPServerConfig, + MCPSSEServerConfig, + MCPStdioServerConfig, +) +from openhands.sdk.mcp.utils import create_mcp_client, create_mcp_tools_from_config + + +class TestCreateMCPClient: + """Test create_mcp_client function.""" + + @pytest.mark.asyncio + async def test_create_mcp_client_stdio(self): + """Test creating MCP client with stdio configuration.""" + config = MCPStdioServerConfig( + name="test_server", + command="python", + args=["-m", "test_server"], + env={"TEST": "value"}, + ) + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = AsyncMock() + mock_client_class.return_value = mock_client + + client = await create_mcp_client(config) + + assert client == mock_client + mock_client.connect_stdio.assert_called_once_with(config, 30.0) + + @pytest.mark.asyncio + async def test_create_mcp_client_sse(self): + """Test creating MCP client with SSE configuration.""" + config = MCPSSEServerConfig(url="http://localhost:8000/sse", api_key="token") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = AsyncMock() + mock_client_class.return_value = mock_client + + client = await create_mcp_client(config) + + assert client == mock_client + mock_client.connect_http.assert_called_once_with(config, None, 30.0) + + @pytest.mark.asyncio + async def test_create_mcp_client_shttp(self): + """Test creating MCP client with SHTTP configuration.""" + config = MCPSHTTPServerConfig( + url="http://localhost:8000/shttp", api_key="token" + ) + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = AsyncMock() + mock_client_class.return_value = mock_client + + client = await create_mcp_client(config) + + assert client == mock_client + mock_client.connect_http.assert_called_once_with(config, None, 30.0) + + @pytest.mark.asyncio + async def test_create_mcp_client_with_timeout(self): + """Test creating MCP client with custom timeout.""" + config = MCPSSEServerConfig(url="http://localhost:8000/sse") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = AsyncMock() + mock_client_class.return_value = mock_client + + client = await create_mcp_client(config, timeout=10.0) + + assert client == mock_client + mock_client.connect_http.assert_called_once_with(config, None, 10.0) + + @pytest.mark.asyncio + async def test_create_mcp_client_with_conversation_id(self): + """Test creating MCP client with conversation ID.""" + config = MCPSSEServerConfig(url="http://localhost:8000/sse") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = AsyncMock() + mock_client_class.return_value = mock_client + + client = await create_mcp_client(config, conversation_id="test-conv-123") + + assert client == mock_client + mock_client.connect_http.assert_called_once_with( + config, "test-conv-123", 30.0 + ) + + @pytest.mark.asyncio + async def test_create_mcp_client_invalid_config(self): + """Test creating MCP client with invalid configuration.""" + config = MagicMock() # Invalid config type + + with pytest.raises(ValueError, match="Unsupported server config type"): + await create_mcp_client(config) + + @pytest.mark.asyncio + async def test_create_mcp_client_connection_failure(self): + """Test creating MCP client with connection failure.""" + config = MCPSSEServerConfig(url="http://unreachable:8000/sse") + + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = AsyncMock() + mock_client_class.return_value = mock_client + mock_client.connect_http.side_effect = ConnectionError("Connection failed") + + with pytest.raises(ConnectionError): + await create_mcp_client(config) + + +class TestCreateMCPToolsFromConfig: + """Test create_mcp_tools_from_config function.""" + + @pytest.mark.asyncio + async def test_create_mcp_tools_from_config_empty(self): + """Test creating MCP tools from empty configuration.""" + config = MCPConfig() + + with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [] + + tools = await create_mcp_tools_from_config(config) + + assert len(tools) == 0 + + @pytest.mark.asyncio + async def test_create_mcp_tools_from_config_sse_success(self): + """Test creating MCP tools from SSE server configuration.""" + config = MCPConfig( + sse_servers=[MCPSSEServerConfig(url="http://localhost:8000/sse")] + ) + + # Mock client and tools + mock_client = AsyncMock() + mock_tool = MagicMock() + mock_tool.name = "tool1" + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client + ): + with patch( + "openhands.sdk.mcp.utils.MCPToolRegistry" + ) as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool] + + tools = await create_mcp_tools_from_config(config) + + assert len(tools) == 1 + assert tools[0] == mock_tool + mock_registry.add_client.assert_called_once_with( + "http://localhost:8000/sse", mock_client + ) + + @pytest.mark.asyncio + async def test_create_mcp_tools_from_config_stdio_success(self): + """Test creating MCP tools from stdio server configuration.""" + config = MCPConfig( + stdio_servers=[ + MCPStdioServerConfig( + name="test_server", command="python", args=["-m", "test_server"] + ) + ] + ) + + # Mock client and tools + mock_client = AsyncMock() + mock_tool = MagicMock() + mock_tool.name = "tool1" + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client + ): + with patch( + "openhands.sdk.mcp.utils.MCPToolRegistry" + ) as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool] + + tools = await create_mcp_tools_from_config(config) + + assert len(tools) == 1 + assert tools[0] == mock_tool + mock_registry.add_client.assert_called_once_with( + "test_server", mock_client + ) + + @pytest.mark.asyncio + async def test_create_mcp_tools_from_config_mixed_servers(self): + """Test creating MCP tools from mixed server configurations.""" + config = MCPConfig( + sse_servers=[MCPSSEServerConfig(url="http://localhost:8000/sse")], + stdio_servers=[ + MCPStdioServerConfig( + name="stdio_server", command="python", args=["-m", "stdio_server"] + ) + ], + shttp_servers=[MCPSHTTPServerConfig(url="http://localhost:8001/shttp")], + ) + + # Mock client and tools + mock_client = AsyncMock() + mock_tool1 = MagicMock() + mock_tool1.name = "tool1" + mock_tool2 = MagicMock() + mock_tool2.name = "tool2" + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client + ): + with patch( + "openhands.sdk.mcp.utils.MCPToolRegistry" + ) as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool1, mock_tool2] + + tools = await create_mcp_tools_from_config(config) + + assert len(tools) == 2 + # Should have called add_client for all 3 servers + assert mock_registry.add_client.call_count == 3 + + @pytest.mark.asyncio + async def test_create_mcp_tools_from_config_with_errors(self): + """Test creating MCP tools from configuration with some connection errors.""" + config = MCPConfig( + sse_servers=[ + MCPSSEServerConfig(url="http://good-server:8000/sse"), + MCPSSEServerConfig(url="http://bad-server:8000/sse"), + ] + ) + + # Mock one successful client and one that fails + mock_good_client = AsyncMock() + mock_tool = MagicMock() + mock_tool.name = "tool1" + + def mock_create_client(server_config, conversation_id=None, timeout=None): + if "good-server" in server_config.url: + return mock_good_client + else: + raise Exception("Connection failed") + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client + ): + with patch( + "openhands.sdk.mcp.utils.MCPToolRegistry" + ) as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool] + + tools = await create_mcp_tools_from_config(config) + + # Should get tools from the good server only + assert len(tools) == 1 + assert tools[0] == mock_tool + # Should have only added the successful client + mock_registry.add_client.assert_called_once_with( + "http://good-server:8000/sse", mock_good_client + ) + + @pytest.mark.asyncio + async def test_create_mcp_tools_from_config_with_timeout(self): + """Test creating MCP tools from configuration with custom timeout.""" + config = MCPConfig( + sse_servers=[MCPSSEServerConfig(url="http://localhost:8000/sse")] + ) + + mock_client = AsyncMock() + mock_tool = MagicMock() + + with patch( + "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client + ) as mock_create: + with patch( + "openhands.sdk.mcp.utils.MCPToolRegistry" + ) as mock_registry_class: + mock_registry = MagicMock() + mock_registry_class.return_value = mock_registry + mock_registry.get_all_tools.return_value = [mock_tool] + + await create_mcp_tools_from_config(config, timeout=15.0) + + # Verify timeout was passed to create_mcp_client + mock_create.assert_called_with(config.sse_servers[0], None, 15.0) diff --git a/uv.lock b/uv.lock index edd6c587043..1b6b35389c0 100644 --- a/uv.lock +++ b/uv.lock @@ -15,6 +15,7 @@ dev = [ { name = "pycodestyle", specifier = ">=2.12.0" }, { name = "pyright", specifier = ">=1.1.404" }, { name = "pytest", specifier = ">=8.4.1" }, + { name = "pytest-asyncio", specifier = ">=1.1.0" }, { name = "pytest-cov", specifier = ">=5.0.0" }, { name = "ruff", specifier = ">=0.12.10" }, ] @@ -1441,6 +1442,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/29/16/c8a903f4c4dffe7a12843191437d7cd8e32751d5de349d45d3fe69544e87/pytest-8.4.1-py3-none-any.whl", hash = "sha256:539c70ba6fcead8e78eebbf1115e8b589e7565830d7d006a8723f19ac8a0afb7", size = 365474, upload-time = "2025-06-18T05:48:03.955Z" }, ] +[[package]] +name = "pytest-asyncio" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4e/51/f8794af39eeb870e87a8c8068642fc07bce0c854d6865d7dd0f2a9d338c2/pytest_asyncio-1.1.0.tar.gz", hash = "sha256:796aa822981e01b68c12e4827b8697108f7205020f24b5793b3c41555dab68ea", size = 46652, upload-time = "2025-07-16T04:29:26.393Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/9d/bf86eddabf8c6c9cb1ea9a869d6873b46f105a5d292d3a6f7071f5b07935/pytest_asyncio-1.1.0-py3-none-any.whl", hash = "sha256:5fe2d69607b0bd75c656d1211f969cadba035030156745ee09e7d71740e58ecf", size = 15157, upload-time = "2025-07-16T04:29:24.929Z" }, +] + [[package]] name = "pytest-cov" version = "6.2.1" From 6b26b6b2f3e74035afffde86c960f37415dcbafb Mon Sep 17 00:00:00 2001 From: Hoang Tran Date: Fri, 5 Sep 2025 06:27:16 +0000 Subject: [PATCH 03/28] fix example --- examples/{mcp_integration.py => 7_mcp_integration.py} | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) rename examples/{mcp_integration.py => 7_mcp_integration.py} (91%) diff --git a/examples/mcp_integration.py b/examples/7_mcp_integration.py similarity index 91% rename from examples/mcp_integration.py rename to examples/7_mcp_integration.py index c54a351a6fc..bcd3bb7a742 100644 --- a/examples/mcp_integration.py +++ b/examples/7_mcp_integration.py @@ -8,7 +8,6 @@ Agent, Conversation, EventType, - LLMConfig, LLMConvertibleEvent, Message, TextContent, @@ -26,11 +25,9 @@ api_key = os.getenv("LITELLM_API_KEY") assert api_key is not None, "LITELLM_API_KEY environment variable is not set." llm = LLM( - config=LLMConfig( - model="litellm_proxy/anthropic/claude-sonnet-4-20250514", - base_url="https://llm-proxy.eval.all-hands.dev", - api_key=SecretStr(api_key), - ) + model="litellm_proxy/anthropic/claude-sonnet-4-20250514", + base_url="https://llm-proxy.eval.all-hands.dev", + api_key=SecretStr(api_key), ) # Configure MCP servers From 0c2693aea73dc98ad625df2eb69347e7dd850f6f Mon Sep 17 00:00:00 2001 From: Hoang Tran Date: Fri, 5 Sep 2025 07:37:44 +0000 Subject: [PATCH 04/28] update api to sync --- examples/7_mcp_integration.py | 3 +- openhands/sdk/mcp/client.py | 127 ++++++++++++++++++++++++---------- openhands/sdk/mcp/tool.py | 5 +- openhands/sdk/mcp/utils.py | 14 ++-- 4 files changed, 100 insertions(+), 49 deletions(-) diff --git a/examples/7_mcp_integration.py b/examples/7_mcp_integration.py index bcd3bb7a742..577ef39e2e0 100644 --- a/examples/7_mcp_integration.py +++ b/examples/7_mcp_integration.py @@ -1,4 +1,3 @@ -import asyncio import os from pydantic import SecretStr @@ -50,7 +49,7 @@ # Add MCP tools if available try: - mcp_tools = asyncio.run(create_mcp_tools_from_config(mcp_config, timeout=10.0)) + mcp_tools = create_mcp_tools_from_config(mcp_config, timeout=10.0) tools.extend(mcp_tools) logger.info(f"Added {len(mcp_tools)} MCP tools") for tool in mcp_tools: diff --git a/openhands/sdk/mcp/client.py b/openhands/sdk/mcp/client.py index 76e574254c6..51642c81958 100644 --- a/openhands/sdk/mcp/client.py +++ b/openhands/sdk/mcp/client.py @@ -1,5 +1,7 @@ """MCP Client implementation.""" +import asyncio +import threading from typing import Optional from fastmcp import Client @@ -24,20 +26,31 @@ class MCPClient(BaseModel): - """MCP client that connects to servers and manages available tools.""" + """MCP client that connects to servers and manages available tools. + + This client provides a synchronous API while managing async operations internally + using a dedicated event loop in a background thread. + """ model_config = ConfigDict(arbitrary_types_allowed=True) - client: Optional[Client] = None tools: list[MCPTool] = Field(default_factory=list) tool_map: dict[str, MCPTool] = Field(default_factory=dict) server_config: ( MCPSSEServerConfig | MCPSHTTPServerConfig | MCPStdioServerConfig | None ) = None - # Connection parameters for client recreation - _timeout: float = 30.0 - _conversation_id: Optional[str] = None + # Internal async management + def __init__(self, **data): + super().__init__(**data) + + # Connection parameters for recreating clients + self._timeout: float = 30.0 + self._conversation_id: Optional[str] = None + + # Event loop and thread for async operations + self._loop: Optional[asyncio.AbstractEventLoop] = None + self._thread: Optional[threading.Thread] = None def _create_stdio_client(self) -> Client: """Create a new stdio client using stored server config.""" @@ -91,31 +104,12 @@ def _create_http_client(self) -> Client: return Client(transport, timeout=self._timeout) - async def _initialize_and_list_tools(self) -> None: - """Initialize session and populate tool map.""" - if not self.client: - raise RuntimeError("Session not initialized.") - - async with self.client: - tools = await self.client.list_tools() - - # Clear existing tools - self.tools = [] - self.tool_map = {} - - # Store tools directly as MCP Tool objects - for tool in tools: - self.tool_map[tool.name] = tool - self.tools.append(tool) - - logger.info(f"Connected to server with tools: {[tool.name for tool in tools]}") - - async def connect_http( + def connect_http( self, server: MCPSSEServerConfig | MCPSHTTPServerConfig, conversation_id: str | None = None, timeout: float = 30.0, - ): + ) -> None: """Connect to MCP server using SHTTP or SSE transport.""" server_url = server.url @@ -123,14 +117,13 @@ async def connect_http( raise ValueError("Server URL is required.") try: - # Store connection parameters for recreation + # Store connection parameters self.server_config = server self._timeout = timeout self._conversation_id = conversation_id - # Create initial client for tool listing - self.client = self._create_http_client() - await self._initialize_and_list_tools() + # Initialize tools using async method + self._run_async(self._initialize_and_list_tools_async()) except McpError as e: error_msg = f"McpError connecting to {server_url}: {e}" logger.error(error_msg) @@ -140,16 +133,17 @@ async def connect_http( logger.error(error_msg) raise - async def connect_stdio(self, server: MCPStdioServerConfig, timeout: float = 30.0): + def connect_stdio( + self, server: MCPStdioServerConfig, timeout: float = 30.0 + ) -> None: """Connect to MCP server using stdio transport.""" try: - # Store connection parameters for recreation + # Store connection parameters self.server_config = server self._timeout = timeout - # Create initial client for tool listing - self.client = self._create_stdio_client() - await self._initialize_and_list_tools() + # Initialize tools using async method + self._run_async(self._initialize_and_list_tools_async()) except Exception as e: server_name = getattr( server, "name", f"{server.command} {' '.join(server.args or [])}" @@ -158,8 +152,34 @@ async def connect_stdio(self, server: MCPStdioServerConfig, timeout: float = 30. logger.error(error_msg) raise - async def call_tool(self, tool_name: str, args: dict) -> CallToolResult: + def call_tool(self, tool_name: str, args: dict) -> CallToolResult: """Call a tool on the MCP server.""" + return self._run_async(self._call_tool_async(tool_name, args)) + + async def _initialize_and_list_tools_async(self) -> None: + """Initialize session and populate tool map (async version).""" + # Create client for tool listing + if isinstance(self.server_config, MCPStdioServerConfig): + client = self._create_stdio_client() + else: + client = self._create_http_client() + + async with client: + tools = await client.list_tools() + + # Clear existing tools + self.tools = [] + self.tool_map = {} + + # Store tools directly as MCP Tool objects + for tool in tools: + self.tool_map[tool.name] = tool + self.tools.append(tool) + + logger.info(f"Connected to server with tools: {[tool.name for tool in tools]}") + + async def _call_tool_async(self, tool_name: str, args: dict) -> CallToolResult: + """Call a tool on the MCP server (async version).""" if tool_name not in self.tool_map: raise ValueError(f"Tool {tool_name} not found.") @@ -174,3 +194,38 @@ async def call_tool(self, tool_name: str, args: dict) -> CallToolResult: async with fresh_client: return await fresh_client.call_tool_mcp(name=tool_name, arguments=args) + + def _start_event_loop(self) -> None: + """Start the background event loop for async operations.""" + if self._loop is not None: + return # Already started + + def run_loop(): + self._loop = asyncio.new_event_loop() + asyncio.set_event_loop(self._loop) + self._loop.run_forever() + + self._thread = threading.Thread(target=run_loop, daemon=True) + self._thread.start() + + # Wait for loop to be ready + while self._loop is None: + threading.Event().wait(0.01) + + def _stop_event_loop(self) -> None: + """Stop the background event loop.""" + if self._loop is not None: + self._loop.call_soon_threadsafe(self._loop.stop) + if self._thread is not None: + self._thread.join(timeout=1.0) + self._loop = None + self._thread = None + + def _run_async(self, coro): + """Run an async coroutine in the managed event loop.""" + if self._loop is None: + self._start_event_loop() + + assert self._loop is not None + future = asyncio.run_coroutine_threadsafe(coro, self._loop) + return future.result() diff --git a/openhands/sdk/mcp/tool.py b/openhands/sdk/mcp/tool.py index 3a7b07b98eb..e1b9a563b3e 100644 --- a/openhands/sdk/mcp/tool.py +++ b/openhands/sdk/mcp/tool.py @@ -1,6 +1,5 @@ """MCPTool definition and implementation.""" -import asyncio import json from typing import Any @@ -61,9 +60,7 @@ def __init__(self, mcp_client: MCPClient): def __call__(self, action: MCPToolAction) -> MCPToolObservation: """Execute an MCP tool call.""" try: - result = asyncio.run( - self.mcp_client.call_tool(action.tool_name, action.arguments) - ) + result = self.mcp_client.call_tool(action.tool_name, action.arguments) return MCPToolObservation( content=json.dumps(result.model_dump(mode="json")), diff --git a/openhands/sdk/mcp/utils.py b/openhands/sdk/mcp/utils.py index 9385479180f..e1b629b821b 100644 --- a/openhands/sdk/mcp/utils.py +++ b/openhands/sdk/mcp/utils.py @@ -15,7 +15,7 @@ logger = get_logger(__name__) -async def create_mcp_client( +def create_mcp_client( server_config: MCPSSEServerConfig | MCPSHTTPServerConfig | MCPStdioServerConfig, conversation_id: str | None = None, timeout: float = 30.0, @@ -36,16 +36,16 @@ async def create_mcp_client( client = MCPClient() if isinstance(server_config, (MCPSSEServerConfig, MCPSHTTPServerConfig)): - await client.connect_http(server_config, conversation_id, timeout) + client.connect_http(server_config, conversation_id, timeout) elif isinstance(server_config, MCPStdioServerConfig): - await client.connect_stdio(server_config, timeout) + client.connect_stdio(server_config, timeout) else: raise ValueError(f"Unsupported server config type: {type(server_config)}") return client -async def create_mcp_tools_from_config( +def create_mcp_tools_from_config( mcp_config: MCPConfig, conversation_id: str | None = None, timeout: float = 30.0, @@ -69,7 +69,7 @@ async def create_mcp_tools_from_config( # Process SSE servers for server_config in mcp_config.sse_servers: try: - client = await create_mcp_client(server_config, conversation_id, timeout) + client = create_mcp_client(server_config, conversation_id, timeout) server_name = getattr(server_config, "name", server_config.url) registry.add_client(server_name, client) logger.info(f"Connected to SSE server: {server_name}") @@ -80,7 +80,7 @@ async def create_mcp_tools_from_config( # Process SHTTP servers for server_config in mcp_config.shttp_servers: try: - client = await create_mcp_client(server_config, conversation_id, timeout) + client = create_mcp_client(server_config, conversation_id, timeout) server_name = getattr(server_config, "name", server_config.url) registry.add_client(server_name, client) logger.info(f"Connected to SHTTP server: {server_name}") @@ -91,7 +91,7 @@ async def create_mcp_tools_from_config( # Process stdio servers for server_config in mcp_config.stdio_servers: try: - client = await create_mcp_client(server_config, conversation_id, timeout) + client = create_mcp_client(server_config, conversation_id, timeout) server_name = getattr(server_config, "name", server_config.command) registry.add_client(server_name, client) logger.info(f"Connected to stdio server: {server_name}") From c41bac570c10e5add786b9df314205ed342deaf7 Mon Sep 17 00:00:00 2001 From: Hoang Tran Date: Fri, 5 Sep 2025 07:50:55 +0000 Subject: [PATCH 05/28] update tests --- .../mcp/test_mcp_create_clients_timeout.py | 72 +++++----- tests/sdk/mcp/test_mcp_timeout.py | 79 +++++------ tests/sdk/mcp/test_tool.py | 128 ++++++++++-------- tests/sdk/mcp/test_utils.py | 89 ++++++------ 4 files changed, 170 insertions(+), 198 deletions(-) diff --git a/tests/sdk/mcp/test_mcp_create_clients_timeout.py b/tests/sdk/mcp/test_mcp_create_clients_timeout.py index 63a5a9e13bf..34ad8f33c19 100644 --- a/tests/sdk/mcp/test_mcp_create_clients_timeout.py +++ b/tests/sdk/mcp/test_mcp_create_clients_timeout.py @@ -1,5 +1,5 @@ import asyncio -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import MagicMock, patch import pytest @@ -12,45 +12,40 @@ from openhands.sdk.mcp.utils import create_mcp_client, create_mcp_tools_from_config -@pytest.mark.asyncio -async def test_create_mcp_client_invalid_url(): +def test_create_mcp_client_invalid_url(): """Test creating MCP client with invalid URL.""" # Use a valid URL format but mock the connection to fail server_config = MCPSSEServerConfig(url="http://invalid-url-format") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = AsyncMock() + mock_client_instance = MagicMock() mock_mcp_client.return_value = mock_client_instance # Mock connect_http to fail for invalid URL - mock_client_instance.connect_http = AsyncMock( - side_effect=ValueError("Invalid URL") - ) + mock_client_instance.connect_http.side_effect = ValueError("Invalid URL") with pytest.raises(ValueError): - await create_mcp_client(server_config) + create_mcp_client(server_config) -@pytest.mark.asyncio -async def test_create_mcp_client_unreachable_host(): +def test_create_mcp_client_unreachable_host(): """Test creating MCP client with unreachable host.""" server_config = MCPSSEServerConfig(url="http://unreachable-host:8080") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = AsyncMock() + mock_client_instance = MagicMock() mock_mcp_client.return_value = mock_client_instance # Mock connect_http to fail with connection error - mock_client_instance.connect_http = AsyncMock( - side_effect=ConnectionError("Host unreachable") + mock_client_instance.connect_http.side_effect = ConnectionError( + "Host unreachable" ) with pytest.raises(ConnectionError): - await create_mcp_client(server_config) + create_mcp_client(server_config) -@pytest.mark.asyncio -async def test_create_mcp_client_stdio_command_not_found(): +def test_create_mcp_client_stdio_command_not_found(): """Test creating MCP stdio client with non-existent command.""" server_config = MCPStdioServerConfig( name="bad_server", @@ -59,20 +54,19 @@ async def test_create_mcp_client_stdio_command_not_found(): ) with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = AsyncMock() + mock_client_instance = MagicMock() mock_mcp_client.return_value = mock_client_instance # Mock connect_stdio to fail for nonexistent command - mock_client_instance.connect_stdio = AsyncMock( - side_effect=FileNotFoundError("Command not found") + mock_client_instance.connect_stdio.side_effect = FileNotFoundError( + "Command not found" ) with pytest.raises(FileNotFoundError): - await create_mcp_client(server_config) + create_mcp_client(server_config) -@pytest.mark.asyncio -async def test_create_mcp_tools_from_config_mixed_failures(): +def test_create_mcp_tools_from_config_mixed_failures(): """Test creating MCP tools with mixed connection failures.""" config = MCPConfig( sse_servers=[ @@ -93,7 +87,7 @@ async def test_create_mcp_tools_from_config_mixed_failures(): ) # Mock clients - some succeed, some fail - mock_client = AsyncMock() + mock_client = MagicMock() mock_tool = MagicMock() mock_tool.name = "tool1" @@ -115,7 +109,7 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [mock_tool] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) # Should get tools from successful servers only (2 out of 4) assert len(tools) == 1 @@ -124,8 +118,7 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): ) # Only successful connections -@pytest.mark.asyncio -async def test_create_mcp_tools_from_config_all_timeout(): +def test_create_mcp_tools_from_config_all_timeout(): """Test creating MCP tools where all connections timeout.""" config = MCPConfig( sse_servers=[ @@ -150,28 +143,27 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) # Should get no tools due to all timeouts assert len(tools) == 0 assert mock_registry.add_client.call_count == 0 # No successful connections -@pytest.mark.asyncio -async def test_create_mcp_client_with_various_timeouts(): +def test_create_mcp_client_with_various_timeouts(): """Test creating MCP client with various timeout scenarios.""" server_config = MCPSSEServerConfig(url="http://server:8080") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = AsyncMock() + mock_client_instance = MagicMock() mock_mcp_client.return_value = mock_client_instance # Test different timeout values timeouts = [1.0, 5.0, 10.0, 30.0] for timeout_val in timeouts: - mock_client_instance.connect_http = AsyncMock() - await create_mcp_client(server_config, timeout=timeout_val) + mock_client_instance.connect_http = MagicMock() + create_mcp_client(server_config, timeout=timeout_val) # Verify timeout was passed correctly mock_client_instance.connect_http.assert_called_with( @@ -179,8 +171,7 @@ async def test_create_mcp_client_with_various_timeouts(): ) -@pytest.mark.asyncio -async def test_create_mcp_tools_from_config_partial_success(): +def test_create_mcp_tools_from_config_partial_success(): """Test creating MCP tools with partial success across different server types.""" config = MCPConfig( sse_servers=[ @@ -198,7 +189,7 @@ async def test_create_mcp_tools_from_config_partial_success(): ) # Mock mixed success/failure - mock_client = AsyncMock() + mock_client = MagicMock() mock_tool1 = MagicMock() mock_tool1.name = "tool1" mock_tool2 = MagicMock() @@ -218,15 +209,14 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [mock_tool1, mock_tool2] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) # Should get tools from successful servers (3 out of 4) assert len(tools) == 2 assert mock_registry.add_client.call_count == 3 # 3 successful connections -@pytest.mark.asyncio -async def test_create_mcp_client_stdio_with_timeout(): +def test_create_mcp_client_stdio_with_timeout(): """Test creating MCP stdio client with timeout parameter.""" server_config = MCPStdioServerConfig( name="test_server", @@ -235,12 +225,12 @@ async def test_create_mcp_client_stdio_with_timeout(): ) with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = AsyncMock() + mock_client_instance = MagicMock() mock_mcp_client.return_value = mock_client_instance - mock_client_instance.connect_stdio = AsyncMock() + mock_client_instance.connect_stdio = MagicMock() # Test with custom timeout - await create_mcp_client(server_config, timeout=15.0) + create_mcp_client(server_config, timeout=15.0) # Verify timeout was passed correctly mock_client_instance.connect_stdio.assert_called_once_with(server_config, 15.0) diff --git a/tests/sdk/mcp/test_mcp_timeout.py b/tests/sdk/mcp/test_mcp_timeout.py index 55992a962d5..2445407e185 100644 --- a/tests/sdk/mcp/test_mcp_timeout.py +++ b/tests/sdk/mcp/test_mcp_timeout.py @@ -1,5 +1,5 @@ import asyncio -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import MagicMock, patch import pytest @@ -11,29 +11,25 @@ from openhands.sdk.mcp.utils import create_mcp_client, create_mcp_tools_from_config -@pytest.mark.asyncio -async def test_create_mcp_client_sse_connection_timeout(): +def test_create_mcp_client_sse_connection_timeout(): """Test SSE connection with timeout.""" server_config = MCPSSEServerConfig(url="http://unreachable-server:8080") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = AsyncMock() + mock_client_instance = MagicMock() mock_mcp_client.return_value = mock_client_instance # Mock connect_http to timeout - async def mock_connect_timeout(*args, **kwargs): - await asyncio.sleep(0.1) # Small delay to simulate timeout - raise asyncio.TimeoutError("Connection timeout") - - mock_client_instance.connect_http = AsyncMock(side_effect=mock_connect_timeout) + mock_client_instance.connect_http.side_effect = asyncio.TimeoutError( + "Connection timeout" + ) # Should raise timeout error with pytest.raises(asyncio.TimeoutError): - await create_mcp_client(server_config) + create_mcp_client(server_config) -@pytest.mark.asyncio -async def test_create_mcp_client_stdio_connection_timeout(): +def test_create_mcp_client_stdio_connection_timeout(): """Test stdio connection with timeout.""" server_config = MCPStdioServerConfig( name="timeout_server", @@ -42,23 +38,20 @@ async def test_create_mcp_client_stdio_connection_timeout(): ) with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = AsyncMock() + mock_client_instance = MagicMock() mock_mcp_client.return_value = mock_client_instance # Mock connect_stdio to timeout - async def mock_connect_timeout(*args, **kwargs): - await asyncio.sleep(0.1) # Small delay to simulate timeout - raise asyncio.TimeoutError("Stdio connection timeout") - - mock_client_instance.connect_stdio = AsyncMock(side_effect=mock_connect_timeout) + mock_client_instance.connect_stdio.side_effect = asyncio.TimeoutError( + "Stdio connection timeout" + ) # Should raise timeout error with pytest.raises(asyncio.TimeoutError): - await create_mcp_client(server_config) + create_mcp_client(server_config) -@pytest.mark.asyncio -async def test_create_mcp_tools_from_config_with_timeout_errors(): +def test_create_mcp_tools_from_config_with_timeout_errors(): """Test creating MCP tools from configuration with timeout errors.""" config = MCPConfig( sse_servers=[ @@ -68,7 +61,7 @@ async def test_create_mcp_tools_from_config_with_timeout_errors(): ) # Mock one successful client and one that times out - mock_good_client = AsyncMock() + mock_good_client = MagicMock() mock_tool = MagicMock() mock_tool.name = "tool1" @@ -86,7 +79,7 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [mock_tool] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) # Should get tools from the good server only assert len(tools) == 1 @@ -97,8 +90,7 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): ) -@pytest.mark.asyncio -async def test_create_mcp_tools_from_config_mixed_timeout_success(): +def test_create_mcp_tools_from_config_mixed_timeout_success(): """Test creating MCP tools with mixed timeout and success results.""" config = MCPConfig( sse_servers=[ @@ -114,7 +106,7 @@ async def test_create_mcp_tools_from_config_mixed_timeout_success(): ) # Mock clients - some succeed, some timeout - mock_client = AsyncMock() + mock_client = MagicMock() mock_tool = MagicMock() mock_tool.name = "tool1" @@ -137,7 +129,7 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [mock_tool] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) # Should get tools from successful servers only (2 out of 4) assert len(tools) == 1 @@ -146,18 +138,17 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): ) # Only successful connections -@pytest.mark.asyncio -async def test_create_mcp_client_with_custom_timeout(): +def test_create_mcp_client_with_custom_timeout(): """Test creating MCP client with custom timeout value.""" server_config = MCPSSEServerConfig(url="http://server:8080") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = AsyncMock() + mock_client_instance = MagicMock() mock_mcp_client.return_value = mock_client_instance - mock_client_instance.connect_http = AsyncMock() + mock_client_instance.connect_http = MagicMock() # Test with custom timeout - await create_mcp_client(server_config, timeout=5.0) + create_mcp_client(server_config, timeout=5.0) # Verify timeout was passed correctly mock_client_instance.connect_http.assert_called_once_with( @@ -165,12 +156,11 @@ async def test_create_mcp_client_with_custom_timeout(): ) -@pytest.mark.asyncio -async def test_create_mcp_tools_from_config_with_custom_timeout(): +def test_create_mcp_tools_from_config_with_custom_timeout(): """Test creating MCP tools with custom timeout value.""" config = MCPConfig(sse_servers=[MCPSSEServerConfig(url="http://server:8080")]) - mock_client = AsyncMock() + mock_client = MagicMock() mock_tool = MagicMock() with patch( @@ -182,31 +172,28 @@ async def test_create_mcp_tools_from_config_with_custom_timeout(): mock_registry.get_all_tools.return_value = [mock_tool] # Test with custom timeout - await create_mcp_tools_from_config(config, timeout=10.0) + create_mcp_tools_from_config(config, timeout=10.0) # Verify timeout was passed to create_mcp_client mock_create.assert_called_with(config.sse_servers[0], None, 10.0) -@pytest.mark.asyncio -async def test_create_mcp_client_connection_error_vs_timeout(): +def test_create_mcp_client_connection_error_vs_timeout(): """Test distinguishing between connection errors and timeouts.""" server_config = MCPSSEServerConfig(url="http://server:8080") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = AsyncMock() + mock_client_instance = MagicMock() mock_mcp_client.return_value = mock_client_instance # Test timeout error - mock_client_instance.connect_http = AsyncMock( - side_effect=asyncio.TimeoutError("Timeout") - ) + mock_client_instance.connect_http.side_effect = asyncio.TimeoutError("Timeout") with pytest.raises(asyncio.TimeoutError): - await create_mcp_client(server_config) + create_mcp_client(server_config) # Test connection error - mock_client_instance.connect_http = AsyncMock( - side_effect=ConnectionError("Connection failed") + mock_client_instance.connect_http.side_effect = ConnectionError( + "Connection failed" ) with pytest.raises(ConnectionError): - await create_mcp_client(server_config) + create_mcp_client(server_config) diff --git a/tests/sdk/mcp/test_tool.py b/tests/sdk/mcp/test_tool.py index bb00e9adcd2..53affa6ed8d 100644 --- a/tests/sdk/mcp/test_tool.py +++ b/tests/sdk/mcp/test_tool.py @@ -1,6 +1,6 @@ """Tests for MCP tool functionality.""" -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock from openhands.sdk.mcp.tool import ( MCPTool, @@ -81,22 +81,23 @@ def test_execute_success(self): "isError": False, } - # Mock asyncio.run to return the mock result - with patch("asyncio.run", return_value=mock_result): - action = MCPToolAction( - tool_name="test_tool", - arguments={"param": "value"}, - ) + # Mock the client's call_tool method directly + self.mock_client.call_tool.return_value = mock_result - observation = self.executor(action) + action = MCPToolAction( + tool_name="test_tool", + arguments={"param": "value"}, + ) - assert isinstance(observation, MCPToolObservation) - assert observation.tool_name == "test_tool" - assert ( - observation.content - == '{"content": [{"text": "Success result"}], "isError": false}' - ) - assert observation.is_error is False + observation = self.executor(action) + + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert ( + observation.content + == '{"content": [{"text": "Success result"}], "isError": false}' + ) + assert observation.is_error is False def test_execute_error(self): """Test tool execution with error.""" @@ -109,41 +110,44 @@ def test_execute_error(self): "isError": True, } - with patch("asyncio.run", return_value=mock_result): - action = MCPToolAction( - tool_name="test_tool", - arguments={"param": "value"}, - ) + # Mock the client's call_tool method directly + self.mock_client.call_tool.return_value = mock_result + + action = MCPToolAction( + tool_name="test_tool", + arguments={"param": "value"}, + ) - observation = self.executor(action) + observation = self.executor(action) - assert isinstance(observation, MCPToolObservation) - assert observation.tool_name == "test_tool" - assert ( - observation.content - == '{"content": [{"text": "Error occurred"}], "isError": true}' - ) - assert observation.is_error is True + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert ( + observation.content + == '{"content": [{"text": "Error occurred"}], "isError": true}' + ) + assert observation.is_error is True def test_execute_exception(self): """Test tool execution with exception.""" # Mock exception during execution - with patch("asyncio.run", side_effect=Exception("Connection failed")): - action = MCPToolAction( - tool_name="test_tool", - arguments={"param": "value"}, - ) - - observation = self.executor(action) - - assert isinstance(observation, MCPToolObservation) - assert observation.tool_name == "test_tool" - assert observation.content == "" - assert observation.is_error is True - assert ( - observation.error_message - and "Connection failed" in observation.error_message - ) + self.mock_client.call_tool.side_effect = Exception("Connection failed") + + action = MCPToolAction( + tool_name="test_tool", + arguments={"param": "value"}, + ) + + observation = self.executor(action) + + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert observation.content == "" + assert observation.is_error is True + assert ( + observation.error_message + and "Connection failed" in observation.error_message + ) def test_execute_empty_content(self): """Test tool execution with empty content.""" @@ -153,18 +157,20 @@ def test_execute_empty_content(self): mock_result.isError = False mock_result.model_dump.return_value = {"content": [], "isError": False} - with patch("asyncio.run", return_value=mock_result): - action = MCPToolAction( - tool_name="test_tool", - arguments={"param": "value"}, - ) + # Mock the client's call_tool method directly + self.mock_client.call_tool.return_value = mock_result + + action = MCPToolAction( + tool_name="test_tool", + arguments={"param": "value"}, + ) - observation = self.executor(action) + observation = self.executor(action) - assert isinstance(observation, MCPToolObservation) - assert observation.tool_name == "test_tool" - assert observation.content == '{"content": [], "isError": false}' - assert observation.is_error is False + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert observation.content == '{"content": [], "isError": false}' + assert observation.is_error is False class TestMCPTool: @@ -209,14 +215,16 @@ def test_execute_action(self): "isError": False, } - with patch("asyncio.run", return_value=mock_result): - action = MCPToolAction(tool_name="test_tool", arguments={"param": "value"}) + # Mock the client's call_tool method directly + self.mock_client.call_tool.return_value = mock_result - observation = self.tool.call(action) + action = MCPToolAction(tool_name="test_tool", arguments={"param": "value"}) + + observation = self.tool.call(action) - assert isinstance(observation, MCPToolObservation) - assert observation.tool_name == "test_tool" - assert observation.is_error is False + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert observation.is_error is False def test_to_openai_tool(self): """Test converting to OpenAI tool format.""" diff --git a/tests/sdk/mcp/test_utils.py b/tests/sdk/mcp/test_utils.py index c7d2183b46b..1636aa4db0c 100644 --- a/tests/sdk/mcp/test_utils.py +++ b/tests/sdk/mcp/test_utils.py @@ -1,4 +1,4 @@ -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import MagicMock, patch import pytest @@ -14,8 +14,7 @@ class TestCreateMCPClient: """Test create_mcp_client function.""" - @pytest.mark.asyncio - async def test_create_mcp_client_stdio(self): + def test_create_mcp_client_stdio(self): """Test creating MCP client with stdio configuration.""" config = MCPStdioServerConfig( name="test_server", @@ -25,101 +24,94 @@ async def test_create_mcp_client_stdio(self): ) with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = AsyncMock() + mock_client = MagicMock() mock_client_class.return_value = mock_client - client = await create_mcp_client(config) + client = create_mcp_client(config) assert client == mock_client mock_client.connect_stdio.assert_called_once_with(config, 30.0) - @pytest.mark.asyncio - async def test_create_mcp_client_sse(self): + def test_create_mcp_client_sse(self): """Test creating MCP client with SSE configuration.""" config = MCPSSEServerConfig(url="http://localhost:8000/sse", api_key="token") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = AsyncMock() + mock_client = MagicMock() mock_client_class.return_value = mock_client - client = await create_mcp_client(config) + client = create_mcp_client(config) assert client == mock_client mock_client.connect_http.assert_called_once_with(config, None, 30.0) - @pytest.mark.asyncio - async def test_create_mcp_client_shttp(self): + def test_create_mcp_client_shttp(self): """Test creating MCP client with SHTTP configuration.""" config = MCPSHTTPServerConfig( url="http://localhost:8000/shttp", api_key="token" ) with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = AsyncMock() + mock_client = MagicMock() mock_client_class.return_value = mock_client - client = await create_mcp_client(config) + client = create_mcp_client(config) assert client == mock_client mock_client.connect_http.assert_called_once_with(config, None, 30.0) - @pytest.mark.asyncio - async def test_create_mcp_client_with_timeout(self): + def test_create_mcp_client_with_timeout(self): """Test creating MCP client with custom timeout.""" config = MCPSSEServerConfig(url="http://localhost:8000/sse") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = AsyncMock() + mock_client = MagicMock() mock_client_class.return_value = mock_client - client = await create_mcp_client(config, timeout=10.0) + client = create_mcp_client(config, timeout=10.0) assert client == mock_client mock_client.connect_http.assert_called_once_with(config, None, 10.0) - @pytest.mark.asyncio - async def test_create_mcp_client_with_conversation_id(self): + def test_create_mcp_client_with_conversation_id(self): """Test creating MCP client with conversation ID.""" config = MCPSSEServerConfig(url="http://localhost:8000/sse") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = AsyncMock() + mock_client = MagicMock() mock_client_class.return_value = mock_client - client = await create_mcp_client(config, conversation_id="test-conv-123") + client = create_mcp_client(config, conversation_id="test-conv-123") assert client == mock_client mock_client.connect_http.assert_called_once_with( config, "test-conv-123", 30.0 ) - @pytest.mark.asyncio - async def test_create_mcp_client_invalid_config(self): + def test_create_mcp_client_invalid_config(self): """Test creating MCP client with invalid configuration.""" config = MagicMock() # Invalid config type with pytest.raises(ValueError, match="Unsupported server config type"): - await create_mcp_client(config) + create_mcp_client(config) - @pytest.mark.asyncio - async def test_create_mcp_client_connection_failure(self): + def test_create_mcp_client_connection_failure(self): """Test creating MCP client with connection failure.""" config = MCPSSEServerConfig(url="http://unreachable:8000/sse") with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = AsyncMock() + mock_client = MagicMock() mock_client_class.return_value = mock_client mock_client.connect_http.side_effect = ConnectionError("Connection failed") with pytest.raises(ConnectionError): - await create_mcp_client(config) + create_mcp_client(config) class TestCreateMCPToolsFromConfig: """Test create_mcp_tools_from_config function.""" - @pytest.mark.asyncio - async def test_create_mcp_tools_from_config_empty(self): + def test_create_mcp_tools_from_config_empty(self): """Test creating MCP tools from empty configuration.""" config = MCPConfig() @@ -128,19 +120,18 @@ async def test_create_mcp_tools_from_config_empty(self): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) assert len(tools) == 0 - @pytest.mark.asyncio - async def test_create_mcp_tools_from_config_sse_success(self): + def test_create_mcp_tools_from_config_sse_success(self): """Test creating MCP tools from SSE server configuration.""" config = MCPConfig( sse_servers=[MCPSSEServerConfig(url="http://localhost:8000/sse")] ) # Mock client and tools - mock_client = AsyncMock() + mock_client = MagicMock() mock_tool = MagicMock() mock_tool.name = "tool1" @@ -154,7 +145,7 @@ async def test_create_mcp_tools_from_config_sse_success(self): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [mock_tool] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) assert len(tools) == 1 assert tools[0] == mock_tool @@ -162,8 +153,7 @@ async def test_create_mcp_tools_from_config_sse_success(self): "http://localhost:8000/sse", mock_client ) - @pytest.mark.asyncio - async def test_create_mcp_tools_from_config_stdio_success(self): + def test_create_mcp_tools_from_config_stdio_success(self): """Test creating MCP tools from stdio server configuration.""" config = MCPConfig( stdio_servers=[ @@ -174,7 +164,7 @@ async def test_create_mcp_tools_from_config_stdio_success(self): ) # Mock client and tools - mock_client = AsyncMock() + mock_client = MagicMock() mock_tool = MagicMock() mock_tool.name = "tool1" @@ -188,7 +178,7 @@ async def test_create_mcp_tools_from_config_stdio_success(self): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [mock_tool] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) assert len(tools) == 1 assert tools[0] == mock_tool @@ -196,8 +186,7 @@ async def test_create_mcp_tools_from_config_stdio_success(self): "test_server", mock_client ) - @pytest.mark.asyncio - async def test_create_mcp_tools_from_config_mixed_servers(self): + def test_create_mcp_tools_from_config_mixed_servers(self): """Test creating MCP tools from mixed server configurations.""" config = MCPConfig( sse_servers=[MCPSSEServerConfig(url="http://localhost:8000/sse")], @@ -210,7 +199,7 @@ async def test_create_mcp_tools_from_config_mixed_servers(self): ) # Mock client and tools - mock_client = AsyncMock() + mock_client = MagicMock() mock_tool1 = MagicMock() mock_tool1.name = "tool1" mock_tool2 = MagicMock() @@ -226,14 +215,13 @@ async def test_create_mcp_tools_from_config_mixed_servers(self): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [mock_tool1, mock_tool2] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) assert len(tools) == 2 # Should have called add_client for all 3 servers assert mock_registry.add_client.call_count == 3 - @pytest.mark.asyncio - async def test_create_mcp_tools_from_config_with_errors(self): + def test_create_mcp_tools_from_config_with_errors(self): """Test creating MCP tools from configuration with some connection errors.""" config = MCPConfig( sse_servers=[ @@ -243,7 +231,7 @@ async def test_create_mcp_tools_from_config_with_errors(self): ) # Mock one successful client and one that fails - mock_good_client = AsyncMock() + mock_good_client = MagicMock() mock_tool = MagicMock() mock_tool.name = "tool1" @@ -263,7 +251,7 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [mock_tool] - tools = await create_mcp_tools_from_config(config) + tools = create_mcp_tools_from_config(config) # Should get tools from the good server only assert len(tools) == 1 @@ -273,14 +261,13 @@ def mock_create_client(server_config, conversation_id=None, timeout=None): "http://good-server:8000/sse", mock_good_client ) - @pytest.mark.asyncio - async def test_create_mcp_tools_from_config_with_timeout(self): + def test_create_mcp_tools_from_config_with_timeout(self): """Test creating MCP tools from configuration with custom timeout.""" config = MCPConfig( sse_servers=[MCPSSEServerConfig(url="http://localhost:8000/sse")] ) - mock_client = AsyncMock() + mock_client = MagicMock() mock_tool = MagicMock() with patch( @@ -293,7 +280,7 @@ async def test_create_mcp_tools_from_config_with_timeout(self): mock_registry_class.return_value = mock_registry mock_registry.get_all_tools.return_value = [mock_tool] - await create_mcp_tools_from_config(config, timeout=15.0) + create_mcp_tools_from_config(config, timeout=15.0) # Verify timeout was passed to create_mcp_client mock_create.assert_called_with(config.sse_servers[0], None, 15.0) From abdab2039da167a3e6a7990661cf187582b66b42 Mon Sep 17 00:00:00 2001 From: Hoang Tran Date: Fri, 5 Sep 2025 08:25:34 +0000 Subject: [PATCH 06/28] improve thread-safety and resource management --- openhands/sdk/mcp/client.py | 74 ++++++++++++++++++++++++------------- 1 file changed, 49 insertions(+), 25 deletions(-) diff --git a/openhands/sdk/mcp/client.py b/openhands/sdk/mcp/client.py index 51642c81958..4d932c3f0d3 100644 --- a/openhands/sdk/mcp/client.py +++ b/openhands/sdk/mcp/client.py @@ -12,7 +12,7 @@ ) from mcp import McpError from mcp.types import CallToolResult, Tool as MCPTool -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, PrivateAttr from openhands.sdk.config.mcp_config import ( MCPSHTTPServerConfig, @@ -36,21 +36,20 @@ class MCPClient(BaseModel): tools: list[MCPTool] = Field(default_factory=list) tool_map: dict[str, MCPTool] = Field(default_factory=dict) - server_config: ( - MCPSSEServerConfig | MCPSHTTPServerConfig | MCPStdioServerConfig | None - ) = None + server_config: Optional[ + MCPSSEServerConfig | MCPSHTTPServerConfig | MCPStdioServerConfig + ] = Field(default=None) - # Internal async management - def __init__(self, **data): - super().__init__(**data) + # Connection parameters for recreating clients + _timeout: float = Field(default=30.0, exclude=True) + _conversation_id: Optional[str] = Field(default=None, exclude=True) - # Connection parameters for recreating clients - self._timeout: float = 30.0 - self._conversation_id: Optional[str] = None - - # Event loop and thread for async operations - self._loop: Optional[asyncio.AbstractEventLoop] = None - self._thread: Optional[threading.Thread] = None + # Private attributes - these don't get serialized + _timeout: float = PrivateAttr(default=30.0) + _conversation_id: Optional[str] = PrivateAttr(default=None) + _loop: Optional[asyncio.AbstractEventLoop] = PrivateAttr(default=None) + _thread: Optional[threading.Thread] = PrivateAttr(default=None) + _loop_lock: threading.Lock = PrivateAttr(default_factory=threading.Lock) def _create_stdio_client(self) -> Client: """Create a new stdio client using stored server config.""" @@ -214,18 +213,43 @@ def run_loop(): def _stop_event_loop(self) -> None: """Stop the background event loop.""" - if self._loop is not None: - self._loop.call_soon_threadsafe(self._loop.stop) - if self._thread is not None: - self._thread.join(timeout=1.0) - self._loop = None - self._thread = None + if self._loop is not None and not self._loop.is_closed(): + try: + self._loop.call_soon_threadsafe(self._loop.stop) + except RuntimeError: + # Loop might already be stopped/closed + pass + + if self._thread is not None and self._thread.is_alive(): + self._thread.join(timeout=1.0) + + self._loop = None + self._thread = None def _run_async(self, coro): """Run an async coroutine in the managed event loop.""" - if self._loop is None: - self._start_event_loop() + with self._loop_lock: + if self._loop is None: + self._start_event_loop() + loop = self._loop - assert self._loop is not None - future = asyncio.run_coroutine_threadsafe(coro, self._loop) - return future.result() + assert loop is not None + try: + future = asyncio.run_coroutine_threadsafe(coro, loop) + return future.result() + except Exception as e: + # Add context about which operation failed + raise RuntimeError(f"MCP async operation failed: {e}") from e + + def __del__(self): + """Ensure cleanup on garbage collection.""" + try: + if hasattr(self, "_loop") and self._loop is not None: + self._stop_event_loop() + except Exception: + # Ignore errors during cleanup in __del__ + pass + + def close(self): + """Explicit cleanup method for proper resource management.""" + self._stop_event_loop() From ee5291d13bfa0a26a010b19de29147a09096b1c0 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 10:11:04 -0400 Subject: [PATCH 07/28] make mcp tool prints in xml format --- openhands/sdk/mcp/tool.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/openhands/sdk/mcp/tool.py b/openhands/sdk/mcp/tool.py index e1b9a563b3e..2039dadf98c 100644 --- a/openhands/sdk/mcp/tool.py +++ b/openhands/sdk/mcp/tool.py @@ -1,6 +1,5 @@ """MCPTool definition and implementation.""" -import json from typing import Any from pydantic import Field @@ -31,7 +30,9 @@ class MCPToolAction(ActionBase): class MCPToolObservation(ObservationBase): """Observation from MCP tool execution.""" - content: str = Field(default="", description="Content returned from the MCP tool") + content: dict[str, Any] = Field( + default_factory=dict, description="Content returned from the MCP tool" + ) is_error: bool = Field( default=False, description="Whether the call resulted in an error" ) @@ -46,9 +47,12 @@ def agent_observation(self) -> str: if self.is_error: return f"Error calling tool {self.tool_name}: {self.error_message}" else: - return ( - f"Tool {self.tool_name} returned: {json.dumps(self.content, indent=2)}" - ) + ret = f"[Tool {self.tool_name} returned]\n" + for k, v in self.content.items(): + ret += f"\n" + ret += str(v) + "\n" + ret += "\n" + return ret class MCPToolExecutor(ToolExecutor): @@ -63,7 +67,7 @@ def __call__(self, action: MCPToolAction) -> MCPToolObservation: result = self.mcp_client.call_tool(action.tool_name, action.arguments) return MCPToolObservation( - content=json.dumps(result.model_dump(mode="json")), + content=result.model_dump(mode="json"), is_error=result.isError, tool_name=action.tool_name, ) From 29cbf4141fdcc4081cc5f0e320b32b096938c4a5 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 10:47:22 -0400 Subject: [PATCH 08/28] make TextContent and ImageContent inherit from mcp types --- openhands/sdk/llm/message.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/openhands/sdk/llm/message.py b/openhands/sdk/llm/message.py index 98cb43d2dd3..27c9c92e5c4 100644 --- a/openhands/sdk/llm/message.py +++ b/openhands/sdk/llm/message.py @@ -1,18 +1,12 @@ -from enum import Enum from typing import Any, Literal, cast +import mcp.types from litellm import ChatCompletionMessageToolCall from litellm.types.utils import Message as LiteLLMMessage from pydantic import BaseModel, Field -class ContentType(Enum): - TEXT = "text" - IMAGE_URL = "image_url" - - -class Content(BaseModel): - type: str +class BaseContent(BaseModel): cache_prompt: bool = False def to_llm_dict( @@ -22,8 +16,8 @@ def to_llm_dict( raise NotImplementedError("Subclasses should implement this method.") -class TextContent(Content): - type: str = ContentType.TEXT.value +class TextContent(mcp.types.TextContent, BaseContent): + type: Literal["text"] = "text" text: str def to_llm_dict(self) -> dict[str, str | dict[str, str]]: @@ -37,8 +31,8 @@ def to_llm_dict(self) -> dict[str, str | dict[str, str]]: return data -class ImageContent(Content): - type: str = ContentType.IMAGE_URL.value +class ImageContent(mcp.types.ImageContent, BaseContent): + type: Literal["image"] = "image" image_urls: list[str] def to_llm_dict(self) -> list[dict[str, str | dict[str, str]]]: From 6ba785b753e80619b1f850b18180980caad2ee6b Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 10:56:24 -0400 Subject: [PATCH 09/28] completely get rid of mcp config --- openhands/sdk/config/__init__.py | 4 - openhands/sdk/config/mcp_config.py | 322 ----------------------------- 2 files changed, 326 deletions(-) delete mode 100644 openhands/sdk/config/mcp_config.py diff --git a/openhands/sdk/config/__init__.py b/openhands/sdk/config/__init__.py index 22df0f208f0..e69de29bb2d 100644 --- a/openhands/sdk/config/__init__.py +++ b/openhands/sdk/config/__init__.py @@ -1,4 +0,0 @@ -from openhands.sdk.config.mcp_config import MCPConfig - - -__all__ = ["MCPConfig"] diff --git a/openhands/sdk/config/mcp_config.py b/openhands/sdk/config/mcp_config.py deleted file mode 100644 index cfab6e228b9..00000000000 --- a/openhands/sdk/config/mcp_config.py +++ /dev/null @@ -1,322 +0,0 @@ -from __future__ import annotations - -import re -import shlex -from typing import TYPE_CHECKING -from urllib.parse import urlparse - -from pydantic import ( - BaseModel, - ConfigDict, - Field, - ValidationError, - field_validator, - model_validator, -) - - -if TYPE_CHECKING: - pass - -from openhands.sdk.logger import get_logger - - -logger = get_logger(__name__) - - -def _validate_mcp_url(url: str) -> str: - """Shared URL validation logic for MCP servers.""" - if not url.strip(): - raise ValueError("URL cannot be empty") - - url = url.strip() - try: - parsed = urlparse(url) - if not parsed.scheme: - raise ValueError("URL must include a scheme (http:// or https://)") - if not parsed.netloc: - raise ValueError("URL must include a valid domain/host") - if parsed.scheme not in ["http", "https", "ws", "wss"]: - raise ValueError("URL scheme must be http, https, ws, or wss") - return url - except Exception as e: - if isinstance(e, ValueError): - raise - raise ValueError(f"Invalid URL format: {str(e)}") - - -class MCPSSEServerConfig(BaseModel): - """Configuration for a single MCP server. - - Attributes: - url: The server URL - api_key: Optional API key for authentication - """ - - url: str - api_key: str | None = None - - @field_validator("url") - @classmethod - def validate_url(cls, v: str) -> str: - """Validate URL format for MCP servers.""" - return _validate_mcp_url(v) - - -class MCPStdioServerConfig(BaseModel): - """Configuration for a MCP server that uses stdio. - - Attributes: - name: The name of the server - command: The command to run the server - args: The arguments to pass to the server - env: The environment variables to set for the server - """ - - name: str - command: str - args: list[str] = Field(default_factory=list) - env: dict[str, str] = Field(default_factory=dict) - - @field_validator("name", mode="before") - @classmethod - def validate_server_name(cls, v: str) -> str: - """Validate server name for stdio MCP servers.""" - if not v.strip(): - raise ValueError("Server name cannot be empty") - - v = v.strip() - - # Check for valid characters (alphanumeric, hyphens, underscores) - if not re.match(r"^[a-zA-Z0-9_-]+$", v): - raise ValueError( - "Server name can only contain letters, numbers, hyphens, and " - "underscores" - ) - - return v - - @field_validator("command", mode="before") - @classmethod - def validate_command(cls, v: str) -> str: - """Validate command for stdio MCP servers.""" - if not v.strip(): - raise ValueError("Command cannot be empty") - - v = v.strip() - - # Check that command doesn't contain spaces (should be a single executable) - if " " in v: - raise ValueError( - "Command should be a single executable without spaces (use " - "arguments field for parameters)" - ) - - return v - - @field_validator("args", mode="before") - @classmethod - def parse_args(cls, v) -> list[str]: - """Parse arguments from string or return list as-is. - - Supports shell-like argument parsing using shlex.split(). - - Examples: - - "-y mcp-remote https://example.com" - - '--config "path with spaces" --debug' - - "arg1 arg2 arg3" - """ - if isinstance(v, str): - if not v.strip(): - return [] - - v = v.strip() - - # Use shell-like parsing for natural argument handling - try: - return shlex.split(v) - except ValueError as e: - # If shlex parsing fails (e.g., unmatched quotes), provide clear error - raise ValueError( - f"Invalid argument format: {str(e)}. Use shell-like format, " - f'e.g., "arg1 arg2" or \'--config "value with spaces"\'' - ) - - return v or [] - - @field_validator("env", mode="before") - @classmethod - def parse_env(cls, v) -> dict[str, str]: - """Parse environment variables from string or return dict as-is.""" - if isinstance(v, str): - if not v.strip(): - return {} - - env = {} - for pair in v.split(","): - pair = pair.strip() - if not pair: - continue - - if "=" not in pair: - raise ValueError( - f"Environment variable '{pair}' must be in KEY=VALUE format" - ) - - key, value = pair.split("=", 1) - key = key.strip() - if not key: - raise ValueError("Environment variable key cannot be empty") - if not re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", key): - raise ValueError( - f"Invalid environment variable name '{key}'. Must start with " - f"letter or underscore, contain only alphanumeric characters " - f"and underscores" - ) - - env[key] = value - return env - return v or {} - - def __eq__(self, other): - """Override equality operator to compare server configurations. - - Two server configurations are considered equal if they have the same - name, command, args, and env values. The order of args is important, - but the order of env variables is not. - """ - if not isinstance(other, MCPStdioServerConfig): - return False - return ( - self.name == other.name - and self.command == other.command - and self.args == other.args - and set(self.env.items()) == set(other.env.items()) - ) - - -class MCPSHTTPServerConfig(BaseModel): - url: str - api_key: str | None = None - - @field_validator("url", mode="before") - @classmethod - def validate_url(cls, v: str) -> str: - """Validate URL format for MCP servers.""" - return _validate_mcp_url(v) - - -class MCPConfig(BaseModel): - """Configuration for MCP (Message Control Protocol) settings. - - Attributes: - sse_servers: List of MCP SSE server configs - stdio_servers: List of MCP stdio server configs. These servers will be - added to the MCP Router running inside runtime container. - shttp_servers: List of MCP HTTP server configs. - """ - - sse_servers: list[MCPSSEServerConfig] = Field(default_factory=list) - stdio_servers: list[MCPStdioServerConfig] = Field(default_factory=list) - shttp_servers: list[MCPSHTTPServerConfig] = Field(default_factory=list) - model_config = ConfigDict(extra="forbid") - - @staticmethod - def _normalize_servers(servers_data: list[dict | str]) -> list[dict]: - """Helper method to normalize SSE server configurations.""" - normalized = [] - for server in servers_data: - if isinstance(server, str): - normalized.append({"url": server}) - else: - normalized.append(server) - return normalized - - @model_validator(mode="before") - def convert_string_urls(cls, data): - """Convert string URLs to MCPSSEServerConfig objects.""" - if isinstance(data, dict): - if "sse_servers" in data: - data["sse_servers"] = cls._normalize_servers(data["sse_servers"]) - - if "shttp_servers" in data: - data["shttp_servers"] = cls._normalize_servers(data["shttp_servers"]) - - return data - - def validate_servers(self) -> None: - """Validate that server URLs are valid and unique.""" - urls = [server.url for server in self.sse_servers] - - # Check for duplicate server URLs - if len(set(urls)) != len(urls): - raise ValueError("Duplicate MCP server URLs are not allowed") - - # Validate URLs - for url in urls: - try: - result = urlparse(url) - if not all([result.scheme, result.netloc]): - raise ValueError(f"Invalid URL format: {url}") - except Exception as e: - raise ValueError(f"Invalid URL {url}: {str(e)}") - - @classmethod - def from_toml_section(cls, data: dict) -> dict[str, "MCPConfig"]: - """Create a mapping of MCPConfig instances from a toml dictionary - representing the [mcp] section. - - The configuration is built from all keys in data. - - Returns: - dict[str, MCPConfig]: A mapping where the key "mcp" corresponds to the - [mcp] configuration - """ - # Initialize the result mapping - mcp_mapping: dict[str, MCPConfig] = {} - - try: - # Convert all entries in sse_servers to MCPSSEServerConfig objects - if "sse_servers" in data: - data["sse_servers"] = cls._normalize_servers(data["sse_servers"]) - servers: list[ - MCPSSEServerConfig | MCPStdioServerConfig | MCPSHTTPServerConfig - ] = [] - for server in data["sse_servers"]: - servers.append(MCPSSEServerConfig(**server)) - data["sse_servers"] = servers - - # Convert all entries in stdio_servers to MCPStdioServerConfig objects - if "stdio_servers" in data: - servers = [] - for server in data["stdio_servers"]: - servers.append(MCPStdioServerConfig(**server)) - data["stdio_servers"] = servers - - if "shttp_servers" in data: - data["shttp_servers"] = cls._normalize_servers(data["shttp_servers"]) - servers = [] - for server in data["shttp_servers"]: - servers.append(MCPSHTTPServerConfig(**server)) - data["shttp_servers"] = servers - - # Create SSE config if present - mcp_config = MCPConfig.model_validate(data) - mcp_config.validate_servers() - - # Create the main MCP config - mcp_mapping["mcp"] = cls( - sse_servers=mcp_config.sse_servers, - stdio_servers=mcp_config.stdio_servers, - shttp_servers=mcp_config.shttp_servers, - ) - except ValidationError as e: - raise ValueError(f"Invalid MCP configuration: {e}") - return mcp_mapping - - def merge(self, other: MCPConfig): - return MCPConfig( - sse_servers=self.sse_servers + other.sse_servers, - stdio_servers=self.stdio_servers + other.stdio_servers, - shttp_servers=self.shttp_servers + other.shttp_servers, - ) From c141f727f6108df6bd758b7af8c0046c40007459 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 11:22:45 -0400 Subject: [PATCH 10/28] refactor to make agent_observation to return list[TextContent | ImageContent]; this make it easier to have observation compatible with MCP --- openhands/sdk/conversation/visualizer.py | 24 ++++++++----------- openhands/sdk/event/llm_convertible.py | 11 +++++---- openhands/sdk/llm/__init__.py | 3 ++- openhands/sdk/llm/message.py | 14 +++++++++++ openhands/sdk/tool/schema.py | 7 ++++-- openhands/sdk/tool/tool.py | 2 ++ openhands/tools/execute_bash/definition.py | 5 ++-- .../tools/str_replace_editor/definition.py | 7 +++--- 8 files changed, 46 insertions(+), 27 deletions(-) diff --git a/openhands/sdk/conversation/visualizer.py b/openhands/sdk/conversation/visualizer.py index b5e3a1e51b7..a3d359db1f4 100644 --- a/openhands/sdk/conversation/visualizer.py +++ b/openhands/sdk/conversation/visualizer.py @@ -12,7 +12,7 @@ ObservationEvent, SystemPromptEvent, ) -from openhands.sdk.llm import ImageContent, TextContent +from openhands.sdk.llm import ImageContent, TextContent, content_to_str class ConversationVisualizer: @@ -120,7 +120,13 @@ def _create_observation_panel(self, event: ObservationEvent) -> Panel: content.append("Tool: ", style="bold blue") content.append(event.tool_name, style="cyan") content.append("\n\nResult:\n", style="bold blue") - content.append(event.observation.agent_observation, style="white") + + text_parts = content_to_str(event.observation.agent_observation) + if text_parts: + full_content = " ".join(text_parts) + content.append(full_content, style="white") + else: + content.append("[no text content]", style="dim white") return Panel( content, @@ -146,17 +152,7 @@ def _create_message_panel(self, event: MessageEvent) -> Panel: f"{event.llm_message.role.title()}:\n", style=f"bold {role_color}" ) - # Extract and display all content - def _display_content(contents: list[TextContent | ImageContent]) -> list[str]: - text_parts = [] - for content_item in contents: - if isinstance(content_item, TextContent): - text_parts.append(content_item.text) - elif isinstance(content_item, ImageContent): - text_parts.append(f"[Image: {len(content_item.image_urls)} URLs]") - return text_parts - - text_parts = _display_content(event.llm_message.content) + text_parts = content_to_str(event.llm_message.content) if text_parts: full_content = " ".join(text_parts) content.append(full_content, style="white") @@ -175,7 +171,7 @@ def _display_content(contents: list[TextContent | ImageContent]) -> list[str]: assert not any( isinstance(c, ImageContent) for c in event.extended_content ), "Extended content should not contain images" - text_parts = _display_content( + text_parts = content_to_str( cast(list[TextContent | ImageContent], event.extended_content) ) content.append("\n\nExtended Content:\n", style="dim yellow") diff --git a/openhands/sdk/event/llm_convertible.py b/openhands/sdk/event/llm_convertible.py index 0dc4826dd02..ea4f85ce67b 100644 --- a/openhands/sdk/event/llm_convertible.py +++ b/openhands/sdk/event/llm_convertible.py @@ -6,7 +6,7 @@ from openhands.sdk.event.base import N_CHAR_PREVIEW, LLMConvertibleEvent from openhands.sdk.event.types import EventType, SourceType -from openhands.sdk.llm import ImageContent, Message, TextContent +from openhands.sdk.llm import ImageContent, Message, TextContent, content_to_str from openhands.sdk.tool import ActionBase, ObservationBase @@ -106,7 +106,7 @@ class ObservationEvent(LLMConvertibleEvent): def to_llm_message(self) -> Message: return Message( role="tool", - content=[TextContent(text=self.observation.agent_observation)], + content=self.observation.agent_observation, name=self.tool_name, tool_call_id=self.tool_call_id, ) @@ -114,10 +114,11 @@ def to_llm_message(self) -> Message: def __str__(self) -> str: """Plain text string representation for ObservationEvent.""" base_str = f"{self.__class__.__name__} ({self.source})" + content_str = "".join(content_to_str(self.observation.agent_observation)) obs_preview = ( - self.observation.agent_observation[:N_CHAR_PREVIEW] + "..." - if len(self.observation.agent_observation) > N_CHAR_PREVIEW - else self.observation.agent_observation + content_str[:N_CHAR_PREVIEW] + "..." + if len(content_str) > N_CHAR_PREVIEW + else content_str ) return f"{base_str}\n Tool: {self.tool_name}\n Result: {obs_preview}" diff --git a/openhands/sdk/llm/__init__.py b/openhands/sdk/llm/__init__.py index 52c29dacaec..3001bd524fb 100644 --- a/openhands/sdk/llm/__init__.py +++ b/openhands/sdk/llm/__init__.py @@ -1,6 +1,6 @@ from openhands.sdk.llm.llm import LLM from openhands.sdk.llm.llm_registry import LLMRegistry, RegistryEvent -from openhands.sdk.llm.message import ImageContent, Message, TextContent +from openhands.sdk.llm.message import ImageContent, Message, TextContent, content_to_str from openhands.sdk.llm.metadata import get_llm_metadata @@ -11,5 +11,6 @@ "Message", "TextContent", "ImageContent", + "content_to_str", "get_llm_metadata", ] diff --git a/openhands/sdk/llm/message.py b/openhands/sdk/llm/message.py index 27c9c92e5c4..cc655aab53d 100644 --- a/openhands/sdk/llm/message.py +++ b/openhands/sdk/llm/message.py @@ -167,3 +167,17 @@ def from_litellm_message(cls, message: LiteLLMMessage) -> "Message": else [], tool_calls=message.tool_calls, ) + + +def content_to_str(contents: list[TextContent | ImageContent]) -> list[str]: + """Convert a list of TextContent and ImageContent to a list of strings. + + This is primarily used for display purposes. + """ + text_parts = [] + for content_item in contents: + if isinstance(content_item, TextContent): + text_parts.append(content_item.text) + elif isinstance(content_item, ImageContent): + text_parts.append(f"[Image: {len(content_item.image_urls)} URLs]") + return text_parts diff --git a/openhands/sdk/tool/schema.py b/openhands/sdk/tool/schema.py index 768734310b5..a2fffcd7212 100644 --- a/openhands/sdk/tool/schema.py +++ b/openhands/sdk/tool/schema.py @@ -1,8 +1,11 @@ -from typing import Any, TypeVar +from typing import TYPE_CHECKING, Any, TypeVar from pydantic import BaseModel, ConfigDict, Field, create_model +if TYPE_CHECKING: + from openhands.sdk.llm import ImageContent, TextContent + S = TypeVar("S", bound="Schema") @@ -137,6 +140,6 @@ class ObservationBase(Schema): model_config = ConfigDict(extra="allow") @property - def agent_observation(self) -> str: + def agent_observation(self) -> list[TextContent | ImageContent]: """Get the observation string to show to the agent.""" raise NotImplementedError("Subclasses must implement agent_observation") diff --git a/openhands/sdk/tool/tool.py b/openhands/sdk/tool/tool.py index 32201134dc8..beaf04923dc 100644 --- a/openhands/sdk/tool/tool.py +++ b/openhands/sdk/tool/tool.py @@ -67,6 +67,7 @@ def __init__( description: str, input_schema: type[ActionBase] | dict[str, Any], output_schema: type[ObservationBase] | dict[str, Any] | None = None, + title: str | None = None, annotations: ToolAnnotations | None = None, _meta: dict[str, Any] | None = None, executor: ToolExecutor | None = None, @@ -77,6 +78,7 @@ def __init__( self._meta = _meta self._set_input_schema(input_schema) self._set_output_schema(output_schema) + self.title = title or name self.executor = executor diff --git a/openhands/tools/execute_bash/definition.py b/openhands/tools/execute_bash/definition.py index 03d4dbff3ac..707a7d81869 100644 --- a/openhands/tools/execute_bash/definition.py +++ b/openhands/tools/execute_bash/definition.py @@ -5,6 +5,7 @@ from pydantic import Field +from openhands.sdk.llm import ImageContent, TextContent from openhands.sdk.tool import ActionBase, ObservationBase, Tool, ToolAnnotations from openhands.tools.execute_bash.constants import NO_CHANGE_TIMEOUT_SECONDS from openhands.tools.execute_bash.metadata import CmdOutputMetadata @@ -65,7 +66,7 @@ def command_id(self) -> int | None: return self.metadata.pid @property - def agent_observation(self) -> str: + def agent_observation(self) -> list[TextContent | ImageContent]: ret = f"{self.metadata.prefix}{self.output}{self.metadata.suffix}" if self.metadata.working_dir: ret += f"\n[Current working directory: {self.metadata.working_dir}]" @@ -75,7 +76,7 @@ def agent_observation(self) -> str: ret += f"\n[Command finished with exit code {self.metadata.exit_code}]" if self.error: ret = f"[There was an error during command execution.]\n{ret}" - return ret + return [TextContent(text=ret)] TOOL_DESCRIPTION = """Execute a bash command in the terminal within a persistent shell session. diff --git a/openhands/tools/str_replace_editor/definition.py b/openhands/tools/str_replace_editor/definition.py index 0586e9aa766..c64facefdbb 100644 --- a/openhands/tools/str_replace_editor/definition.py +++ b/openhands/tools/str_replace_editor/definition.py @@ -4,6 +4,7 @@ from pydantic import Field +from openhands.sdk.llm import ImageContent, TextContent from openhands.sdk.tool import ActionBase, ObservationBase, Tool, ToolAnnotations from openhands.tools.utils.security_prompt import ( SECURITY_RISK_DESC, @@ -77,10 +78,10 @@ class StrReplaceEditorObservation(ObservationBase): error: str | None = Field(default=None, description="Error message if any.") @property - def agent_observation(self) -> str: + def agent_observation(self) -> list[TextContent | ImageContent]: if self.error: - return self.error - return self.output + return [TextContent(text=self.error)] + return [TextContent(text=self.output)] Command = Literal[ From 0d07c60930c5171ab94cad9427128c1dd5a4e53c Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 11:26:30 -0400 Subject: [PATCH 11/28] add async utils --- openhands/sdk/utils/async_utils.py | 122 +++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 openhands/sdk/utils/async_utils.py diff --git a/openhands/sdk/utils/async_utils.py b/openhands/sdk/utils/async_utils.py new file mode 100644 index 00000000000..4d1827fb86d --- /dev/null +++ b/openhands/sdk/utils/async_utils.py @@ -0,0 +1,122 @@ +import asyncio +from concurrent import futures +from concurrent.futures import ThreadPoolExecutor +from typing import Callable, Coroutine, Iterable + + +GENERAL_TIMEOUT: int = 15 +EXECUTOR = ThreadPoolExecutor() + + +async def call_sync_from_async(fn: Callable, *args, **kwargs): + """Shorthand for running a function in the default background thread pool executor + and awaiting the result. The nature of synchronous code is that the future + returned by this function is not cancellable + """ + loop = asyncio.get_event_loop() + coro = loop.run_in_executor(None, lambda: fn(*args, **kwargs)) + result = await coro + return result + + +def call_async_from_sync( + corofn: Callable, timeout: float = GENERAL_TIMEOUT, *args, **kwargs +): + """Shorthand for running a coroutine in the default background thread pool executor + and awaiting the result + """ + if corofn is None: + raise ValueError("corofn is None") + if not asyncio.iscoroutinefunction(corofn): + raise ValueError("corofn is not a coroutine function") + + async def arun(): + coro = corofn(*args, **kwargs) + result = await coro + return result + + def run(): + loop_for_thread = asyncio.new_event_loop() + try: + asyncio.set_event_loop(loop_for_thread) + return asyncio.run(arun()) + finally: + loop_for_thread.close() + + if getattr(EXECUTOR, "_shutdown", False): + result = run() + return result + + future = EXECUTOR.submit(run) + futures.wait([future], timeout=timeout or None) + result = future.result() + return result + + +async def call_coro_in_bg_thread( + corofn: Callable, timeout: float = GENERAL_TIMEOUT, *args, **kwargs +): + """Function for running a coroutine in a background thread.""" + await call_sync_from_async(call_async_from_sync, corofn, timeout, *args, **kwargs) + + +async def wait_all( + iterable: Iterable[Coroutine], timeout: int = GENERAL_TIMEOUT +) -> list: + """Shorthand for waiting for all the coroutines in the iterable given in parallel. + + Creates a task for each coroutine. + Returns a list of results in the original order. + If any single task raised an exception, this is raised. + If multiple tasks raised exceptions, an AsyncException + is raised containing all exceptions. + """ + tasks = [asyncio.create_task(c) for c in iterable] + if not tasks: + return [] + _, pending = await asyncio.wait(tasks, timeout=timeout) + if pending: + for task in pending: + task.cancel() + raise asyncio.TimeoutError() + results = [] + errors = [] + for task in tasks: + try: + results.append(task.result()) + except Exception as e: + errors.append(e) + if errors: + if len(errors) == 1: + raise errors[0] + raise AsyncException(errors) + return [task.result() for task in tasks] + + +class AsyncException(Exception): + def __init__(self, exceptions): + self.exceptions = exceptions + + def __str__(self): + return "\n".join(str(e) for e in self.exceptions) + + +async def run_in_loop( + coro: Coroutine, loop: asyncio.AbstractEventLoop, timeout: float = GENERAL_TIMEOUT +): + """Mitigate the dreaded "coroutine was created in a different event loop" error. + Pass the coroutine to a different event loop if needed. + """ + running_loop = asyncio.get_running_loop() + if running_loop == loop: + result = await coro + return result + + result = await call_sync_from_async(_run_in_loop, coro, loop, timeout) + return result + + +def _run_in_loop(coro: Coroutine, loop: asyncio.AbstractEventLoop, timeout: float): + future = asyncio.run_coroutine_threadsafe(coro, loop) + result = future.result(timeout=timeout) + return result From a16743a5ce7d0b0a75f0d1234525d1ce80ba424f Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 11:26:46 -0400 Subject: [PATCH 12/28] fix microagent validation --- .../sdk/context/microagents/microagent.py | 31 ++++++------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/openhands/sdk/context/microagents/microagent.py b/openhands/sdk/context/microagents/microagent.py index 75159c2753c..5a9b0afdc98 100644 --- a/openhands/sdk/context/microagents/microagent.py +++ b/openhands/sdk/context/microagents/microagent.py @@ -5,9 +5,9 @@ from typing import ClassVar, Union import frontmatter +from fastmcp.mcp_config import MCPConfig from pydantic import BaseModel, Field, field_validator, model_validator -from openhands.sdk.config import MCPConfig from openhands.sdk.context.microagents.exceptions import MicroagentValidationError from openhands.sdk.context.microagents.types import ( InputMetadata, @@ -197,7 +197,7 @@ class RepoMicroagent(BaseMicroagent): """ type: MicroagentType = MicroagentType.REPO_KNOWLEDGE - mcp_tools: MCPConfig | None = Field( + mcp_tools: MCPConfig | dict | None = Field( default=None, description="MCP tools configuration for the microagent", ) @@ -205,27 +205,16 @@ class RepoMicroagent(BaseMicroagent): # Field-level validation for mcp_tools @field_validator("mcp_tools") @classmethod - def _validate_mcp_tools(cls, v: MCPConfig | None, info): + def _validate_mcp_tools(cls, v: MCPConfig | dict | None, info): if v is None: return v - # Warn on SSE servers - if v.sse_servers: - logger.warning( - f"Microagent {getattr(info, 'data', {}).get('name', '')} has SSE servers. " # noqa: E501 - "Only stdio servers are currently supported." - ) - # Require stdio servers to be configured (non-empty) - stdio = v.stdio_servers - if not stdio: - # Try to include the agent name if available - agent_name = ( - getattr(info, "data", {}).get("name") if hasattr(info, "data") else None - ) - agent_label = agent_name or "" - raise MicroagentValidationError( - f"Microagent {agent_label} has MCP tools configuration but no stdio servers. " # noqa: E501 - "Only stdio servers are currently supported." - ) + if isinstance(v, dict): + try: + v = MCPConfig.model_validate(v) + except Exception as e: + raise MicroagentValidationError( + f"Invalid MCPConfig dictionary: {e}" + ) from e return v @model_validator(mode="after") From 47a6657b9f1802d937a6e308095355f7dcc7efb1 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 11:40:10 -0400 Subject: [PATCH 13/28] improve visualization for available tools --- openhands/sdk/conversation/visualizer.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/openhands/sdk/conversation/visualizer.py b/openhands/sdk/conversation/visualizer.py index a3d359db1f4..e4e3b3fdb94 100644 --- a/openhands/sdk/conversation/visualizer.py +++ b/openhands/sdk/conversation/visualizer.py @@ -1,3 +1,4 @@ +import json from typing import cast from rich.console import Console @@ -58,7 +59,28 @@ def _create_system_prompt_panel(self, event: SystemPromptEvent) -> Panel: content = Text() content.append("System Prompt:\n", style="bold cyan") content.append(event.system_prompt.text, style="white") - content.append(f"\n\nTools Available: {len(event.tools)}", style="dim cyan") + content.append(f"\n\nTools Available: {len(event.tools)}", style="cyan") + for tool in event.tools: + tool_fn = tool.get("function", None) + # make each field short + for k, v in tool.items(): + if isinstance(v, str) and len(v) > 30: + tool[k] = v[:27] + "..." + if tool_fn: + assert "name" in tool_fn + assert "description" in tool_fn + assert "parameters" in tool_fn + params_str = json.dumps(tool_fn["parameters"]) + content.append( + f"\n - {tool_fn['name']}: " + f"{tool_fn['description'].split('\n')[0][:100]}...\n", + style="dim cyan", + ) + content.append(f" Parameters: {params_str}", style="dim white") + else: + content.append( + f"\n - Cannot access .function for {tool}", style="dim cyan" + ) return Panel( content, From 6b8c128e99b5d4542b481ab54ec2e77a886a86f1 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 12:01:15 -0400 Subject: [PATCH 14/28] move security_risk to ActionBase --- examples/2_custom_tools.py | 10 ++++++---- openhands/sdk/__init__.py | 11 ++--------- openhands/sdk/context/microagents/types.py | 5 +---- openhands/sdk/tool/schema.py | 13 +++++++++---- .../{tools/utils => sdk/tool}/security_prompt.py | 2 +- openhands/tools/execute_bash/definition.py | 5 ----- openhands/tools/str_replace_editor/definition.py | 5 ----- 7 files changed, 19 insertions(+), 32 deletions(-) rename openhands/{tools/utils => sdk/tool}/security_prompt.py (61%) diff --git a/examples/2_custom_tools.py b/examples/2_custom_tools.py index af0e4aadf4a..71646344f0e 100644 --- a/examples/2_custom_tools.py +++ b/examples/2_custom_tools.py @@ -10,6 +10,7 @@ Agent, Conversation, EventType, + ImageContent, LLMConvertibleEvent, Message, TextContent, @@ -47,17 +48,18 @@ class GrepObservation(ObservationBase): count: int = 0 @property - def agent_observation(self) -> str: + def agent_observation(self) -> list[TextContent | ImageContent]: if not self.count: - return "No matches found." + return [TextContent(text="No matches found.")] files_list = "\n".join(f"- {f}" for f in self.files[:20]) sample = "\n".join(self.matches[:10]) more = "\n..." if self.count > 10 else "" - return ( + ret = ( f"Found {self.count} matching lines.\n" f"Files:\n{files_list}\n" f"Sample:\n{sample}{more}" ) + return [TextContent(text=ret)] # --- Executor --- @@ -79,7 +81,7 @@ def __call__(self, action: GrepAction) -> GrepObservation: else: cmd = f"grep -rHnE {pat} {root_q} 2>/dev/null | head -100" - result = self.bash(ExecuteBashAction(command=cmd, security_risk="LOW")) + result = self.bash(ExecuteBashAction(command=cmd)) matches: list[str] = [] files: set[str] = set() diff --git a/openhands/sdk/__init__.py b/openhands/sdk/__init__.py index 7984ad92936..d8eace03308 100644 --- a/openhands/sdk/__init__.py +++ b/openhands/sdk/__init__.py @@ -1,7 +1,6 @@ from importlib.metadata import PackageNotFoundError, version from openhands.sdk.agent import Agent, AgentBase -from openhands.sdk.config import MCPConfig from openhands.sdk.context import AgentContext from openhands.sdk.conversation import Conversation, ConversationCallbackType from openhands.sdk.event import EventBase, EventType, LLMConvertibleEvent @@ -14,11 +13,7 @@ TextContent, ) from openhands.sdk.logger import get_logger -from openhands.sdk.mcp import ( - MCPClient, - MCPTool, - create_mcp_tools_from_config, -) +from openhands.sdk.mcp import MCPTool, create_mcp_tools from openhands.sdk.tool import ActionBase, ObservationBase, Tool @@ -39,10 +34,8 @@ "Agent", "ActionBase", "ObservationBase", - "MCPConfig", - "MCPClient", "MCPTool", - "create_mcp_tools_from_config", + "create_mcp_tools", "get_logger", "Conversation", "ConversationCallbackType", diff --git a/openhands/sdk/context/microagents/types.py b/openhands/sdk/context/microagents/types.py index c8a81ba4777..c373240c043 100644 --- a/openhands/sdk/context/microagents/types.py +++ b/openhands/sdk/context/microagents/types.py @@ -1,12 +1,9 @@ from datetime import datetime, timezone from enum import Enum +from fastmcp.mcp_config import MCPConfig from pydantic import BaseModel, Field -from openhands.sdk.config.mcp_config import ( - MCPConfig, -) - class MicroagentType(str, Enum): """Type of microagent.""" diff --git a/openhands/sdk/tool/schema.py b/openhands/sdk/tool/schema.py index a2fffcd7212..5688c5dee8e 100644 --- a/openhands/sdk/tool/schema.py +++ b/openhands/sdk/tool/schema.py @@ -1,10 +1,13 @@ -from typing import TYPE_CHECKING, Any, TypeVar +from typing import Any, TypeVar from pydantic import BaseModel, ConfigDict, Field, create_model +from openhands.sdk.llm import ImageContent, TextContent +from openhands.sdk.tool.security_prompt import ( + SECURITY_RISK_DESC, + SECURITY_RISK_LITERAL, +) -if TYPE_CHECKING: - from openhands.sdk.llm import ImageContent, TextContent S = TypeVar("S", bound="Schema") @@ -131,7 +134,9 @@ def from_mcp_schema( class ActionBase(Schema): """Base schema for input action.""" - pass + security_risk: SECURITY_RISK_LITERAL = Field( + default="UNKNOWN", description=SECURITY_RISK_DESC, exclude=True + ) class ObservationBase(Schema): diff --git a/openhands/tools/utils/security_prompt.py b/openhands/sdk/tool/security_prompt.py similarity index 61% rename from openhands/tools/utils/security_prompt.py rename to openhands/sdk/tool/security_prompt.py index 7467ac24187..2121f8f6283 100644 --- a/openhands/tools/utils/security_prompt.py +++ b/openhands/sdk/tool/security_prompt.py @@ -2,4 +2,4 @@ SECURITY_RISK_DESC = "The LLM's assessment of the safety risk of this action." -SECURITY_RISK_LITERAL = Literal["LOW", "MEDIUM", "HIGH"] +SECURITY_RISK_LITERAL = Literal["LOW", "MEDIUM", "HIGH", "UNKNOWN"] diff --git a/openhands/tools/execute_bash/definition.py b/openhands/tools/execute_bash/definition.py index 707a7d81869..0780fafc774 100644 --- a/openhands/tools/execute_bash/definition.py +++ b/openhands/tools/execute_bash/definition.py @@ -9,10 +9,6 @@ from openhands.sdk.tool import ActionBase, ObservationBase, Tool, ToolAnnotations from openhands.tools.execute_bash.constants import NO_CHANGE_TIMEOUT_SECONDS from openhands.tools.execute_bash.metadata import CmdOutputMetadata -from openhands.tools.utils.security_prompt import ( - SECURITY_RISK_DESC, - SECURITY_RISK_LITERAL, -) if TYPE_CHECKING: @@ -33,7 +29,6 @@ class ExecuteBashAction(ActionBase): default=None, description=f"Optional. Sets a maximum time limit (in seconds) for running the command. If the command takes longer than this limit, you’ll be asked whether to continue or stop it. If you don’t set a value, the command will instead pause and ask for confirmation when it produces no new output for {NO_CHANGE_TIMEOUT_SECONDS} seconds. Use a higher value if the command is expected to take a long time (like installation or testing), or if it has a known fixed duration (like sleep).", # noqa ) - security_risk: SECURITY_RISK_LITERAL = Field(description=SECURITY_RISK_DESC) class ExecuteBashObservation(ObservationBase): diff --git a/openhands/tools/str_replace_editor/definition.py b/openhands/tools/str_replace_editor/definition.py index c64facefdbb..b4b7b0413fb 100644 --- a/openhands/tools/str_replace_editor/definition.py +++ b/openhands/tools/str_replace_editor/definition.py @@ -6,10 +6,6 @@ from openhands.sdk.llm import ImageContent, TextContent from openhands.sdk.tool import ActionBase, ObservationBase, Tool, ToolAnnotations -from openhands.tools.utils.security_prompt import ( - SECURITY_RISK_DESC, - SECURITY_RISK_LITERAL, -) CommandLiteral = Literal["view", "create", "str_replace", "insert", "undo_edit"] @@ -55,7 +51,6 @@ class StrReplaceEditorAction(ActionBase): "show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, " "-1]` shows all lines from `start_line` to the end of the file.", ) - security_risk: SECURITY_RISK_LITERAL = Field(description=SECURITY_RISK_DESC) class StrReplaceEditorObservation(ObservationBase): From 0a4aaba810ab025fc6c126ad02063b3feb1d4658 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 12:33:51 -0400 Subject: [PATCH 15/28] refactor of MCP to keep MCPClient from fastmcp --- examples/7_mcp_integration.py | 34 +--- openhands/sdk/__init__.py | 3 +- openhands/sdk/mcp/__init__.py | 15 +- openhands/sdk/mcp/client.py | 308 ++++++++--------------------- openhands/sdk/mcp/definition.py | 69 +++++++ openhands/sdk/mcp/tool.py | 203 ++++++------------- openhands/sdk/mcp/utils.py | 125 ++++-------- openhands/sdk/utils/async_utils.py | 122 ------------ 8 files changed, 267 insertions(+), 612 deletions(-) create mode 100644 openhands/sdk/mcp/definition.py delete mode 100644 openhands/sdk/utils/async_utils.py diff --git a/examples/7_mcp_integration.py b/examples/7_mcp_integration.py index 577ef39e2e0..e3988ad85ae 100644 --- a/examples/7_mcp_integration.py +++ b/examples/7_mcp_integration.py @@ -11,10 +11,9 @@ Message, TextContent, Tool, + create_mcp_tools, get_logger, ) -from openhands.sdk.config.mcp_config import MCPConfig, MCPStdioServerConfig -from openhands.sdk.mcp.utils import create_mcp_tools_from_config from openhands.tools import BashTool, FileEditorTool @@ -29,34 +28,20 @@ api_key=SecretStr(api_key), ) -# Configure MCP servers -mcp_config = MCPConfig( - stdio_servers=[ - MCPStdioServerConfig( - name="fetch", - command="uvx", - args=["mcp-server-fetch"], - ) - ] -) - -# Tools cwd = os.getcwd() tools: list[Tool] = [ BashTool(working_dir=cwd), FileEditorTool(), ] -# Add MCP tools if available -try: - mcp_tools = create_mcp_tools_from_config(mcp_config, timeout=10.0) - tools.extend(mcp_tools) - logger.info(f"Added {len(mcp_tools)} MCP tools") - for tool in mcp_tools: - logger.info(f" - {tool.name}: {tool.description}") -except Exception as e: - logger.warning(f"Failed to load MCP tools: {e}") - logger.info("Continuing with standard tools only") +# Add MCP Tools +mcp_config = {"mcpServers": {"fetch": {"command": "uvx", "args": ["mcp-server-fetch"]}}} +mcp_tools = create_mcp_tools(mcp_config, timeout=30) +tools.extend(mcp_tools) +logger.info(f"Added {len(mcp_tools)} MCP tools") +for tool in mcp_tools: + logger.info(f" - {tool.name}: {tool.description}") + # Agent agent = Agent(llm=llm, tools=tools) @@ -65,7 +50,6 @@ def conversation_callback(event: EventType): - logger.info(f"Found a conversation message: {str(event)[:200]}...") if isinstance(event, LLMConvertibleEvent): llm_messages.append(event.to_llm_message()) diff --git a/openhands/sdk/__init__.py b/openhands/sdk/__init__.py index d8eace03308..c3c99680637 100644 --- a/openhands/sdk/__init__.py +++ b/openhands/sdk/__init__.py @@ -13,7 +13,7 @@ TextContent, ) from openhands.sdk.logger import get_logger -from openhands.sdk.mcp import MCPTool, create_mcp_tools +from openhands.sdk.mcp import MCPClient, MCPTool, create_mcp_tools from openhands.sdk.tool import ActionBase, ObservationBase, Tool @@ -34,6 +34,7 @@ "Agent", "ActionBase", "ObservationBase", + "MCPClient", "MCPTool", "create_mcp_tools", "get_logger", diff --git a/openhands/sdk/mcp/__init__.py b/openhands/sdk/mcp/__init__.py index a7c68ed3e0c..04c1466b0cc 100644 --- a/openhands/sdk/mcp/__init__.py +++ b/openhands/sdk/mcp/__init__.py @@ -1,29 +1,20 @@ """MCP (Model Context Protocol) integration for agent-sdk.""" from openhands.sdk.mcp.client import MCPClient +from openhands.sdk.mcp.definition import MCPToolObservation from openhands.sdk.mcp.tool import ( MCPTool, - MCPToolAction, MCPToolExecutor, - MCPToolObservation, - MCPToolRegistry, ) from openhands.sdk.mcp.utils import ( - create_mcp_client, - create_mcp_tools_from_config, + create_mcp_tools, ) __all__ = [ - # Client "MCPClient", - # Tools "MCPTool", - "MCPToolAction", "MCPToolObservation", "MCPToolExecutor", - "MCPToolRegistry", - # Utilities - "create_mcp_client", - "create_mcp_tools_from_config", + "create_mcp_tools", ] diff --git a/openhands/sdk/mcp/client.py b/openhands/sdk/mcp/client.py index 4d932c3f0d3..66ba7f019e7 100644 --- a/openhands/sdk/mcp/client.py +++ b/openhands/sdk/mcp/client.py @@ -1,255 +1,113 @@ -"""MCP Client implementation.""" +"""Minimal sync helpers on top of fastmcp.Client, preserving original behavior.""" import asyncio +import inspect import threading -from typing import Optional +from typing import Any, Callable -from fastmcp import Client -from fastmcp.client.transports import ( - SSETransport, - StdioTransport, - StreamableHttpTransport, -) -from mcp import McpError -from mcp.types import CallToolResult, Tool as MCPTool -from pydantic import BaseModel, ConfigDict, Field, PrivateAttr +from fastmcp import Client as AsyncMCPClient -from openhands.sdk.config.mcp_config import ( - MCPSHTTPServerConfig, - MCPSSEServerConfig, - MCPStdioServerConfig, -) -from openhands.sdk.logger import get_logger - -logger = get_logger(__name__) - - -class MCPClient(BaseModel): - """MCP client that connects to servers and manages available tools. - - This client provides a synchronous API while managing async operations internally - using a dedicated event loop in a background thread. +class MCPClient(AsyncMCPClient): + """ + Behaves exactly like fastmcp.Client (same constructor & async API), + but owns a background event loop and offers: + - call_async_from_sync(awaitable_or_fn, *args, timeout=None, **kwargs) + - call_sync_from_async(fn, *args, **kwargs) # await this from async code """ - model_config = ConfigDict(arbitrary_types_allowed=True) - - tools: list[MCPTool] = Field(default_factory=list) - tool_map: dict[str, MCPTool] = Field(default_factory=dict) - server_config: Optional[ - MCPSSEServerConfig | MCPSHTTPServerConfig | MCPStdioServerConfig - ] = Field(default=None) - - # Connection parameters for recreating clients - _timeout: float = Field(default=30.0, exclude=True) - _conversation_id: Optional[str] = Field(default=None, exclude=True) - - # Private attributes - these don't get serialized - _timeout: float = PrivateAttr(default=30.0) - _conversation_id: Optional[str] = PrivateAttr(default=None) - _loop: Optional[asyncio.AbstractEventLoop] = PrivateAttr(default=None) - _thread: Optional[threading.Thread] = PrivateAttr(default=None) - _loop_lock: threading.Lock = PrivateAttr(default_factory=threading.Lock) - - def _create_stdio_client(self) -> Client: - """Create a new stdio client using stored server config.""" - if not isinstance(self.server_config, MCPStdioServerConfig): - raise RuntimeError("Server config is not for stdio transport") - - transport = StdioTransport( - command=self.server_config.command, - args=self.server_config.args or [], - env=self.server_config.env, - ) - return Client(transport, timeout=self._timeout) - - def _create_http_client(self) -> Client: - """Create a new HTTP client using stored server config.""" - if not isinstance( - self.server_config, (MCPSSEServerConfig, MCPSHTTPServerConfig) - ): - raise RuntimeError("Server config is not for HTTP transport") - - server_url = self.server_config.url - api_key = self.server_config.api_key - - if not server_url: - raise ValueError("Server URL is required.") - - headers = ( - { - "Authorization": f"Bearer {api_key}", - "s": api_key, # For action execution server's MCP Router - "X-Session-API-Key": api_key, # For Remote Runtime - } - if api_key - else {} - ) - - if self._conversation_id: - headers["X-OpenHands-ServerConversation-ID"] = self._conversation_id - - # Instantiate custom transports due to custom headers - if isinstance(self.server_config, MCPSHTTPServerConfig): - transport = StreamableHttpTransport( - url=server_url, - headers=headers if headers else None, - ) - else: - transport = SSETransport( - url=server_url, - headers=headers if headers else None, - ) - - return Client(transport, timeout=self._timeout) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._loop: asyncio.AbstractEventLoop | None = None + self._thread: threading.Thread | None = None + self._lock = threading.Lock() - def connect_http( - self, - server: MCPSSEServerConfig | MCPSHTTPServerConfig, - conversation_id: str | None = None, - timeout: float = 30.0, - ) -> None: - """Connect to MCP server using SHTTP or SSE transport.""" - server_url = server.url + # ---------- loop management ---------- - if not server_url: - raise ValueError("Server URL is required.") + def _ensure_loop(self) -> asyncio.AbstractEventLoop: + with self._lock: + if self._loop is not None: + return self._loop - try: - # Store connection parameters - self.server_config = server - self._timeout = timeout - self._conversation_id = conversation_id - - # Initialize tools using async method - self._run_async(self._initialize_and_list_tools_async()) - except McpError as e: - error_msg = f"McpError connecting to {server_url}: {e}" - logger.error(error_msg) - raise - except Exception as e: - error_msg = f"Error connecting to {server_url}: {e}" - logger.error(error_msg) - raise - - def connect_stdio( - self, server: MCPStdioServerConfig, timeout: float = 30.0 - ) -> None: - """Connect to MCP server using stdio transport.""" - try: - # Store connection parameters - self.server_config = server - self._timeout = timeout - - # Initialize tools using async method - self._run_async(self._initialize_and_list_tools_async()) - except Exception as e: - server_name = getattr( - server, "name", f"{server.command} {' '.join(server.args or [])}" - ) - error_msg = f"Failed to connect to stdio server {server_name}: {e}" - logger.error(error_msg) - raise - - def call_tool(self, tool_name: str, args: dict) -> CallToolResult: - """Call a tool on the MCP server.""" - return self._run_async(self._call_tool_async(tool_name, args)) - - async def _initialize_and_list_tools_async(self) -> None: - """Initialize session and populate tool map (async version).""" - # Create client for tool listing - if isinstance(self.server_config, MCPStdioServerConfig): - client = self._create_stdio_client() - else: - client = self._create_http_client() + loop = asyncio.new_event_loop() - async with client: - tools = await client.list_tools() + def _runner(): + asyncio.set_event_loop(loop) + loop.run_forever() - # Clear existing tools - self.tools = [] - self.tool_map = {} + t = threading.Thread(target=_runner, daemon=True) + t.start() + while not loop.is_running(): + pass - # Store tools directly as MCP Tool objects - for tool in tools: - self.tool_map[tool.name] = tool - self.tools.append(tool) + self._loop = loop + self._thread = t + return loop - logger.info(f"Connected to server with tools: {[tool.name for tool in tools]}") + def _shutdown_loop(self) -> None: + with self._lock: + loop, t = self._loop, self._thread + self._loop = None + self._thread = None - async def _call_tool_async(self, tool_name: str, args: dict) -> CallToolResult: - """Call a tool on the MCP server (async version).""" - if tool_name not in self.tool_map: - raise ValueError(f"Tool {tool_name} not found.") + if loop and loop.is_running(): + try: + loop.call_soon_threadsafe(loop.stop) + except RuntimeError: + pass + if t and t.is_alive(): + t.join(timeout=1.0) - if not self.server_config: - raise RuntimeError("Server config is not available.") + # ---------- public helpers ---------- - # Recreate client for each tool call - if isinstance(self.server_config, MCPStdioServerConfig): - fresh_client = self._create_stdio_client() + def call_async_from_sync( + self, + awaitable_or_fn: Callable[..., Any] | Any, + *args, + timeout: float, + **kwargs, + ): + """ + Run a coroutine or async function on this client's loop from sync code. + + Usage: + mcp.call_async_from_sync(async_fn, arg1, kw=...) + mcp.call_async_from_sync(coro) + """ + if inspect.iscoroutine(awaitable_or_fn): + coro = awaitable_or_fn + elif inspect.iscoroutinefunction(awaitable_or_fn): + coro = awaitable_or_fn(*args, **kwargs) else: - fresh_client = self._create_http_client() - - async with fresh_client: - return await fresh_client.call_tool_mcp(name=tool_name, arguments=args) - - def _start_event_loop(self) -> None: - """Start the background event loop for async operations.""" - if self._loop is not None: - return # Already started + raise TypeError( + "call_async_from_sync expects a coroutine or async function" + ) - def run_loop(): - self._loop = asyncio.new_event_loop() - asyncio.set_event_loop(self._loop) - self._loop.run_forever() + loop = self._ensure_loop() + fut = asyncio.run_coroutine_threadsafe(coro, loop) + return fut.result(timeout) - self._thread = threading.Thread(target=run_loop, daemon=True) - self._thread.start() + async def call_sync_from_async(self, fn: Callable[..., Any], *args, **kwargs): + """ + Await running a blocking function in the default threadpool from async code. + """ + loop = asyncio.get_running_loop() + return await loop.run_in_executor(None, lambda: fn(*args, **kwargs)) - # Wait for loop to be ready - while self._loop is None: - threading.Event().wait(0.01) + # ---------- optional cleanup ---------- - def _stop_event_loop(self) -> None: - """Stop the background event loop.""" - if self._loop is not None and not self._loop.is_closed(): + def sync_close(self): + # Best-effort: try async close if parent provides it + aclose = self.close + if inspect.iscoroutinefunction(aclose): try: - self._loop.call_soon_threadsafe(self._loop.stop) - except RuntimeError: - # Loop might already be stopped/closed + self.call_async_from_sync(aclose, timeout=10.0) + except Exception: pass - - if self._thread is not None and self._thread.is_alive(): - self._thread.join(timeout=1.0) - - self._loop = None - self._thread = None - - def _run_async(self, coro): - """Run an async coroutine in the managed event loop.""" - with self._loop_lock: - if self._loop is None: - self._start_event_loop() - loop = self._loop - - assert loop is not None - try: - future = asyncio.run_coroutine_threadsafe(coro, loop) - return future.result() - except Exception as e: - # Add context about which operation failed - raise RuntimeError(f"MCP async operation failed: {e}") from e + self._shutdown_loop() def __del__(self): - """Ensure cleanup on garbage collection.""" try: - if hasattr(self, "_loop") and self._loop is not None: - self._stop_event_loop() + self.sync_close() except Exception: - # Ignore errors during cleanup in __del__ pass - - def close(self): - """Explicit cleanup method for proper resource management.""" - self._stop_event_loop() diff --git a/openhands/sdk/mcp/definition.py b/openhands/sdk/mcp/definition.py new file mode 100644 index 00000000000..514a3f2e08c --- /dev/null +++ b/openhands/sdk/mcp/definition.py @@ -0,0 +1,69 @@ +"""MCPTool definition and implementation.""" + +import mcp.types +from pydantic import Field + +from openhands.sdk.llm import ImageContent, TextContent +from openhands.sdk.logger import get_logger +from openhands.sdk.tool import ( + ObservationBase, +) + + +logger = get_logger(__name__) + + +# NOTE: We don't define MCPToolAction because it +# will be dynamically created from the MCP tool schema. + + +class MCPToolObservation(ObservationBase): + """Observation from MCP tool execution.""" + + content: list[TextContent | ImageContent] = Field( + default_factory=list, + description="Content returned from the MCP tool converted " + "to LLM Ready TextContent or ImageContent", + ) + is_error: bool = Field( + default=False, description="Whether the call resulted in an error" + ) + tool_name: str = Field(description="Name of the tool that was called") + + @classmethod + def from_call_tool_result( + cls, tool_name: str, result: mcp.types.CallToolResult + ) -> "MCPToolObservation": + """Create an MCPToolObservation from a CallToolResult.""" + content: list[mcp.types.ContentBlock] = result.content + convrted_content = [] + for block in content: + if isinstance(block, mcp.types.TextContent): + convrted_content.append(TextContent(text=block.text)) + elif isinstance(block, mcp.types.ImageContent): + convrted_content.append( + ImageContent( + image_urls=[f"data:{block.mimeType};base64,{block.data}"], + # ImageContent is inherited from mcp.types.ImageContent + # so we need to pass these fields + data=block.data, + mimeType=block.mimeType, + ) + ) + else: + logger.warning( + f"Unsupported MCP content block type: {type(block)}. Ignoring." + ) + return cls( + content=convrted_content, + is_error=result.isError, + tool_name=tool_name, + ) + + @property + def agent_observation(self) -> list[TextContent | ImageContent]: + """Format the observation for agent display.""" + initial_message = f"[Tool '{self.tool_name}' executed.]\n" + if self.is_error: + initial_message += "[An error occurred during execution.]" + return [TextContent(text=initial_message)] + self.content diff --git a/openhands/sdk/mcp/tool.py b/openhands/sdk/mcp/tool.py index 2039dadf98c..bbb05e9701b 100644 --- a/openhands/sdk/mcp/tool.py +++ b/openhands/sdk/mcp/tool.py @@ -1,163 +1,86 @@ -"""MCPTool definition and implementation.""" +"""Utility functions for MCP integration.""" -from typing import Any +import traceback +from typing import TYPE_CHECKING -from pydantic import Field +import mcp.types +from openhands.sdk.llm import TextContent from openhands.sdk.logger import get_logger -from openhands.sdk.mcp.client import MCPClient -from openhands.sdk.tool import ( - ActionBase, - ObservationBase, - Tool, - ToolAnnotations, - ToolExecutor, -) +from openhands.sdk.mcp import MCPToolObservation +from openhands.sdk.tool import ActionBase, Tool, ToolAnnotations, ToolExecutor -logger = get_logger(__name__) - - -class MCPToolAction(ActionBase): - """Action for calling MCP tools.""" +if TYPE_CHECKING: + from openhands.sdk.mcp.client import MCPClient - tool_name: str = Field(description="Name of the MCP tool to call") - arguments: dict[str, Any] = Field( - default_factory=dict, description="Arguments to pass to the MCP tool" - ) - - -class MCPToolObservation(ObservationBase): - """Observation from MCP tool execution.""" +logger = get_logger(__name__) - content: dict[str, Any] = Field( - default_factory=dict, description="Content returned from the MCP tool" - ) - is_error: bool = Field( - default=False, description="Whether the call resulted in an error" - ) - error_message: str | None = Field( - default=None, description="Error message if the call failed" - ) - tool_name: str = Field(description="Name of the tool that was called") - @property - def agent_observation(self) -> str: - """Format the observation for agent display.""" - if self.is_error: - return f"Error calling tool {self.tool_name}: {self.error_message}" - else: - ret = f"[Tool {self.tool_name} returned]\n" - for k, v in self.content.items(): - ret += f"\n" - ret += str(v) + "\n" - ret += "\n" - return ret +# NOTE: We don't define MCPToolAction because it +# will be a pydantic BaseModel dynamically created from the MCP tool schema. +# It will be available as "tool.action_type". class MCPToolExecutor(ToolExecutor): """Executor for MCP tools.""" - def __init__(self, mcp_client: MCPClient): - self.mcp_client = mcp_client - - def __call__(self, action: MCPToolAction) -> MCPToolObservation: + def __init__(self, tool_name: str, client: "MCPClient"): + self.tool_name = tool_name + self.client = client + + async def call_tool(self, action: ActionBase) -> MCPToolObservation: + async with self.client: + assert self.client.is_connected(), "MCP client is not connected." + try: + logger.debug( + f"Calling MCP tool {self.tool_name} " + f"with args: {action.model_dump()}" + ) + result: mcp.types.CallToolResult = await self.client.call_tool_mcp( + name=self.tool_name, arguments=action.model_dump() + ) + return MCPToolObservation.from_call_tool_result( + tool_name=self.tool_name, result=result + ) + except Exception as e: + traceback_str = traceback.format_exc() + error_msg = ( + f"Error calling MCP tool {self.tool_name}" + f": {str(e)}\n{traceback_str}" + ) + logger.error(error_msg) + return MCPToolObservation( + content=[TextContent(text=error_msg)], + is_error=True, + tool_name=self.tool_name, + ) + + def __call__(self, action: ActionBase) -> MCPToolObservation: """Execute an MCP tool call.""" - try: - result = self.mcp_client.call_tool(action.tool_name, action.arguments) - - return MCPToolObservation( - content=result.model_dump(mode="json"), - is_error=result.isError, - tool_name=action.tool_name, - ) - - except Exception as e: - error_msg = f"Error calling MCP tool {action.tool_name}: {str(e)}" - logger.error(error_msg) - - return MCPToolObservation( - is_error=True, - error_message=error_msg, - tool_name=action.tool_name, - ) + return self.client.call_async_from_sync( + self.call_tool, action=action, timeout=60.0 + ) -class MCPTool(Tool[MCPToolAction, MCPToolObservation]): +class MCPTool(Tool[ActionBase, MCPToolObservation]): """MCP Tool that wraps an MCP client and provides tool functionality.""" - def __init__(self, mcp_client: MCPClient, tool_name: str): - """Initialize MCPTool with an MCP client and specific tool name. - - Args: - mcp_client: The MCP client to use for tool calls - tool_name: Name of the specific MCP tool to wrap - """ - if tool_name not in mcp_client.tool_map: - raise ValueError(f"Tool {tool_name} not found in MCP client") - - mcp_tool = mcp_client.tool_map[tool_name] - - # Create executor - executor = MCPToolExecutor(mcp_client) - - # Initialize the parent Tool + def __init__( + self, + mcp_tool: mcp.types.Tool, + mcp_client: "MCPClient", + ): + self.mcp_client = mcp_client + self.mcp_tool = mcp_tool super().__init__( - name=tool_name, + name=mcp_tool.name, description=mcp_tool.description or "No description provided", - input_schema=MCPToolAction, + input_schema=mcp_tool.inputSchema, output_schema=MCPToolObservation, - annotations=ToolAnnotations( - title=tool_name, - readOnlyHint=False, # MCP tools can be read-only or not - destructiveHint=True, # Conservative default - idempotentHint=False, # Conservative default - openWorldHint=True, # MCP tools often interact with external systems - ), - executor=executor, + annotations=ToolAnnotations.model_validate(mcp_tool.annotations) + if mcp_tool.annotations + else None, + _meta=mcp_tool.meta, + executor=MCPToolExecutor(tool_name=mcp_tool.name, client=mcp_client), ) - - self.mcp_client = mcp_client - self.mcp_tool = mcp_tool - - def to_mcp_tool(self) -> dict[str, Any]: - """Convert to MCP tool format using the original MCP tool schema.""" - return { - "name": self.mcp_tool.name, - "description": self.mcp_tool.description, - "inputSchema": self.mcp_tool.inputSchema, - } - - -class MCPToolRegistry: - """Registry for managing MCP tools from multiple clients.""" - - def __init__(self): - self.clients: dict[str, MCPClient] = {} - self.tools: dict[str, MCPTool] = {} - - def add_client(self, name: str, client: MCPClient) -> None: - """Add an MCP client to the registry.""" - self.clients[name] = client - - # Create tools for all available tools in the client - for tool_name in client.tool_map: - # Use client_name:tool_name as the key to avoid conflicts - full_tool_name = f"{name}:{tool_name}" - self.tools[full_tool_name] = MCPTool(client, tool_name) - - def get_tool(self, tool_name: str) -> MCPTool | None: - """Get a tool by name.""" - return self.tools.get(tool_name) - - def get_all_tools(self) -> list[MCPTool]: - """Get all registered MCP tools.""" - return list(self.tools.values()) - - def get_tools_for_client(self, client_name: str) -> list[MCPTool]: - """Get all tools for a specific client.""" - return [ - tool - for name, tool in self.tools.items() - if name.startswith(f"{client_name}:") - ] diff --git a/openhands/sdk/mcp/utils.py b/openhands/sdk/mcp/utils.py index e1b629b821b..f0c756b5d14 100644 --- a/openhands/sdk/mcp/utils.py +++ b/openhands/sdk/mcp/utils.py @@ -1,108 +1,59 @@ """Utility functions for MCP integration.""" -from openhands.sdk.config.mcp_config import ( - MCPConfig, - MCPSHTTPServerConfig, - MCPSSEServerConfig, - MCPStdioServerConfig, -) +import logging + +import mcp.types +from fastmcp.client.logging import LogMessage +from fastmcp.mcp_config import MCPConfig + from openhands.sdk.logger import get_logger -from openhands.sdk.mcp.client import MCPClient -from openhands.sdk.mcp.tool import MCPToolRegistry +from openhands.sdk.mcp import MCPClient, MCPTool from openhands.sdk.tool import Tool logger = get_logger(__name__) +LOGGING_LEVEL_MAP = logging.getLevelNamesMapping() -def create_mcp_client( - server_config: MCPSSEServerConfig | MCPSHTTPServerConfig | MCPStdioServerConfig, - conversation_id: str | None = None, - timeout: float = 30.0, -) -> MCPClient: - """Create and connect an MCP client from server configuration. +async def log_handler(message: LogMessage): + """ + Handles incoming logs from the MCP server and forwards them + to the standard Python logging system. + """ + msg = message.data.get("msg") + extra = message.data.get("extra") - Args: - server_config: MCP server configuration - conversation_id: Optional conversation ID for HTTP-based servers - timeout: Connection timeout in seconds + # Convert the MCP log level to a Python log level + level = LOGGING_LEVEL_MAP.get(message.level.upper(), logging.INFO) - Returns: - Connected MCP client + # Log the message using the standard logging library + logger.log(level, msg, extra=extra) - Raises: - Exception: If connection fails - """ - client = MCPClient() - if isinstance(server_config, (MCPSSEServerConfig, MCPSHTTPServerConfig)): - client.connect_http(server_config, conversation_id, timeout) - elif isinstance(server_config, MCPStdioServerConfig): - client.connect_stdio(server_config, timeout) - else: - raise ValueError(f"Unsupported server config type: {type(server_config)}") +async def _list_tools(client: MCPClient) -> list[Tool]: + """List tools from an MCP client.""" + tools: list[Tool] = [] - return client + async with client: + assert client.is_connected(), "MCP client is not connected." + mcp_type_tools: list[mcp.types.Tool] = await client.list_tools() + tools = [MCPTool(mcp_tool=t, mcp_client=client) for t in mcp_type_tools] + assert not client.is_connected(), ( + "MCP client should be disconnected after listing tools." + ) + return tools -def create_mcp_tools_from_config( - mcp_config: MCPConfig, - conversation_id: str | None = None, +def create_mcp_tools( + config: dict | MCPConfig, timeout: float = 30.0, ) -> list[Tool]: - """Create MCP tools from MCP configuration. - - Args: - mcp_config: MCP configuration containing server definitions - conversation_id: Optional conversation ID for HTTP-based servers - timeout: Connection timeout in seconds - - Returns: - List of MCP tools ready to use with agents - - Raises: - Exception: If any server connection fails - """ + """Create MCP tools from MCP configuration.""" tools: list[Tool] = [] - registry = MCPToolRegistry() - - # Process SSE servers - for server_config in mcp_config.sse_servers: - try: - client = create_mcp_client(server_config, conversation_id, timeout) - server_name = getattr(server_config, "name", server_config.url) - registry.add_client(server_name, client) - logger.info(f"Connected to SSE server: {server_name}") - except Exception as e: - logger.error(f"Failed to connect to SSE server {server_config.url}: {e}") - # Continue with other servers instead of failing completely - - # Process SHTTP servers - for server_config in mcp_config.shttp_servers: - try: - client = create_mcp_client(server_config, conversation_id, timeout) - server_name = getattr(server_config, "name", server_config.url) - registry.add_client(server_name, client) - logger.info(f"Connected to SHTTP server: {server_name}") - except Exception as e: - logger.error(f"Failed to connect to SHTTP server {server_config.url}: {e}") - # Continue with other servers instead of failing completely - - # Process stdio servers - for server_config in mcp_config.stdio_servers: - try: - client = create_mcp_client(server_config, conversation_id, timeout) - server_name = getattr(server_config, "name", server_config.command) - registry.add_client(server_name, client) - logger.info(f"Connected to stdio server: {server_name}") - except Exception as e: - logger.error( - f"Failed to connect to stdio server {server_config.command}: {e}" - ) - # Continue with other servers instead of failing completely - - # Convert all MCP tools to agent-sdk tools - tools.extend(registry.get_all_tools()) + if isinstance(config, dict): + config = MCPConfig.model_validate(config) + client = MCPClient(config, log_handler=log_handler) + tools = client.call_async_from_sync(_list_tools, timeout=timeout, client=client) - logger.info(f"Created {len(tools)} MCP tools from {len(registry.clients)} servers") + logger.info(f"Created {len(tools)} MCP tools: {[t.name for t in tools]}") return tools diff --git a/openhands/sdk/utils/async_utils.py b/openhands/sdk/utils/async_utils.py deleted file mode 100644 index 4d1827fb86d..00000000000 --- a/openhands/sdk/utils/async_utils.py +++ /dev/null @@ -1,122 +0,0 @@ -import asyncio -from concurrent import futures -from concurrent.futures import ThreadPoolExecutor -from typing import Callable, Coroutine, Iterable - - -GENERAL_TIMEOUT: int = 15 -EXECUTOR = ThreadPoolExecutor() - - -async def call_sync_from_async(fn: Callable, *args, **kwargs): - """Shorthand for running a function in the default background thread pool executor - and awaiting the result. The nature of synchronous code is that the future - returned by this function is not cancellable - """ - loop = asyncio.get_event_loop() - coro = loop.run_in_executor(None, lambda: fn(*args, **kwargs)) - result = await coro - return result - - -def call_async_from_sync( - corofn: Callable, timeout: float = GENERAL_TIMEOUT, *args, **kwargs -): - """Shorthand for running a coroutine in the default background thread pool executor - and awaiting the result - """ - if corofn is None: - raise ValueError("corofn is None") - if not asyncio.iscoroutinefunction(corofn): - raise ValueError("corofn is not a coroutine function") - - async def arun(): - coro = corofn(*args, **kwargs) - result = await coro - return result - - def run(): - loop_for_thread = asyncio.new_event_loop() - try: - asyncio.set_event_loop(loop_for_thread) - return asyncio.run(arun()) - finally: - loop_for_thread.close() - - if getattr(EXECUTOR, "_shutdown", False): - result = run() - return result - - future = EXECUTOR.submit(run) - futures.wait([future], timeout=timeout or None) - result = future.result() - return result - - -async def call_coro_in_bg_thread( - corofn: Callable, timeout: float = GENERAL_TIMEOUT, *args, **kwargs -): - """Function for running a coroutine in a background thread.""" - await call_sync_from_async(call_async_from_sync, corofn, timeout, *args, **kwargs) - - -async def wait_all( - iterable: Iterable[Coroutine], timeout: int = GENERAL_TIMEOUT -) -> list: - """Shorthand for waiting for all the coroutines in the iterable given in parallel. - - Creates a task for each coroutine. - Returns a list of results in the original order. - If any single task raised an exception, this is raised. - If multiple tasks raised exceptions, an AsyncException - is raised containing all exceptions. - """ - tasks = [asyncio.create_task(c) for c in iterable] - if not tasks: - return [] - _, pending = await asyncio.wait(tasks, timeout=timeout) - if pending: - for task in pending: - task.cancel() - raise asyncio.TimeoutError() - results = [] - errors = [] - for task in tasks: - try: - results.append(task.result()) - except Exception as e: - errors.append(e) - if errors: - if len(errors) == 1: - raise errors[0] - raise AsyncException(errors) - return [task.result() for task in tasks] - - -class AsyncException(Exception): - def __init__(self, exceptions): - self.exceptions = exceptions - - def __str__(self): - return "\n".join(str(e) for e in self.exceptions) - - -async def run_in_loop( - coro: Coroutine, loop: asyncio.AbstractEventLoop, timeout: float = GENERAL_TIMEOUT -): - """Mitigate the dreaded "coroutine was created in a different event loop" error. - Pass the coroutine to a different event loop if needed. - """ - running_loop = asyncio.get_running_loop() - if running_loop == loop: - result = await coro - return result - - result = await call_sync_from_async(_run_in_loop, coro, loop, timeout) - return result - - -def _run_in_loop(coro: Coroutine, loop: asyncio.AbstractEventLoop, timeout: float): - future = asyncio.run_coroutine_threadsafe(coro, loop) - result = future.result(timeout=timeout) - return result From 8cc48a5973dd006b8ec06e8b5db4e9ef7199a9de Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 12:44:14 -0400 Subject: [PATCH 16/28] finally got everything working! --- openhands/sdk/mcp/definition.py | 2 +- openhands/sdk/mcp/tool.py | 2 +- openhands/sdk/tool/builtins/finish.py | 5 +++-- openhands/sdk/tool/schema.py | 29 ++++++++++++++++++++------- 4 files changed, 27 insertions(+), 11 deletions(-) diff --git a/openhands/sdk/mcp/definition.py b/openhands/sdk/mcp/definition.py index 514a3f2e08c..52ff4a8bd9a 100644 --- a/openhands/sdk/mcp/definition.py +++ b/openhands/sdk/mcp/definition.py @@ -65,5 +65,5 @@ def agent_observation(self) -> list[TextContent | ImageContent]: """Format the observation for agent display.""" initial_message = f"[Tool '{self.tool_name}' executed.]\n" if self.is_error: - initial_message += "[An error occurred during execution.]" + initial_message += "[An error occurred during execution.]\n" return [TextContent(text=initial_message)] + self.content diff --git a/openhands/sdk/mcp/tool.py b/openhands/sdk/mcp/tool.py index bbb05e9701b..cf3105baec5 100644 --- a/openhands/sdk/mcp/tool.py +++ b/openhands/sdk/mcp/tool.py @@ -38,7 +38,7 @@ async def call_tool(self, action: ActionBase) -> MCPToolObservation: f"with args: {action.model_dump()}" ) result: mcp.types.CallToolResult = await self.client.call_tool_mcp( - name=self.tool_name, arguments=action.model_dump() + name=self.tool_name, arguments=action.model_dump(exclude_none=True) ) return MCPToolObservation.from_call_tool_result( tool_name=self.tool_name, result=result diff --git a/openhands/sdk/tool/builtins/finish.py b/openhands/sdk/tool/builtins/finish.py index 7e932b76459..ae1bd3a59df 100644 --- a/openhands/sdk/tool/builtins/finish.py +++ b/openhands/sdk/tool/builtins/finish.py @@ -1,5 +1,6 @@ from pydantic import Field +from openhands.sdk.llm.message import ImageContent, TextContent from openhands.sdk.tool.tool import ( ActionBase, ObservationBase, @@ -17,8 +18,8 @@ class FinishObservation(ObservationBase): message: str = Field(description="Final message sent to the user.") @property - def agent_observation(self) -> str: - return self.message + def agent_observation(self) -> list[TextContent | ImageContent]: + return [TextContent(text=self.message)] TOOL_DESCRIPTION = """Signals the completion of the current task or conversation. diff --git a/openhands/sdk/tool/schema.py b/openhands/sdk/tool/schema.py index 5688c5dee8e..962f6153579 100644 --- a/openhands/sdk/tool/schema.py +++ b/openhands/sdk/tool/schema.py @@ -108,7 +108,11 @@ def to_mcp_schema(cls) -> dict[str, Any]: def from_mcp_schema( cls: type[S], model_name: str, schema: dict[str, Any] ) -> type["S"]: - """Create a Schema subclass from an MCP/JSON Schema object.""" + """Create a Schema subclass from an MCP/JSON Schema object. + + For non-required fields, we annotate as `T | None` + so explicit nulls are allowed. + """ assert isinstance(schema, dict), "Schema must be a dict" assert schema.get("type") == "object", "Only object schemas are supported" @@ -117,17 +121,28 @@ def from_mcp_schema( fields: dict[str, tuple] = {} for fname, spec in props.items(): - tp = py_type(spec if isinstance(spec, dict) else {}) - default = ... if fname in required else None - desc: str | None = ( - spec.get("description") if isinstance(spec, dict) else None - ) + spec = spec if isinstance(spec, dict) else {} + tp = py_type(spec) + + # Add description if present + desc: str | None = spec.get("description") + + # Required → bare type, ellipsis sentinel + # Optional → make nullable via `| None`, default None + if fname in required: + anno = tp + default = ... + else: + anno = tp | None # allow explicit null in addition to omission + default = None + fields[fname] = ( - tp, + anno, Field(default=default, description=desc) if desc else Field(default=default), ) + return create_model(model_name, __base__=cls, **fields) # type: ignore[return-value] From 4108ce918c4fa5c7d8d9ae32c51a6f64c83d726f Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 12:55:17 -0400 Subject: [PATCH 17/28] fix tests related to .agent_observation --- .../tools/execute_bash/test_bash_ps1_metadata.py | 15 ++++++++++----- tests/tools/execute_bash/test_bash_session.py | 10 +++++++--- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/tests/tools/execute_bash/test_bash_ps1_metadata.py b/tests/tools/execute_bash/test_bash_ps1_metadata.py index 00157181f5f..155602ebe5e 100644 --- a/tests/tools/execute_bash/test_bash_ps1_metadata.py +++ b/tests/tools/execute_bash/test_bash_ps1_metadata.py @@ -1,5 +1,6 @@ import json +from openhands.sdk import TextContent from openhands.tools.execute_bash.constants import ( CMD_OUTPUT_METADATA_PS1_REGEX, CMD_OUTPUT_PS1_BEGIN, @@ -277,10 +278,12 @@ def test_cmd_output_observation_properties(): assert obs.command_id == 123 assert obs.exit_code == 0 assert not obs.error - assert "exit code 0" in obs.agent_observation - assert "ls" not in obs.agent_observation - assert "file1\n" in obs.agent_observation - assert "file2\n" in obs.agent_observation + assert len(obs.agent_observation) == 1 + assert isinstance(obs.agent_observation[0], TextContent) + assert "exit code 0" in obs.agent_observation[0].text + assert "ls" not in obs.agent_observation[0].text + assert "file1\n" in obs.agent_observation[0].text + assert "file2\n" in obs.agent_observation[0].text # Test with failed command metadata = CmdOutputMetadata(exit_code=1, pid=456) @@ -290,7 +293,9 @@ def test_cmd_output_observation_properties(): assert obs.command_id == 456 assert obs.exit_code == 1 assert obs.error - assert "exit code 1" in obs.agent_observation + assert len(obs.agent_observation) == 1 + assert isinstance(obs.agent_observation[0], TextContent) + assert "exit code 1" in obs.agent_observation[0].text assert obs.error diff --git a/tests/tools/execute_bash/test_bash_session.py b/tests/tools/execute_bash/test_bash_session.py index 69a1c441633..3a4aaecec91 100644 --- a/tests/tools/execute_bash/test_bash_session.py +++ b/tests/tools/execute_bash/test_bash_session.py @@ -15,6 +15,7 @@ import pytest +from openhands.sdk import TextContent from openhands.sdk.logger import get_logger from openhands.tools.execute_bash.definition import ExecuteBashAction from openhands.tools.execute_bash.terminal import ( @@ -66,7 +67,6 @@ def test_cwd_property(tmp_path, terminal_type): # For other implementations, just verify the command executed successfully obs = session.execute(ExecuteBashAction(command="pwd", security_risk="LOW")) assert str(random_dir) in obs.output - print(obs.agent_observation) # Note: CWD tracking may vary between terminal implementations # For tmux, it should track properly. For subprocess, it may not. @@ -308,10 +308,14 @@ def test_empty_command_error(terminal_type): assert obs.error is True assert obs.output == "ERROR: No previous running command to retrieve logs from." - assert "There was an error during command execution." in obs.agent_observation + assert len(obs.agent_observation) == 1 + assert isinstance(obs.agent_observation[0], TextContent) + assert ( + "There was an error during command execution." in obs.agent_observation[0].text + ) assert ( "ERROR: No previous running command to retrieve logs from." - in obs.agent_observation + in obs.agent_observation[0].text ) assert obs.metadata.exit_code == -1 assert obs.metadata.prefix == "" From 581154ccfdad418cc60b19fb46c8403b5c403551 Mon Sep 17 00:00:00 2001 From: Hoang Tran Date: Fri, 5 Sep 2025 17:19:13 +0000 Subject: [PATCH 18/28] remove mcp config tests --- tests/sdk/config/test_mcp_config.py | 501 --------------------- tests/sdk/config/test_mcp_configs_merge.py | 273 ----------- 2 files changed, 774 deletions(-) delete mode 100644 tests/sdk/config/test_mcp_config.py delete mode 100644 tests/sdk/config/test_mcp_configs_merge.py diff --git a/tests/sdk/config/test_mcp_config.py b/tests/sdk/config/test_mcp_config.py deleted file mode 100644 index 6ef13f3d1f1..00000000000 --- a/tests/sdk/config/test_mcp_config.py +++ /dev/null @@ -1,501 +0,0 @@ -import pytest -from pydantic import ValidationError - -from openhands.sdk.config import MCPConfig -from openhands.sdk.config.mcp_config import ( - MCPSHTTPServerConfig, - MCPSSEServerConfig, - MCPStdioServerConfig, -) - - -def test_mcp_sse_server_config_basic(): - """Test basic MCPSSEServerConfig.""" - config = MCPSSEServerConfig(url="http://server1:8080") - assert config.url == "http://server1:8080" - assert config.api_key is None - - -def test_mcp_sse_server_config_with_api_key(): - """Test MCPSSEServerConfig with API key.""" - config = MCPSSEServerConfig(url="http://server1:8080", api_key="test-api-key") - assert config.url == "http://server1:8080" - assert config.api_key == "test-api-key" - - -def test_mcp_sse_server_config_invalid_url(): - """Test MCPSSEServerConfig with invalid URL format.""" - with pytest.raises(ValidationError) as exc_info: - MCPSSEServerConfig(url="not_a_url") - assert "URL must include a scheme" in str(exc_info.value) - - -def test_mcp_sse_server_config_empty_url(): - """Test MCPSSEServerConfig with empty URL.""" - with pytest.raises(ValidationError) as exc_info: - MCPSSEServerConfig(url="") - assert "URL cannot be empty" in str(exc_info.value) - - -def test_mcp_sse_server_config_valid_schemes(): - """Test MCPSSEServerConfig with various valid URL schemes.""" - valid_urls = [ - "http://server1:8080", - "https://server1:8080", - "ws://server1:8080", - "wss://server1:8080", - ] - - for url in valid_urls: - config = MCPSSEServerConfig(url=url) - assert config.url == url - - -def test_mcp_sse_server_config_invalid_schemes(): - """Test MCPSSEServerConfig with invalid URL schemes.""" - invalid_urls = [ - "ftp://server1:8080", - "file://server1:8080", - "tcp://server1:8080", - ] - - for url in invalid_urls: - with pytest.raises(ValidationError) as exc_info: - MCPSSEServerConfig(url=url) - assert "URL scheme must be http, https, ws, or wss" in str(exc_info.value) - - -def test_mcp_stdio_server_config_basic(): - """Test basic MCPStdioServerConfig.""" - config = MCPStdioServerConfig(name="test-server", command="python") - assert config.name == "test-server" - assert config.command == "python" - assert config.args == [] - assert config.env == {} - - -def test_mcp_stdio_server_config_with_args_and_env(): - """Test MCPStdioServerConfig with args and env.""" - config = MCPStdioServerConfig( - name="test-server", - command="python", - args=["-m", "server"], - env={"DEBUG": "true", "PORT": "8080"}, - ) - assert config.name == "test-server" - assert config.command == "python" - assert config.args == ["-m", "server"] - assert config.env == {"DEBUG": "true", "PORT": "8080"} - - -def test_mcp_stdio_server_config_invalid_name(): - """Test MCPStdioServerConfig with invalid server name.""" - with pytest.raises(ValidationError) as exc_info: - MCPStdioServerConfig(name="", command="python") - assert "Server name cannot be empty" in str(exc_info.value) - - with pytest.raises(ValidationError) as exc_info: - MCPStdioServerConfig(name="invalid name with spaces", command="python") - assert ( - "Server name can only contain letters, numbers, hyphens, and underscores" - in str(exc_info.value) - ) - - -def test_mcp_stdio_server_config_invalid_command(): - """Test MCPStdioServerConfig with invalid command.""" - with pytest.raises(ValidationError) as exc_info: - MCPStdioServerConfig(name="test-server", command="") - assert "Command cannot be empty" in str(exc_info.value) - - with pytest.raises(ValidationError) as exc_info: - MCPStdioServerConfig(name="test-server", command="python -m server") - assert "Command should be a single executable without spaces" in str(exc_info.value) - - -def test_mcp_stdio_server_config_args_parsing(): - """Test MCPStdioServerConfig args parsing from string.""" - # Test basic space-separated parsing - config = MCPStdioServerConfig( - name="test-server", - command="python", - args="arg1 arg2 arg3", # type: ignore - ) - assert config.args == ["arg1", "arg2", "arg3"] - - # Test single argument - config = MCPStdioServerConfig( - name="test-server", - command="python", - args="single-arg", # type: ignore - ) - assert config.args == ["single-arg"] - - # Test empty string - config = MCPStdioServerConfig( - name="test-server", - command="python", - args="", # type: ignore - ) - assert config.args == [] - - # Test quoted arguments - config = MCPStdioServerConfig( - name="test-server", - command="python", - args='--config "path with spaces" --debug', # type: ignore - ) - assert config.args == ["--config", "path with spaces", "--debug"] - - -def test_mcp_stdio_server_config_args_parsing_invalid_quotes(): - """Test MCPStdioServerConfig args parsing with invalid quotes.""" - with pytest.raises(ValidationError) as exc_info: - MCPStdioServerConfig( - name="test-server", - command="python", - args='--config "unmatched quote', # type: ignore - ) - assert "Invalid argument format" in str(exc_info.value) - - -def test_mcp_stdio_server_config_env_parsing(): - """Test MCPStdioServerConfig env parsing from string.""" - # Test basic env parsing - config = MCPStdioServerConfig( - name="test-server", - command="python", - env="DEBUG=true,PORT=8080", # type: ignore - ) - assert config.env == {"DEBUG": "true", "PORT": "8080"} - - # Test empty string - config = MCPStdioServerConfig( - name="test-server", - command="python", - env="", # type: ignore - ) - assert config.env == {} - - # Test single env var - config = MCPStdioServerConfig( - name="test-server", - command="python", - env="DEBUG=true", # type: ignore - ) - assert config.env == {"DEBUG": "true"} - - -def test_mcp_stdio_server_config_env_parsing_invalid(): - """Test MCPStdioServerConfig env parsing with invalid format.""" - with pytest.raises(ValidationError) as exc_info: - MCPStdioServerConfig( - name="test-server", - command="python", - env="INVALID_FORMAT", # type: ignore - ) - assert "must be in KEY=VALUE format" in str(exc_info.value) - - with pytest.raises(ValidationError) as exc_info: - MCPStdioServerConfig( - name="test-server", - command="python", - env="=value", # type: ignore - ) - assert "Environment variable key cannot be empty" in str(exc_info.value) - - with pytest.raises(ValidationError) as exc_info: - MCPStdioServerConfig( - name="test-server", - command="python", - env="123INVALID=value", # type: ignore - ) - assert "Invalid environment variable name" in str(exc_info.value) - - -def test_mcp_stdio_server_config_equality(): - """Test MCPStdioServerConfig equality operator.""" - server1 = MCPStdioServerConfig( - name="test-server", - command="python", - args=["--verbose", "--debug", "--port=8080"], - env={"DEBUG": "true", "PORT": "8080"}, - ) - - server2 = MCPStdioServerConfig( - name="test-server", - command="python", - args=["--verbose", "--debug", "--port=8080"], # Same order - env={"PORT": "8080", "DEBUG": "true"}, # Different order - ) - - # Should be equal because env is compared as a set - assert server1 == server2 - - # Test different args order - server3 = MCPStdioServerConfig( - name="test-server", - command="python", - args=["--debug", "--port=8080", "--verbose"], # Different order - env={"DEBUG": "true", "PORT": "8080"}, - ) - - # Should NOT be equal because args order matters - assert server1 != server3 - - # Test different type - assert server1 != "not a server config" - - -def test_mcp_shttp_server_config_basic(): - """Test basic MCPSHTTPServerConfig.""" - config = MCPSHTTPServerConfig(url="http://server1:8080") - assert config.url == "http://server1:8080" - assert config.api_key is None - - -def test_mcp_shttp_server_config_with_api_key(): - """Test MCPSHTTPServerConfig with API key.""" - config = MCPSHTTPServerConfig(url="http://server1:8080", api_key="test-api-key") - assert config.url == "http://server1:8080" - assert config.api_key == "test-api-key" - - -def test_mcp_shttp_server_config_invalid_url(): - """Test MCPSHTTPServerConfig with invalid URL format.""" - with pytest.raises(ValidationError) as exc_info: - MCPSHTTPServerConfig(url="not_a_url") - assert "URL must include a scheme" in str(exc_info.value) - - -def test_mcp_config_empty(): - """Test empty MCPConfig.""" - config = MCPConfig() - assert config.sse_servers == [] - assert config.stdio_servers == [] - assert config.shttp_servers == [] - - -def test_mcp_config_with_sse_servers(): - """Test MCPConfig with SSE servers.""" - sse_servers = [ - MCPSSEServerConfig(url="http://server1:8080"), - MCPSSEServerConfig(url="http://server2:8080", api_key="test-key"), - ] - config = MCPConfig(sse_servers=sse_servers) - assert len(config.sse_servers) == 2 - assert config.sse_servers[0].url == "http://server1:8080" - assert config.sse_servers[1].url == "http://server2:8080" - assert config.sse_servers[1].api_key == "test-key" - - -def test_mcp_config_with_stdio_servers(): - """Test MCPConfig with stdio servers.""" - stdio_servers = [ - MCPStdioServerConfig(name="server1", command="python"), - MCPStdioServerConfig(name="server2", command="node", args=["server.js"]), - ] - config = MCPConfig(stdio_servers=stdio_servers) - assert len(config.stdio_servers) == 2 - assert config.stdio_servers[0].name == "server1" - assert config.stdio_servers[1].name == "server2" - assert config.stdio_servers[1].args == ["server.js"] - - -def test_mcp_config_with_shttp_servers(): - """Test MCPConfig with SHTTP servers.""" - shttp_servers = [ - MCPSHTTPServerConfig(url="http://server1:8080"), - MCPSHTTPServerConfig(url="http://server2:8080", api_key="test-key"), - ] - config = MCPConfig(shttp_servers=shttp_servers) - assert len(config.shttp_servers) == 2 - assert config.shttp_servers[0].url == "http://server1:8080" - assert config.shttp_servers[1].url == "http://server2:8080" - assert config.shttp_servers[1].api_key == "test-key" - - -def test_mcp_config_with_all_server_types(): - """Test MCPConfig with all server types.""" - sse_server = MCPSSEServerConfig(url="http://sse-server:8080") - stdio_server = MCPStdioServerConfig(name="stdio-server", command="python") - shttp_server = MCPSHTTPServerConfig(url="http://shttp-server:8080") - - config = MCPConfig( - sse_servers=[sse_server], - stdio_servers=[stdio_server], - shttp_servers=[shttp_server], - ) - - assert len(config.sse_servers) == 1 - assert len(config.stdio_servers) == 1 - assert len(config.shttp_servers) == 1 - assert config.sse_servers[0].url == "http://sse-server:8080" - assert config.stdio_servers[0].name == "stdio-server" - assert config.shttp_servers[0].url == "http://shttp-server:8080" - - -def test_mcp_config_validate_servers(): - """Test MCPConfig server validation.""" - # Valid configuration should not raise - config = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://server1:8080"), - MCPSSEServerConfig(url="http://server2:8080"), - ] - ) - config.validate_servers() # Should not raise - - # Duplicate URLs in sse_servers should raise - config = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://server1:8080"), - MCPSSEServerConfig(url="http://server1:8080"), - ] - ) - with pytest.raises(ValueError) as exc_info: - config.validate_servers() - assert "Duplicate MCP server URLs are not allowed" in str(exc_info.value) - - -def test_mcp_config_validate_servers_shttp_duplicates(): - """Test MCPConfig validation for duplicate URLs in shttp_servers.""" - # Note: Current implementation only validates sse_servers, - # but this test documents expected behavior for shttp_servers - config = MCPConfig( - shttp_servers=[ - MCPSHTTPServerConfig(url="http://server1:8080"), - MCPSHTTPServerConfig(url="http://server1:8080"), - ] - ) - # This currently passes but should ideally fail - testing current behavior - config.validate_servers() # Currently doesn't validate shttp_servers - - -def test_mcp_config_validate_servers_stdio_duplicates(): - """Test MCPConfig validation for duplicate names in stdio_servers.""" - # Note: Current implementation doesn't validate stdio server names, - # but this test documents expected behavior - config = MCPConfig( - stdio_servers=[ - MCPStdioServerConfig(name="server1", command="python"), - MCPStdioServerConfig(name="server1", command="node"), - ] - ) - # This currently passes but should ideally fail - testing current behavior - config.validate_servers() # Currently doesn't validate stdio server names - - -def test_mcp_config_validate_servers_cross_type_duplicates(): - """Test MCPConfig validation for duplicate URLs between sse and shttp servers.""" - # Note: Current implementation doesn't check cross-type duplicates, - # but this test documents expected behavior - config = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://server1:8080")], - shttp_servers=[MCPSHTTPServerConfig(url="http://server1:8080")], - ) - # This currently passes but should ideally fail - testing current behavior - config.validate_servers() # Currently doesn't check cross-type duplicates - - -def test_mcp_config_from_toml_section_basic(): - """Test MCPConfig.from_toml_section with basic data.""" - data = { - "sse_servers": ["http://server1:8080"], - } - result = MCPConfig.from_toml_section(data) - assert "mcp" in result - assert len(result["mcp"].sse_servers) == 1 - assert result["mcp"].sse_servers[0].url == "http://server1:8080" - - -def test_mcp_config_from_toml_section_with_stdio(): - """Test MCPConfig.from_toml_section with stdio servers.""" - data = { - "sse_servers": ["http://server1:8080"], - "stdio_servers": [ - { - "name": "test-server", - "command": "python", - "args": ["-m", "server"], - "env": {"DEBUG": "true"}, - } - ], - } - result = MCPConfig.from_toml_section(data) - assert "mcp" in result - assert len(result["mcp"].sse_servers) == 1 - assert len(result["mcp"].stdio_servers) == 1 - assert result["mcp"].stdio_servers[0].name == "test-server" - assert result["mcp"].stdio_servers[0].command == "python" - assert result["mcp"].stdio_servers[0].args == ["-m", "server"] - assert result["mcp"].stdio_servers[0].env == {"DEBUG": "true"} - - -def test_mcp_config_from_toml_section_with_shttp(): - """Test MCPConfig.from_toml_section with SHTTP servers.""" - data = { - "shttp_servers": [{"url": "http://server1:8080", "api_key": "test-key"}], - } - result = MCPConfig.from_toml_section(data) - assert "mcp" in result - assert len(result["mcp"].shttp_servers) == 1 - assert result["mcp"].shttp_servers[0].url == "http://server1:8080" - assert result["mcp"].shttp_servers[0].api_key == "test-key" - - -def test_mcp_config_from_toml_section_invalid(): - """Test MCPConfig.from_toml_section with invalid data.""" - data = { - "sse_servers": ["not_a_url"], - } - with pytest.raises(ValueError) as exc_info: - MCPConfig.from_toml_section(data) - assert "URL must include a scheme" in str(exc_info.value) - - -def test_mcp_config_merge(): - """Test MCPConfig merge functionality.""" - config1 = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://server1:8080")], - stdio_servers=[MCPStdioServerConfig(name="server1", command="python")], - shttp_servers=[MCPSHTTPServerConfig(url="http://shttp1:8080")], - ) - - config2 = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://server2:8080")], - stdio_servers=[MCPStdioServerConfig(name="server2", command="node")], - shttp_servers=[MCPSHTTPServerConfig(url="http://shttp2:8080")], - ) - - merged = config1.merge(config2) - - assert len(merged.sse_servers) == 2 - assert len(merged.stdio_servers) == 2 - assert len(merged.shttp_servers) == 2 - assert merged.sse_servers[0].url == "http://server1:8080" - assert merged.sse_servers[1].url == "http://server2:8080" - assert merged.stdio_servers[0].name == "server1" - assert merged.stdio_servers[1].name == "server2" - assert merged.shttp_servers[0].url == "http://shttp1:8080" - assert merged.shttp_servers[1].url == "http://shttp2:8080" - - -def test_mcp_config_extra_fields_forbidden(): - """Test that extra fields are forbidden in MCPConfig.""" - with pytest.raises(ValidationError) as exc_info: - MCPConfig(extra_field="value") # type: ignore - assert "Extra inputs are not permitted" in str(exc_info.value) - - -def test_mcp_config_complex_urls(): - """Test MCPConfig with complex URLs.""" - config = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="https://user:pass@server1:8080/path?query=1"), - MCPSSEServerConfig(url="wss://server2:8443/ws"), - MCPSSEServerConfig(url="http://subdomain.example.com:9090"), - ] - ) - config.validate_servers() # Should not raise any exception - assert len(config.sse_servers) == 3 diff --git a/tests/sdk/config/test_mcp_configs_merge.py b/tests/sdk/config/test_mcp_configs_merge.py deleted file mode 100644 index 011d12bd370..00000000000 --- a/tests/sdk/config/test_mcp_configs_merge.py +++ /dev/null @@ -1,273 +0,0 @@ -"""Test MCP config merging functionality.""" - -import pytest - -from openhands.sdk.config import MCPConfig -from openhands.sdk.config.mcp_config import ( - MCPSHTTPServerConfig, - MCPSSEServerConfig, - MCPStdioServerConfig, -) - - -def test_mcp_config_merge_empty(): - """Test merging empty MCP configs.""" - config1 = MCPConfig() - config2 = MCPConfig() - - merged = config1.merge(config2) - - assert merged.sse_servers == [] - assert merged.stdio_servers == [] - assert merged.shttp_servers == [] - - -def test_mcp_config_merge_sse_servers(): - """Test merging MCP configs with SSE servers.""" - config1 = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://server1:8080"), - MCPSSEServerConfig(url="http://server2:8080", api_key="key1"), - ] - ) - - config2 = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://server3:8080"), - MCPSSEServerConfig(url="http://server4:8080", api_key="key2"), - ] - ) - - merged = config1.merge(config2) - - assert len(merged.sse_servers) == 4 - assert merged.sse_servers[0].url == "http://server1:8080" - assert merged.sse_servers[1].url == "http://server2:8080" - assert merged.sse_servers[1].api_key == "key1" - assert merged.sse_servers[2].url == "http://server3:8080" - assert merged.sse_servers[3].url == "http://server4:8080" - assert merged.sse_servers[3].api_key == "key2" - - -def test_mcp_config_merge_stdio_servers(): - """Test merging MCP configs with stdio servers.""" - config1 = MCPConfig( - stdio_servers=[ - MCPStdioServerConfig(name="server1", command="python"), - MCPStdioServerConfig(name="server2", command="node", args=["app.js"]), - ] - ) - - config2 = MCPConfig( - stdio_servers=[ - MCPStdioServerConfig( - name="server3", command="java", args=["-jar", "app.jar"] - ), - MCPStdioServerConfig( - name="server4", command="go", env={"GO_ENV": "production"} - ), - ] - ) - - merged = config1.merge(config2) - - assert len(merged.stdio_servers) == 4 - assert merged.stdio_servers[0].name == "server1" - assert merged.stdio_servers[0].command == "python" - assert merged.stdio_servers[1].name == "server2" - assert merged.stdio_servers[1].command == "node" - assert merged.stdio_servers[1].args == ["app.js"] - assert merged.stdio_servers[2].name == "server3" - assert merged.stdio_servers[2].command == "java" - assert merged.stdio_servers[2].args == ["-jar", "app.jar"] - assert merged.stdio_servers[3].name == "server4" - assert merged.stdio_servers[3].command == "go" - assert merged.stdio_servers[3].env == {"GO_ENV": "production"} - - -def test_mcp_config_merge_shttp_servers(): - """Test merging MCP configs with SHTTP servers.""" - config1 = MCPConfig( - shttp_servers=[ - MCPSHTTPServerConfig(url="http://server1:8080"), - MCPSHTTPServerConfig(url="http://server2:8080", api_key="key1"), - ] - ) - - config2 = MCPConfig( - shttp_servers=[ - MCPSHTTPServerConfig(url="http://server3:8080"), - MCPSHTTPServerConfig(url="http://server4:8080", api_key="key2"), - ] - ) - - merged = config1.merge(config2) - - assert len(merged.shttp_servers) == 4 - assert merged.shttp_servers[0].url == "http://server1:8080" - assert merged.shttp_servers[1].url == "http://server2:8080" - assert merged.shttp_servers[1].api_key == "key1" - assert merged.shttp_servers[2].url == "http://server3:8080" - assert merged.shttp_servers[3].url == "http://server4:8080" - assert merged.shttp_servers[3].api_key == "key2" - - -def test_mcp_config_merge_all_server_types(): - """Test merging MCP configs with all server types.""" - config1 = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://sse1:8080")], - stdio_servers=[MCPStdioServerConfig(name="stdio1", command="python")], - shttp_servers=[MCPSHTTPServerConfig(url="http://shttp1:8080")], - ) - - config2 = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://sse2:8080")], - stdio_servers=[MCPStdioServerConfig(name="stdio2", command="node")], - shttp_servers=[MCPSHTTPServerConfig(url="http://shttp2:8080")], - ) - - merged = config1.merge(config2) - - assert len(merged.sse_servers) == 2 - assert len(merged.stdio_servers) == 2 - assert len(merged.shttp_servers) == 2 - - assert merged.sse_servers[0].url == "http://sse1:8080" - assert merged.sse_servers[1].url == "http://sse2:8080" - - assert merged.stdio_servers[0].name == "stdio1" - assert merged.stdio_servers[1].name == "stdio2" - - assert merged.shttp_servers[0].url == "http://shttp1:8080" - assert merged.shttp_servers[1].url == "http://shttp2:8080" - - -def test_mcp_config_merge_one_empty(): - """Test merging when one config is empty.""" - config1 = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://server1:8080")], - stdio_servers=[MCPStdioServerConfig(name="server1", command="python")], - shttp_servers=[MCPSHTTPServerConfig(url="http://shttp1:8080")], - ) - - config2 = MCPConfig() - - merged = config1.merge(config2) - - assert len(merged.sse_servers) == 1 - assert len(merged.stdio_servers) == 1 - assert len(merged.shttp_servers) == 1 - assert merged.sse_servers[0].url == "http://server1:8080" - assert merged.stdio_servers[0].name == "server1" - assert merged.shttp_servers[0].url == "http://shttp1:8080" - - # Test the other way around - merged2 = config2.merge(config1) - - assert len(merged2.sse_servers) == 1 - assert len(merged2.stdio_servers) == 1 - assert len(merged2.shttp_servers) == 1 - assert merged2.sse_servers[0].url == "http://server1:8080" - assert merged2.stdio_servers[0].name == "server1" - assert merged2.shttp_servers[0].url == "http://shttp1:8080" - - -def test_mcp_config_merge_preserves_original(): - """Test that merging preserves original configs.""" - config1 = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://server1:8080")], - ) - - config2 = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://server2:8080")], - ) - - merged = config1.merge(config2) - - # Original configs should be unchanged - assert len(config1.sse_servers) == 1 - assert len(config2.sse_servers) == 1 - assert config1.sse_servers[0].url == "http://server1:8080" - assert config2.sse_servers[0].url == "http://server2:8080" - - # Merged config should have both - assert len(merged.sse_servers) == 2 - assert merged.sse_servers[0].url == "http://server1:8080" - assert merged.sse_servers[1].url == "http://server2:8080" - - -def test_mcp_config_merge_complex_scenario(): - """Test merging with a complex scenario involving different server configs.""" - config1 = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://sse1:8080", api_key="sse-key1"), - MCPSSEServerConfig(url="http://sse2:8080"), - ], - stdio_servers=[ - MCPStdioServerConfig( - name="stdio1", - command="python", - args=["-m", "server"], - env={"DEBUG": "true"}, - ), - ], - ) - - config2 = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://sse3:8080"), - ], - stdio_servers=[ - MCPStdioServerConfig( - name="stdio2", - command="node", - args=["server.js", "--port", "3000"], - env={"NODE_ENV": "production", "PORT": "3000"}, - ), - ], - shttp_servers=[ - MCPSHTTPServerConfig(url="http://shttp1:8080", api_key="shttp-key1"), - ], - ) - - merged = config1.merge(config2) - - # Check SSE servers - assert len(merged.sse_servers) == 3 - assert merged.sse_servers[0].url == "http://sse1:8080" - assert merged.sse_servers[0].api_key == "sse-key1" - assert merged.sse_servers[1].url == "http://sse2:8080" - assert merged.sse_servers[1].api_key is None - assert merged.sse_servers[2].url == "http://sse3:8080" - assert merged.sse_servers[2].api_key is None - - # Check stdio servers - assert len(merged.stdio_servers) == 2 - assert merged.stdio_servers[0].name == "stdio1" - assert merged.stdio_servers[0].command == "python" - assert merged.stdio_servers[0].args == ["-m", "server"] - assert merged.stdio_servers[0].env == {"DEBUG": "true"} - assert merged.stdio_servers[1].name == "stdio2" - assert merged.stdio_servers[1].command == "node" - assert merged.stdio_servers[1].args == ["server.js", "--port", "3000"] - assert merged.stdio_servers[1].env == {"NODE_ENV": "production", "PORT": "3000"} - - # Check SHTTP servers - assert len(merged.shttp_servers) == 1 - assert merged.shttp_servers[0].url == "http://shttp1:8080" - assert merged.shttp_servers[0].api_key == "shttp-key1" - - -def test_mcp_config_merge_validation_on_merged_config(): - """Test that validate_servers() works correctly on merged configurations.""" - config1 = MCPConfig(sse_servers=[MCPSSEServerConfig(url="http://server1:8080")]) - - config2 = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://server1:8080")] # Same URL - ) - - merged = config1.merge(config2) - - # The merged config should have duplicate URLs and validation should fail - with pytest.raises(ValueError, match="Duplicate MCP server URLs are not allowed"): - merged.validate_servers() From 6546117a10cdc586f84d494812a37a55e005a4a4 Mon Sep 17 00:00:00 2001 From: Hoang Tran Date: Fri, 5 Sep 2025 17:38:09 +0000 Subject: [PATCH 19/28] fix tests --- .../mcp/test_mcp_create_clients_timeout.py | 236 --------- tests/sdk/mcp/test_mcp_timeout.py | 199 -------- tests/sdk/mcp/test_tool.py | 473 +++++++----------- tests/sdk/mcp/test_utils.py | 406 ++++++--------- 4 files changed, 350 insertions(+), 964 deletions(-) delete mode 100644 tests/sdk/mcp/test_mcp_create_clients_timeout.py delete mode 100644 tests/sdk/mcp/test_mcp_timeout.py diff --git a/tests/sdk/mcp/test_mcp_create_clients_timeout.py b/tests/sdk/mcp/test_mcp_create_clients_timeout.py deleted file mode 100644 index 34ad8f33c19..00000000000 --- a/tests/sdk/mcp/test_mcp_create_clients_timeout.py +++ /dev/null @@ -1,236 +0,0 @@ -import asyncio -from unittest.mock import MagicMock, patch - -import pytest - -from openhands.sdk.config.mcp_config import ( - MCPConfig, - MCPSHTTPServerConfig, - MCPSSEServerConfig, - MCPStdioServerConfig, -) -from openhands.sdk.mcp.utils import create_mcp_client, create_mcp_tools_from_config - - -def test_create_mcp_client_invalid_url(): - """Test creating MCP client with invalid URL.""" - # Use a valid URL format but mock the connection to fail - server_config = MCPSSEServerConfig(url="http://invalid-url-format") - - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = MagicMock() - mock_mcp_client.return_value = mock_client_instance - - # Mock connect_http to fail for invalid URL - mock_client_instance.connect_http.side_effect = ValueError("Invalid URL") - - with pytest.raises(ValueError): - create_mcp_client(server_config) - - -def test_create_mcp_client_unreachable_host(): - """Test creating MCP client with unreachable host.""" - server_config = MCPSSEServerConfig(url="http://unreachable-host:8080") - - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = MagicMock() - mock_mcp_client.return_value = mock_client_instance - - # Mock connect_http to fail with connection error - mock_client_instance.connect_http.side_effect = ConnectionError( - "Host unreachable" - ) - - with pytest.raises(ConnectionError): - create_mcp_client(server_config) - - -def test_create_mcp_client_stdio_command_not_found(): - """Test creating MCP stdio client with non-existent command.""" - server_config = MCPStdioServerConfig( - name="bad_server", - command="nonexistent_command", - args=["--help"], - ) - - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = MagicMock() - mock_mcp_client.return_value = mock_client_instance - - # Mock connect_stdio to fail for nonexistent command - mock_client_instance.connect_stdio.side_effect = FileNotFoundError( - "Command not found" - ) - - with pytest.raises(FileNotFoundError): - create_mcp_client(server_config) - - -def test_create_mcp_tools_from_config_mixed_failures(): - """Test creating MCP tools with mixed connection failures.""" - config = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://good-sse:8080"), - MCPSSEServerConfig(url="http://bad-sse:8080"), - ], - stdio_servers=[ - MCPStdioServerConfig( - name="good_stdio", - command="python", - args=["-m", "good_stdio"], - ), - MCPStdioServerConfig( - name="bad_stdio", - command="bad_command", - ), - ], - ) - - # Mock clients - some succeed, some fail - mock_client = MagicMock() - mock_tool = MagicMock() - mock_tool.name = "tool1" - - def mock_create_client(server_config, conversation_id=None, timeout=None): - if hasattr(server_config, "url") and "bad-sse" in server_config.url: - raise ConnectionError("SSE connection failed") - elif ( - hasattr(server_config, "command") and "bad_command" in server_config.command - ): - raise FileNotFoundError("Stdio command not found") - else: - return mock_client - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client - ): - with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool] - - tools = create_mcp_tools_from_config(config) - - # Should get tools from successful servers only (2 out of 4) - assert len(tools) == 1 - assert ( - mock_registry.add_client.call_count == 2 - ) # Only successful connections - - -def test_create_mcp_tools_from_config_all_timeout(): - """Test creating MCP tools where all connections timeout.""" - config = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://timeout1:8080"), - MCPSSEServerConfig(url="http://timeout2:8080"), - ], - stdio_servers=[ - MCPStdioServerConfig(name="timeout3", command="timeout_cmd1"), - MCPStdioServerConfig(name="timeout4", command="timeout_cmd2"), - ], - ) - - # Mock all connections to timeout - def mock_create_client(server_config, conversation_id=None, timeout=None): - raise asyncio.TimeoutError("Connection timeout") - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client - ): - with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [] - - tools = create_mcp_tools_from_config(config) - - # Should get no tools due to all timeouts - assert len(tools) == 0 - assert mock_registry.add_client.call_count == 0 # No successful connections - - -def test_create_mcp_client_with_various_timeouts(): - """Test creating MCP client with various timeout scenarios.""" - server_config = MCPSSEServerConfig(url="http://server:8080") - - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = MagicMock() - mock_mcp_client.return_value = mock_client_instance - - # Test different timeout values - timeouts = [1.0, 5.0, 10.0, 30.0] - - for timeout_val in timeouts: - mock_client_instance.connect_http = MagicMock() - create_mcp_client(server_config, timeout=timeout_val) - - # Verify timeout was passed correctly - mock_client_instance.connect_http.assert_called_with( - server_config, None, timeout_val - ) - - -def test_create_mcp_tools_from_config_partial_success(): - """Test creating MCP tools with partial success across different server types.""" - config = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://working-sse:8080"), - MCPSSEServerConfig(url="http://failing-sse:8080"), - ], - stdio_servers=[ - MCPStdioServerConfig( - name="working_stdio", command="python", args=["-m", "server"] - ), - ], - shttp_servers=[ - MCPSHTTPServerConfig(url="http://working-shttp:8080"), - ], - ) - - # Mock mixed success/failure - mock_client = MagicMock() - mock_tool1 = MagicMock() - mock_tool1.name = "tool1" - mock_tool2 = MagicMock() - mock_tool2.name = "tool2" - - def mock_create_client(server_config, conversation_id=None, timeout=None): - if hasattr(server_config, "url") and "failing-sse" in server_config.url: - raise ConnectionError("Failed SSE connection") - else: - return mock_client - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client - ): - with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool1, mock_tool2] - - tools = create_mcp_tools_from_config(config) - - # Should get tools from successful servers (3 out of 4) - assert len(tools) == 2 - assert mock_registry.add_client.call_count == 3 # 3 successful connections - - -def test_create_mcp_client_stdio_with_timeout(): - """Test creating MCP stdio client with timeout parameter.""" - server_config = MCPStdioServerConfig( - name="test_server", - command="python", - args=["-m", "test_server"], - ) - - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = MagicMock() - mock_mcp_client.return_value = mock_client_instance - mock_client_instance.connect_stdio = MagicMock() - - # Test with custom timeout - create_mcp_client(server_config, timeout=15.0) - - # Verify timeout was passed correctly - mock_client_instance.connect_stdio.assert_called_once_with(server_config, 15.0) diff --git a/tests/sdk/mcp/test_mcp_timeout.py b/tests/sdk/mcp/test_mcp_timeout.py deleted file mode 100644 index 2445407e185..00000000000 --- a/tests/sdk/mcp/test_mcp_timeout.py +++ /dev/null @@ -1,199 +0,0 @@ -import asyncio -from unittest.mock import MagicMock, patch - -import pytest - -from openhands.sdk.config.mcp_config import ( - MCPConfig, - MCPSSEServerConfig, - MCPStdioServerConfig, -) -from openhands.sdk.mcp.utils import create_mcp_client, create_mcp_tools_from_config - - -def test_create_mcp_client_sse_connection_timeout(): - """Test SSE connection with timeout.""" - server_config = MCPSSEServerConfig(url="http://unreachable-server:8080") - - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = MagicMock() - mock_mcp_client.return_value = mock_client_instance - - # Mock connect_http to timeout - mock_client_instance.connect_http.side_effect = asyncio.TimeoutError( - "Connection timeout" - ) - - # Should raise timeout error - with pytest.raises(asyncio.TimeoutError): - create_mcp_client(server_config) - - -def test_create_mcp_client_stdio_connection_timeout(): - """Test stdio connection with timeout.""" - server_config = MCPStdioServerConfig( - name="timeout_server", - command="sleep", - args=["10"], # Command that takes too long - ) - - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = MagicMock() - mock_mcp_client.return_value = mock_client_instance - - # Mock connect_stdio to timeout - mock_client_instance.connect_stdio.side_effect = asyncio.TimeoutError( - "Stdio connection timeout" - ) - - # Should raise timeout error - with pytest.raises(asyncio.TimeoutError): - create_mcp_client(server_config) - - -def test_create_mcp_tools_from_config_with_timeout_errors(): - """Test creating MCP tools from configuration with timeout errors.""" - config = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://good-server:8080"), - MCPSSEServerConfig(url="http://timeout-server:8080"), - ] - ) - - # Mock one successful client and one that times out - mock_good_client = MagicMock() - mock_tool = MagicMock() - mock_tool.name = "tool1" - - def mock_create_client(server_config, conversation_id=None, timeout=None): - if "timeout-server" in server_config.url: - raise asyncio.TimeoutError("Connection timeout") - else: - return mock_good_client - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client - ): - with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool] - - tools = create_mcp_tools_from_config(config) - - # Should get tools from the good server only - assert len(tools) == 1 - assert tools[0] == mock_tool - # Should have only added the successful client - mock_registry.add_client.assert_called_once_with( - "http://good-server:8080", mock_good_client - ) - - -def test_create_mcp_tools_from_config_mixed_timeout_success(): - """Test creating MCP tools with mixed timeout and success results.""" - config = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://server1:8080"), - MCPSSEServerConfig(url="http://server2:8080"), - ], - stdio_servers=[ - MCPStdioServerConfig( - name="stdio1", command="python", args=["-m", "server"] - ), - MCPStdioServerConfig(name="stdio2", command="timeout_command"), - ], - ) - - # Mock clients - some succeed, some timeout - mock_client = MagicMock() - mock_tool = MagicMock() - mock_tool.name = "tool1" - - def mock_create_client(server_config, conversation_id=None, timeout=None): - if hasattr(server_config, "url") and "server2" in server_config.url: - raise asyncio.TimeoutError("HTTP timeout") - elif ( - hasattr(server_config, "command") - and "timeout_command" in server_config.command - ): - raise asyncio.TimeoutError("Stdio timeout") - else: - return mock_client - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client - ): - with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool] - - tools = create_mcp_tools_from_config(config) - - # Should get tools from successful servers only (2 out of 4) - assert len(tools) == 1 - assert ( - mock_registry.add_client.call_count == 2 - ) # Only successful connections - - -def test_create_mcp_client_with_custom_timeout(): - """Test creating MCP client with custom timeout value.""" - server_config = MCPSSEServerConfig(url="http://server:8080") - - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = MagicMock() - mock_mcp_client.return_value = mock_client_instance - mock_client_instance.connect_http = MagicMock() - - # Test with custom timeout - create_mcp_client(server_config, timeout=5.0) - - # Verify timeout was passed correctly - mock_client_instance.connect_http.assert_called_once_with( - server_config, None, 5.0 - ) - - -def test_create_mcp_tools_from_config_with_custom_timeout(): - """Test creating MCP tools with custom timeout value.""" - config = MCPConfig(sse_servers=[MCPSSEServerConfig(url="http://server:8080")]) - - mock_client = MagicMock() - mock_tool = MagicMock() - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client - ) as mock_create: - with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool] - - # Test with custom timeout - create_mcp_tools_from_config(config, timeout=10.0) - - # Verify timeout was passed to create_mcp_client - mock_create.assert_called_with(config.sse_servers[0], None, 10.0) - - -def test_create_mcp_client_connection_error_vs_timeout(): - """Test distinguishing between connection errors and timeouts.""" - server_config = MCPSSEServerConfig(url="http://server:8080") - - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_mcp_client: - mock_client_instance = MagicMock() - mock_mcp_client.return_value = mock_client_instance - - # Test timeout error - mock_client_instance.connect_http.side_effect = asyncio.TimeoutError("Timeout") - with pytest.raises(asyncio.TimeoutError): - create_mcp_client(server_config) - - # Test connection error - mock_client_instance.connect_http.side_effect = ConnectionError( - "Connection failed" - ) - with pytest.raises(ConnectionError): - create_mcp_client(server_config) diff --git a/tests/sdk/mcp/test_tool.py b/tests/sdk/mcp/test_tool.py index 53affa6ed8d..f1d28fa52bd 100644 --- a/tests/sdk/mcp/test_tool.py +++ b/tests/sdk/mcp/test_tool.py @@ -1,65 +1,108 @@ -"""Tests for MCP tool functionality.""" +"""Tests for MCP tool functionality with new simplified implementation.""" from unittest.mock import MagicMock -from openhands.sdk.mcp.tool import ( - MCPTool, - MCPToolAction, - MCPToolExecutor, - MCPToolObservation, - MCPToolRegistry, -) +import mcp.types +from openhands.sdk.llm import TextContent +from openhands.sdk.mcp.definition import MCPToolObservation +from openhands.sdk.mcp.tool import MCPTool, MCPToolExecutor -class TestMCPToolAction: - """Test MCPToolAction data class.""" - def test_mcp_tool_action_creation(self): - """Test creating an MCP tool action.""" - action = MCPToolAction( - tool_name="test_tool", - arguments={"param1": "value1", "param2": 42}, +class TestMCPToolObservation: + """Test MCPToolObservation functionality.""" + + def test_from_call_tool_result_success(self): + """Test creating observation from successful MCP result.""" + # Create mock MCP result + result = MagicMock(spec=mcp.types.CallToolResult) + result.content = [ + mcp.types.TextContent(type="text", text="Operation completed successfully") + ] + result.isError = False + + observation = MCPToolObservation.from_call_tool_result( + tool_name="test_tool", result=result ) - assert action.tool_name == "test_tool" - assert action.arguments == {"param1": "value1", "param2": 42} + assert observation.tool_name == "test_tool" + assert len(observation.content) == 1 + assert isinstance(observation.content[0], TextContent) + assert observation.content[0].text == "Operation completed successfully" + assert observation.is_error is False + + def test_from_call_tool_result_error(self): + """Test creating observation from error MCP result.""" + # Create mock MCP result + result = MagicMock(spec=mcp.types.CallToolResult) + result.content = [mcp.types.TextContent(type="text", text="Operation failed")] + result.isError = True - def test_mcp_tool_action_empty_arguments(self): - """Test creating an MCP tool action with empty arguments.""" - action = MCPToolAction(tool_name="test_tool") + observation = MCPToolObservation.from_call_tool_result( + tool_name="test_tool", result=result + ) - assert action.tool_name == "test_tool" - assert action.arguments == {} + assert observation.tool_name == "test_tool" + assert len(observation.content) == 1 + assert isinstance(observation.content[0], TextContent) + assert observation.content[0].text == "Operation failed" + assert observation.is_error is True + def test_from_call_tool_result_with_image(self): + """Test creating observation from MCP result with image content.""" + # Create mock MCP result with image + result = MagicMock(spec=mcp.types.CallToolResult) + result.content = [ + mcp.types.TextContent(type="text", text="Here's the image:"), + mcp.types.ImageContent( + type="image", data="base64data", mimeType="image/png" + ), + ] + result.isError = False + + observation = MCPToolObservation.from_call_tool_result( + tool_name="test_tool", result=result + ) -class TestMCPToolObservation: - """Test MCPToolObservation data class.""" + assert observation.tool_name == "test_tool" + assert len(observation.content) == 2 + assert isinstance(observation.content[0], TextContent) + assert observation.content[0].text == "Here's the image:" + # Second content should be ImageContent + assert hasattr(observation.content[1], "image_urls") + assert observation.is_error is False - def test_mcp_tool_observation_success(self): - """Test creating a successful MCP tool observation.""" + def test_agent_observation_success(self): + """Test agent observation formatting for success.""" observation = MCPToolObservation( tool_name="test_tool", - content="Operation completed successfully", + content=[TextContent(text="Success result")], is_error=False, ) - assert observation.tool_name == "test_tool" - assert observation.content == "Operation completed successfully" - assert observation.is_error is False + agent_obs = observation.agent_observation + assert len(agent_obs) == 2 + assert isinstance(agent_obs[0], TextContent) + assert "[Tool 'test_tool' executed.]" in agent_obs[0].text + assert "[An error occurred during execution.]" not in agent_obs[0].text + assert isinstance(agent_obs[1], TextContent) + assert agent_obs[1].text == "Success result" - def test_mcp_tool_observation_error(self): - """Test creating an error MCP tool observation.""" + def test_agent_observation_error(self): + """Test agent observation formatting for error.""" observation = MCPToolObservation( tool_name="test_tool", - content="Operation failed: Invalid parameter", + content=[TextContent(text="Error occurred")], is_error=True, - error_message="Invalid parameter", ) - assert observation.tool_name == "test_tool" - assert observation.content == "Operation failed: Invalid parameter" - assert observation.is_error is True - assert observation.error_message == "Invalid parameter" + agent_obs = observation.agent_observation + assert len(agent_obs) == 2 + assert isinstance(agent_obs[0], TextContent) + assert isinstance(agent_obs[1], TextContent) + assert "[Tool 'test_tool' executed.]" in agent_obs[0].text + assert "[An error occurred during execution.]" in agent_obs[0].text + assert agent_obs[1].text == "Error occurred" class TestMCPToolExecutor: @@ -68,109 +111,89 @@ class TestMCPToolExecutor: def setup_method(self): """Set up test fixtures.""" self.mock_client = MagicMock() - self.executor = MCPToolExecutor(mcp_client=self.mock_client) + self.executor = MCPToolExecutor(tool_name="test_tool", client=self.mock_client) - def test_execute_success(self): + def test_call_tool_success(self): """Test successful tool execution.""" # Mock successful MCP call - mock_result = MagicMock() - mock_result.content = [{"text": "Success result"}] + mock_result = MagicMock(spec=mcp.types.CallToolResult) + mock_result.content = [ + mcp.types.TextContent(type="text", text="Success result") + ] mock_result.isError = False - mock_result.model_dump.return_value = { - "content": [{"text": "Success result"}], - "isError": False, - } - # Mock the client's call_tool method directly - self.mock_client.call_tool.return_value = mock_result + # Mock action + mock_action = MagicMock() + mock_action.model_dump.return_value = {"param": "value"} - action = MCPToolAction( - tool_name="test_tool", - arguments={"param": "value"}, - ) + # Mock call_async_from_sync to return the expected observation + def mock_call_async_from_sync(coro_func, **kwargs): + return MCPToolObservation.from_call_tool_result( + tool_name="test_tool", result=mock_result + ) + + self.mock_client.call_async_from_sync = mock_call_async_from_sync - observation = self.executor(action) + observation = self.executor(mock_action) assert isinstance(observation, MCPToolObservation) assert observation.tool_name == "test_tool" - assert ( - observation.content - == '{"content": [{"text": "Success result"}], "isError": false}' - ) assert observation.is_error is False - def test_execute_error(self): + def test_call_tool_error(self): """Test tool execution with error.""" # Mock error MCP call - mock_result = MagicMock() - mock_result.content = [{"text": "Error occurred"}] + mock_result = MagicMock(spec=mcp.types.CallToolResult) + mock_result.content = [ + mcp.types.TextContent(type="text", text="Error occurred") + ] mock_result.isError = True - mock_result.model_dump.return_value = { - "content": [{"text": "Error occurred"}], - "isError": True, - } - # Mock the client's call_tool method directly - self.mock_client.call_tool.return_value = mock_result + # Mock action + mock_action = MagicMock() + mock_action.model_dump.return_value = {"param": "value"} - action = MCPToolAction( - tool_name="test_tool", - arguments={"param": "value"}, - ) + # Mock call_async_from_sync to return the expected observation + def mock_call_async_from_sync(coro_func, **kwargs): + return MCPToolObservation.from_call_tool_result( + tool_name="test_tool", result=mock_result + ) + + self.mock_client.call_async_from_sync = mock_call_async_from_sync - observation = self.executor(action) + observation = self.executor(mock_action) assert isinstance(observation, MCPToolObservation) assert observation.tool_name == "test_tool" - assert ( - observation.content - == '{"content": [{"text": "Error occurred"}], "isError": true}' - ) assert observation.is_error is True - def test_execute_exception(self): + def test_call_tool_exception(self): """Test tool execution with exception.""" - # Mock exception during execution - self.mock_client.call_tool.side_effect = Exception("Connection failed") - - action = MCPToolAction( - tool_name="test_tool", - arguments={"param": "value"}, - ) - - observation = self.executor(action) + # Mock action + mock_action = MagicMock() + mock_action.model_dump.return_value = {"param": "value"} + + # Mock call_async_from_sync to return an error observation + def mock_call_async_from_sync(coro_func, **kwargs): + return MCPToolObservation( + content=[ + TextContent( + text="Error calling MCP tool test_tool: Connection failed" + ) + ], + is_error=True, + tool_name="test_tool", + ) + + self.mock_client.call_async_from_sync = mock_call_async_from_sync + + observation = self.executor(mock_action) assert isinstance(observation, MCPToolObservation) + assert isinstance(observation.content[0], TextContent) assert observation.tool_name == "test_tool" - assert observation.content == "" assert observation.is_error is True - assert ( - observation.error_message - and "Connection failed" in observation.error_message - ) - - def test_execute_empty_content(self): - """Test tool execution with empty content.""" - # Mock result with empty content - mock_result = MagicMock() - mock_result.content = [] - mock_result.isError = False - mock_result.model_dump.return_value = {"content": [], "isError": False} - - # Mock the client's call_tool method directly - self.mock_client.call_tool.return_value = mock_result - - action = MCPToolAction( - tool_name="test_tool", - arguments={"param": "value"}, - ) - - observation = self.executor(action) - - assert isinstance(observation, MCPToolObservation) - assert observation.tool_name == "test_tool" - assert observation.content == '{"content": [], "isError": false}' - assert observation.is_error is False + assert "Connection failed" in observation.content[0].text class TestMCPTool: @@ -180,185 +203,61 @@ def setup_method(self): """Set up test fixtures.""" self.mock_client = MagicMock() - # Mock tool map - mock_tool = MagicMock() - mock_tool.name = "test_tool" - mock_tool.description = "A test tool" - mock_tool.inputSchema = {"type": "object", "properties": {}} - - self.mock_client.tool_map = {"test_tool": mock_tool} + # Create mock MCP tool + self.mock_mcp_tool = MagicMock(spec=mcp.types.Tool) + self.mock_mcp_tool.name = "test_tool" + self.mock_mcp_tool.description = "A test tool" + self.mock_mcp_tool.inputSchema = { + "type": "object", + "properties": {"param": {"type": "string"}}, + } + self.mock_mcp_tool.annotations = None + self.mock_mcp_tool.meta = None - self.tool = MCPTool(mcp_client=self.mock_client, tool_name="test_tool") + self.tool = MCPTool(mcp_tool=self.mock_mcp_tool, mcp_client=self.mock_client) def test_mcp_tool_creation(self): """Test creating an MCP tool.""" assert self.tool.name == "test_tool" assert self.tool.description == "A test tool" - - def test_create_action(self): - """Test creating an action for the tool.""" - # Create action directly using the action type - action = MCPToolAction(tool_name="test_tool", arguments={"param": "value"}) - - assert isinstance(action, MCPToolAction) - assert action.tool_name == "test_tool" - assert action.arguments == {"param": "value"} - - def test_execute_action(self): - """Test executing an action through the tool.""" - # Mock successful execution - mock_result = MagicMock() - mock_result.content = [{"text": "Success"}] - mock_result.isError = False - mock_result.model_dump.return_value = { - "content": [{"text": "Success"}], - "isError": False, + assert self.tool.input_schema == { + "type": "object", + "properties": {"param": {"type": "string"}}, } - # Mock the client's call_tool method directly - self.mock_client.call_tool.return_value = mock_result - - action = MCPToolAction(tool_name="test_tool", arguments={"param": "value"}) - - observation = self.tool.call(action) - - assert isinstance(observation, MCPToolObservation) - assert observation.tool_name == "test_tool" - assert observation.is_error is False - - def test_to_openai_tool(self): - """Test converting to OpenAI tool format.""" - openai_tool = self.tool.to_openai_tool() - - assert openai_tool["type"] == "function" - assert openai_tool["function"]["name"] == "test_tool" - assert ( - "description" in openai_tool["function"] - and openai_tool["function"]["description"] == "A test tool" - ) - - def test_to_mcp_tool(self): - """Test converting to MCP tool format.""" - mcp_tool = self.tool.to_mcp_tool() - - assert mcp_tool["name"] == "test_tool" - assert mcp_tool["description"] == "A test tool" - assert "inputSchema" in mcp_tool - - -class TestMCPToolRegistry: - """Test MCPToolRegistry functionality.""" - - def setup_method(self): - """Set up test fixtures.""" - self.registry = MCPToolRegistry() - - def test_empty_registry(self): - """Test empty registry state.""" - assert len(self.registry.clients) == 0 - assert len(self.registry.tools) == 0 - assert len(self.registry.get_all_tools()) == 0 - - def test_add_client(self): - """Test adding a client to the registry.""" - mock_client = MagicMock() - - # Mock tool map with two tools - mock_tool1 = MagicMock() - mock_tool1.name = "tool1" - mock_tool1.description = "Tool 1" - mock_tool1.inputSchema = {} - - mock_tool2 = MagicMock() - mock_tool2.name = "tool2" - mock_tool2.description = "Tool 2" - mock_tool2.inputSchema = {} - - mock_client.tool_map = {"tool1": mock_tool1, "tool2": mock_tool2} - - self.registry.add_client("test_server", mock_client) - - assert "test_server" in self.registry.clients - assert self.registry.clients["test_server"] == mock_client - - # Should have created tools with prefixed names - assert "test_server:tool1" in self.registry.tools - assert "test_server:tool2" in self.registry.tools - - def test_get_all_tools(self): - """Test getting all tools from registry.""" - mock_client = MagicMock() - - # Mock tool map - mock_tool1 = MagicMock() - mock_tool1.name = "tool1" - mock_tool1.description = "Tool 1" - mock_tool1.inputSchema = {} - - mock_tool2 = MagicMock() - mock_tool2.name = "tool2" - mock_tool2.description = "Tool 2" - mock_tool2.inputSchema = {} - - mock_client.tool_map = {"tool1": mock_tool1, "tool2": mock_tool2} - - self.registry.add_client("test_server", mock_client) - - tools = self.registry.get_all_tools() - assert len(tools) == 2 - - tool_names = [tool.name for tool in tools] - assert "tool1" in tool_names - assert "tool2" in tool_names - - def test_get_tools_for_client(self): - """Test getting tools for a specific client.""" - mock_client1 = MagicMock() - mock_client2 = MagicMock() - - # Mock tool maps - mock_tool1 = MagicMock() - mock_tool1.name = "tool1" - mock_tool1.description = "Tool 1" - mock_tool1.inputSchema = {} - - mock_tool2 = MagicMock() - mock_tool2.name = "tool2" - mock_tool2.description = "Tool 2" - mock_tool2.inputSchema = {} - - mock_client1.tool_map = {"tool1": mock_tool1} - mock_client2.tool_map = {"tool2": mock_tool2} - - self.registry.add_client("server1", mock_client1) - self.registry.add_client("server2", mock_client2) - - server1_tools = self.registry.get_tools_for_client("server1") - server2_tools = self.registry.get_tools_for_client("server2") - - assert len(server1_tools) == 1 - assert len(server2_tools) == 1 - assert server1_tools[0].name == "tool1" - assert server2_tools[0].name == "tool2" - - def test_get_tool(self): - """Test getting a specific tool by name.""" - mock_client = MagicMock() - - mock_tool = MagicMock() - mock_tool.name = "test_tool" - mock_tool.description = "Test Tool" - mock_tool.inputSchema = {} - - mock_client.tool_map = {"test_tool": mock_tool} - - self.registry.add_client("test_server", mock_client) - - # Get tool by full name - tool = self.registry.get_tool("test_server:test_tool") - assert tool is not None - assert tool.name == "test_tool" - - # Non-existent tool should return None - non_existent = self.registry.get_tool("non_existent") - assert non_existent is None + def test_mcp_tool_with_annotations(self): + """Test creating an MCP tool with annotations.""" + # Mock tool with annotations + mock_tool_with_annotations = MagicMock(spec=mcp.types.Tool) + mock_tool_with_annotations.name = "annotated_tool" + mock_tool_with_annotations.description = "Tool with annotations" + mock_tool_with_annotations.inputSchema = {"type": "object"} + mock_tool_with_annotations.annotations = {"category": "utility"} + mock_tool_with_annotations.meta = {"version": "1.0"} + + tool = MCPTool(mcp_tool=mock_tool_with_annotations, mcp_client=self.mock_client) + + assert tool.name == "annotated_tool" + assert tool.description == "Tool with annotations" + assert tool.annotations is not None + + def test_mcp_tool_no_description(self): + """Test creating an MCP tool without description.""" + # Mock tool without description + mock_tool_no_desc = MagicMock(spec=mcp.types.Tool) + mock_tool_no_desc.name = "no_desc_tool" + mock_tool_no_desc.description = None + mock_tool_no_desc.inputSchema = {"type": "object"} + mock_tool_no_desc.annotations = None + mock_tool_no_desc.meta = None + + tool = MCPTool(mcp_tool=mock_tool_no_desc, mcp_client=self.mock_client) + + assert tool.name == "no_desc_tool" + assert tool.description == "No description provided" + + def test_executor_assignment(self): + """Test that the tool has the correct executor.""" + assert isinstance(self.tool.executor, MCPToolExecutor) + assert self.tool.executor.tool_name == "test_tool" + assert self.tool.executor.client == self.mock_client diff --git a/tests/sdk/mcp/test_utils.py b/tests/sdk/mcp/test_utils.py index 1636aa4db0c..098ba389c5c 100644 --- a/tests/sdk/mcp/test_utils.py +++ b/tests/sdk/mcp/test_utils.py @@ -1,286 +1,208 @@ +"""Tests for MCP utils functionality with new simplified implementation.""" + from unittest.mock import MagicMock, patch -import pytest +from openhands.sdk.mcp.utils import create_mcp_tools -from openhands.sdk.config.mcp_config import ( - MCPConfig, - MCPSHTTPServerConfig, - MCPSSEServerConfig, - MCPStdioServerConfig, -) -from openhands.sdk.mcp.utils import create_mcp_client, create_mcp_tools_from_config +def test_create_mcp_tools_empty_config(): + """Test creating MCP tools with empty configuration.""" + config = {} -class TestCreateMCPClient: - """Test create_mcp_client function.""" + # Mock the MCPClient and its methods + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = MagicMock() + mock_client_class.return_value = mock_client - def test_create_mcp_client_stdio(self): - """Test creating MCP client with stdio configuration.""" - config = MCPStdioServerConfig( - name="test_server", - command="python", - args=["-m", "test_server"], - env={"TEST": "value"}, - ) + # Mock call_async_from_sync to return empty list + mock_client.call_async_from_sync.return_value = [] - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = MagicMock() - mock_client_class.return_value = mock_client + tools = create_mcp_tools(config) - client = create_mcp_client(config) + assert len(tools) == 0 - assert client == mock_client - mock_client.connect_stdio.assert_called_once_with(config, 30.0) - def test_create_mcp_client_sse(self): - """Test creating MCP client with SSE configuration.""" - config = MCPSSEServerConfig(url="http://localhost:8000/sse", api_key="token") +def test_create_mcp_tools_stdio_server(): + """Test creating MCP tools with stdio server configuration.""" + config = { + "mcpServers": { + "stdio_server": { + "transport": "stdio", + "command": "python", + "args": ["./server.py"], + "env": {"DEBUG": "true"}, + "cwd": "/path/to/server", + } + } + } - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = MagicMock() - mock_client_class.return_value = mock_client + # Mock the MCPClient and its methods + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = MagicMock() + mock_client_class.return_value = mock_client + + # Mock tool + mock_tool = MagicMock() + mock_tool.name = "test_tool" - client = create_mcp_client(config) + # Mock call_async_from_sync to return the tools + mock_client.call_async_from_sync.return_value = [mock_tool] - assert client == mock_client - mock_client.connect_http.assert_called_once_with(config, None, 30.0) + tools = create_mcp_tools(config) - def test_create_mcp_client_shttp(self): - """Test creating MCP client with SHTTP configuration.""" - config = MCPSHTTPServerConfig( - url="http://localhost:8000/shttp", api_key="token" - ) + assert len(tools) == 1 + assert tools[0] == mock_tool - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = MagicMock() - mock_client_class.return_value = mock_client - client = create_mcp_client(config) +def test_create_mcp_tools_http_server(): + """Test creating MCP tools with HTTP server configuration.""" + config = { + "mcpServers": { + "http_server": { + "transport": "http", + "url": "https://api.example.com/mcp", + "headers": {"Authorization": "Bearer token"}, + "auth": "oauth", + } + } + } - assert client == mock_client - mock_client.connect_http.assert_called_once_with(config, None, 30.0) + # Mock the MCPClient and its methods + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = MagicMock() + mock_client_class.return_value = mock_client - def test_create_mcp_client_with_timeout(self): - """Test creating MCP client with custom timeout.""" - config = MCPSSEServerConfig(url="http://localhost:8000/sse") + # Mock tool + mock_tool = MagicMock() + mock_tool.name = "http_tool" + + # Mock call_async_from_sync to return the tools + mock_client.call_async_from_sync.return_value = [mock_tool] + + tools = create_mcp_tools(config) + + assert len(tools) == 1 + assert tools[0] == mock_tool + + +def test_create_mcp_tools_mixed_servers(): + """Test creating MCP tools with mixed server configurations.""" + config = { + "mcpServers": { + "stdio_server": { + "transport": "stdio", + "command": "python", + "args": ["./server.py"], + }, + "http_server": { + "transport": "http", + "url": "https://api.example.com/mcp", + }, + } + } + + # Mock the MCPClient and its methods + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = MagicMock() + mock_client_class.return_value = mock_client - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = MagicMock() - mock_client_class.return_value = mock_client + # Mock tools + mock_tool1 = MagicMock() + mock_tool1.name = "stdio_tool" + mock_tool2 = MagicMock() + mock_tool2.name = "http_tool" - client = create_mcp_client(config, timeout=10.0) + # Mock call_async_from_sync to return the tools + mock_client.call_async_from_sync.return_value = [mock_tool1, mock_tool2] - assert client == mock_client - mock_client.connect_http.assert_called_once_with(config, None, 10.0) + tools = create_mcp_tools(config) - def test_create_mcp_client_with_conversation_id(self): - """Test creating MCP client with conversation ID.""" - config = MCPSSEServerConfig(url="http://localhost:8000/sse") + assert len(tools) == 2 + assert tools[0] == mock_tool1 + assert tools[1] == mock_tool2 - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = MagicMock() - mock_client_class.return_value = mock_client - client = create_mcp_client(config, conversation_id="test-conv-123") +def test_create_mcp_tools_with_timeout(): + """Test creating MCP tools with custom timeout.""" + config = { + "mcpServers": { + "test_server": { + "transport": "stdio", + "command": "python", + "args": ["./server.py"], + } + } + } - assert client == mock_client - mock_client.connect_http.assert_called_once_with( - config, "test-conv-123", 30.0 - ) + # Mock the MCPClient and its methods + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = MagicMock() + mock_client_class.return_value = mock_client - def test_create_mcp_client_invalid_config(self): - """Test creating MCP client with invalid configuration.""" - config = MagicMock() # Invalid config type + # Mock call_async_from_sync to return empty list + mock_client.call_async_from_sync.return_value = [] - with pytest.raises(ValueError, match="Unsupported server config type"): - create_mcp_client(config) + tools = create_mcp_tools(config, timeout=60.0) - def test_create_mcp_client_connection_failure(self): - """Test creating MCP client with connection failure.""" - config = MCPSSEServerConfig(url="http://unreachable:8000/sse") + # Verify timeout was passed to call_async_from_sync + mock_client.call_async_from_sync.assert_called_once() + call_args = mock_client.call_async_from_sync.call_args + assert call_args.kwargs.get("timeout") == 60.0 - with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: - mock_client = MagicMock() - mock_client_class.return_value = mock_client - mock_client.connect_http.side_effect = ConnectionError("Connection failed") + assert len(tools) == 0 - with pytest.raises(ConnectionError): - create_mcp_client(config) +def test_create_mcp_tools_connection_error(): + """Test creating MCP tools with connection error.""" + config = { + "mcpServers": { + "failing_server": { + "transport": "stdio", + "command": "nonexistent_command", + } + } + } -class TestCreateMCPToolsFromConfig: - """Test create_mcp_tools_from_config function.""" + # Mock the MCPClient and its methods + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: + mock_client = MagicMock() + mock_client_class.return_value = mock_client - def test_create_mcp_tools_from_config_empty(self): - """Test creating MCP tools from empty configuration.""" - config = MCPConfig() + # Mock call_async_from_sync to return empty list (connection + # error handled internally) + mock_client.call_async_from_sync.return_value = [] - with patch("openhands.sdk.mcp.utils.MCPToolRegistry") as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [] + # Should not raise exception, but return empty list + tools = create_mcp_tools(config) - tools = create_mcp_tools_from_config(config) + assert len(tools) == 0 - assert len(tools) == 0 - def test_create_mcp_tools_from_config_sse_success(self): - """Test creating MCP tools from SSE server configuration.""" - config = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://localhost:8000/sse")] - ) +def test_create_mcp_tools_dict_config(): + """Test creating MCP tools with dict configuration (not MCPConfig object).""" + config = { + "mcpServers": { + "test_server": { + "transport": "stdio", + "command": "python", + "args": ["./server.py"], + } + } + } - # Mock client and tools - mock_client = MagicMock() - mock_tool = MagicMock() - mock_tool.name = "tool1" - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client - ): - with patch( - "openhands.sdk.mcp.utils.MCPToolRegistry" - ) as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool] - - tools = create_mcp_tools_from_config(config) - - assert len(tools) == 1 - assert tools[0] == mock_tool - mock_registry.add_client.assert_called_once_with( - "http://localhost:8000/sse", mock_client - ) - - def test_create_mcp_tools_from_config_stdio_success(self): - """Test creating MCP tools from stdio server configuration.""" - config = MCPConfig( - stdio_servers=[ - MCPStdioServerConfig( - name="test_server", command="python", args=["-m", "test_server"] - ) - ] - ) - - # Mock client and tools - mock_client = MagicMock() - mock_tool = MagicMock() - mock_tool.name = "tool1" - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client - ): - with patch( - "openhands.sdk.mcp.utils.MCPToolRegistry" - ) as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool] - - tools = create_mcp_tools_from_config(config) - - assert len(tools) == 1 - assert tools[0] == mock_tool - mock_registry.add_client.assert_called_once_with( - "test_server", mock_client - ) - - def test_create_mcp_tools_from_config_mixed_servers(self): - """Test creating MCP tools from mixed server configurations.""" - config = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://localhost:8000/sse")], - stdio_servers=[ - MCPStdioServerConfig( - name="stdio_server", command="python", args=["-m", "stdio_server"] - ) - ], - shttp_servers=[MCPSHTTPServerConfig(url="http://localhost:8001/shttp")], - ) - - # Mock client and tools + # Mock the MCPClient and its methods + with patch("openhands.sdk.mcp.utils.MCPClient") as mock_client_class: mock_client = MagicMock() - mock_tool1 = MagicMock() - mock_tool1.name = "tool1" - mock_tool2 = MagicMock() - mock_tool2.name = "tool2" - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client - ): - with patch( - "openhands.sdk.mcp.utils.MCPToolRegistry" - ) as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool1, mock_tool2] - - tools = create_mcp_tools_from_config(config) - - assert len(tools) == 2 - # Should have called add_client for all 3 servers - assert mock_registry.add_client.call_count == 3 - - def test_create_mcp_tools_from_config_with_errors(self): - """Test creating MCP tools from configuration with some connection errors.""" - config = MCPConfig( - sse_servers=[ - MCPSSEServerConfig(url="http://good-server:8000/sse"), - MCPSSEServerConfig(url="http://bad-server:8000/sse"), - ] - ) - - # Mock one successful client and one that fails - mock_good_client = MagicMock() - mock_tool = MagicMock() - mock_tool.name = "tool1" - - def mock_create_client(server_config, conversation_id=None, timeout=None): - if "good-server" in server_config.url: - return mock_good_client - else: - raise Exception("Connection failed") - - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", side_effect=mock_create_client - ): - with patch( - "openhands.sdk.mcp.utils.MCPToolRegistry" - ) as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool] - - tools = create_mcp_tools_from_config(config) - - # Should get tools from the good server only - assert len(tools) == 1 - assert tools[0] == mock_tool - # Should have only added the successful client - mock_registry.add_client.assert_called_once_with( - "http://good-server:8000/sse", mock_good_client - ) - - def test_create_mcp_tools_from_config_with_timeout(self): - """Test creating MCP tools from configuration with custom timeout.""" - config = MCPConfig( - sse_servers=[MCPSSEServerConfig(url="http://localhost:8000/sse")] - ) + mock_client_class.return_value = mock_client - mock_client = MagicMock() + # Mock tool mock_tool = MagicMock() + mock_tool.name = "dict_tool" - with patch( - "openhands.sdk.mcp.utils.create_mcp_client", return_value=mock_client - ) as mock_create: - with patch( - "openhands.sdk.mcp.utils.MCPToolRegistry" - ) as mock_registry_class: - mock_registry = MagicMock() - mock_registry_class.return_value = mock_registry - mock_registry.get_all_tools.return_value = [mock_tool] + # Mock call_async_from_sync to return the tools + mock_client.call_async_from_sync.return_value = [mock_tool] - create_mcp_tools_from_config(config, timeout=15.0) + tools = create_mcp_tools(config) - # Verify timeout was passed to create_mcp_client - mock_create.assert_called_with(config.sse_servers[0], None, 15.0) + assert len(tools) == 1 + assert tools[0] == mock_tool From 991f93f3531fbd96e27d224303ad082c5c3b840c Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 14:10:20 -0400 Subject: [PATCH 20/28] define a MCPActionBase to make a special case for MCP --- openhands/sdk/mcp/tool.py | 8 ++++---- openhands/sdk/tool/__init__.py | 6 +++++- openhands/sdk/tool/schema.py | 6 ++++++ 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/openhands/sdk/mcp/tool.py b/openhands/sdk/mcp/tool.py index cf3105baec5..bad1e6503b9 100644 --- a/openhands/sdk/mcp/tool.py +++ b/openhands/sdk/mcp/tool.py @@ -8,7 +8,7 @@ from openhands.sdk.llm import TextContent from openhands.sdk.logger import get_logger from openhands.sdk.mcp import MCPToolObservation -from openhands.sdk.tool import ActionBase, Tool, ToolAnnotations, ToolExecutor +from openhands.sdk.tool import MCPActionBase, Tool, ToolAnnotations, ToolExecutor if TYPE_CHECKING: @@ -29,7 +29,7 @@ def __init__(self, tool_name: str, client: "MCPClient"): self.tool_name = tool_name self.client = client - async def call_tool(self, action: ActionBase) -> MCPToolObservation: + async def call_tool(self, action: MCPActionBase) -> MCPToolObservation: async with self.client: assert self.client.is_connected(), "MCP client is not connected." try: @@ -56,14 +56,14 @@ async def call_tool(self, action: ActionBase) -> MCPToolObservation: tool_name=self.tool_name, ) - def __call__(self, action: ActionBase) -> MCPToolObservation: + def __call__(self, action: MCPActionBase) -> MCPToolObservation: """Execute an MCP tool call.""" return self.client.call_async_from_sync( self.call_tool, action=action, timeout=60.0 ) -class MCPTool(Tool[ActionBase, MCPToolObservation]): +class MCPTool(Tool[MCPActionBase, MCPToolObservation]): """MCP Tool that wraps an MCP client and provides tool functionality.""" def __init__( diff --git a/openhands/sdk/tool/__init__.py b/openhands/sdk/tool/__init__.py index 8a003a43201..d886a547699 100644 --- a/openhands/sdk/tool/__init__.py +++ b/openhands/sdk/tool/__init__.py @@ -1,9 +1,12 @@ """OpenHands runtime package.""" from openhands.sdk.tool.builtins import BUILT_IN_TOOLS, FinishTool -from openhands.sdk.tool.tool import ( +from openhands.sdk.tool.schema import ( ActionBase, + MCPActionBase, ObservationBase, +) +from openhands.sdk.tool.tool import ( Tool, ToolAnnotations, ToolExecutor, @@ -15,6 +18,7 @@ "ToolAnnotations", "ToolExecutor", "ActionBase", + "MCPActionBase", "ObservationBase", "FinishTool", "BUILT_IN_TOOLS", diff --git a/openhands/sdk/tool/schema.py b/openhands/sdk/tool/schema.py index 962f6153579..84b8855dec2 100644 --- a/openhands/sdk/tool/schema.py +++ b/openhands/sdk/tool/schema.py @@ -154,6 +154,12 @@ class ActionBase(Schema): ) +class MCPActionBase(ActionBase): + """Base schema for MCP input action.""" + + model_config = ConfigDict(extra="allow") + + class ObservationBase(Schema): """Base schema for output observation.""" From 7df9459d029779333c3ed60d7e78a9b5d68292c9 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 14:22:23 -0400 Subject: [PATCH 21/28] modify readme --- README.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b92470b3d10..f46136dd8f6 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,10 @@ A clean, modular SDK for building AI agents with OpenHands. This project represe ## Project Overview The OpenHands Agent SDK provides a streamlined framework for creating AI agents that can interact with tools, manage conversations, and integrate with various LLM providers. + ## Repository Structure -``` +```plain agent-sdk/ ├── Makefile # Build and development commands ├── pyproject.toml # Workspace configuration @@ -102,7 +103,7 @@ conversation.run() ### Agents -Agents are the central orchestrators that coordinate between LLMs, tools, and conversations: +Agents are the central orchestrators that coordinate between LLMs and tools: ```python from openhands.sdk import Agent, LLM @@ -142,6 +143,7 @@ Tools provide agents with capabilities to interact with the environment: #### Simplified Pattern (Recommended) ```python +from openhands.sdk import TextContent, ImageContent from openhands.tools import BashTool, FileEditorTool # Direct instantiation with simplified API @@ -182,8 +184,8 @@ class GrepObservation(ObservationBase): output: str = Field(default='') @property - def agent_observation(self) -> str: - return self.output + def agent_observation(self) -> list[TextContent | ImageContent]: + return TextContent(text=self.output) # --- Executor --- class GrepExecutor(ToolExecutor[GrepAction, GrepObservation]): @@ -229,6 +231,7 @@ conversation.run() The context system manages agent state, environment, and conversation history. Context is automatically managed but you can customize your context with: + 1. [Repo Microagents](https://docs.all-hands.dev/usage/prompting/microagents-repo) that provide agent with context of your repository. 2. [Knowledge Microagents](https://docs.all-hands.dev/usage/prompting/microagents-keyword) that provide agent with context when user mentioned certain keywords 3. Providing custom suffix for system and user prompt. From 04e2cfb0737bd7318315e59d142d4511c8b87764 Mon Sep 17 00:00:00 2001 From: openhands Date: Fri, 5 Sep 2025 18:30:15 +0000 Subject: [PATCH 22/28] Fix failing tests after base class definition changes - Fixed security_risk enum to only include {'LOW', 'MEDIUM', 'HIGH'} values - Made security_risk field required in JSON schema but with default value for backward compatibility - Fixed MockObservation instantiations to include required MCP fields - Fixed ImageContent instantiations to include required data and mimeType fields - Fixed Content import to use BaseContent in test_message.py - Fixed TextContent serialization by removing multiple inheritance conflicts - Fixed ImageContent type to use 'image_url' instead of 'image' - Added security_risk parameter to all MockAction test instantiations - Fixed type annotations for model_json_schema method override Co-authored-by: openhands --- openhands/sdk/llm/message.py | 14 +++++--- openhands/sdk/tool/schema.py | 35 +++++++++++++++++-- openhands/sdk/tool/security_prompt.py | 2 +- .../conversation/test_confirmation_mode.py | 6 ++-- tests/sdk/event/test_events_to_messages.py | 6 ++-- tests/sdk/llm/test_message.py | 21 ++++++++--- tests/sdk/llm/test_message_serialization.py | 18 ++++++++-- tests/sdk/tool/test_tool.py | 19 +++++----- 8 files changed, 91 insertions(+), 30 deletions(-) diff --git a/openhands/sdk/llm/message.py b/openhands/sdk/llm/message.py index cc655aab53d..fc5bb02736a 100644 --- a/openhands/sdk/llm/message.py +++ b/openhands/sdk/llm/message.py @@ -16,9 +16,11 @@ def to_llm_dict( raise NotImplementedError("Subclasses should implement this method.") -class TextContent(mcp.types.TextContent, BaseContent): +class TextContent(BaseContent): type: Literal["text"] = "text" text: str + annotations: mcp.types.Annotations | None = None + meta: dict[str, Any] | None = None def to_llm_dict(self) -> dict[str, str | dict[str, str]]: """Convert to LLM API format.""" @@ -31,15 +33,19 @@ def to_llm_dict(self) -> dict[str, str | dict[str, str]]: return data -class ImageContent(mcp.types.ImageContent, BaseContent): - type: Literal["image"] = "image" +class ImageContent(BaseContent): + type: Literal["image_url"] = "image_url" image_urls: list[str] + data: str + mimeType: str + annotations: mcp.types.Annotations | None = None + meta: dict[str, Any] | None = None def to_llm_dict(self) -> list[dict[str, str | dict[str, str]]]: """Convert to LLM API format.""" images: list[dict[str, str | dict[str, str]]] = [] for url in self.image_urls: - images.append({"type": self.type, "image_url": {"url": url}}) + images.append({"type": "image_url", "image_url": {"url": url}}) if self.cache_prompt and images: images[-1]["cache_control"] = {"type": "ephemeral"} return images diff --git a/openhands/sdk/tool/schema.py b/openhands/sdk/tool/schema.py index 84b8855dec2..9abf149ba8c 100644 --- a/openhands/sdk/tool/schema.py +++ b/openhands/sdk/tool/schema.py @@ -1,4 +1,4 @@ -from typing import Any, TypeVar +from typing import Any, Literal, TypeVar from pydantic import BaseModel, ConfigDict, Field, create_model @@ -150,9 +150,40 @@ class ActionBase(Schema): """Base schema for input action.""" security_risk: SECURITY_RISK_LITERAL = Field( - default="UNKNOWN", description=SECURITY_RISK_DESC, exclude=True + default="LOW", description=SECURITY_RISK_DESC ) + @classmethod + def model_json_schema( + cls, + by_alias: bool = True, + ref_template: str = "#/$defs/{model}", + schema_generator: type | None = None, + mode: Literal["validation", "serialization"] = "validation", + ) -> dict[str, Any]: + """Generate JSON schema with security_risk as required field.""" + # Import here to avoid circular imports + from pydantic.json_schema import GenerateJsonSchema + + if schema_generator is None: + schema_generator = GenerateJsonSchema + + schema = super().model_json_schema( + by_alias=by_alias, + ref_template=ref_template, + schema_generator=schema_generator, + mode=mode, + ) + + # Force security_risk to be in required fields for MCP compatibility + if "properties" in schema and "security_risk" in schema["properties"]: + if "required" not in schema: + schema["required"] = [] + if "security_risk" not in schema["required"]: + schema["required"].append("security_risk") + + return schema + class MCPActionBase(ActionBase): """Base schema for MCP input action.""" diff --git a/openhands/sdk/tool/security_prompt.py b/openhands/sdk/tool/security_prompt.py index 2121f8f6283..7467ac24187 100644 --- a/openhands/sdk/tool/security_prompt.py +++ b/openhands/sdk/tool/security_prompt.py @@ -2,4 +2,4 @@ SECURITY_RISK_DESC = "The LLM's assessment of the safety risk of this action." -SECURITY_RISK_LITERAL = Literal["LOW", "MEDIUM", "HIGH", "UNKNOWN"] +SECURITY_RISK_LITERAL = Literal["LOW", "MEDIUM", "HIGH"] diff --git a/tests/sdk/conversation/test_confirmation_mode.py b/tests/sdk/conversation/test_confirmation_mode.py index 63cada8e539..5b06dd4628e 100644 --- a/tests/sdk/conversation/test_confirmation_mode.py +++ b/tests/sdk/conversation/test_confirmation_mode.py @@ -20,7 +20,7 @@ from openhands.sdk.event import ActionEvent, MessageEvent, ObservationEvent from openhands.sdk.event.llm_convertible import UserRejectObservation from openhands.sdk.event.utils import get_unmatched_actions -from openhands.sdk.llm import Message, TextContent +from openhands.sdk.llm import ImageContent, Message, TextContent from openhands.sdk.tool import Tool, ToolExecutor from openhands.sdk.tool.schema import ActionBase, ObservationBase @@ -37,8 +37,8 @@ class MockObservation(ObservationBase): result: str @property - def agent_observation(self) -> str: - return self.result + def agent_observation(self) -> list[TextContent | ImageContent]: + return [TextContent(text=self.result)] class TestConfirmationMode: diff --git a/tests/sdk/event/test_events_to_messages.py b/tests/sdk/event/test_events_to_messages.py index 5d6b8ca9c14..c260110b536 100644 --- a/tests/sdk/event/test_events_to_messages.py +++ b/tests/sdk/event/test_events_to_messages.py @@ -15,7 +15,7 @@ ObservationEvent, SystemPromptEvent, ) -from openhands.sdk.llm import Message, TextContent +from openhands.sdk.llm import ImageContent, Message, TextContent from openhands.sdk.tool import ActionBase, ObservationBase @@ -31,8 +31,8 @@ class MockObservation(ObservationBase): result: str @property - def agent_observation(self) -> str: - return self.result + def agent_observation(self) -> list[TextContent | ImageContent]: + return [TextContent(text=self.result)] def create_tool_call( diff --git a/tests/sdk/llm/test_message.py b/tests/sdk/llm/test_message.py index e48277b3816..2e973c38ba1 100644 --- a/tests/sdk/llm/test_message.py +++ b/tests/sdk/llm/test_message.py @@ -2,10 +2,10 @@ def test_content_base_class_not_implemented(): - """Test that Content base class raises NotImplementedError.""" - from openhands.sdk.llm.message import Content + """Test that BaseContent base class raises NotImplementedError.""" + from openhands.sdk.llm.message import BaseContent - content = Content(type="test") + content = BaseContent() with pytest.raises( NotImplementedError, match="Subclasses should implement this method" ): @@ -31,6 +31,8 @@ def test_image_content_with_cache_prompt(): content = ImageContent( image_urls=["data:image/png;base64,abc123", "data:image/jpeg;base64,def456"], cache_prompt=True, + data="abc123", # Required by MCP base class + mimeType="image/png", # Required by MCP base class ) result = content.to_llm_dict() @@ -57,7 +59,11 @@ def test_message_contains_image_property(): role="user", content=[ TextContent(text="Look at this:"), - ImageContent(image_urls=["data:image/png;base64,abc123"]), + ImageContent( + image_urls=["data:image/png;base64,abc123"], + data="abc123", + mimeType="image/png", + ), ], ) assert image_message.contains_image @@ -90,7 +96,12 @@ def test_message_tool_role_with_image_cache_prompt(): message = Message( role="tool", content=[ - ImageContent(image_urls=["data:image/png;base64,abc123"], cache_prompt=True) + ImageContent( + image_urls=["data:image/png;base64,abc123"], + cache_prompt=True, + data="abc123", + mimeType="image/png", + ) ], tool_call_id="call_123", name="test_tool", diff --git a/tests/sdk/llm/test_message_serialization.py b/tests/sdk/llm/test_message_serialization.py index f30c3669809..7987d348b5f 100644 --- a/tests/sdk/llm/test_message_serialization.py +++ b/tests/sdk/llm/test_message_serialization.py @@ -51,7 +51,11 @@ def test_vision_message_storage_serialization(self): role="user", content=[ TextContent(text="What's in this image?"), - ImageContent(image_urls=["https://example.com/image.jpg"]), + ImageContent( + image_urls=["https://example.com/image.jpg"], + data="dummy_data", + mimeType="image/jpeg", + ), ], vision_enabled=True, ) @@ -198,7 +202,11 @@ def test_vision_enabled_triggers_list_serialization(self): role="user", content=[ TextContent(text="What's in this image?"), - ImageContent(image_urls=["https://example.com/image.jpg"]), + ImageContent( + image_urls=["https://example.com/image.jpg"], + data="dummy_data", + mimeType="image/jpeg", + ), ], vision_enabled=True, ) @@ -286,7 +294,11 @@ def test_content_type_preservation_in_list_serializer(self): role="user", content=[ TextContent(text="Describe this image"), - ImageContent(image_urls=["https://example.com/image.jpg"]), + ImageContent( + image_urls=["https://example.com/image.jpg"], + data="dummy_data", + mimeType="image/jpeg", + ), ], vision_enabled=True, # Forces list serializer ) diff --git a/tests/sdk/tool/test_tool.py b/tests/sdk/tool/test_tool.py index ebdb72bf5ba..4a03a6966bc 100644 --- a/tests/sdk/tool/test_tool.py +++ b/tests/sdk/tool/test_tool.py @@ -64,7 +64,7 @@ def __call__(self, action: MockAction) -> MockObservation: ) assert tool.executor is not None - action = MockAction(command="test") + action = MockAction(command="test", security_risk="LOW") result = tool.call(action) assert isinstance(result, MockObservation) assert result.result == "Executed: test" @@ -147,7 +147,7 @@ def test_call_without_executor(self): output_schema=MockObservation, ) - action = MockAction(command="test") + action = MockAction(command="test", security_risk="LOW") with pytest.raises( NotImplementedError, match="Tool 'test_tool' has no executor" ): @@ -168,7 +168,7 @@ def __call__(self, action: MockAction) -> MockObservation: executor=MockExecutor(), ) - action = MockAction(command="test_command") + action = MockAction(command="test_command", security_risk="LOW") result = tool.call(action) assert isinstance(result, MockObservation) @@ -218,7 +218,7 @@ def __call__(self, action: MockAction) -> MockObservation: executor=MockExecutor(), ) - action = MockAction(command="test") + action = MockAction(command="test", security_risk="LOW") result = tool.call(action) # Should return the correct observation type @@ -240,7 +240,7 @@ def __call__(self, action: MockAction) -> MockObservation: executor=MockExecutor(), ) - action = MockAction(command="test") + action = MockAction(command="test", security_risk="LOW") result = tool.call(action) assert isinstance(result, MockObservation) @@ -261,6 +261,7 @@ def test_action_validation_with_nested_data(self): "command": "test", "nested": {"value": "test"}, "array_field": [1, 2, 3], + "security_risk": "LOW", } action = tool.action_type.model_validate(action_data) @@ -324,7 +325,7 @@ def __call__(self, action: MockAction) -> MockObservation: tool.executor = MockExecutor() # Now it should work - action = MockAction(command="test") + action = MockAction(command="test", security_risk="LOW") result = tool.call(action) assert isinstance(result, MockObservation) assert result.result == "Attached: test" @@ -373,7 +374,7 @@ def __call__(self, action: MockAction) -> ComplexObservation: executor=MockComplexExecutor(), ) - action = MockAction(command="test_command") + action = MockAction(command="test_command", security_risk="LOW") result = tool.call(action) assert isinstance(result, ComplexObservation) @@ -395,7 +396,7 @@ def __call__(self, action: MockAction) -> MockObservation: executor=FailingExecutor(), ) - action = MockAction(command="test") + action = MockAction(command="test", security_risk="LOW") with pytest.raises(RuntimeError, match="Executor failed"): tool.call(action) @@ -418,7 +419,7 @@ def __call__(self, action: MockAction) -> StrictObservation: executor=ValidExecutor(), ) - action = MockAction(command="test") + action = MockAction(command="test", security_risk="LOW") result = tool.call(action) assert isinstance(result, StrictObservation) assert result.message == "success" From 694d82c8da3cf0c4c8ce65cf34c56b4a35073a7b Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 14:39:41 -0400 Subject: [PATCH 23/28] Revert "Fix failing tests after base class definition changes" This reverts commit 04e2cfb0737bd7318315e59d142d4511c8b87764. --- openhands/sdk/llm/message.py | 14 +++----- openhands/sdk/tool/schema.py | 35 ++----------------- openhands/sdk/tool/security_prompt.py | 2 +- .../conversation/test_confirmation_mode.py | 6 ++-- tests/sdk/event/test_events_to_messages.py | 6 ++-- tests/sdk/llm/test_message.py | 21 +++-------- tests/sdk/llm/test_message_serialization.py | 18 ++-------- tests/sdk/tool/test_tool.py | 19 +++++----- 8 files changed, 30 insertions(+), 91 deletions(-) diff --git a/openhands/sdk/llm/message.py b/openhands/sdk/llm/message.py index fc5bb02736a..cc655aab53d 100644 --- a/openhands/sdk/llm/message.py +++ b/openhands/sdk/llm/message.py @@ -16,11 +16,9 @@ def to_llm_dict( raise NotImplementedError("Subclasses should implement this method.") -class TextContent(BaseContent): +class TextContent(mcp.types.TextContent, BaseContent): type: Literal["text"] = "text" text: str - annotations: mcp.types.Annotations | None = None - meta: dict[str, Any] | None = None def to_llm_dict(self) -> dict[str, str | dict[str, str]]: """Convert to LLM API format.""" @@ -33,19 +31,15 @@ def to_llm_dict(self) -> dict[str, str | dict[str, str]]: return data -class ImageContent(BaseContent): - type: Literal["image_url"] = "image_url" +class ImageContent(mcp.types.ImageContent, BaseContent): + type: Literal["image"] = "image" image_urls: list[str] - data: str - mimeType: str - annotations: mcp.types.Annotations | None = None - meta: dict[str, Any] | None = None def to_llm_dict(self) -> list[dict[str, str | dict[str, str]]]: """Convert to LLM API format.""" images: list[dict[str, str | dict[str, str]]] = [] for url in self.image_urls: - images.append({"type": "image_url", "image_url": {"url": url}}) + images.append({"type": self.type, "image_url": {"url": url}}) if self.cache_prompt and images: images[-1]["cache_control"] = {"type": "ephemeral"} return images diff --git a/openhands/sdk/tool/schema.py b/openhands/sdk/tool/schema.py index 9abf149ba8c..84b8855dec2 100644 --- a/openhands/sdk/tool/schema.py +++ b/openhands/sdk/tool/schema.py @@ -1,4 +1,4 @@ -from typing import Any, Literal, TypeVar +from typing import Any, TypeVar from pydantic import BaseModel, ConfigDict, Field, create_model @@ -150,40 +150,9 @@ class ActionBase(Schema): """Base schema for input action.""" security_risk: SECURITY_RISK_LITERAL = Field( - default="LOW", description=SECURITY_RISK_DESC + default="UNKNOWN", description=SECURITY_RISK_DESC, exclude=True ) - @classmethod - def model_json_schema( - cls, - by_alias: bool = True, - ref_template: str = "#/$defs/{model}", - schema_generator: type | None = None, - mode: Literal["validation", "serialization"] = "validation", - ) -> dict[str, Any]: - """Generate JSON schema with security_risk as required field.""" - # Import here to avoid circular imports - from pydantic.json_schema import GenerateJsonSchema - - if schema_generator is None: - schema_generator = GenerateJsonSchema - - schema = super().model_json_schema( - by_alias=by_alias, - ref_template=ref_template, - schema_generator=schema_generator, - mode=mode, - ) - - # Force security_risk to be in required fields for MCP compatibility - if "properties" in schema and "security_risk" in schema["properties"]: - if "required" not in schema: - schema["required"] = [] - if "security_risk" not in schema["required"]: - schema["required"].append("security_risk") - - return schema - class MCPActionBase(ActionBase): """Base schema for MCP input action.""" diff --git a/openhands/sdk/tool/security_prompt.py b/openhands/sdk/tool/security_prompt.py index 7467ac24187..2121f8f6283 100644 --- a/openhands/sdk/tool/security_prompt.py +++ b/openhands/sdk/tool/security_prompt.py @@ -2,4 +2,4 @@ SECURITY_RISK_DESC = "The LLM's assessment of the safety risk of this action." -SECURITY_RISK_LITERAL = Literal["LOW", "MEDIUM", "HIGH"] +SECURITY_RISK_LITERAL = Literal["LOW", "MEDIUM", "HIGH", "UNKNOWN"] diff --git a/tests/sdk/conversation/test_confirmation_mode.py b/tests/sdk/conversation/test_confirmation_mode.py index 5b06dd4628e..63cada8e539 100644 --- a/tests/sdk/conversation/test_confirmation_mode.py +++ b/tests/sdk/conversation/test_confirmation_mode.py @@ -20,7 +20,7 @@ from openhands.sdk.event import ActionEvent, MessageEvent, ObservationEvent from openhands.sdk.event.llm_convertible import UserRejectObservation from openhands.sdk.event.utils import get_unmatched_actions -from openhands.sdk.llm import ImageContent, Message, TextContent +from openhands.sdk.llm import Message, TextContent from openhands.sdk.tool import Tool, ToolExecutor from openhands.sdk.tool.schema import ActionBase, ObservationBase @@ -37,8 +37,8 @@ class MockObservation(ObservationBase): result: str @property - def agent_observation(self) -> list[TextContent | ImageContent]: - return [TextContent(text=self.result)] + def agent_observation(self) -> str: + return self.result class TestConfirmationMode: diff --git a/tests/sdk/event/test_events_to_messages.py b/tests/sdk/event/test_events_to_messages.py index c260110b536..5d6b8ca9c14 100644 --- a/tests/sdk/event/test_events_to_messages.py +++ b/tests/sdk/event/test_events_to_messages.py @@ -15,7 +15,7 @@ ObservationEvent, SystemPromptEvent, ) -from openhands.sdk.llm import ImageContent, Message, TextContent +from openhands.sdk.llm import Message, TextContent from openhands.sdk.tool import ActionBase, ObservationBase @@ -31,8 +31,8 @@ class MockObservation(ObservationBase): result: str @property - def agent_observation(self) -> list[TextContent | ImageContent]: - return [TextContent(text=self.result)] + def agent_observation(self) -> str: + return self.result def create_tool_call( diff --git a/tests/sdk/llm/test_message.py b/tests/sdk/llm/test_message.py index 2e973c38ba1..e48277b3816 100644 --- a/tests/sdk/llm/test_message.py +++ b/tests/sdk/llm/test_message.py @@ -2,10 +2,10 @@ def test_content_base_class_not_implemented(): - """Test that BaseContent base class raises NotImplementedError.""" - from openhands.sdk.llm.message import BaseContent + """Test that Content base class raises NotImplementedError.""" + from openhands.sdk.llm.message import Content - content = BaseContent() + content = Content(type="test") with pytest.raises( NotImplementedError, match="Subclasses should implement this method" ): @@ -31,8 +31,6 @@ def test_image_content_with_cache_prompt(): content = ImageContent( image_urls=["data:image/png;base64,abc123", "data:image/jpeg;base64,def456"], cache_prompt=True, - data="abc123", # Required by MCP base class - mimeType="image/png", # Required by MCP base class ) result = content.to_llm_dict() @@ -59,11 +57,7 @@ def test_message_contains_image_property(): role="user", content=[ TextContent(text="Look at this:"), - ImageContent( - image_urls=["data:image/png;base64,abc123"], - data="abc123", - mimeType="image/png", - ), + ImageContent(image_urls=["data:image/png;base64,abc123"]), ], ) assert image_message.contains_image @@ -96,12 +90,7 @@ def test_message_tool_role_with_image_cache_prompt(): message = Message( role="tool", content=[ - ImageContent( - image_urls=["data:image/png;base64,abc123"], - cache_prompt=True, - data="abc123", - mimeType="image/png", - ) + ImageContent(image_urls=["data:image/png;base64,abc123"], cache_prompt=True) ], tool_call_id="call_123", name="test_tool", diff --git a/tests/sdk/llm/test_message_serialization.py b/tests/sdk/llm/test_message_serialization.py index 7987d348b5f..f30c3669809 100644 --- a/tests/sdk/llm/test_message_serialization.py +++ b/tests/sdk/llm/test_message_serialization.py @@ -51,11 +51,7 @@ def test_vision_message_storage_serialization(self): role="user", content=[ TextContent(text="What's in this image?"), - ImageContent( - image_urls=["https://example.com/image.jpg"], - data="dummy_data", - mimeType="image/jpeg", - ), + ImageContent(image_urls=["https://example.com/image.jpg"]), ], vision_enabled=True, ) @@ -202,11 +198,7 @@ def test_vision_enabled_triggers_list_serialization(self): role="user", content=[ TextContent(text="What's in this image?"), - ImageContent( - image_urls=["https://example.com/image.jpg"], - data="dummy_data", - mimeType="image/jpeg", - ), + ImageContent(image_urls=["https://example.com/image.jpg"]), ], vision_enabled=True, ) @@ -294,11 +286,7 @@ def test_content_type_preservation_in_list_serializer(self): role="user", content=[ TextContent(text="Describe this image"), - ImageContent( - image_urls=["https://example.com/image.jpg"], - data="dummy_data", - mimeType="image/jpeg", - ), + ImageContent(image_urls=["https://example.com/image.jpg"]), ], vision_enabled=True, # Forces list serializer ) diff --git a/tests/sdk/tool/test_tool.py b/tests/sdk/tool/test_tool.py index 4a03a6966bc..ebdb72bf5ba 100644 --- a/tests/sdk/tool/test_tool.py +++ b/tests/sdk/tool/test_tool.py @@ -64,7 +64,7 @@ def __call__(self, action: MockAction) -> MockObservation: ) assert tool.executor is not None - action = MockAction(command="test", security_risk="LOW") + action = MockAction(command="test") result = tool.call(action) assert isinstance(result, MockObservation) assert result.result == "Executed: test" @@ -147,7 +147,7 @@ def test_call_without_executor(self): output_schema=MockObservation, ) - action = MockAction(command="test", security_risk="LOW") + action = MockAction(command="test") with pytest.raises( NotImplementedError, match="Tool 'test_tool' has no executor" ): @@ -168,7 +168,7 @@ def __call__(self, action: MockAction) -> MockObservation: executor=MockExecutor(), ) - action = MockAction(command="test_command", security_risk="LOW") + action = MockAction(command="test_command") result = tool.call(action) assert isinstance(result, MockObservation) @@ -218,7 +218,7 @@ def __call__(self, action: MockAction) -> MockObservation: executor=MockExecutor(), ) - action = MockAction(command="test", security_risk="LOW") + action = MockAction(command="test") result = tool.call(action) # Should return the correct observation type @@ -240,7 +240,7 @@ def __call__(self, action: MockAction) -> MockObservation: executor=MockExecutor(), ) - action = MockAction(command="test", security_risk="LOW") + action = MockAction(command="test") result = tool.call(action) assert isinstance(result, MockObservation) @@ -261,7 +261,6 @@ def test_action_validation_with_nested_data(self): "command": "test", "nested": {"value": "test"}, "array_field": [1, 2, 3], - "security_risk": "LOW", } action = tool.action_type.model_validate(action_data) @@ -325,7 +324,7 @@ def __call__(self, action: MockAction) -> MockObservation: tool.executor = MockExecutor() # Now it should work - action = MockAction(command="test", security_risk="LOW") + action = MockAction(command="test") result = tool.call(action) assert isinstance(result, MockObservation) assert result.result == "Attached: test" @@ -374,7 +373,7 @@ def __call__(self, action: MockAction) -> ComplexObservation: executor=MockComplexExecutor(), ) - action = MockAction(command="test_command", security_risk="LOW") + action = MockAction(command="test_command") result = tool.call(action) assert isinstance(result, ComplexObservation) @@ -396,7 +395,7 @@ def __call__(self, action: MockAction) -> MockObservation: executor=FailingExecutor(), ) - action = MockAction(command="test", security_risk="LOW") + action = MockAction(command="test") with pytest.raises(RuntimeError, match="Executor failed"): tool.call(action) @@ -419,7 +418,7 @@ def __call__(self, action: MockAction) -> StrictObservation: executor=ValidExecutor(), ) - action = MockAction(command="test", security_risk="LOW") + action = MockAction(command="test") result = tool.call(action) assert isinstance(result, StrictObservation) assert result.message == "success" From 1016eaaefb7d17d5af0dc91efdd8ac440476ac32 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 14:59:11 -0400 Subject: [PATCH 24/28] make validation error clearer --- openhands/sdk/mcp/tool.py | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/openhands/sdk/mcp/tool.py b/openhands/sdk/mcp/tool.py index bad1e6503b9..a0bf2e15cc9 100644 --- a/openhands/sdk/mcp/tool.py +++ b/openhands/sdk/mcp/tool.py @@ -4,6 +4,7 @@ from typing import TYPE_CHECKING import mcp.types +from pydantic import ValidationError from openhands.sdk.llm import TextContent from openhands.sdk.logger import get_logger @@ -73,14 +74,26 @@ def __init__( ): self.mcp_client = mcp_client self.mcp_tool = mcp_tool - super().__init__( - name=mcp_tool.name, - description=mcp_tool.description or "No description provided", - input_schema=mcp_tool.inputSchema, - output_schema=MCPToolObservation, - annotations=ToolAnnotations.model_validate(mcp_tool.annotations) - if mcp_tool.annotations - else None, - _meta=mcp_tool.meta, - executor=MCPToolExecutor(tool_name=mcp_tool.name, client=mcp_client), - ) + + try: + if mcp_tool.annotations: + anno_dict = mcp_tool.annotations.model_dump(exclude_none=True) + annotations = ToolAnnotations.model_validate(anno_dict) + else: + annotations = None + + super().__init__( + name=mcp_tool.name, + description=mcp_tool.description or "No description provided", + input_schema=mcp_tool.inputSchema, + output_schema=MCPToolObservation, + annotations=annotations, + _meta=mcp_tool.meta, + executor=MCPToolExecutor(tool_name=mcp_tool.name, client=mcp_client), + ) + except ValidationError as e: + logger.error( + f"Validation error creating MCPTool for {mcp_tool.name}: " + f"{e.json(indent=2)}" + ) + raise e From cba94b9d33d2a4ad658af109fdf30105205990e5 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 15:00:32 -0400 Subject: [PATCH 25/28] add notion example --- examples/8_mcp_with_oauth.py | 78 ++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 examples/8_mcp_with_oauth.py diff --git a/examples/8_mcp_with_oauth.py b/examples/8_mcp_with_oauth.py new file mode 100644 index 00000000000..b7ab2a0174d --- /dev/null +++ b/examples/8_mcp_with_oauth.py @@ -0,0 +1,78 @@ +import os + +from pydantic import SecretStr + +from openhands.sdk import ( + LLM, + Agent, + Conversation, + EventType, + LLMConvertibleEvent, + Message, + TextContent, + Tool, + create_mcp_tools, + get_logger, +) +from openhands.tools import BashTool, FileEditorTool + + +logger = get_logger(__name__) + +# Configure LLM +api_key = os.getenv("LITELLM_API_KEY") +assert api_key is not None, "LITELLM_API_KEY environment variable is not set." +llm = LLM( + model="litellm_proxy/anthropic/claude-sonnet-4-20250514", + base_url="https://llm-proxy.eval.all-hands.dev", + api_key=SecretStr(api_key), +) + +cwd = os.getcwd() +tools: list[Tool] = [ + BashTool(working_dir=cwd), + FileEditorTool(), +] + +# Add MCP Tools +mcp_config = { + "mcpServers": {"Notion": {"url": "https://mcp.notion.com/mcp", "auth": "oauth"}} +} +mcp_tools = create_mcp_tools(mcp_config, timeout=30) +tools.extend(mcp_tools) +logger.info(f"Added {len(mcp_tools)} MCP tools") +for tool in mcp_tools: + logger.info(f" - {tool.name}: {tool.description}") + + +# Agent +agent = Agent(llm=llm, tools=tools) + +llm_messages = [] # collect raw LLM messages + + +def conversation_callback(event: EventType): + if isinstance(event, LLMConvertibleEvent): + llm_messages.append(event.to_llm_message()) + + +# Conversation +conversation = Conversation( + agent=agent, + callbacks=[conversation_callback], +) + +# Example message that can use MCP tools if available +message = Message( + role="user", + content=[TextContent(text="Summarize my notion workspace.")], +) + +logger.info("Starting conversation with MCP integration...") +response = conversation.send_message(message) +conversation.run() + +print("=" * 100) +print("Conversation finished. Got the following LLM messages:") +for i, message in enumerate(llm_messages): + print(f"Message {i}: {str(message)[:200]}") From ac20b1f41dbff371377b829d712979e3c37caec2 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 15:31:58 -0400 Subject: [PATCH 26/28] fix all tests --- openhands/sdk/llm/message.py | 10 ++- openhands/sdk/tool/schema.py | 5 +- .../conversation/test_confirmation_mode.py | 6 +- tests/sdk/event/test_events_to_messages.py | 6 +- tests/sdk/llm/test_message.py | 19 +++-- tests/sdk/llm/test_message_serialization.py | 20 ++++-- tests/sdk/mcp/test_tool.py | 3 +- tests/sdk/tool/test_tool.py | 69 ------------------- tests/tools/execute_bash/test_schema.py | 31 +++++++++ tests/tools/str_replace_editor/test_schema.py | 36 ++++++++++ 10 files changed, 118 insertions(+), 87 deletions(-) create mode 100644 tests/tools/execute_bash/test_schema.py create mode 100644 tests/tools/str_replace_editor/test_schema.py diff --git a/openhands/sdk/llm/message.py b/openhands/sdk/llm/message.py index cc655aab53d..2899281c4b3 100644 --- a/openhands/sdk/llm/message.py +++ b/openhands/sdk/llm/message.py @@ -3,7 +3,7 @@ import mcp.types from litellm import ChatCompletionMessageToolCall from litellm.types.utils import Message as LiteLLMMessage -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field class BaseContent(BaseModel): @@ -19,6 +19,9 @@ def to_llm_dict( class TextContent(mcp.types.TextContent, BaseContent): type: Literal["text"] = "text" text: str + # We use populate_by_name since mcp.types.TextContent + # alias meta -> _meta, but .model_dumps() will output "meta" + model_config = ConfigDict(extra="forbid", populate_by_name=True) def to_llm_dict(self) -> dict[str, str | dict[str, str]]: """Convert to LLM API format.""" @@ -34,12 +37,15 @@ def to_llm_dict(self) -> dict[str, str | dict[str, str]]: class ImageContent(mcp.types.ImageContent, BaseContent): type: Literal["image"] = "image" image_urls: list[str] + # We use populate_by_name since mcp.types.ImageContent + # alias meta -> _meta, but .model_dumps() will output "meta" + model_config = ConfigDict(extra="forbid", populate_by_name=True) def to_llm_dict(self) -> list[dict[str, str | dict[str, str]]]: """Convert to LLM API format.""" images: list[dict[str, str | dict[str, str]]] = [] for url in self.image_urls: - images.append({"type": self.type, "image_url": {"url": url}}) + images.append({"type": "image_url", "image_url": {"url": url}}) if self.cache_prompt and images: images[-1]["cache_control"] = {"type": "ephemeral"} return images diff --git a/openhands/sdk/tool/schema.py b/openhands/sdk/tool/schema.py index 84b8855dec2..4083dc98c5b 100644 --- a/openhands/sdk/tool/schema.py +++ b/openhands/sdk/tool/schema.py @@ -149,8 +149,11 @@ def from_mcp_schema( class ActionBase(Schema): """Base schema for input action.""" + # NOTE: We make it optional since some weaker + # LLMs may not be able to fill it out correctly. + # https://github.com/All-Hands-AI/OpenHands/issues/10797 security_risk: SECURITY_RISK_LITERAL = Field( - default="UNKNOWN", description=SECURITY_RISK_DESC, exclude=True + default="UNKNOWN", description=SECURITY_RISK_DESC ) diff --git a/tests/sdk/conversation/test_confirmation_mode.py b/tests/sdk/conversation/test_confirmation_mode.py index 63cada8e539..5b06dd4628e 100644 --- a/tests/sdk/conversation/test_confirmation_mode.py +++ b/tests/sdk/conversation/test_confirmation_mode.py @@ -20,7 +20,7 @@ from openhands.sdk.event import ActionEvent, MessageEvent, ObservationEvent from openhands.sdk.event.llm_convertible import UserRejectObservation from openhands.sdk.event.utils import get_unmatched_actions -from openhands.sdk.llm import Message, TextContent +from openhands.sdk.llm import ImageContent, Message, TextContent from openhands.sdk.tool import Tool, ToolExecutor from openhands.sdk.tool.schema import ActionBase, ObservationBase @@ -37,8 +37,8 @@ class MockObservation(ObservationBase): result: str @property - def agent_observation(self) -> str: - return self.result + def agent_observation(self) -> list[TextContent | ImageContent]: + return [TextContent(text=self.result)] class TestConfirmationMode: diff --git a/tests/sdk/event/test_events_to_messages.py b/tests/sdk/event/test_events_to_messages.py index 5d6b8ca9c14..c260110b536 100644 --- a/tests/sdk/event/test_events_to_messages.py +++ b/tests/sdk/event/test_events_to_messages.py @@ -15,7 +15,7 @@ ObservationEvent, SystemPromptEvent, ) -from openhands.sdk.llm import Message, TextContent +from openhands.sdk.llm import ImageContent, Message, TextContent from openhands.sdk.tool import ActionBase, ObservationBase @@ -31,8 +31,8 @@ class MockObservation(ObservationBase): result: str @property - def agent_observation(self) -> str: - return self.result + def agent_observation(self) -> list[TextContent | ImageContent]: + return [TextContent(text=self.result)] def create_tool_call( diff --git a/tests/sdk/llm/test_message.py b/tests/sdk/llm/test_message.py index e48277b3816..3b90ae106cb 100644 --- a/tests/sdk/llm/test_message.py +++ b/tests/sdk/llm/test_message.py @@ -3,9 +3,9 @@ def test_content_base_class_not_implemented(): """Test that Content base class raises NotImplementedError.""" - from openhands.sdk.llm.message import Content + from openhands.sdk.llm.message import BaseContent - content = Content(type="test") + content = BaseContent() with pytest.raises( NotImplementedError, match="Subclasses should implement this method" ): @@ -30,6 +30,8 @@ def test_image_content_with_cache_prompt(): content = ImageContent( image_urls=["data:image/png;base64,abc123", "data:image/jpeg;base64,def456"], + data="fake_image_data", + mimeType="image/jpeg", cache_prompt=True, ) result = content.to_llm_dict() @@ -57,7 +59,11 @@ def test_message_contains_image_property(): role="user", content=[ TextContent(text="Look at this:"), - ImageContent(image_urls=["data:image/png;base64,abc123"]), + ImageContent( + image_urls=["data:image/png;base64,abc123"], + data="fake_image_data", + mimeType="image/jpeg", + ), ], ) assert image_message.contains_image @@ -90,7 +96,12 @@ def test_message_tool_role_with_image_cache_prompt(): message = Message( role="tool", content=[ - ImageContent(image_urls=["data:image/png;base64,abc123"], cache_prompt=True) + ImageContent( + image_urls=["data:image/png;base64,abc123"], + data="fake_image_data", + mimeType="image/jpeg", + cache_prompt=True, + ) ], tool_call_id="call_123", name="test_tool", diff --git a/tests/sdk/llm/test_message_serialization.py b/tests/sdk/llm/test_message_serialization.py index f30c3669809..538f2ecdff7 100644 --- a/tests/sdk/llm/test_message_serialization.py +++ b/tests/sdk/llm/test_message_serialization.py @@ -51,7 +51,11 @@ def test_vision_message_storage_serialization(self): role="user", content=[ TextContent(text="What's in this image?"), - ImageContent(image_urls=["https://example.com/image.jpg"]), + ImageContent( + image_urls=["https://example.com/image.jpg"], + data="fake_image_data", + mimeType="image/jpeg", + ), ], vision_enabled=True, ) @@ -61,7 +65,7 @@ def test_vision_message_storage_serialization(self): assert isinstance(storage_data["content"], list) assert len(storage_data["content"]) == 2 assert storage_data["content"][0]["type"] == "text" - assert storage_data["content"][1]["type"] == "image_url" + assert storage_data["content"][1]["type"] == "image" assert storage_data["vision_enabled"] is True # Round-trip works @@ -198,7 +202,11 @@ def test_vision_enabled_triggers_list_serialization(self): role="user", content=[ TextContent(text="What's in this image?"), - ImageContent(image_urls=["https://example.com/image.jpg"]), + ImageContent( + image_urls=["https://example.com/image.jpg"], + data="fake_image_data", + mimeType="image/jpeg", + ), ], vision_enabled=True, ) @@ -286,7 +294,11 @@ def test_content_type_preservation_in_list_serializer(self): role="user", content=[ TextContent(text="Describe this image"), - ImageContent(image_urls=["https://example.com/image.jpg"]), + ImageContent( + image_urls=["https://example.com/image.jpg"], + data="fake_image_data", + mimeType="image/jpeg", + ), ], vision_enabled=True, # Forces list serializer ) diff --git a/tests/sdk/mcp/test_tool.py b/tests/sdk/mcp/test_tool.py index f1d28fa52bd..0ef65f1d053 100644 --- a/tests/sdk/mcp/test_tool.py +++ b/tests/sdk/mcp/test_tool.py @@ -7,6 +7,7 @@ from openhands.sdk.llm import TextContent from openhands.sdk.mcp.definition import MCPToolObservation from openhands.sdk.mcp.tool import MCPTool, MCPToolExecutor +from openhands.sdk.tool import ToolAnnotations class TestMCPToolObservation: @@ -232,7 +233,7 @@ def test_mcp_tool_with_annotations(self): mock_tool_with_annotations.name = "annotated_tool" mock_tool_with_annotations.description = "Tool with annotations" mock_tool_with_annotations.inputSchema = {"type": "object"} - mock_tool_with_annotations.annotations = {"category": "utility"} + mock_tool_with_annotations.annotations = ToolAnnotations(title="Annotated Tool") mock_tool_with_annotations.meta = {"version": "1.0"} tool = MCPTool(mcp_tool=mock_tool_with_annotations, mcp_client=self.mock_client) diff --git a/tests/sdk/tool/test_tool.py b/tests/sdk/tool/test_tool.py index ebdb72bf5ba..4d97b8e0165 100644 --- a/tests/sdk/tool/test_tool.py +++ b/tests/sdk/tool/test_tool.py @@ -522,75 +522,6 @@ def test_tool_with_meta_data(self): assert "_meta" in mcp_tool assert mcp_tool["_meta"] == meta_data - def test_to_mcp_tool_detailed_type_validation_editor(self): - """Test detailed type validation for MCP tool schema generation.""" - from openhands.tools.str_replace_editor import ( - str_replace_editor_tool, - ) - - # Test str_replace_editor tool schema - str_editor_mcp = str_replace_editor_tool.to_mcp_tool() - str_editor_schema = str_editor_mcp["inputSchema"] - str_editor_props = str_editor_schema["properties"] - - assert "command" in str_editor_props - assert "path" in str_editor_props - assert "file_text" in str_editor_props - assert "old_str" in str_editor_props - assert "new_str" in str_editor_props - assert "insert_line" in str_editor_props - assert "view_range" in str_editor_props - assert "security_risk" in str_editor_props - - view_range_schema = str_editor_props["view_range"] - assert "anyOf" not in view_range_schema - assert view_range_schema["type"] == "array" - assert view_range_schema["items"]["type"] == "integer" - - assert "description" in view_range_schema - assert ( - "Optional parameter of `view` command" in view_range_schema["description"] - ) - - command_schema = str_editor_props["command"] - assert "enum" in command_schema - expected_commands = ["view", "create", "str_replace", "insert", "undo_edit"] - assert set(command_schema["enum"]) == set(expected_commands) - - path_schema = str_editor_props["path"] - assert path_schema["type"] == "string" - assert "path" in str_editor_schema["required"] - - def test_to_mcp_tool_detailed_type_validation_bash(self): - """Test detailed type validation for MCP tool schema generation (execute_bash).""" # noqa: E501 - from openhands.tools.execute_bash import execute_bash_tool - - # Test execute_bash tool schema - bash_mcp = execute_bash_tool.to_mcp_tool() - bash_schema = bash_mcp["inputSchema"] - bash_props = bash_schema["properties"] - - # Test command field is required string - bash_command_schema = bash_props["command"] - assert bash_command_schema["type"] == "string" - assert "command" in bash_schema["required"] - - # Test is_input field is optional boolean with default - is_input_schema = bash_props["is_input"] - assert is_input_schema["type"] == "boolean" - assert "is_input" not in bash_schema["required"] - - # Test timeout field is optional number - timeout_schema = bash_props["timeout"] - assert "anyOf" not in timeout_schema - assert timeout_schema["type"] == "number" - - # Test security_risk field has enum constraint - security_risk_schema = bash_props["security_risk"] - assert "enum" in security_risk_schema - assert set(security_risk_schema["enum"]) == {"LOW", "MEDIUM", "HIGH"} - assert "security_risk" in bash_schema["required"] - def test_to_mcp_tool_complex_nested_types(self): """Test MCP tool schema generation with complex nested types.""" diff --git a/tests/tools/execute_bash/test_schema.py b/tests/tools/execute_bash/test_schema.py new file mode 100644 index 00000000000..6f70d9037c3 --- /dev/null +++ b/tests/tools/execute_bash/test_schema.py @@ -0,0 +1,31 @@ +from openhands.tools.execute_bash import execute_bash_tool + + +def test_to_mcp_tool_detailed_type_validation_bash(): + """Test detailed type validation for MCP tool schema generation (execute_bash).""" # noqa: E501 + + # Test execute_bash tool schema + bash_mcp = execute_bash_tool.to_mcp_tool() + bash_schema = bash_mcp["inputSchema"] + bash_props = bash_schema["properties"] + + # Test command field is required string + bash_command_schema = bash_props["command"] + assert bash_command_schema["type"] == "string" + assert "command" in bash_schema["required"] + + # Test is_input field is optional boolean with default + is_input_schema = bash_props["is_input"] + assert is_input_schema["type"] == "boolean" + assert "is_input" not in bash_schema["required"] + + # Test timeout field is optional number + timeout_schema = bash_props["timeout"] + assert "anyOf" not in timeout_schema + assert timeout_schema["type"] == "number" + + # Test security_risk field has enum constraint + assert "security_risk" in bash_props + security_risk_schema = bash_props["security_risk"] + assert "enum" in security_risk_schema + assert set(security_risk_schema["enum"]) == {"LOW", "MEDIUM", "HIGH", "UNKNOWN"} diff --git a/tests/tools/str_replace_editor/test_schema.py b/tests/tools/str_replace_editor/test_schema.py new file mode 100644 index 00000000000..4d81c9159f6 --- /dev/null +++ b/tests/tools/str_replace_editor/test_schema.py @@ -0,0 +1,36 @@ +from openhands.tools.str_replace_editor import str_replace_editor_tool + + +def test_to_mcp_tool_detailed_type_validation_editor(): + """Test detailed type validation for MCP tool schema generation.""" + + # Test str_replace_editor tool schema + str_editor_mcp = str_replace_editor_tool.to_mcp_tool() + str_editor_schema = str_editor_mcp["inputSchema"] + str_editor_props = str_editor_schema["properties"] + + assert "command" in str_editor_props + assert "path" in str_editor_props + assert "file_text" in str_editor_props + assert "old_str" in str_editor_props + assert "new_str" in str_editor_props + assert "insert_line" in str_editor_props + assert "view_range" in str_editor_props + assert "security_risk" in str_editor_props + + view_range_schema = str_editor_props["view_range"] + assert "anyOf" not in view_range_schema + assert view_range_schema["type"] == "array" + assert view_range_schema["items"]["type"] == "integer" + + assert "description" in view_range_schema + assert "Optional parameter of `view` command" in view_range_schema["description"] + + command_schema = str_editor_props["command"] + assert "enum" in command_schema + expected_commands = ["view", "create", "str_replace", "insert", "undo_edit"] + assert set(command_schema["enum"]) == set(expected_commands) + + path_schema = str_editor_props["path"] + assert path_schema["type"] == "string" + assert "path" in str_editor_schema["required"] From e27d425b70524d41e67691a1d0f00119ac50eb3a Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 16:08:12 -0400 Subject: [PATCH 27/28] fix all tests --- openhands/sdk/tool/schema.py | 17 ++++++ openhands/sdk/tool/tool.py | 2 + .../{test_utils.py => test_create_tool.py} | 61 ++++++++++++++++--- tests/sdk/mcp/test_tool.py | 4 ++ tests/sdk/tool/test_tool.py | 3 + 5 files changed, 79 insertions(+), 8 deletions(-) rename tests/sdk/mcp/{test_utils.py => test_create_tool.py} (73%) diff --git a/openhands/sdk/tool/schema.py b/openhands/sdk/tool/schema.py index 4083dc98c5b..07fb1c566c7 100644 --- a/openhands/sdk/tool/schema.py +++ b/openhands/sdk/tool/schema.py @@ -156,6 +156,23 @@ class ActionBase(Schema): default="UNKNOWN", description=SECURITY_RISK_DESC ) + @classmethod + def to_mcp_schema(cls) -> dict[str, Any]: + """Convert to JSON schema format compatible with MCP.""" + schema = super().to_mcp_schema() + + # We need to move the fields from ActionBase to the END of the properties + # We use these properties to generate the llm schema for tool calling + # and we want the ActionBase fields to be at the end + # e.g. LLM should already outputs the argument for tools + # BEFORE it predicts security_risk + assert "properties" in schema, "Schema must have properties" + for field_name in ActionBase.model_fields.keys(): + if field_name in schema["properties"]: + v = schema["properties"].pop(field_name) + schema["properties"][field_name] = v + return schema + class MCPActionBase(ActionBase): """Base schema for MCP input action.""" diff --git a/openhands/sdk/tool/tool.py b/openhands/sdk/tool/tool.py index beaf04923dc..2f3fbe38204 100644 --- a/openhands/sdk/tool/tool.py +++ b/openhands/sdk/tool/tool.py @@ -101,6 +101,8 @@ def _set_input_schema( self.action_type = ActionBase.from_mcp_schema( f"{to_camel_case(self.name)}Action", input_schema ) + # Update mcp schema in case we have additional fields in ActionBase + self.input_schema = self.action_type.to_mcp_schema() else: raise TypeError( "input_schema must be ActionBase subclass or dict JSON schema" diff --git a/tests/sdk/mcp/test_utils.py b/tests/sdk/mcp/test_create_tool.py similarity index 73% rename from tests/sdk/mcp/test_utils.py rename to tests/sdk/mcp/test_create_tool.py index 098ba389c5c..138435aa144 100644 --- a/tests/sdk/mcp/test_utils.py +++ b/tests/sdk/mcp/test_create_tool.py @@ -2,10 +2,10 @@ from unittest.mock import MagicMock, patch -from openhands.sdk.mcp.utils import create_mcp_tools +from openhands.sdk.mcp import create_mcp_tools -def test_create_mcp_tools_empty_config(): +def test_mock_create_mcp_tools_empty_config(): """Test creating MCP tools with empty configuration.""" config = {} @@ -22,7 +22,7 @@ def test_create_mcp_tools_empty_config(): assert len(tools) == 0 -def test_create_mcp_tools_stdio_server(): +def test_mock_create_mcp_tools_stdio_server(): """Test creating MCP tools with stdio server configuration.""" config = { "mcpServers": { @@ -54,7 +54,7 @@ def test_create_mcp_tools_stdio_server(): assert tools[0] == mock_tool -def test_create_mcp_tools_http_server(): +def test_mock_create_mcp_tools_http_server(): """Test creating MCP tools with HTTP server configuration.""" config = { "mcpServers": { @@ -85,7 +85,7 @@ def test_create_mcp_tools_http_server(): assert tools[0] == mock_tool -def test_create_mcp_tools_mixed_servers(): +def test_mock_create_mcp_tools_mixed_servers(): """Test creating MCP tools with mixed server configurations.""" config = { "mcpServers": { @@ -122,7 +122,7 @@ def test_create_mcp_tools_mixed_servers(): assert tools[1] == mock_tool2 -def test_create_mcp_tools_with_timeout(): +def test_mock_create_mcp_tools_with_timeout(): """Test creating MCP tools with custom timeout.""" config = { "mcpServers": { @@ -152,7 +152,7 @@ def test_create_mcp_tools_with_timeout(): assert len(tools) == 0 -def test_create_mcp_tools_connection_error(): +def test_mock_create_mcp_tools_connection_error(): """Test creating MCP tools with connection error.""" config = { "mcpServers": { @@ -178,7 +178,7 @@ def test_create_mcp_tools_connection_error(): assert len(tools) == 0 -def test_create_mcp_tools_dict_config(): +def test_mock_create_mcp_tools_dict_config(): """Test creating MCP tools with dict configuration (not MCPConfig object).""" config = { "mcpServers": { @@ -206,3 +206,48 @@ def test_create_mcp_tools_dict_config(): assert len(tools) == 1 assert tools[0] == mock_tool + + +def test_real_create_mcp_tools_dict_config(): + """Test creating MCP tools with dict configuration (not MCPConfig object).""" + mcp_config = { + "mcpServers": {"fetch": {"command": "uvx", "args": ["mcp-server-fetch"]}} + } + + tools = create_mcp_tools(mcp_config) + assert len(tools) == 1 + assert tools[0].name == "fetch" + input_schema = tools[0].input_schema + + assert "type" in input_schema + assert input_schema["type"] == "object" + assert "properties" in input_schema + assert "url" in input_schema["properties"] + assert input_schema["properties"]["url"]["type"] == "string" + assert "required" in input_schema + assert "url" in input_schema["required"] + + # attribute from ActionBase is added to the MCP input schema + assert "security_risk" not in input_schema["required"] + assert "security_risk" in input_schema["properties"] + assert list(input_schema["properties"].keys())[-1] == "security_risk" + + mcp_tool = tools[0].to_mcp_tool() + assert mcp_tool["inputSchema"] == input_schema + + openai_tool = tools[0].to_openai_tool() + assert openai_tool["type"] == "function" + assert "parameters" in openai_tool["function"] + parameters = openai_tool["function"]["parameters"] + assert "url" in parameters["properties"] + assert parameters["properties"]["url"]["type"] == "string" + assert "required" in parameters + assert "url" in parameters["required"] + assert openai_tool["function"]["name"] == "fetch" + + assert "security_risk" not in parameters["required"] + assert "security_risk" in parameters["properties"] + # The security_risk should be added to the end of the properties + assert list(parameters["properties"].keys())[-1] == "security_risk" + + assert tools[0].executor is not None diff --git a/tests/sdk/mcp/test_tool.py b/tests/sdk/mcp/test_tool.py index 0ef65f1d053..cd887c7cebb 100644 --- a/tests/sdk/mcp/test_tool.py +++ b/tests/sdk/mcp/test_tool.py @@ -221,6 +221,10 @@ def test_mcp_tool_creation(self): """Test creating an MCP tool.""" assert self.tool.name == "test_tool" assert self.tool.description == "A test tool" + + assert len(self.tool.input_schema["properties"]) == 2 + assert "security_risk" in self.tool.input_schema["properties"] + self.tool.input_schema["properties"].pop("security_risk") assert self.tool.input_schema == { "type": "object", "properties": {"param": {"type": "string"}}, diff --git a/tests/sdk/tool/test_tool.py b/tests/sdk/tool/test_tool.py index 4d97b8e0165..81d32cf591d 100644 --- a/tests/sdk/tool/test_tool.py +++ b/tests/sdk/tool/test_tool.py @@ -496,6 +496,9 @@ def test_tool_with_dict_schemas(self): ) assert tool.name == "dict_tool" + assert tool.input_schema != input_schema + # this supposed to be added by the ActionBase + tool.input_schema["properties"].pop("security_risk") assert tool.input_schema == input_schema assert tool.output_schema == output_schema From f801d04942fc2304bc94f3e691b20d64e373d690 Mon Sep 17 00:00:00 2001 From: Xingyao Wang Date: Fri, 5 Sep 2025 16:09:04 -0400 Subject: [PATCH 28/28] remove config folder --- openhands/sdk/config/__init__.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 openhands/sdk/config/__init__.py diff --git a/openhands/sdk/config/__init__.py b/openhands/sdk/config/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000