Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
6f730d3
Fix MCP HTTP session persistence across tool calls
openhands-agent Jan 16, 2026
ee6b11d
Fix pre-commit issues: pyright type errors and formatting
openhands-agent Jan 16, 2026
cb82210
Simplify MCP session persistence fix
openhands-agent Jan 16, 2026
73d342b
Make MCPClient.sync_close() idempotent
openhands-agent Jan 16, 2026
b156a81
Add per-session state test proving session persistence fix works
openhands-agent Jan 16, 2026
6a9f14b
Merge branch 'main' into openhands/fix-mcp-session-persistence
neubig Jan 16, 2026
0232c81
Fix pre-commit issues in test_stateful_mcp.py
openhands-agent Jan 16, 2026
e9bc840
Address review comments: add connect()/disconnect() methods and conte…
openhands-agent Jan 16, 2026
d46a321
Move _closed flag to after cleanup in sync_close()
openhands-agent Jan 18, 2026
598a572
Fix empty except clauses by adding logging
openhands-agent Jan 19, 2026
c86351f
Introduce MCPToolset for explicit lifecycle management
openhands-agent Jan 21, 2026
5e50b4b
Simplify MCP connection management to single approach
openhands-agent Jan 21, 2026
da237e1
Simplify MCP lifecycle with MCPToolset class
openhands-agent Jan 22, 2026
f1ea8d6
Clean up MCP code review issues
openhands-agent Jan 22, 2026
6840b82
Simplify: put tools directly on MCPClient, remove MCPToolset
openhands-agent Jan 22, 2026
90e797f
Fix MCP session persistence with minimal changes
openhands-agent Jan 22, 2026
89a5195
Fix pre-commit formatting issues
openhands-agent Jan 22, 2026
7ab9207
Fix pyright type errors in test conftest
openhands-agent Jan 22, 2026
8b07e37
Remove conftest.py and define test servers inline
openhands-agent Jan 22, 2026
0d7778c
Merge branch 'main' into openhands/fix-mcp-session-persistence
neubig Jan 22, 2026
b85508d
Address code review feedback
openhands-agent Jan 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 53 additions & 6 deletions openhands-sdk/openhands/sdk/mcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,53 @@

import asyncio
import inspect
from collections.abc import Callable
from typing import Any
from collections.abc import Callable, Iterator
from typing import TYPE_CHECKING, Any

from fastmcp import Client as AsyncMCPClient

from openhands.sdk.utils.async_executor import AsyncExecutor


if TYPE_CHECKING:
from openhands.sdk.mcp.tool import MCPToolDefinition


class MCPClient(AsyncMCPClient):
"""
Behaves exactly like fastmcp.Client (same constructor & async API),
but owns a background event loop and offers:
"""MCP client with sync helpers and lifecycle management.

Extends fastmcp.Client with:
- call_async_from_sync(awaitable_or_fn, *args, timeout=None, **kwargs)
- call_sync_from_async(fn, *args, **kwargs) # await this from async code

After create_mcp_tools() populates it, use as a sync context manager:

with create_mcp_tools(config) as client:
for tool in client.tools:
# use tool
# Connection automatically closed

Or manage lifecycle manually by calling sync_close() when done.
"""

_executor: AsyncExecutor
_closed: bool
_tools: "list[MCPToolDefinition]"

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._executor = AsyncExecutor()
self._closed = False
self._tools = []

@property
def tools(self) -> "list[MCPToolDefinition]":
"""The MCP tools using this client connection (returns a copy)."""
return list(self._tools)

async def connect(self) -> None:
"""Establish connection to the MCP server."""
await self.__aenter__()

def call_async_from_sync(
self,
Expand Down Expand Up @@ -56,8 +82,11 @@ def sync_close(self) -> None:
Synchronously close the MCP client and cleanup resources.

This will attempt to call the async close() method if available,
then shutdown the background event loop.
then shutdown the background event loop. Safe to call multiple times.
"""
if self._closed:
return

# Best-effort: try async close if parent provides it
if hasattr(self, "close") and inspect.iscoroutinefunction(self.close):
try:
Expand All @@ -67,10 +96,28 @@ def sync_close(self) -> None:

# Always cleanup the executor
self._executor.close()
self._closed = True

def __del__(self):
"""Cleanup on deletion."""
try:
self.sync_close()
except Exception:
pass # Ignore cleanup errors during deletion

# Sync context manager support
def __enter__(self) -> "MCPClient":
return self
Comment thread
neubig marked this conversation as resolved.
Resolved

def __exit__(self, *args: object) -> None:
self.sync_close()

# Iteration support for tools
def __iter__(self) -> "Iterator[MCPToolDefinition]":
return iter(self._tools)

def __len__(self) -> int:
return len(self._tools)

def __getitem__(self, index: int) -> "MCPToolDefinition":
return self._tools[index]
45 changes: 24 additions & 21 deletions openhands-sdk/openhands/sdk/mcp/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,30 @@ def __init__(self, tool_name: str, client: MCPClient):

@observe(name="MCPToolExecutor.call_tool", span_type="TOOL")
async def call_tool(self, action: MCPToolAction) -> 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.to_mcp_arguments()
)
return MCPToolObservation.from_call_tool_result(
tool_name=self.tool_name, result=result
)
except Exception as e:
error_msg = f"Error calling MCP tool {self.tool_name}: {str(e)}"
logger.error(error_msg, exc_info=True)
return MCPToolObservation.from_text(
text=error_msg,
is_error=True,
tool_name=self.tool_name,
)
"""Execute the MCP tool call using the already-connected client."""
if not self.client.is_connected():
raise RuntimeError(
f"MCP client not connected for tool '{self.tool_name}'. "
"The connection may have been closed or failed to establish."
)
Comment thread
neubig marked this conversation as resolved.
Resolved
try:
logger.debug(
f"Calling MCP tool {self.tool_name} with args: {action.model_dump()}"
)
result: mcp.types.CallToolResult = await self.client.call_tool_mcp(
name=self.tool_name, arguments=action.to_mcp_arguments()
)
return MCPToolObservation.from_call_tool_result(
tool_name=self.tool_name, result=result
)
except Exception as e:
error_msg = f"Error calling MCP tool {self.tool_name}: {str(e)}"
logger.error(error_msg, exc_info=True)
return MCPToolObservation.from_text(
text=error_msg,
is_error=True,
tool_name=self.tool_name,
)

def __call__(
self,
Expand Down
54 changes: 31 additions & 23 deletions openhands-sdk/openhands/sdk/mcp/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from openhands.sdk.mcp.client import MCPClient
from openhands.sdk.mcp.exceptions import MCPTimeoutError
from openhands.sdk.mcp.tool import MCPToolDefinition
from openhands.sdk.tool.tool import ToolDefinition


logger = get_logger(__name__)
Expand All @@ -32,37 +31,38 @@ async def log_handler(message: LogMessage):
logger.log(level, msg, extra=extra)


async def _list_tools(client: MCPClient) -> list[ToolDefinition]:
"""List tools from an MCP client."""
tools: list[ToolDefinition] = []

async with client:
assert client.is_connected(), "MCP client is not connected."
mcp_type_tools: list[mcp.types.Tool] = await client.list_tools()
for mcp_tool in mcp_type_tools:
tool_sequence = MCPToolDefinition.create(
mcp_tool=mcp_tool, mcp_client=client
)
tools.extend(tool_sequence) # Flatten sequence into list
assert not client.is_connected(), (
"MCP client should be disconnected after listing tools."
)
return tools
async def _connect_and_list_tools(client: MCPClient) -> None:
"""Connect to MCP server and populate client._tools."""
await client.connect()
mcp_type_tools: list[mcp.types.Tool] = await client.list_tools()
for mcp_tool in mcp_type_tools:
tool_sequence = MCPToolDefinition.create(mcp_tool=mcp_tool, mcp_client=client)
client._tools.extend(tool_sequence)
Comment thread
neubig marked this conversation as resolved.
Resolved


def create_mcp_tools(
config: dict | MCPConfig,
timeout: float = 30.0,
) -> list[MCPToolDefinition]:
"""Create MCP tools from MCP configuration."""
tools: list[MCPToolDefinition] = []
) -> MCPClient:
Comment thread
neubig marked this conversation as resolved.
Resolved
"""Create MCP tools from MCP configuration.

Returns an MCPClient with tools populated. Use as a context manager:

with create_mcp_tools(config) as client:
for tool in client.tools:
# use tool
# Connection automatically closed
"""
if isinstance(config, dict):
config = MCPConfig.model_validate(config)
client = MCPClient(config, log_handler=log_handler)

try:
tools = client.call_async_from_sync(_list_tools, timeout=timeout, client=client)
client.call_async_from_sync(
_connect_and_list_tools, timeout=timeout, client=client
)
except TimeoutError as e:
client.sync_close()
# Extract server names from config for better error message
server_names = (
list(config.mcpServers.keys()) if config.mcpServers else ["unknown"]
Expand All @@ -78,6 +78,14 @@ def create_mcp_tools(
raise MCPTimeoutError(
error_msg, timeout=timeout, config=config.model_dump()
) from e
except BaseException:
try:
client.sync_close()
except Exception as close_exc:
logger.warning(
"Failed to close MCP client during error cleanup", exc_info=close_exc
)
raise

logger.info(f"Created {len(tools)} MCP tools: {[t.name for t in tools]}")
return tools
logger.info(f"Created {len(client.tools)} MCP tools: {[t.name for t in client]}")
return client
121 changes: 121 additions & 0 deletions tests/sdk/mcp/test_mcp_session_persistence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""Tests for MCP session persistence across tool calls.

Verifies that MCP connections are reused across multiple tool calls,
avoiding the overhead of reconnecting for each call.

Related issue: https://github.com/OpenHands/software-agent-sdk/issues/1739
"""

import asyncio
import socket
import threading
import time

import pytest
from fastmcp import FastMCP

from openhands.sdk.mcp import create_mcp_tools
from openhands.sdk.mcp.tool import MCPToolExecutor


def _find_free_port() -> int:
"""Find an available port."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]


@pytest.fixture
def live_server():
"""Fixture providing a live MCP test server with echo/add tools."""
mcp = FastMCP("session-test-server")

@mcp.tool()
def echo(message: str) -> str:
"""Echo a message."""
return f"Echo: {message}"

@mcp.tool()
def add_numbers(a: int, b: int) -> str:
"""Add two numbers."""
return str(a + b)

port = _find_free_port()

def run():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
mcp.run_http_async(
host="127.0.0.1",
port=port,
transport="http",
show_banner=False,
path="/mcp",
)
)

thread = threading.Thread(target=run, daemon=True)
thread.start()
time.sleep(0.5)
yield port


class TestSessionPersistence:
"""Tests verifying session/connection persistence."""

def test_connection_reused_across_tool_calls(self, live_server: int):
"""Test that multiple tool calls reuse the same connection."""
config = {
"mcpServers": {
"test": {
"transport": "http",
"url": f"http://127.0.0.1:{live_server}/mcp",
}
}
}

with create_mcp_tools(config, timeout=10.0) as client:
assert len(client) == 2

echo_tool = next(t for t in client if t.name == "echo")
add_tool = next(t for t in client if t.name == "add_numbers")

# Verify they share the same client
echo_executor = echo_tool.executor
add_executor = add_tool.executor
assert isinstance(echo_executor, MCPToolExecutor)
assert isinstance(add_executor, MCPToolExecutor)
assert echo_executor.client is add_executor.client

# Make multiple calls - should all use same connection
for i in range(3):
action = echo_tool.action_from_arguments({"message": f"test_{i}"})
result = echo_executor(action)
assert f"test_{i}" in result.text

# Call different tool - same connection
action = add_tool.action_from_arguments({"a": 5, "b": 3})
result = add_executor(action)
assert "8" in result.text

def test_close_releases_connection(self, live_server: int):
"""Test that close() properly releases the connection."""
config = {
"mcpServers": {
"test": {
"transport": "http",
"url": f"http://127.0.0.1:{live_server}/mcp",
}
}
}

with create_mcp_tools(config, timeout=10.0) as client:
tool = next(t for t in client if t.name == "echo")
executor = tool.executor
assert isinstance(executor, MCPToolExecutor)

# Make a call
action = tool.action_from_arguments({"message": "test"})
result = executor(action)
assert "test" in result.text
Loading