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. 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/examples/7_mcp_integration.py b/examples/7_mcp_integration.py new file mode 100644 index 00000000000..e3988ad85ae --- /dev/null +++ b/examples/7_mcp_integration.py @@ -0,0 +1,81 @@ +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": {"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) + +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="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/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]}") diff --git a/openhands/sdk/__init__.py b/openhands/sdk/__init__.py index 878fe9ff059..c3c99680637 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,6 +13,7 @@ TextContent, ) from openhands.sdk.logger import get_logger +from openhands.sdk.mcp import MCPClient, MCPTool, create_mcp_tools from openhands.sdk.tool import ActionBase, ObservationBase, Tool @@ -34,7 +34,9 @@ "Agent", "ActionBase", "ObservationBase", - "MCPConfig", + "MCPClient", + "MCPTool", + "create_mcp_tools", "get_logger", "Conversation", "ConversationCallbackType", diff --git a/openhands/sdk/config/__init__.py b/openhands/sdk/config/__init__.py deleted file mode 100644 index 22df0f208f0..00000000000 --- a/openhands/sdk/config/__init__.py +++ /dev/null @@ -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, - ) 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") 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/conversation/visualizer.py b/openhands/sdk/conversation/visualizer.py index b5e3a1e51b7..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 @@ -12,7 +13,7 @@ ObservationEvent, SystemPromptEvent, ) -from openhands.sdk.llm import ImageContent, TextContent +from openhands.sdk.llm import ImageContent, TextContent, content_to_str class ConversationVisualizer: @@ -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, @@ -120,7 +142,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 +174,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 +193,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 98cb43d2dd3..2899281c4b3 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 +from pydantic import BaseModel, ConfigDict, 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,9 +16,12 @@ 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 + # 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.""" @@ -37,15 +34,18 @@ 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] + # 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 @@ -173,3 +173,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/mcp/__init__.py b/openhands/sdk/mcp/__init__.py new file mode 100644 index 00000000000..04c1466b0cc --- /dev/null +++ b/openhands/sdk/mcp/__init__.py @@ -0,0 +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, + MCPToolExecutor, +) +from openhands.sdk.mcp.utils import ( + create_mcp_tools, +) + + +__all__ = [ + "MCPClient", + "MCPTool", + "MCPToolObservation", + "MCPToolExecutor", + "create_mcp_tools", +] diff --git a/openhands/sdk/mcp/client.py b/openhands/sdk/mcp/client.py new file mode 100644 index 00000000000..66ba7f019e7 --- /dev/null +++ b/openhands/sdk/mcp/client.py @@ -0,0 +1,113 @@ +"""Minimal sync helpers on top of fastmcp.Client, preserving original behavior.""" + +import asyncio +import inspect +import threading +from typing import Any, Callable + +from fastmcp import Client as AsyncMCPClient + + +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 + """ + + 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() + + # ---------- loop management ---------- + + def _ensure_loop(self) -> asyncio.AbstractEventLoop: + with self._lock: + if self._loop is not None: + return self._loop + + loop = asyncio.new_event_loop() + + def _runner(): + asyncio.set_event_loop(loop) + loop.run_forever() + + t = threading.Thread(target=_runner, daemon=True) + t.start() + while not loop.is_running(): + pass + + self._loop = loop + self._thread = t + return loop + + def _shutdown_loop(self) -> None: + with self._lock: + loop, t = self._loop, self._thread + self._loop = None + self._thread = None + + 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) + + # ---------- public helpers ---------- + + 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: + raise TypeError( + "call_async_from_sync expects a coroutine or async function" + ) + + loop = self._ensure_loop() + fut = asyncio.run_coroutine_threadsafe(coro, loop) + return fut.result(timeout) + + 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)) + + # ---------- optional cleanup ---------- + + def sync_close(self): + # Best-effort: try async close if parent provides it + aclose = self.close + if inspect.iscoroutinefunction(aclose): + try: + self.call_async_from_sync(aclose, timeout=10.0) + except Exception: + pass + self._shutdown_loop() + + def __del__(self): + try: + self.sync_close() + except Exception: + pass diff --git a/openhands/sdk/mcp/definition.py b/openhands/sdk/mcp/definition.py new file mode 100644 index 00000000000..52ff4a8bd9a --- /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.]\n" + return [TextContent(text=initial_message)] + self.content diff --git a/openhands/sdk/mcp/tool.py b/openhands/sdk/mcp/tool.py new file mode 100644 index 00000000000..a0bf2e15cc9 --- /dev/null +++ b/openhands/sdk/mcp/tool.py @@ -0,0 +1,99 @@ +"""Utility functions for MCP integration.""" + +import traceback +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 +from openhands.sdk.mcp import MCPToolObservation +from openhands.sdk.tool import MCPActionBase, Tool, ToolAnnotations, ToolExecutor + + +if TYPE_CHECKING: + from openhands.sdk.mcp.client import MCPClient + +logger = get_logger(__name__) + + +# 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, tool_name: str, client: "MCPClient"): + self.tool_name = tool_name + self.client = client + + async def call_tool(self, action: MCPActionBase) -> 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(exclude_none=True) + ) + 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: 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[MCPActionBase, MCPToolObservation]): + """MCP Tool that wraps an MCP client and provides tool functionality.""" + + def __init__( + self, + mcp_tool: mcp.types.Tool, + mcp_client: "MCPClient", + ): + self.mcp_client = mcp_client + self.mcp_tool = mcp_tool + + 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 diff --git a/openhands/sdk/mcp/utils.py b/openhands/sdk/mcp/utils.py new file mode 100644 index 00000000000..f0c756b5d14 --- /dev/null +++ b/openhands/sdk/mcp/utils.py @@ -0,0 +1,59 @@ +"""Utility functions for MCP integration.""" + +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 import MCPClient, MCPTool +from openhands.sdk.tool import Tool + + +logger = get_logger(__name__) +LOGGING_LEVEL_MAP = logging.getLevelNamesMapping() + + +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") + + # Convert the MCP log level to a Python log level + level = LOGGING_LEVEL_MAP.get(message.level.upper(), logging.INFO) + + # Log the message using the standard logging library + logger.log(level, msg, extra=extra) + + +async def _list_tools(client: MCPClient) -> list[Tool]: + """List tools from an MCP client.""" + tools: list[Tool] = [] + + 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( + config: dict | MCPConfig, + timeout: float = 30.0, +) -> list[Tool]: + """Create MCP tools from MCP configuration.""" + tools: list[Tool] = [] + 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: {[t.name for t in tools]}") + return tools 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/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 768734310b5..07fb1c566c7 100644 --- a/openhands/sdk/tool/schema.py +++ b/openhands/sdk/tool/schema.py @@ -2,6 +2,12 @@ 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, +) + S = TypeVar("S", bound="Schema") @@ -102,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" @@ -111,24 +121,63 @@ 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] class ActionBase(Schema): """Base schema for input action.""" - pass + # 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 + ) + + @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.""" + + model_config = ConfigDict(extra="allow") class ObservationBase(Schema): @@ -137,6 +186,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/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/sdk/tool/tool.py b/openhands/sdk/tool/tool.py index 32201134dc8..2f3fbe38204 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 @@ -99,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/openhands/tools/execute_bash/definition.py b/openhands/tools/execute_bash/definition.py index 03d4dbff3ac..0780fafc774 100644 --- a/openhands/tools/execute_bash/definition.py +++ b/openhands/tools/execute_bash/definition.py @@ -5,13 +5,10 @@ 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 -from openhands.tools.utils.security_prompt import ( - SECURITY_RISK_DESC, - SECURITY_RISK_LITERAL, -) if TYPE_CHECKING: @@ -32,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): @@ -65,7 +61,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 +71,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..b4b7b0413fb 100644 --- a/openhands/tools/str_replace_editor/definition.py +++ b/openhands/tools/str_replace_editor/definition.py @@ -4,11 +4,8 @@ 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, - SECURITY_RISK_LITERAL, -) CommandLiteral = Literal["view", "create", "str_replace", "insert", "undo_edit"] @@ -54,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): @@ -77,10 +73,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[ 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/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() 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/__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_create_tool.py b/tests/sdk/mcp/test_create_tool.py new file mode 100644 index 00000000000..138435aa144 --- /dev/null +++ b/tests/sdk/mcp/test_create_tool.py @@ -0,0 +1,253 @@ +"""Tests for MCP utils functionality with new simplified implementation.""" + +from unittest.mock import MagicMock, patch + +from openhands.sdk.mcp import create_mcp_tools + + +def test_mock_create_mcp_tools_empty_config(): + """Test creating MCP tools with empty configuration.""" + config = {} + + # 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 call_async_from_sync to return empty list + mock_client.call_async_from_sync.return_value = [] + + tools = create_mcp_tools(config) + + assert len(tools) == 0 + + +def test_mock_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", + } + } + } + + # 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" + + # 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_mock_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", + } + } + } + + # 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 = "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_mock_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 + + # Mock tools + mock_tool1 = MagicMock() + mock_tool1.name = "stdio_tool" + mock_tool2 = MagicMock() + mock_tool2.name = "http_tool" + + # Mock call_async_from_sync to return the tools + mock_client.call_async_from_sync.return_value = [mock_tool1, mock_tool2] + + tools = create_mcp_tools(config) + + assert len(tools) == 2 + assert tools[0] == mock_tool1 + assert tools[1] == mock_tool2 + + +def test_mock_create_mcp_tools_with_timeout(): + """Test creating MCP tools with custom timeout.""" + config = { + "mcpServers": { + "test_server": { + "transport": "stdio", + "command": "python", + "args": ["./server.py"], + } + } + } + + # 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 call_async_from_sync to return empty list + mock_client.call_async_from_sync.return_value = [] + + tools = create_mcp_tools(config, timeout=60.0) + + # 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 + + assert len(tools) == 0 + + +def test_mock_create_mcp_tools_connection_error(): + """Test creating MCP tools with connection error.""" + config = { + "mcpServers": { + "failing_server": { + "transport": "stdio", + "command": "nonexistent_command", + } + } + } + + # 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 call_async_from_sync to return empty list (connection + # error handled internally) + mock_client.call_async_from_sync.return_value = [] + + # Should not raise exception, but return empty list + tools = create_mcp_tools(config) + + assert len(tools) == 0 + + +def test_mock_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 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 = "dict_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_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 new file mode 100644 index 00000000000..cd887c7cebb --- /dev/null +++ b/tests/sdk/mcp/test_tool.py @@ -0,0 +1,268 @@ +"""Tests for MCP tool functionality with new simplified implementation.""" + +from unittest.mock import MagicMock + +import mcp.types + +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: + """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 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 + + observation = MCPToolObservation.from_call_tool_result( + tool_name="test_tool", result=result + ) + + 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 + ) + + 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_agent_observation_success(self): + """Test agent observation formatting for success.""" + observation = MCPToolObservation( + tool_name="test_tool", + content=[TextContent(text="Success result")], + is_error=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_agent_observation_error(self): + """Test agent observation formatting for error.""" + observation = MCPToolObservation( + tool_name="test_tool", + content=[TextContent(text="Error occurred")], + is_error=True, + ) + + 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: + """Test MCPToolExecutor functionality.""" + + def setup_method(self): + """Set up test fixtures.""" + self.mock_client = MagicMock() + self.executor = MCPToolExecutor(tool_name="test_tool", client=self.mock_client) + + def test_call_tool_success(self): + """Test successful tool execution.""" + # Mock successful MCP call + mock_result = MagicMock(spec=mcp.types.CallToolResult) + mock_result.content = [ + mcp.types.TextContent(type="text", text="Success result") + ] + mock_result.isError = False + + # Mock action + mock_action = MagicMock() + mock_action.model_dump.return_value = {"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(mock_action) + + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert observation.is_error is False + + def test_call_tool_error(self): + """Test tool execution with error.""" + # Mock error MCP call + mock_result = MagicMock(spec=mcp.types.CallToolResult) + mock_result.content = [ + mcp.types.TextContent(type="text", text="Error occurred") + ] + mock_result.isError = True + + # Mock action + mock_action = MagicMock() + mock_action.model_dump.return_value = {"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(mock_action) + + assert isinstance(observation, MCPToolObservation) + assert observation.tool_name == "test_tool" + assert observation.is_error is True + + def test_call_tool_exception(self): + """Test tool execution with exception.""" + # 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.is_error is True + assert "Connection failed" in observation.content[0].text + + +class TestMCPTool: + """Test MCPTool functionality.""" + + def setup_method(self): + """Set up test fixtures.""" + self.mock_client = MagicMock() + + # 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_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" + + 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"}}, + } + + 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 = 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) + + 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/tool/test_tool.py b/tests/sdk/tool/test_tool.py index ebdb72bf5ba..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 @@ -522,75 +525,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_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 5a9659e9137..0c6521180a4 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 == "" 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"] diff --git a/uv.lock b/uv.lock index fc99df39504..b48059953b1 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" }, ] @@ -1442,6 +1443,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"