π OpenHands: AI-Driven Development
V0 Code Removals: Conversation Validator, MCP Updates, and Cleanup (#14135)
Tim O'Farrell237948978b29
diff --git a/.pr/gifs/13971-verification-basic-vs-advanced.gif b/.pr/gifs/13971-verification-basic-vs-advanced.gifdeleted file mode 100644index 9eca78140b..0000000000Binary files a/.pr/gifs/13971-verification-basic-vs-advanced.gif and /dev/null differdiff --git a/enterprise/enterprise_local/convert_to_env.py b/enterprise/enterprise_local/convert_to_env.pyindex cfef08bf19..9863d333bb 100644--- a/enterprise/enterprise_local/convert_to_env.py+++ b/enterprise/enterprise_local/convert_to_env.py@@ -112,9 +112,6 @@ lines.append(lines.append('OPENHANDS_BITBUCKET_DATA_CENTER_SERVICE_CLS=integrations.bitbucket_data_center.bitbucket_dc_service.SaaSBitbucketDCService')-lines.append(- 'OPENHANDS_CONVERSATION_VALIDATOR_CLS=storage.saas_conversation_validator.SaasConversationValidator'-)lines.append('POSTHOG_CLIENT_KEY=test')lines.append('ENABLE_PROACTIVE_CONVERSATION_STARTERS=true')lines.append('MAX_CONCURRENT_CONVERSATIONS=10')diff --git a/enterprise/server/middleware.py b/enterprise/server/middleware.pyindex c014864b0b..7db0b33f7c 100644--- a/enterprise/server/middleware.py+++ b/enterprise/server/middleware.py@@ -16,8 +16,8 @@ from server.routes.auth import set_response_cookiefrom server.utils.url_utils import get_cookie_domain, get_cookie_samesitefrom openhands.core.logger import openhands_logger as logger+from openhands.server.shared import configfrom openhands.server.user_auth.user_auth import AuthType, UserAuth, get_user_auth-from openhands.server.utils import configclass SetAuthCookieMiddleware:diff --git a/enterprise/server/routes/mcp_patch.py b/enterprise/server/routes/mcp_patch.pyindex a131a986d0..ea56f7d9ba 100644--- a/enterprise/server/routes/mcp_patch.py+++ b/enterprise/server/routes/mcp_patch.py@@ -3,8 +3,8 @@ import osfrom fastmcp import Client, FastMCPfrom fastmcp.client.transports import NpxStdioTransport+from openhands.app_server.mcp.mcp_router import mcp_serverfrom openhands.core.logger import openhands_logger as logger-from openhands.server.routes.mcp import mcp_serverENABLE_MCP_SEARCH_ENGINE = (os.getenv('ENABLE_MCP_SEARCH_ENGINE', 'false').lower() == 'true'diff --git a/enterprise/server/verified_models/verified_model_router.py b/enterprise/server/verified_models/verified_model_router.pyindex f34efe1ba6..bc4f6ef6ec 100644--- a/enterprise/server/verified_models/verified_model_router.py+++ b/enterprise/server/verified_models/verified_model_router.py@@ -16,7 +16,7 @@ from server.verified_models.verified_model_service import ()from openhands.app_server.config import get_db_session-from openhands.server.routes import public+from openhands.app_server.config_api.config_router import get_llm_models_dependencyfrom openhands.utils.llm import ModelsResponse, get_supported_llm_modelsapi_router = APIRouter(prefix='/api/admin/verified-models', tags=['Verified Models'])@@ -138,6 +138,4 @@ async def get_saas_llm_models_dependency(request: Request) -> ModelsResponse:# This must be called after the app is created in saas_server.pydef override_llm_models_dependency(app):"""Override the default LLM models implementation with SaaS version."""- app.dependency_overrides[public.get_llm_models_dependency] = (- get_saas_llm_models_dependency- )+ app.dependency_overrides[get_llm_models_dependency] = get_saas_llm_models_dependencydiff --git a/enterprise/storage/saas_conversation_validator.py b/enterprise/storage/saas_conversation_validator.pydeleted file mode 100644index 6493fdd602..0000000000--- a/enterprise/storage/saas_conversation_validator.py+++ /dev/null@@ -1,148 +0,0 @@-from server.auth.auth_error import AuthError, ExpiredError-from server.auth.saas_user_auth import saas_user_auth_from_signed_token-from server.auth.token_manager import TokenManager-from socketio.exceptions import ConnectionRefusedError-from storage.api_key_store import ApiKeyStore--from openhands.core.config import load_openhands_config-from openhands.core.logger import openhands_logger as logger-from openhands.server.shared import ConversationStoreImpl-from openhands.storage.conversation.conversation_validator import ConversationValidator---class SaasConversationValidator(ConversationValidator):- """Storage for conversation metadata. May or may not support multiple users depending on the environment."""-- async def _validate_api_key(self, api_key: str) -> str | None:- """- Validate an API key and return the user_id if valid.-- Args:- api_key: The API key to validate-- Returns:- The user_id if the API key is valid, None otherwise- """- try:- token_manager = TokenManager()-- # Validate the API key and get the user_id- api_key_store = ApiKeyStore.get_instance()- validation_result = await api_key_store.validate_api_key(api_key)-- if not validation_result:- logger.warning('Invalid API key')- return None-- user_id = validation_result.user_id-- # Get the offline token for the user- offline_token = await token_manager.load_offline_token(user_id)- if not offline_token:- logger.warning(f'No offline token found for user {user_id}')- return None-- return user_id-- except Exception as e:- logger.warning(f'Error validating API key: {str(e)}')- return None-- async def _validate_conversation_access(- self, conversation_id: str, user_id: str- ) -> bool:- """- Validate that the user has access to the conversation.-- Args:- conversation_id: The ID of the conversation- user_id: The ID of the user- github_user_id: The GitHub user ID, if available-- Returns:- True if the user has access to the conversation, False otherwise-- Raises:- ConnectionRefusedError: If the user does not have access to the conversation- """- config = load_openhands_config()- conversation_store = await ConversationStoreImpl.get_instance(config, user_id)-- if not await conversation_store.validate_metadata(conversation_id, user_id):- logger.error(- f'User {user_id} is not allowed to join conversation {conversation_id}'- )- raise ConnectionRefusedError(- f'User {user_id} is not allowed to join conversation {conversation_id}'- )- return True-- async def validate(- self,- conversation_id: str,- cookies_str: str,- authorization_header: str | None = None,- ) -> str | None:- """- Validate the conversation access using either an API key from the Authorization header- or a keycloak_auth cookie.-- Args:- conversation_id: The ID of the conversation- cookies_str: The cookies string from the request- authorization_header: The Authorization header from the request, if available-- Returns:- A tuple of (user_id, github_user_id)-- Raises:- ConnectionRefusedError: If the user does not have access to the conversation- AuthError: If the authentication fails- RuntimeError: If there is an error with the configuration or user info- """- # Try to authenticate using Authorization header first- if authorization_header and authorization_header.startswith('Bearer '):- api_key = authorization_header.replace('Bearer ', '')- user_id = await self._validate_api_key(api_key)-- if user_id:- logger.info(- f'User {user_id} is connecting to conversation {conversation_id} via API key'- )-- await self._validate_conversation_access(conversation_id, user_id)- return user_id-- # Fall back to cookie authentication- token_manager = TokenManager()- config = load_openhands_config()- cookies = (- dict(cookie.split('=', 1) for cookie in cookies_str.split('; '))- if cookies_str- else {}- )-- signed_token = cookies.get('keycloak_auth', '')- if not signed_token:- logger.warning('No keycloak_auth cookie or valid Authorization header')- raise ConnectionRefusedError(- 'No keycloak_auth cookie or valid Authorization header'- )- if not config.jwt_secret:- raise RuntimeError('JWT secret not found')-- try:- user_auth = await saas_user_auth_from_signed_token(signed_token)- access_token = await user_auth.get_access_token()- except ExpiredError:- raise ConnectionRefusedError('SESSION$TIMEOUT_MESSAGE')- if access_token is None:- raise AuthError('no_access_token')- user_info = await token_manager.get_user_info(access_token.get_secret_value())- # sub is a required field in KeycloakUserInfo, validation happens in get_user_info- user_id = user_info.sub-- logger.info(f'User {user_id} is connecting to conversation {conversation_id}')-- await self._validate_conversation_access(conversation_id, user_id) # type: ignore- return user_iddiff --git a/openhands/app_server/config_api/config_router.py b/openhands/app_server/config_api/config_router.pyindex 355154870a..9e1715b643 100644--- a/openhands/app_server/config_api/config_router.py+++ b/openhands/app_server/config_api/config_router.py@@ -6,7 +6,7 @@ provider search with pagination support.from typing import Annotated-from fastapi import APIRouter, Depends, Query+from fastapi import APIRouter, Depends, Query, Requestfrom openhands.app_server.config_api.config_models import (LLMModel,@@ -19,8 +19,18 @@ from openhands.app_server.utils.paging_utils import (paginate_results,)from openhands.sdk.llm.utils.verified_models import VERIFIED_MODELS-from openhands.server.routes.public import get_llm_models_dependency-from openhands.utils.llm import ModelsResponse+from openhands.server.shared import config+from openhands.utils.llm import ModelsResponse, get_supported_llm_models+++async def get_llm_models_dependency(request: Request) -> ModelsResponse:+ """Returns a callable that provides the LLM models implementation.++ Returns a factory that produces the actual implementation function.+ Override this in enterprise/saas mode via app.dependency_overrides.+ """+ return get_supported_llm_models(config)+# We use the get_dependencies method here to signal to the OpenAPI docs that this endpoint# is protected. The actual protection is provided by SetAuthCookieMiddlewarediff --git a/openhands/server/routes/mcp.py b/openhands/app_server/mcp/mcp_router.pysimilarity index 86%rename from openhands/server/routes/mcp.pyrename to openhands/app_server/mcp/mcp_router.pyindex 6cd62b2712..c8b1d3384f 100644--- a/openhands/server/routes/mcp.py+++ b/openhands/app_server/mcp/mcp_router.py@@ -1,12 +1,22 @@import osimport refrom typing import Annotated+from uuid import UUIDfrom fastmcp import FastMCPfrom fastmcp.exceptions import ToolErrorfrom fastmcp.server.dependencies import get_http_requestfrom pydantic import Field+from openhands.app_server.config import (+ get_app_conversation_info_service,+ get_global_config,+)+from openhands.app_server.services.injector import InjectorState+from openhands.app_server.user.specifiy_user_context import (+ USER_CONTEXT_ATTR,+ SpecifyUserContext,+)from openhands.core.logger import openhands_logger as loggerfrom openhands.integrations.azure_devops.azure_devops_service import (AzureDevOpsServiceImpl,@@ -19,14 +29,12 @@ from openhands.integrations.github.github_service import GithubServiceImplfrom openhands.integrations.gitlab.gitlab_service import GitLabServiceImplfrom openhands.integrations.provider import ProviderTokenfrom openhands.integrations.service_types import GitService, ProviderType-from openhands.server.shared import ConversationStoreImpl, config, server_configfrom openhands.server.types import AppModefrom openhands.server.user_auth import (get_access_token,get_provider_tokens,get_user_id,)-from openhands.storage.data_models.conversation_metadata import ConversationMetadatamcp_server = FastMCP('mcp', mask_error_details=True)@@ -38,7 +46,7 @@ async def get_conversation_link(service: GitService, conversation_id: str | None, body: str) -> str:"""Appends a followup link, in the PR body, to the OpenHands conversation that opened the PR"""- if server_config.app_mode != AppMode.SAAS:+ if get_global_config().app_mode != AppMode.SAAS:return bodyif not conversation_id:@@ -57,37 +65,50 @@ async def get_conversation_link(async def save_pr_metadata(user_id: str | None, conversation_id: str, tool_result: str) -> None:- conversation_store = await ConversationStoreImpl.get_instance(config, user_id)- conversation: ConversationMetadata = await conversation_store.get_metadata(- conversation_id- )-- pull_pattern = r'pull/(\d+)'- merge_request_pattern = r'merge_requests/(\d+)'- pull_requests_pattern = r'pull-requests/(\d+)'-- # Check if the tool_result contains the PR number- pr_number = None- match_pull = re.search(pull_pattern, tool_result)- match_merge_request = re.search(merge_request_pattern, tool_result)- match_pull_requests = re.search(pull_requests_pattern, tool_result)-- if match_pull:- pr_number = int(match_pull.group(1))- elif match_merge_request:- pr_number = int(match_merge_request.group(1))- elif match_pull_requests:- pr_number = int(match_pull_requests.group(1))-- if pr_number:- logger.info(f'Saving PR number: {pr_number} for conversation {conversation_id}')- conversation.pr_number.append(pr_number)- else:- logger.warning(- f'Failed to extract PR number for conversation {conversation_id}'+ # Manually construct state for background operation (no request context available)+ state = InjectorState()+ setattr(state, USER_CONTEXT_ATTR, SpecifyUserContext(user_id))+ async with get_app_conversation_info_service(+ state+ ) as app_conversation_info_service:+ app_conversation_info = (+ await app_conversation_info_service.get_app_conversation_info(+ UUID(conversation_id)+ )+ )+ if not app_conversation_info:+ raise ToolError(f'No such conversation {conversation_id}')++ pull_pattern = r'pull/(\d+)'+ merge_request_pattern = r'merge_requests/(\d+)'+ pull_requests_pattern = r'pull-requests/(\d+)'++ # Check if the tool_result contains the PR number+ pr_number = None+ match_pull = re.search(pull_pattern, tool_result)+ match_merge_request = re.search(merge_request_pattern, tool_result)+ match_pull_requests = re.search(pull_requests_pattern, tool_result)++ if match_pull:+ pr_number = int(match_pull.group(1))+ elif match_merge_request:+ pr_number = int(match_merge_request.group(1))+ elif match_pull_requests:+ pr_number = int(match_pull_requests.group(1))++ if pr_number:+ logger.info(+ f'Saving PR number: {pr_number} for conversation {conversation_id}'+ )+ app_conversation_info.pr_number.append(pr_number)+ else:+ logger.warning(+ f'Failed to extract PR number for conversation {conversation_id}'+ )++ await app_conversation_info_service.save_app_conversation_info(+ app_conversation_info)-- await conversation_store.save_metadata(conversation)@mcp_server.tool()diff --git a/openhands/mcp/__init__.py b/openhands/mcp/__init__.pydeleted file mode 100644index 963dcef01d..0000000000--- a/openhands/mcp/__init__.py+++ /dev/null@@ -1,19 +0,0 @@-from openhands.mcp.client import MCPClient-from openhands.mcp.error_collector import mcp_error_collector-from openhands.mcp.tool import MCPClientTool-from openhands.mcp.utils import (- call_tool_mcp,- convert_mcp_clients_to_tools,- create_mcp_clients,- fetch_mcp_tools_from_config,-)--__all__ = [- 'MCPClient',- 'convert_mcp_clients_to_tools',- 'create_mcp_clients',- 'MCPClientTool',- 'fetch_mcp_tools_from_config',- 'call_tool_mcp',- 'mcp_error_collector',-]diff --git a/openhands/mcp/client.py b/openhands/mcp/client.pydeleted file mode 100644index 22bfba0525..0000000000--- a/openhands/mcp/client.py+++ /dev/null@@ -1,177 +0,0 @@-import asyncio-from typing import Optional--from fastmcp import Client-from fastmcp.client.transports import (- SSETransport,- StdioTransport,- StreamableHttpTransport,-)-from mcp import McpError-from mcp.types import CallToolResult-from pydantic import BaseModel, ConfigDict, Field--from openhands.core.config.mcp_config import RemoteMCPServer, StdioMCPServer-from openhands.core.logger import openhands_logger as logger-from openhands.mcp.error_collector import mcp_error_collector-from openhands.mcp.tool import MCPClientTool---class MCPClient(BaseModel):- """A collection of tools that connects to an MCP server and manages available tools through the Model Context Protocol."""-- model_config = ConfigDict(arbitrary_types_allowed=True)-- client: Optional[Client] = None- description: str = 'MCP client tools for server interaction'- tools: list[MCPClientTool] = Field(default_factory=list)- tool_map: dict[str, MCPClientTool] = Field(default_factory=dict)- server_timeout: Optional[float] = None # Timeout from server config for tool calls-- async def _initialize_and_list_tools(self) -> None:- """Initialize session and populate tool map."""- if not self.client:- raise RuntimeError('Session not initialized.')-- async with self.client:- tools = await self.client.list_tools()-- # Clear existing tools- self.tools = []-- # Create proper tool objects for each server tool- for tool in tools:- server_tool = MCPClientTool(- name=tool.name,- description=tool.description,- inputSchema=tool.inputSchema,- )- self.tool_map[tool.name] = server_tool- self.tools.append(server_tool)-- logger.info(f'Connected to server with tools: {[tool.name for tool in tools]}')-- async def connect_http(- self,- server: RemoteMCPServer,- conversation_id: str | None = None,- timeout: float = 30.0,- ):- """Connect to MCP server using streamable HTTP or SSE transport."""- server_url = server.url- api_key = (- str(server.auth) if server.auth else None- ) # SDK uses `auth` for bearer token-- if not server_url:- raise ValueError('Server URL is required.')-- transport_type = server.transport or 'http'-- try:- headers: dict[str, str] = (- {k: str(v) for k, v in server.headers.items()} if server.headers else {}- )- if api_key:- headers.update(- {- 'Authorization': f'Bearer {api_key}',- 's': api_key,- 'X-Session-API-Key': api_key,- }- )-- if conversation_id:- headers['X-OpenHands-ServerConversation-ID'] = conversation_id-- transport: SSETransport | StreamableHttpTransport- if transport_type == 'sse':- transport = SSETransport(- url=server_url,- headers=headers or None,- )- else:- transport = StreamableHttpTransport(- url=server_url,- headers=headers or None,- )- self.client = Client(transport, timeout=timeout)-- await self._initialize_and_list_tools()- except McpError as e:- error_msg = f'McpError connecting to {server_url}: {e}'- logger.error(error_msg)- mcp_error_collector.add_error(- server_name=server_url,- server_type=transport_type,- error_message=error_msg,- exception_details=str(e),- )- raise-- except Exception as e:- error_msg = f'Error connecting to {server_url}: {e}'- logger.error(error_msg)- mcp_error_collector.add_error(- server_name=server_url,- server_type=transport_type,- error_message=error_msg,- exception_details=str(e),- )- raise-- async def connect_stdio(- self,- server: StdioMCPServer,- name: str | None = None,- timeout: float = 30.0,- ):- """Connect to MCP server using stdio transport."""- server_name = name or f'{server.command} {" ".join(server.args or [])}'- try:- transport = StdioTransport(- command=server.command, args=server.args or [], env=server.env- )- self.client = Client(transport, timeout=timeout)- await self._initialize_and_list_tools()- except Exception as e:- error_msg = f'Failed to connect to stdio server {server_name}: {e}'- logger.error(error_msg)- mcp_error_collector.add_error(- server_name=server_name,- server_type='stdio',- error_message=error_msg,- exception_details=str(e),- )- raise-- async def call_tool(self, tool_name: str, args: dict) -> CallToolResult:- """Call a tool on the MCP server with timeout from server configuration.-- Args:- tool_name: Name of the tool to call- args: Arguments to pass to the tool-- Returns:- CallToolResult from the MCP server-- Raises:- asyncio.TimeoutError: If the tool call times out- ValueError: If the tool is not found- RuntimeError: If the client session is not available- """- if tool_name not in self.tool_map:- raise ValueError(f'Tool {tool_name} not found.')- # The MCPClientTool is primarily for metadata; use the session to call the actual tool.- if not self.client:- raise RuntimeError('Client session is not available.')-- async with self.client:- # Use server timeout if configured- if self.server_timeout is not None:- return await asyncio.wait_for(- self.client.call_tool_mcp(name=tool_name, arguments=args),- timeout=self.server_timeout,- )- else:- return await self.client.call_tool_mcp(name=tool_name, arguments=args)diff --git a/openhands/mcp/error_collector.py b/openhands/mcp/error_collector.pydeleted file mode 100644index 69fabd8e24..0000000000--- a/openhands/mcp/error_collector.py+++ /dev/null@@ -1,78 +0,0 @@-"""MCP Error Collector for capturing and storing MCP-related errors during startup."""--import threading-import time-from dataclasses import dataclass---@dataclass-class MCPError:- """Represents an MCP-related error."""-- timestamp: float- server_name: str- server_type: str # 'stdio', 'sse', 'shttp'- error_message: str- exception_details: str | None = None---class MCPErrorCollector:- """Thread-safe collector for MCP errors during startup."""-- def __init__(self):- self._errors: list[MCPError] = []- self._lock = threading.Lock()- self._collection_enabled = True-- def add_error(- self,- server_name: str,- server_type: str,- error_message: str,- exception_details: str | None = None,- ) -> None:- """Add an MCP error to the collection."""- if not self._collection_enabled:- return-- with self._lock:- error = MCPError(- timestamp=time.time(),- server_name=server_name,- server_type=server_type,- error_message=error_message,- exception_details=exception_details,- )- self._errors.append(error)-- def get_errors(self) -> list[MCPError]:- """Get a copy of all collected errors."""- with self._lock:- return self._errors.copy()-- def has_errors(self) -> bool:- """Check if there are any collected errors."""- with self._lock:- return len(self._errors) > 0-- def clear_errors(self) -> None:- """Clear all collected errors."""- with self._lock:- self._errors.clear()-- def disable_collection(self) -> None:- """Disable error collection (useful after startup)."""- self._collection_enabled = False-- def enable_collection(self) -> None:- """Enable error collection."""- self._collection_enabled = True-- def get_error_count(self) -> int:- """Get the number of collected errors."""- with self._lock:- return len(self._errors)---# Global instance for collecting MCP errors-mcp_error_collector = MCPErrorCollector()diff --git a/openhands/mcp/tool.py b/openhands/mcp/tool.pydeleted file mode 100644index 895dabb8d8..0000000000--- a/openhands/mcp/tool.py+++ /dev/null@@ -1,23 +0,0 @@-from mcp.types import Tool-from pydantic import ConfigDict---class MCPClientTool(Tool):- """Represents a tool proxy that can be called on the MCP server from the client side.-- This version doesn't store a session reference, as sessions are created on-demand- by the MCPClient for each operation.- """-- model_config = ConfigDict(arbitrary_types_allowed=True)-- def to_param(self) -> dict:- """Convert tool to function call format."""- return {- 'type': 'function',- 'function': {- 'name': self.name,- 'description': self.description,- 'parameters': self.inputSchema,- },- }diff --git a/openhands/mcp/utils.py b/openhands/mcp/utils.pydeleted file mode 100644index fac4dfb4d3..0000000000--- a/openhands/mcp/utils.py+++ /dev/null@@ -1,264 +0,0 @@-import asyncio-import json-import shutil--from mcp import McpError--from openhands.core.config.mcp_config import (- MCPConfig,- RemoteMCPServer,- StdioMCPServer,-)-from openhands.core.logger import openhands_logger as logger-from openhands.events.action.mcp import MCPAction-from openhands.events.observation.mcp import MCPObservation-from openhands.events.observation.observation import Observation-from openhands.mcp.client import MCPClient-from openhands.mcp.error_collector import mcp_error_collector-from openhands.utils._redact_compat import (- redact_text_secrets,- redact_url_params,- sanitize_config,-)---def convert_mcp_clients_to_tools(mcp_clients: list[MCPClient] | None) -> list[dict]:- """Converts a list of MCPClient instances to ChatCompletionToolParam format- that can be used by CodeActAgent.-- Args:- mcp_clients: List of MCPClient instances or None-- Returns:- List of dicts of tools ready to be used by CodeActAgent- """- if mcp_clients is None:- logger.warning('mcp_clients is None, returning empty list')- return []-- all_mcp_tools = []- try:- for client in mcp_clients:- # Each MCPClient has an mcp_clients property that is a ToolCollection- # The ToolCollection has a to_params method that converts tools to ChatCompletionToolParam format- for tool in client.tools:- mcp_tools = tool.to_param()- all_mcp_tools.append(mcp_tools)- except Exception as e:- error_msg = f'Error in convert_mcp_clients_to_tools: {e}'- logger.error(error_msg)- mcp_error_collector.add_error(- server_name='general',- server_type='conversion',- error_message=error_msg,- exception_details=str(e),- )- return []- return all_mcp_tools---async def create_mcp_clients(- mcp_config: MCPConfig,- conversation_id: str | None = None,-) -> list[MCPClient]:- """Create MCP clients from an MCPConfig.-- Args:- mcp_config: Unified MCP configuration.- conversation_id: Optional conversation ID for remote servers.- """- import sys-- if sys.platform == 'win32':- logger.info(- 'MCP functionality is disabled on Windows, skipping client creation'- )- return []-- if not mcp_config.mcpServers:- return []-- mcp_clients: list[MCPClient] = []-- for name, server in mcp_config.mcpServers.items():- if isinstance(server, StdioMCPServer):- if not shutil.which(server.command):- logger.error(- f'Skipping MCP stdio server "{name}": command "{server.command}" not found. '- f'Please install {server.command} or remove this server from your configuration.'- )- continue-- logger.info(- f'Initializing MCP agent for {redact_text_secrets(str(server))} with stdio connection...'- )- client = MCPClient()- try:- await client.connect_stdio(server, name=name)- tool_names = [tool.name for tool in client.tools]- logger.debug(- f'Successfully connected to MCP stdio server {name} - '- f'provides {len(tool_names)} tools: {tool_names}'- )- mcp_clients.append(client)- except Exception as e:- logger.error(- f'Failed to connect to {redact_text_secrets(str(server))}: {str(e)}',- exc_info=True,- )- continue-- if isinstance(server, RemoteMCPServer):- transport = server.transport or 'http'- logger.info(- f'Initializing MCP agent for {redact_text_secrets(str(server))} with {transport} connection...'- )- client = MCPClient()-- if server.timeout is not None:- client.server_timeout = float(server.timeout)- logger.debug(f'Set server timeout to {server.timeout}s')-- try:- await client.connect_http(server, conversation_id=conversation_id)- tool_names = [tool.name for tool in client.tools]- logger.debug(- f'Successfully connected to MCP server {redact_url_params(server.url)} - '- f'provides {len(tool_names)} tools: {tool_names}'- )- mcp_clients.append(client)- except Exception as e:- logger.error(- f'Failed to connect to {redact_text_secrets(str(server))}: {str(e)}',- exc_info=True,- )-- return mcp_clients---async def fetch_mcp_tools_from_config(- mcp_config: MCPConfig, conversation_id: str | None = None-) -> list[dict]:- """Retrieves the list of MCP tools from the MCP clients.-- Args:- mcp_config: The MCP configuration- conversation_id: Optional conversation ID to associate with the MCP clients-- Returns:- A list of tool dictionaries. Returns an empty list if no connections could be established.- """- import sys-- # Skip MCP tools on Windows- if sys.platform == 'win32':- logger.info('MCP functionality is disabled on Windows, skipping tool fetching')- return []-- mcp_clients = []- mcp_tools = []- try:- logger.debug(- f'Creating MCP clients with config: {sanitize_config(mcp_config.model_dump())}'- )-- # Create clients - this will fetch tools but not maintain active connections- mcp_clients = await create_mcp_clients(mcp_config, conversation_id)-- if not mcp_clients:- logger.debug('No MCP clients were successfully connected')- return []-- # Convert tools to the format expected by the agent- mcp_tools = convert_mcp_clients_to_tools(mcp_clients)-- except Exception as e:- error_msg = f'Error fetching MCP tools: {str(e)}'- logger.error(error_msg)- mcp_error_collector.add_error(- server_name='general',- server_type='fetch',- error_message=error_msg,- exception_details=str(e),- )- return []-- logger.debug(f'MCP tools: {mcp_tools}')- return mcp_tools---async def call_tool_mcp(mcp_clients: list[MCPClient], action: MCPAction) -> Observation:- """Call a tool on an MCP server and return the observation.-- Args:- mcp_clients: The list of MCP clients to execute the action on- action: The MCP action to execute-- Returns:- The observation from the MCP server- """- import sys-- from openhands.events.observation import ErrorObservation-- # Skip MCP tools on Windows- if sys.platform == 'win32':- logger.info('MCP functionality is disabled on Windows')- return ErrorObservation('MCP functionality is not available on Windows')-- if not mcp_clients:- raise ValueError('No MCP clients found')-- logger.debug(f'MCP action received: {action}')-- # Find the MCP client that has the matching tool name- matching_client = None- logger.debug(f'MCP clients: {mcp_clients}')- logger.debug(f'MCP action name: {action.name}')-- for client in mcp_clients:- logger.debug(f'MCP client tools: {client.tools}')- if action.name in [tool.name for tool in client.tools]:- matching_client = client- break-- if matching_client is None:- raise ValueError(f'No matching MCP agent found for tool name: {action.name}')-- logger.debug(f'Matching client: {matching_client}')-- try:- # Call the tool - this will create a new connection internally- response = await matching_client.call_tool(action.name, action.arguments)- logger.debug(f'MCP response: {response}')-- return MCPObservation(- content=json.dumps(response.model_dump(mode='json')),- name=action.name,- arguments=action.arguments,- )- except asyncio.TimeoutError:- # Handle timeout errors specifically- timeout_val = getattr(matching_client, 'server_timeout', 'unknown')- logger.error(f'MCP tool {action.name} timed out after {timeout_val}s')- error_content = json.dumps(- {- 'isError': True,- 'error': f'Tool "{action.name}" timed out after {timeout_val} seconds',- 'content': [],- }- )- return MCPObservation(- content=error_content,- name=action.name,- arguments=action.arguments,- )- except McpError as e:- # Handle MCP errors by returning an error observation instead of raising- logger.error(f'MCP error when calling tool {action.name}: {e}')- error_content = json.dumps({'isError': True, 'error': str(e), 'content': []})- return MCPObservation(- content=error_content,- name=action.name,- arguments=action.arguments,- )diff --git a/openhands/server/app.py b/openhands/server/app.pyindex ccacf82f28..a572314980 100644--- a/openhands/server/app.py+++ b/openhands/server/app.py@@ -22,9 +22,9 @@ from fastapi.responses import JSONResponsefrom openhands.app_server import v1_routerfrom openhands.app_server.config import get_app_lifespan_service+from openhands.app_server.mcp.mcp_router import mcp_serverfrom openhands.app_server.status.status_router import router as health_routerfrom openhands.integrations.service_types import AuthenticationError-from openhands.server.routes.mcp import mcp_serverfrom openhands.version import get_versionmcp_app = mcp_server.http_app(path='/mcp', stateless_http=True)diff --git a/openhands/server/routes/public.py b/openhands/server/routes/public.pydeleted file mode 100644index a840210bc8..0000000000--- a/openhands/server/routes/public.py+++ /dev/null@@ -1,15 +0,0 @@-# Function migrated from the deprecated routes/public.py-# This is used by the V1 config router to get LLM models-from fastapi import Request--from openhands.server.shared import config-from openhands.utils.llm import ModelsResponse, get_supported_llm_models---async def get_llm_models_dependency(request: Request) -> ModelsResponse:- """Returns a callable that provides the LLM models implementation.-- Returns a factory that produces the actual implementation function.- Override this in enterprise/saas mode via app.dependency_overrides.- """- return get_supported_llm_models(config)diff --git a/openhands/server/utils.py b/openhands/server/utils.pydeleted file mode 100644index 0a8a045454..0000000000--- a/openhands/server/utils.py+++ /dev/null@@ -1,88 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.-from fastapi import Depends, HTTPException, Request, status--from openhands.server.shared import (- ConversationStoreImpl,- config,-)-from openhands.server.user_auth import get_user_id-from openhands.storage.conversation.conversation_store import ConversationStore-from openhands.storage.data_models.conversation_metadata import ConversationMetadata---def validate_conversation_id(conversation_id: str) -> str:- """- Validate conversation ID format and length.-- Args:- conversation_id: The conversation ID to validate-- Returns:- The validated conversation ID-- Raises:- HTTPException: If the conversation ID is invalid- """- # Check length - UUID hex is 32 characters, allow some flexibility but not excessive- if len(conversation_id) > 100:- raise HTTPException(- status_code=status.HTTP_400_BAD_REQUEST,- detail='Conversation ID is too long',- )-- # Check for null bytes and other problematic characters- if '\x00' in conversation_id:- raise HTTPException(- status_code=status.HTTP_400_BAD_REQUEST,- detail='Conversation ID contains invalid characters',- )-- # Check for path traversal attempts- if '..' in conversation_id or '/' in conversation_id or '\\' in conversation_id:- raise HTTPException(- status_code=status.HTTP_400_BAD_REQUEST,- detail='Conversation ID contains invalid path characters',- )-- # Check for control characters and newlines- if any(ord(c) < 32 for c in conversation_id):- raise HTTPException(- status_code=status.HTTP_400_BAD_REQUEST,- detail='Conversation ID contains control characters',- )-- return conversation_id---async def get_conversation_store(request: Request) -> ConversationStore | None:- conversation_store: ConversationStore | None = getattr(- request.state, 'conversation_store', None- )- if conversation_store:- return conversation_store- user_id = await get_user_id(request)- conversation_store = await ConversationStoreImpl.get_instance(config, user_id)- request.state.conversation_store = conversation_store- return conversation_store---async def get_conversation_metadata(- conversation_id: str,- conversation_store: ConversationStore = Depends(get_conversation_store),-) -> ConversationMetadata:- """Get conversation metadata and validate user access without requiring an active conversation."""- try:- metadata = await conversation_store.get_metadata(conversation_id)- return metadata- except FileNotFoundError:- raise HTTPException(- status_code=status.HTTP_404_NOT_FOUND,- detail=f'Conversation {conversation_id} not found',- )diff --git a/openhands/storage/conversation/conversation_validator.py b/openhands/storage/conversation/conversation_validator.pydeleted file mode 100644index 55e8ae2e0a..0000000000--- a/openhands/storage/conversation/conversation_validator.py+++ /dev/null@@ -1,81 +0,0 @@-import os-from datetime import datetime, timezone--from openhands.core.config.utils import load_openhands_config-from openhands.core.logger import openhands_logger as logger-from openhands.server.config.server_config import ServerConfig-from openhands.storage.conversation.conversation_store import ConversationStore-from openhands.storage.data_models.conversation_metadata import ConversationMetadata-from openhands.utils.conversation_summary import get_default_conversation_title-from openhands.utils.import_utils import get_impl---class ConversationValidator:- """Abstract base class for validating conversation access.-- This is an extension point in OpenHands that allows applications to customize how- conversation access is validated. Applications can substitute their own implementation by:- 1. Creating a class that inherits from ConversationValidator- 2. Implementing the validate method- 3. Setting OPENHANDS_CONVERSATION_VALIDATOR_CLS environment variable to the fully qualified name of the class-- The class is instantiated via get_impl() in create_conversation_validator().-- The default implementation performs no validation and returns None, None.- """-- async def validate(- self,- conversation_id: str,- cookies_str: str,- authorization_header: str | None = None,- ) -> str | None:- user_id = None- metadata = await self._ensure_metadata_exists(conversation_id, user_id)- return metadata.user_id-- async def _ensure_metadata_exists(- self,- conversation_id: str,- user_id: str | None,- ) -> ConversationMetadata:- config = load_openhands_config()- server_config = ServerConfig()-- conversation_store_class: type[ConversationStore] = get_impl(- ConversationStore,- server_config.conversation_store_class,- )- conversation_store = await conversation_store_class.get_instance(- config, user_id- )-- try:- metadata = await conversation_store.get_metadata(conversation_id)- except FileNotFoundError:- logger.info(- f'Creating new conversation metadata for {conversation_id}',- extra={'session_id': conversation_id},- )- await conversation_store.save_metadata(- ConversationMetadata(- conversation_id=conversation_id,- user_id=user_id,- title=get_default_conversation_title(conversation_id),- last_updated_at=datetime.now(timezone.utc),- selected_repository=None,- )- )- metadata = await conversation_store.get_metadata(conversation_id)- return metadata---def create_conversation_validator() -> ConversationValidator:- conversation_validator_cls = os.environ.get(- 'OPENHANDS_CONVERSATION_VALIDATOR_CLS',- 'openhands.storage.conversation.conversation_validator.ConversationValidator',- )- ConversationValidatorImpl = get_impl(- ConversationValidator, conversation_validator_cls- )- return ConversationValidatorImpl()diff --git a/tests/unit/mcp/test_cve_2025_66416.py b/tests/unit/mcp/test_cve_2025_66416.pydeleted file mode 100644index 6c404616c9..0000000000--- a/tests/unit/mcp/test_cve_2025_66416.py+++ /dev/null@@ -1,219 +0,0 @@-"""Tests to verify CVE-2025-66416 (DNS rebinding vulnerability) is fixed.--CVE-2025-66416: The Model Context Protocol (MCP) Python SDK prior to version 1.23.0-did not enable DNS rebinding protection by default for HTTP-based servers. When an-HTTP-based MCP server is run on localhost without authentication using FastMCP with-streamable HTTP or SSE transport, and has not configured TransportSecuritySettings,-a malicious website could exploit DNS rebinding to bypass same-origin policy-restrictions and send requests to the local MCP server.--Fix: MCP version 1.23.0+ enables DNS rebinding protection by default when the host-parameter is 127.0.0.1 or localhost. This is enforced through TransportSecuritySettings.--Reference: https://github.com/modelcontextprotocol/python-sdk/security/advisories/GHSA-9h52-p55h-vw2f-"""--import pytest---class TestTransportSecuritySettingsAvailability:- """Test that TransportSecuritySettings is available for DNS rebinding protection."""-- def test_transport_security_settings_exists(self):- """Verify TransportSecuritySettings class is available in mcp module."""- from mcp.server.fastmcp.server import Settings-- # The Settings class should have security-related configuration- assert hasattr(Settings, '__annotations__'), (- 'Settings class should have annotations for configuration'- )-- def test_fastmcp_accepts_security_settings(self):- """Test FastMCP can be instantiated (security defaults are applied internally)."""- from fastmcp import FastMCP-- # Create a server - in 1.23.0+ DNS rebinding protection is enabled by default- # for localhost/127.0.0.1 hosts- server = FastMCP('cve-test-server')- assert server is not None---class TestDNSRebindingProtectionDefaults:- """Test that DNS rebinding protection is enabled by default for localhost."""-- def test_fastmcp_has_localhost_protection(self):- """Verify FastMCP applies security defaults for localhost servers."""- from fastmcp import FastMCP-- # Creating a server for localhost should have protection by default- # per the CVE fix in mcp 1.23.0+- server = FastMCP('localhost-test-server')-- # Server should be created successfully with defaults- assert server is not None- assert server.name == 'localhost-test-server'-- def test_mcp_server_has_security_configuration(self):- """Test that MCP server components have security configuration options."""- # Check that security-related imports are available- from mcp.server.session import ServerSession # noqa: F401- from mcp.shared.exceptions import McpError # noqa: F401-- # These should be importable if mcp 1.23.0+ is installed- # and the security fix is in place- assert True---class TestSSETransportSecurity:- """Test SSE transport has appropriate security settings."""-- def test_sse_transport_can_be_created(self):- """Test SSETransport can be instantiated from fastmcp."""- from fastmcp.client.transports import SSETransport-- # Create SSE transport - should work without errors- transport = SSETransport(- url='http://localhost:8080/sse',- headers={'X-Test': 'value'},- )- assert transport is not None-- def test_sse_transport_with_localhost_url(self):- """Test SSE transport with localhost URL has proper configuration."""- from fastmcp.client.transports import SSETransport-- # Localhost URLs should work with the security fix- transport = SSETransport(url='http://127.0.0.1:8080/sse')- assert transport is not None- assert any(host in str(transport.url) for host in ('127.0.0.1', 'localhost'))---class TestStreamableHttpTransportSecurity:- """Test StreamableHttp transport has appropriate security settings."""-- def test_streamable_http_transport_can_be_created(self):- """Test StreamableHttpTransport can be instantiated."""- from fastmcp.client.transports import StreamableHttpTransport-- transport = StreamableHttpTransport(- url='http://localhost:8080/mcp',- headers={'Authorization': 'Bearer test'},- )- assert transport is not None-- def test_streamable_http_transport_with_localhost(self):- """Test StreamableHttp transport with localhost URL."""- from fastmcp.client.transports import StreamableHttpTransport-- transport = StreamableHttpTransport(url='http://localhost:3000/mcp')- assert transport is not None---class TestMCPErrorHandling:- """Test MCP error handling for security-related errors."""-- def test_mcp_error_exists(self):- """Verify McpError is properly defined for error handling."""- from mcp import McpError-- assert issubclass(McpError, Exception)-- def test_mcp_error_can_be_raised(self):- """Test McpError can be raised and caught."""- from mcp import McpError- from mcp.types import ErrorData-- # McpError requires ErrorData object, not a string- error_data = ErrorData(code=-1, message='Test security error')- with pytest.raises(McpError):- raise McpError(error_data)-- def test_tool_error_exists(self):- """Verify ToolError from fastmcp is available."""- from fastmcp.exceptions import ToolError-- assert issubclass(ToolError, Exception)---class TestMCPTypesIntegrity:- """Test MCP types are properly defined (integrity check for the fix)."""-- def test_call_tool_result_type(self):- """Verify CallToolResult type is available."""- from mcp.types import CallToolResult-- assert CallToolResult is not None-- def test_tool_type(self):- """Verify Tool type is available."""- from mcp.types import Tool-- assert Tool is not None-- def test_text_content_type(self):- """Verify TextContent type is available for tool responses."""- from mcp.types import TextContent-- assert TextContent is not None---class TestFastMCPVersionCompatibility:- """Test FastMCP version is compatible with the security fix."""-- def test_fastmcp_server_creation_with_mask_error_details(self):- """Test FastMCP server can be created with mask_error_details option."""- from fastmcp import FastMCP-- # This option helps prevent leaking sensitive information in errors- server = FastMCP('secure-server', mask_error_details=True)- assert server is not None---class TestSecurityIntegration:- """Integration tests for security-related functionality."""-- def test_full_import_chain(self):- """Test the full import chain for security-fixed modules."""- # MCP core- # FastMCP components- from fastmcp import FastMCP- from fastmcp.client.transports import (- SSETransport,- StdioTransport,- StreamableHttpTransport,- )- from fastmcp.exceptions import ToolError- from mcp import McpError- from mcp.types import CallToolResult, Tool-- # All imports should succeed with the CVE fix in place- assert all(- [- McpError is not None,- CallToolResult is not None,- Tool is not None,- FastMCP is not None,- SSETransport is not None,- StreamableHttpTransport is not None,- StdioTransport is not None,- ToolError is not None,- ]- )-- def test_openhands_mcp_client_imports(self):- """Test OpenHands MCP client can import required dependencies."""- from openhands.mcp.client import MCPClient- from openhands.mcp.tool import MCPClientTool-- assert MCPClient is not None- assert MCPClientTool is not None-- def test_openhands_mcp_config_types(self):- """Test OpenHands MCP config types are available."""- from openhands.core.config.mcp_config import (- RemoteMCPServer,- StdioMCPServer,- )-- assert RemoteMCPServer is not None- assert StdioMCPServer is not Nonediff --git a/tests/unit/mcp/test_mcp_create_clients_timeout.py b/tests/unit/mcp/test_mcp_create_clients_timeout.pydeleted file mode 100644index 6577e4d077..0000000000--- a/tests/unit/mcp/test_mcp_create_clients_timeout.py+++ /dev/null@@ -1,71 +0,0 @@-import asyncio--import pytest--from openhands.core.config.mcp_config import MCPConfig, RemoteMCPServer-from openhands.mcp.client import MCPClient-from openhands.mcp.utils import create_mcp_clients---async def test_create_mcp_clients_timeout_with_invalid_url():- """Test that create_mcp_clients properly times out when given an invalid URL."""- mcp_config = MCPConfig(- mcpServers={- 'invalid': RemoteMCPServer(- url='http://non-existent-domain-that-will-timeout.invalid',- transport='sse',- )- }- )-- original_connect_http = MCPClient.connect_http-- async def connect_http_with_short_timeout(self, server, **kwargs):- return await original_connect_http(self, server, timeout=0.5)-- try:- MCPClient.connect_http = connect_http_with_short_timeout-- start_time = asyncio.get_event_loop().time()- clients = await create_mcp_clients(mcp_config)- end_time = asyncio.get_event_loop().time()-- assert len(clients) == 0- assert end_time - start_time < 5.0, (- 'Operation took too long, timeout may not be working'- )- finally:- MCPClient.connect_http = original_connect_http---async def test_create_mcp_clients_with_unreachable_host():- """Test that create_mcp_clients handles unreachable hosts properly."""- mcp_config = MCPConfig(- mcpServers={- 'unreachable': RemoteMCPServer(- url='http://192.0.2.1:8080',- transport='sse',- )- }- )-- original_connect_http = MCPClient.connect_http-- async def connect_http_with_short_timeout(self, server, **kwargs):- return await original_connect_http(self, server, timeout=1.0)-- try:- MCPClient.connect_http = connect_http_with_short_timeout-- start_time = asyncio.get_event_loop().time()- clients = await create_mcp_clients(mcp_config)- end_time = asyncio.get_event_loop().time()-- assert len(clients) == 0- assert end_time - start_time < 5.0, (- 'Operation took too long, timeout may not be working'- )- finally:- MCPClient.connect_http = original_connect_httpdiff --git a/tests/unit/mcp/test_mcp_error_collector.py b/tests/unit/mcp/test_mcp_error_collector.pydeleted file mode 100644index f3291bd730..0000000000--- a/tests/unit/mcp/test_mcp_error_collector.py+++ /dev/null@@ -1,159 +0,0 @@-"""Tests for MCP Error Collector functionality."""--import time--from openhands.mcp.error_collector import (- MCPError,- MCPErrorCollector,- mcp_error_collector,-)---class TestMCPError:- """Test MCPError dataclass."""-- def test_mcp_error_creation(self):- """Test creating an MCP error."""- timestamp = time.time()- error = MCPError(- timestamp=timestamp,- server_name='test-server',- server_type='stdio',- error_message='Connection failed',- exception_details='Socket timeout',- )-- assert error.timestamp == timestamp- assert error.server_name == 'test-server'- assert error.server_type == 'stdio'- assert error.error_message == 'Connection failed'- assert error.exception_details == 'Socket timeout'-- def test_mcp_error_creation_without_exception_details(self):- """Test creating an MCP error without exception details."""- timestamp = time.time()- error = MCPError(- timestamp=timestamp,- server_name='test-server',- server_type='sse',- error_message='Server unreachable',- )-- assert error.timestamp == timestamp- assert error.server_name == 'test-server'- assert error.server_type == 'sse'- assert error.error_message == 'Server unreachable'- assert error.exception_details is None---class TestMCPErrorCollector:- """Test MCPErrorCollector functionality."""-- def setup_method(self):- """Set up test fixtures."""- self.collector = MCPErrorCollector()-- def test_initialization(self):- """Test collector initialization."""- assert self.collector._errors == []- assert self.collector._collection_enabled is True-- def test_add_error(self):- """Test adding an error to the collector."""- self.collector.add_error(- server_name='test-server',- server_type='stdio',- error_message='Connection failed',- exception_details='Socket timeout',- )-- errors = self.collector.get_errors()- assert len(errors) == 1- assert errors[0].server_name == 'test-server'- assert errors[0].server_type == 'stdio'- assert errors[0].error_message == 'Connection failed'- assert errors[0].exception_details == 'Socket timeout'- assert errors[0].timestamp > 0-- def test_add_multiple_errors(self):- """Test adding multiple errors."""- self.collector.add_error('server1', 'stdio', 'Error 1')- self.collector.add_error('server2', 'sse', 'Error 2')- self.collector.add_error('server3', 'shttp', 'Error 3')-- errors = self.collector.get_errors()- assert len(errors) == 3- assert errors[0].server_name == 'server1'- assert errors[1].server_name == 'server2'- assert errors[2].server_name == 'server3'-- def test_has_errors(self):- """Test has_errors method."""- assert not self.collector.has_errors()-- self.collector.add_error('server1', 'stdio', 'Error 1')- assert self.collector.has_errors()-- self.collector.clear_errors()- assert not self.collector.has_errors()-- def test_clear_errors(self):- """Test clearing errors."""- self.collector.add_error('server1', 'stdio', 'Error 1')- self.collector.add_error('server2', 'sse', 'Error 2')-- assert len(self.collector.get_errors()) == 2-- self.collector.clear_errors()- assert len(self.collector.get_errors()) == 0- assert not self.collector.has_errors()-- def test_enable_disable_collection(self):- """Test enabling and disabling error collection."""- self.collector.add_error('server1', 'stdio', 'Error 1')- assert len(self.collector.get_errors()) == 1-- # Disable collection- self.collector.disable_collection()-- # Adding error should be ignored- self.collector.add_error('server2', 'sse', 'Error 2')- assert len(self.collector.get_errors()) == 1 # Still only 1 error-- # Re-enable collection- self.collector.enable_collection()-- # Adding error should work again- self.collector.add_error('server3', 'shttp', 'Error 3')- assert len(self.collector.get_errors()) == 2---class TestGlobalMCPErrorCollector:- """Test the global MCP error collector instance."""-- def setup_method(self):- """Clear global collector before each test."""- mcp_error_collector.clear_errors()- mcp_error_collector.enable_collection()-- def teardown_method(self):- """Clean up after each test."""- mcp_error_collector.clear_errors()- mcp_error_collector.enable_collection()-- def test_global_collector_exists(self):- """Test that global collector instance exists."""- assert mcp_error_collector is not None- assert isinstance(mcp_error_collector, MCPErrorCollector)-- def test_global_collector_functionality(self):- """Test basic functionality of global collector."""- assert not mcp_error_collector.has_errors()-- mcp_error_collector.add_error('global-server', 'stdio', 'Global error')- assert mcp_error_collector.has_errors()- assert mcp_error_collector.get_error_count() == 1-- errors = mcp_error_collector.get_errors()- assert len(errors) == 1- assert errors[0].server_name == 'global-server'diff --git a/tests/unit/mcp/test_mcp_timeout.py b/tests/unit/mcp/test_mcp_timeout.pydeleted file mode 100644index d847384610..0000000000--- a/tests/unit/mcp/test_mcp_timeout.py+++ /dev/null@@ -1,87 +0,0 @@-import asyncio-from unittest import mock--import pytest--from openhands.core.config.mcp_config import MCPConfig, RemoteMCPServer-from openhands.mcp import MCPClient, create_mcp_clients, fetch_mcp_tools_from_config---async def test_sse_connection_timeout():- """Test that SSE connection timeout is handled gracefully."""- mock_client = mock.MagicMock(spec=MCPClient)-- async def mock_connect_http(*args, **kwargs):- await asyncio.sleep(0.1)- raise asyncio.TimeoutError('Connection timed out')-- mock_client.connect_http.side_effect = mock_connect_http- mock_client.disconnect = mock.AsyncMock()-- with mock.patch('openhands.mcp.utils.MCPClient', return_value=mock_client):- mcp_config = MCPConfig(- mcpServers={- 's1': RemoteMCPServer(url='http://server1:8080', transport='sse'),- 's2': RemoteMCPServer(url='http://server2:8080', transport='sse'),- }- )-- clients = await create_mcp_clients(mcp_config)-- assert len(clients) == 0- assert mock_client.connect_http.call_count == 2---async def test_fetch_mcp_tools_with_timeout():- """Test that fetch_mcp_tools_from_config handles timeouts gracefully."""- mock_config = MCPConfig(- mcpServers={- 's1': RemoteMCPServer(url='http://server1:8080', transport='sse'),- }- )-- with mock.patch('openhands.mcp.utils.create_mcp_clients', return_value=[]):- tools = await fetch_mcp_tools_from_config(mock_config, None)- assert tools == []---async def test_mixed_connection_results():- """Test that fetch_mcp_tools_from_config returns tools even when some connections fail."""- mock_config = MCPConfig(- mcpServers={- 's1': RemoteMCPServer(url='http://server1:8080', transport='sse'),- 's2': RemoteMCPServer(url='http://server2:8080', transport='sse'),- }- )-- # Create a successful client- successful_client = mock.MagicMock(spec=MCPClient)-- # Create a mock tool with a to_param method that returns a tool dictionary- mock_tool = mock.MagicMock()- mock_tool.name = 'mock_tool'- mock_tool.to_param.return_value = {- 'type': 'function',- 'function': {- 'name': 'mock_tool',- 'description': 'A mock tool for testing',- 'parameters': {},- },- }-- # Set the client's tools- successful_client.tools = [mock_tool]-- # Mock create_mcp_clients to return our successful client- with mock.patch(- 'openhands.mcp.utils.create_mcp_clients', return_value=[successful_client]- ):- # Call fetch_mcp_tools_from_config- tools = await fetch_mcp_tools_from_config(mock_config, None)-- # Verify that tools were returned- assert len(tools) > 0- assert tools[0]['function']['name'] == 'mock_tool'diff --git a/tests/unit/mcp/test_mcp_utils.py b/tests/unit/mcp/test_mcp_utils.pydeleted file mode 100644index ac4cf40a8a..0000000000--- a/tests/unit/mcp/test_mcp_utils.py+++ /dev/null@@ -1,261 +0,0 @@-import json-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--# Import the module, not the functions directly to avoid circular imports-import openhands.mcp.utils-from openhands.core.config.mcp_config import (- MCPConfig,- RemoteMCPServer,- StdioMCPServer,-)-from openhands.events.action.mcp import MCPAction-from openhands.events.observation.mcp import MCPObservation---async def test_create_mcp_clients_empty():- """Test creating MCP clients with empty config."""- clients = await openhands.mcp.utils.create_mcp_clients(MCPConfig(mcpServers={}))- assert clients == []---@patch('openhands.mcp.utils.MCPClient')-async def test_create_mcp_clients_success(mock_mcp_client):- """Test successful creation of MCP clients."""- mock_client_instance = AsyncMock()- mock_mcp_client.return_value = mock_client_instance- mock_client_instance.connect_http = AsyncMock()-- s1 = RemoteMCPServer(url='http://server1:8080', transport='sse')- s2 = RemoteMCPServer(url='http://server2:8080', transport='sse', auth='test-key')- mcp_config = MCPConfig(mcpServers={'s1': s1, 's2': s2})-- clients = await openhands.mcp.utils.create_mcp_clients(mcp_config)-- assert len(clients) == 2- assert mock_mcp_client.call_count == 2---@patch('openhands.mcp.utils.MCPClient')-async def test_create_mcp_clients_connection_failure(mock_mcp_client):- """Test handling of connection failures when creating MCP clients."""- mock_client_instance = AsyncMock()- mock_mcp_client.return_value = mock_client_instance-- mock_client_instance.connect_http.side_effect = [- None,- Exception('Connection failed'),- ]-- s1 = RemoteMCPServer(url='http://server1:8080', transport='sse')- s2 = RemoteMCPServer(url='http://server2:8080', transport='sse')- mcp_config = MCPConfig(mcpServers={'s1': s1, 's2': s2})-- clients = await openhands.mcp.utils.create_mcp_clients(mcp_config)-- assert len(clients) == 1---def test_convert_mcp_clients_to_tools_empty():- """Test converting empty MCP clients list to tools."""- tools = openhands.mcp.utils.convert_mcp_clients_to_tools(None)- assert tools == []-- tools = openhands.mcp.utils.convert_mcp_clients_to_tools([])- assert tools == []---def test_convert_mcp_clients_to_tools():- """Test converting MCP clients to tools."""- # Create mock clients with tools- mock_client1 = MagicMock()- mock_client2 = MagicMock()-- # Create mock tools- mock_tool1 = MagicMock()- mock_tool1.to_param.return_value = {'function': {'name': 'tool1'}}-- mock_tool2 = MagicMock()- mock_tool2.to_param.return_value = {'function': {'name': 'tool2'}}-- mock_tool3 = MagicMock()- mock_tool3.to_param.return_value = {'function': {'name': 'tool3'}}-- # Set up the clients with their tools- mock_client1.tools = [mock_tool1, mock_tool2]- mock_client2.tools = [mock_tool3]-- # Convert to tools- tools = openhands.mcp.utils.convert_mcp_clients_to_tools(- [mock_client1, mock_client2]- )-- # Verify- assert len(tools) == 3- assert tools[0] == {'function': {'name': 'tool1'}}- assert tools[1] == {'function': {'name': 'tool2'}}- assert tools[2] == {'function': {'name': 'tool3'}}---async def test_call_tool_mcp_no_clients():- """Test calling MCP tool with no clients."""- action = MCPAction(name='test_tool', arguments={'arg1': 'value1'})-- with pytest.raises(ValueError, match='No MCP clients found'):- await openhands.mcp.utils.call_tool_mcp([], action)---async def test_call_tool_mcp_no_matching_client():- """Test calling MCP tool with no matching client."""- # Create mock client without the requested tool- mock_client = MagicMock()- mock_client.tools = [MagicMock(name='other_tool')]-- action = MCPAction(name='test_tool', arguments={'arg1': 'value1'})-- with pytest.raises(ValueError, match='No matching MCP agent found for tool name'):- await openhands.mcp.utils.call_tool_mcp([mock_client], action)---async def test_call_tool_mcp_success():- """Test successful MCP tool call."""- # Create mock client with the requested tool- mock_client = MagicMock()- mock_tool = MagicMock()- # Set the name attribute properly for the tool- mock_tool.name = 'test_tool'- mock_client.tools = [mock_tool]-- # Setup response- mock_response = MagicMock()- mock_response.model_dump.return_value = {'result': 'success'}-- # Setup call_tool method- mock_client.call_tool = AsyncMock(return_value=mock_response)-- action = MCPAction(name='test_tool', arguments={'arg1': 'value1'})-- # Call the function- observation = await openhands.mcp.utils.call_tool_mcp([mock_client], action)-- # Verify- assert isinstance(observation, MCPObservation)- assert json.loads(observation.content) == {'result': 'success'}- mock_client.call_tool.assert_called_once_with('test_tool', {'arg1': 'value1'})---@patch('openhands.mcp.utils.MCPClient')-async def test_create_mcp_clients_stdio_success(mock_mcp_client):- """Test successful creation of MCP clients with stdio servers."""- mock_client_instance = AsyncMock()- mock_mcp_client.return_value = mock_client_instance- mock_client_instance.connect_stdio = AsyncMock()-- mcp_config = MCPConfig(- mcpServers={- 'test-server-1': StdioMCPServer(- command='python',- args=['-m', 'server1'],- env={'DEBUG': 'true'},- ),- 'test-server-2': StdioMCPServer(- command='node',- args=['server2.js'],- env={'NODE_ENV': 'development'},- ),- }- )-- clients = await openhands.mcp.utils.create_mcp_clients(mcp_config)-- assert len(clients) == 2- assert mock_mcp_client.call_count == 2---@patch('openhands.mcp.utils.MCPClient')-async def test_create_mcp_clients_stdio_connection_failure(mock_mcp_client):- """Test handling of stdio connection failures when creating MCP clients."""- mock_client_instance = AsyncMock()- mock_mcp_client.return_value = mock_client_instance-- mock_client_instance.connect_stdio.side_effect = [- None,- Exception('Stdio connection failed'),- ]-- mcp_config = MCPConfig(- mcpServers={- 'server1': StdioMCPServer(command='python'),- 'server2': StdioMCPServer(command='invalid_command'),- }- )-- clients = await openhands.mcp.utils.create_mcp_clients(mcp_config)-- assert len(clients) == 1---@patch('openhands.mcp.utils.create_mcp_clients')-async def test_fetch_mcp_tools_from_config_with_stdio(mock_create_clients):- """Test fetching MCP tools with stdio servers."""- mock_client = MagicMock()- mock_tool = MagicMock()- mock_tool.to_param.return_value = {'function': {'name': 'stdio_tool'}}- mock_client.tools = [mock_tool]- mock_create_clients.return_value = [mock_client]-- mcp_config = MCPConfig(mcpServers={'test-server': StdioMCPServer(command='python')})-- tools = await openhands.mcp.utils.fetch_mcp_tools_from_config(- mcp_config, conversation_id='test-conv'- )-- assert len(tools) == 1- assert tools[0] == {'function': {'name': 'stdio_tool'}}-- mock_create_clients.assert_called_once_with(mcp_config, 'test-conv')---async def test_call_tool_mcp_stdio_client():- """Test calling MCP tool on a stdio client."""- # Create mock stdio client with the requested tool- mock_client = MagicMock()- mock_tool = MagicMock()- mock_tool.name = 'stdio_test_tool'- mock_client.tools = [mock_tool]-- # Setup response- mock_response = MagicMock()- mock_response.model_dump.return_value = {- 'result': 'stdio_success',- 'data': 'test_data',- }-- # Setup call_tool method- mock_client.call_tool = AsyncMock(return_value=mock_response)-- action = MCPAction(name='stdio_test_tool', arguments={'input': 'test_input'})-- # Call the function- observation = await openhands.mcp.utils.call_tool_mcp([mock_client], action)-- # Verify- assert isinstance(observation, MCPObservation)- assert json.loads(observation.content) == {- 'result': 'stdio_success',- 'data': 'test_data',- }- mock_client.call_tool.assert_called_once_with(- 'stdio_test_tool', {'input': 'test_input'}- )diff --git a/tests/unit/server/routes/test_conversation_id_validation.py b/tests/unit/server/routes/test_conversation_id_validation.pydeleted file mode 100644index e40924a50e..0000000000--- a/tests/unit/server/routes/test_conversation_id_validation.py+++ /dev/null@@ -1,118 +0,0 @@-"""-Test cases for conversation ID validation to ensure proper error handling.--This addresses GitHub issue #10489 where long conversation IDs were returning-500 Internal Server Error instead of proper 4xx errors.-"""--import pytest-from fastapi import HTTPException, status--from openhands.server.utils import validate_conversation_id---class TestConversationIdValidation:- """Test conversation ID validation function."""-- def test_valid_conversation_id(self):- """Test that valid conversation IDs pass validation."""- # Test normal UUID hex format (32 characters)- valid_id = 'a1b2c3d4e5f6789012345678901234ab'- result = validate_conversation_id(valid_id)- assert result == valid_id-- # Test shorter valid ID- valid_id = 'abc123'- result = validate_conversation_id(valid_id)- assert result == valid_id-- # Test alphanumeric with hyphens (UUID format)- valid_id = 'a1b2c3d4-e5f6-7890-1234-5678901234ab'- result = validate_conversation_id(valid_id)- assert result == valid_id-- def test_long_conversation_id_rejected(self):- """Test that very long conversation IDs are rejected with 400 Bad Request.-- This is the main test case for GitHub issue #10489.- """- # Test with 1000 character ID (similar to the reported issue)- long_id = 'a' * 1000-- with pytest.raises(HTTPException) as exc_info:- validate_conversation_id(long_id)-- assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST- assert 'too long' in exc_info.value.detail-- def test_conversation_id_with_null_bytes_rejected(self):- """Test that conversation IDs with null bytes are rejected."""- invalid_id = 'valid\x00id'-- with pytest.raises(HTTPException) as exc_info:- validate_conversation_id(invalid_id)-- assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST- assert 'invalid characters' in exc_info.value.detail-- def test_conversation_id_with_path_traversal_rejected(self):- """Test that conversation IDs with path traversal attempts are rejected."""- invalid_ids = [- '../../../etc/passwd',- 'id/../other',- 'id\\..\\other',- 'id/with/slashes',- 'id\\with\\backslashes',- ]-- for invalid_id in invalid_ids:- with pytest.raises(HTTPException) as exc_info:- validate_conversation_id(invalid_id)-- assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST- assert 'invalid path characters' in exc_info.value.detail-- def test_conversation_id_with_control_characters_rejected(self):- """Test that conversation IDs with control characters are rejected."""- invalid_ids = [- 'id\nwith\nnewlines',- 'id\twith\ttabs',- 'id\rwith\rcarriage',- 'id\x01with\x02control',- ]-- for invalid_id in invalid_ids:- with pytest.raises(HTTPException) as exc_info:- validate_conversation_id(invalid_id)-- assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST- assert 'control characters' in exc_info.value.detail-- def test_conversation_id_boundary_length(self):- """Test conversation ID length boundaries."""- # Test exactly 100 characters (should pass)- boundary_id = 'a' * 100- result = validate_conversation_id(boundary_id)- assert result == boundary_id-- # Test 101 characters (should fail)- too_long_id = 'a' * 101- with pytest.raises(HTTPException) as exc_info:- validate_conversation_id(too_long_id)-- assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST- assert 'too long' in exc_info.value.detail-- def test_empty_conversation_id(self):- """Test that empty conversation ID is handled."""- # Empty string should pass validation (will fail later in business logic)- result = validate_conversation_id('')- assert result == ''-- def test_conversation_id_with_spaces(self):- """Test that conversation IDs with spaces are allowed."""- # Spaces are printable characters (ASCII 32), so they should be allowed- # The business logic might reject them, but validation should pass- id_with_spaces = 'id with spaces'- result = validate_conversation_id(id_with_spaces)- assert result == id_with_spacesdiff --git a/tests/unit/server/routes/test_mcp_routes.py b/tests/unit/server/routes/test_mcp_routes.pyindex 54c1a8a43c..7aebc7ca27 100644--- a/tests/unit/server/routes/test_mcp_routes.py+++ b/tests/unit/server/routes/test_mcp_routes.py@@ -3,8 +3,8 @@ from unittest.mock import AsyncMock, patchimport pytest+from openhands.app_server.mcp.mcp_router import get_conversation_linkfrom openhands.integrations.service_types import GitService-from openhands.server.routes.mcp import get_conversation_linkfrom openhands.server.types import AppMode@@ -22,7 +22,7 @@ def test_mcp_server_no_stateless_http_deprecation_warning():warnings.simplefilter('always')# Import the mcp_server which triggers FastMCP creation- from openhands.server.routes.mcp import mcp_server+ from openhands.app_server.mcp.mcp_router import mcp_server# Check that no deprecation warning about stateless_http was raisedstateless_http_warnings = [@@ -47,8 +47,8 @@ async def test_get_conversation_link_non_saas_mode():mock_service = AsyncMock(spec=GitService)# Test with non-SAAS mode- with patch('openhands.server.routes.mcp.server_config') as mock_config:- mock_config.app_mode = AppMode.OPENHANDS+ with patch('openhands.app_server.mcp.mcp_router.get_global_config') as mock_config:+ mock_config.return_value.app_mode = AppMode.OPENHANDS# Call the functionresult = await get_conversation_link(@@ -72,13 +72,13 @@ async def test_get_conversation_link_saas_mode():# Test with SAAS modewith (- patch('openhands.server.routes.mcp.server_config') as mock_config,+ patch('openhands.app_server.mcp.mcp_router.get_global_config') as mock_config,patch(- 'openhands.server.routes.mcp.CONVERSATION_URL',+ 'openhands.app_server.mcp.mcp_router.CONVERSATION_URL','https://test.example.com/conversations/{}',),):- mock_config.app_mode = AppMode.SAAS+ mock_config.return_value.app_mode = AppMode.SAAS# Call the functionresult = await get_conversation_link(@@ -104,13 +104,13 @@ async def test_get_conversation_link_empty_body():# Test with SAAS mode and empty bodywith (- patch('openhands.server.routes.mcp.server_config') as mock_config,+ patch('openhands.app_server.mcp.mcp_router.get_global_config') as mock_config,patch(- 'openhands.server.routes.mcp.CONVERSATION_URL',+ 'openhands.app_server.mcp.mcp_router.CONVERSATION_URL','https://test.example.com/conversations/{}',),):- mock_config.app_mode = AppMode.SAAS+ mock_config.return_value.app_mode = AppMode.SAAS# Call the functionresult = await get_conversation_link(@@ -130,8 +130,8 @@ async def test_get_conversation_link_none_conversation_id():"""Test get_conversation_link returns body unchanged when conversation_id is None."""mock_service = AsyncMock(spec=GitService)- with patch('openhands.server.routes.mcp.server_config') as mock_config:- mock_config.app_mode = AppMode.SAAS+ with patch('openhands.app_server.mcp.mcp_router.get_global_config') as mock_config:+ mock_config.return_value.app_mode = AppMode.SAASbody = 'This is the PR body.'