Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(mcp): enforce per-operation timeout in stdio + http loaders

xf gong34b83cc207b0
diff --git a/cubepi/mcp/http_loader.py b/cubepi/mcp/http_loader.py
index 0013c3f..9b3817c 100644
--- a/cubepi/mcp/http_loader.py
+++ b/cubepi/mcp/http_loader.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
from typing import Any
from cubepi.agent.types import AgentTool
@@ -18,6 +19,10 @@ async def load_mcp_tools_http(
Uses the `mcp` SDK's HTTP client. Each returned tool's execute method
invokes tools/call against a fresh session — v1 simplicity, no pooling.
+
+ The transport's own timeout bounds the SSE connection; we additionally
+ wrap initialize/list/call awaits in asyncio.wait_for so a server that
+ accepts the connection but stalls on protocol messages still aborts.
"""
from mcp import ClientSession
from mcp.client.sse import sse_client
@@ -25,14 +30,16 @@ async def load_mcp_tools_http(
async def _call_remote(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
async with sse_client(server_url, headers=headers, timeout=timeout) as streams:
async with ClientSession(*streams) as session:
- await session.initialize()
- resp = await session.call_tool(tool_name, args)
+ await asyncio.wait_for(session.initialize(), timeout=timeout)
+ resp = await asyncio.wait_for(
+ session.call_tool(tool_name, args), timeout=timeout
+ )
return _serialize_call_tool_response(resp)
async with sse_client(server_url, headers=headers, timeout=timeout) as streams:
async with ClientSession(*streams) as session:
- await session.initialize()
- tools_resp = await session.list_tools()
+ await asyncio.wait_for(session.initialize(), timeout=timeout)
+ tools_resp = await asyncio.wait_for(session.list_tools(), timeout=timeout)
tool_descs = tools_resp.tools
return [
@@ -47,12 +54,31 @@ async def load_mcp_tools_http(
def _serialize_call_tool_response(resp: Any) -> dict[str, Any]:
- """Normalize mcp SDK CallToolResult → dict for adapter."""
- content = []
+ """Normalize mcp SDK CallToolResult → dict for adapter.
+
+ Preserves text and image content blocks plus the optional
+ ``structuredContent`` field. Unknown block types are dropped (after
+ being surfaced once the agent loop has a place to put them).
+ """
+ content: list[dict[str, Any]] = []
for c in resp.content or []:
- if getattr(c, "type", None) == "text":
+ ctype = getattr(c, "type", None)
+ if ctype == "text":
content.append({"type": "text", "text": c.text})
- return {
+ elif ctype == "image":
+ content.append(
+ {
+ "type": "image",
+ "data": getattr(c, "data", ""),
+ "mimeType": getattr(c, "mimeType", "")
+ or getattr(c, "media_type", ""),
+ }
+ )
+ out: dict[str, Any] = {
"content": content,
"isError": bool(getattr(resp, "isError", False)),
}
+ structured = getattr(resp, "structuredContent", None)
+ if structured is not None:
+ out["structuredContent"] = structured
+ return out
diff --git a/cubepi/mcp/stdio_loader.py b/cubepi/mcp/stdio_loader.py
index b2b35c6..af1b44d 100644
--- a/cubepi/mcp/stdio_loader.py
+++ b/cubepi/mcp/stdio_loader.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
from typing import Any
from cubepi.agent.types import AgentTool
@@ -26,7 +27,8 @@ async def load_mcp_tools_stdio(
args: argv for the server process
env: environment variables (passed to subprocess)
cwd: working directory for the subprocess
- timeout: per-call timeout (not currently enforced strictly)
+ timeout: per-call wall-clock timeout for initialize/list/call awaits.
+ A hung server raises asyncio.TimeoutError instead of blocking forever.
"""
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
@@ -41,14 +43,16 @@ async def load_mcp_tools_stdio(
async def _call_remote(tool_name: str, args_dict: dict[str, Any]) -> dict[str, Any]:
async with stdio_client(server_params) as streams:
async with ClientSession(*streams) as session:
- await session.initialize()
- resp = await session.call_tool(tool_name, args_dict)
+ await asyncio.wait_for(session.initialize(), timeout=timeout)
+ resp = await asyncio.wait_for(
+ session.call_tool(tool_name, args_dict), timeout=timeout
+ )
return _serialize_call_tool_response(resp)
async with stdio_client(server_params) as streams:
async with ClientSession(*streams) as session:
- await session.initialize()
- tools_resp = await session.list_tools()
+ await asyncio.wait_for(session.initialize(), timeout=timeout)
+ tools_resp = await asyncio.wait_for(session.list_tools(), timeout=timeout)
tool_descs = tools_resp.tools
return [
@@ -63,11 +67,30 @@ async def load_mcp_tools_stdio(
def _serialize_call_tool_response(resp: Any) -> dict[str, Any]:
- content = []
+ """Normalize mcp SDK CallToolResult → dict for adapter.
+
+ Mirrors http_loader._serialize_call_tool_response so both transports
+ feed the adapter identically.
+ """
+ content: list[dict[str, Any]] = []
for c in resp.content or []:
- if getattr(c, "type", None) == "text":
+ ctype = getattr(c, "type", None)
+ if ctype == "text":
content.append({"type": "text", "text": c.text})
- return {
+ elif ctype == "image":
+ content.append(
+ {
+ "type": "image",
+ "data": getattr(c, "data", ""),
+ "mimeType": getattr(c, "mimeType", "")
+ or getattr(c, "media_type", ""),
+ }
+ )
+ out: dict[str, Any] = {
"content": content,
"isError": bool(getattr(resp, "isError", False)),
}
+ structured = getattr(resp, "structuredContent", None)
+ if structured is not None:
+ out["structuredContent"] = structured
+ return out
diff --git a/tests/mcp/test_http_loader.py b/tests/mcp/test_http_loader.py
index c5b8dbc..e690b93 100644
--- a/tests/mcp/test_http_loader.py
+++ b/tests/mcp/test_http_loader.py
@@ -5,6 +5,7 @@ test runs without a real MCP server. End-to-end against a live server is
gated behind CUBEPI_TEST_MCP_HTTP_URL.
"""
+import asyncio
import os
from contextlib import asynccontextmanager
from types import SimpleNamespace
@@ -87,7 +88,8 @@ async def test_load_mcp_tools_http_lists_and_calls_tool(monkeypatch) -> None:
call_resp = SimpleNamespace(
content=[
SimpleNamespace(type="text", text="hello"),
- SimpleNamespace(type="image", data="ignored"), # non-text dropped
+ SimpleNamespace(type="image", data="base64payload", mimeType="image/png"),
+ SimpleNamespace(type="resource", uri="ignored"), # unsupported → dropped
],
isError=False,
)
@@ -119,10 +121,15 @@ async def test_load_mcp_tools_http_lists_and_calls_tool(monkeypatch) -> None:
assert len(sessions) == 2
assert sessions[1].calls == [("search", {"query": "cats"})]
- # only the text content block survives serialization
- assert len(result.content) == 1
+ # text + image preserved; unsupported "resource" dropped
+ from cubepi.providers.base import ImageContent
+
+ assert len(result.content) == 2
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "hello"
+ assert isinstance(result.content[1], ImageContent)
+ assert result.content[1].source == "base64payload"
+ assert result.content[1].media_type == "image/png"
assert result.is_error is None
@@ -154,6 +161,31 @@ async def test_load_mcp_tools_http_propagates_is_error(monkeypatch) -> None:
assert result.is_error is True
+async def test_load_mcp_tools_http_preserves_structured_content(monkeypatch) -> None:
+ """structuredContent flows through to AgentToolResult.details."""
+ from cubepi.mcp import load_mcp_tools_http
+
+ tools_resp = [
+ SimpleNamespace(
+ name="weather",
+ description="",
+ inputSchema={"type": "object", "properties": {}},
+ ),
+ ]
+ call_resp = SimpleNamespace(
+ content=[SimpleNamespace(type="text", text="73F")],
+ isError=False,
+ structuredContent={"temp_f": 73, "conditions": "clear"},
+ )
+ _install_fake_transport(monkeypatch, tools=tools_resp, call_response=call_resp)
+
+ tools = await load_mcp_tools_http("https://mcp.example/sse")
+ args = tools[0].parameters()
+ result = await tools[0].execute("tc-sc", args, signal=None, on_update=None)
+ assert result.details["structuredContent"] == {"temp_f": 73, "conditions": "clear"}
+
+
@pytest.mark.asyncio
async def test_load_mcp_tools_http_handles_empty_content(monkeypatch) -> None:
"""resp.content == None should not break the serializer."""
@@ -175,6 +207,44 @@ async def test_load_mcp_tools_http_handles_empty_content(monkeypatch) -> None:
assert result.content == []
+async def test_load_mcp_tools_http_initialize_timeout(monkeypatch) -> None:
+ """A session that hangs on initialize must raise TimeoutError, not block."""
+ from cubepi.mcp import load_mcp_tools_http
+
+ class _HangingSession:
+ def __init__(self, *streams):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return None
+
+ async def initialize(self):
+ await asyncio.sleep(10) # forever, from the test's perspective
+
+ async def list_tools(self): # pragma: no cover - never reached
+ return SimpleNamespace(tools=[])
+
+ async def call_tool(self, *a, **k): # pragma: no cover - never reached
+ return SimpleNamespace(content=[], isError=False)
+
+ import mcp
+ import mcp.client.sse as sse_mod
+
+ @asynccontextmanager
+ async def fake_sse_client(url, *, headers=None, timeout=None):
+ yield ("r", "w")
+
+ monkeypatch.setattr(sse_mod, "sse_client", fake_sse_client)
+ monkeypatch.setattr(mcp, "ClientSession", _HangingSession)
+
+ with pytest.raises(asyncio.TimeoutError):
+ await load_mcp_tools_http("https://mcp.example/sse", timeout=0.05)
+
+
@pytest.mark.asyncio
async def test_load_mcp_tools_http_against_test_server() -> None:
"""End-to-end: connect to a real MCP test server, list + call a tool."""