"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(mcp): report the server's own explanation on a remote HTTP failure
Haozhe Wue897f5966b5f
diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.pyindex 6b43a1c68..b93621e30 100644--- a/agent/src/tools/mcp.py+++ b/agent/src/tools/mcp.py@@ -14,6 +14,7 @@ from copy import deepcopyfrom dataclasses import dataclass, is_dataclassfrom typing import Any, Awaitable, Callable, Coroutine, Iterable, Protocol, TypeVar+import httpxfrom fastmcp.client import Clientfrom fastmcp.client.auth import OAuthfrom fastmcp.client.client import CallToolResult@@ -450,7 +451,18 @@ class MCPServerAdapter:Raises:Exception: Propagates discovery failures after retry exhaustion."""- tools = _run_sync(self._list_tools)+ try:+ tools = _run_sync(self._list_tools)+ except httpx.HTTPStatusError as exc:+ # Same reason as _http_error_body: discovery propagates raw, so the+ # traceback the user sees would otherwise carry no server detail.+ if body := _http_error_body(exc):+ raise httpx.HTTPStatusError(+ f"{exc} - server said: {body}",+ request=exc.request,+ response=exc.response,+ ) from exc+ raiseseen_names: dict[str, str] = {}specs: list[MCPRemoteToolSpec] = []@@ -1161,6 +1173,41 @@ def _message_looks_transient(message: str) -> bool:return any(token in lowered for token in _TRANSIENT_ERROR_TOKENS)+#: Cap on the remote error body echoed back to the user. Enough for a JSON+#: error envelope, short enough that a stray HTML page does not fill the log.+_HTTP_ERROR_BODY_LIMIT = 300+++def _http_error_body(exc: BaseException) -> str:+ """Return the response body of an HTTP status error, if there is one.++ ``httpx.HTTPStatusError`` stringifies to the status and URL only, so the+ server's own explanation is dropped — which turns an auth rejection into an+ unreadable "Client error 400". IBKR, for one, answers a token it will not+ accept with ``{"error":"Status failed 500","statusCode":400}`` and a 400,+ while an unauthenticated request gets a 401 (issue #1126); without the body+ those two are indistinguishable to the user.++ Args:+ exc: Exception that may carry an HTTP response.++ Returns:+ The trimmed body, or ``""`` when there is none to report.+ """+ response = getattr(exc, "response", None)+ if response is None:+ return ""+ try:+ body = (response.text or "").strip()+ except Exception: # noqa: BLE001 - a body we cannot read is not reportable+ return ""+ if not body:+ return ""+ if len(body) > _HTTP_ERROR_BODY_LIMIT:+ body = body[:_HTTP_ERROR_BODY_LIMIT] + "..."+ return " ".join(body.split())++def _format_exception_message(exc: Exception) -> str:"""Render an exception into a user-facing error string.@@ -1172,7 +1219,10 @@ def _format_exception_message(exc: Exception) -> str:"""if isinstance(exc, McpError) and getattr(exc, "error", None) is not None:return getattr(exc.error, "message", str(exc))- return str(exc) or type(exc).__name__+ message = str(exc) or type(exc).__name__+ if isinstance(exc, httpx.HTTPStatusError) and (body := _http_error_body(exc)):+ return f"{message} - server said: {body}"+ return messagedef _make_jsonable(value: Any) -> Any:diff --git a/agent/tests/test_mcp_client_adapter.py b/agent/tests/test_mcp_client_adapter.pyindex a9c9493cd..f4bba61a5 100644--- a/agent/tests/test_mcp_client_adapter.py+++ b/agent/tests/test_mcp_client_adapter.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Anyfrom uuid import UUID+import httpximport pytestfrom fastmcp import Client, FastMCPfrom fastmcp.client.client import CallToolResult@@ -19,6 +20,7 @@ from fastmcp.exceptions import McpError, ToolErrorfrom mcp import types as mcp_typesfrom pydantic import BaseModel, field_serializer+import src.tools.mcp as mcp_modulefrom src.config.schema import MCPServerConfigfrom src.tools.mcp import (MCPServerAdapter,@@ -779,3 +781,57 @@ def test_build_client_rejects_url_only_config_without_explicit_type() -> None:with pytest.raises(ValueError, match="explicit type"):adapter._build_client()+++class TestHttpErrorBodyIsReported:+ """A remote HTTP failure must carry the server's own explanation.++ ``httpx.HTTPStatusError`` stringifies to status + URL only. IBKR answers a+ token it will not accept with a 400 and+ ``{"error":"Status failed 500","statusCode":400}``, while an unauthenticated+ request gets a 401 — indistinguishable without the body, which is what made+ issue #1126 read as a malformed-request bug rather than an auth rejection.+ """++ @staticmethod+ def _status_error(status: int, body: str) -> httpx.HTTPStatusError:+ request = httpx.Request("POST", "https://api.example.test/v1/api/mcp")+ response = httpx.Response(status, text=body, request=request)+ return httpx.HTTPStatusError(+ f"Client error '{status}' for url '{request.url}'",+ request=request,+ response=response,+ )++ def test_the_message_includes_the_response_body(self) -> None:+ exc = self._status_error(400, '{"error":"Status failed 500","statusCode":400}')+ message = mcp_module._format_exception_message(exc)+ assert "Status failed 500" in message++ def test_an_empty_body_adds_nothing(self) -> None:+ exc = self._status_error(400, " ")+ assert mcp_module._format_exception_message(exc) == str(exc)++ def test_an_oversized_body_is_truncated(self) -> None:+ exc = self._status_error(500, "x" * 5000)+ message = mcp_module._format_exception_message(exc)+ assert message.endswith("...")+ assert len(message) < 700++ def test_a_non_http_exception_is_unchanged(self) -> None:+ assert mcp_module._format_exception_message(ValueError("plain")) == "plain"++ def test_discovery_reraises_the_same_type_with_the_body(self, monkeypatch) -> None:+ exc = self._status_error(400, '{"error":"Status failed 500","statusCode":400}')++ def _raise(_operation):+ raise exc++ monkeypatch.setattr(mcp_module, "_run_sync", _raise)+ adapter = MCPServerAdapter.__new__(MCPServerAdapter)++ with pytest.raises(httpx.HTTPStatusError) as caught:+ MCPServerAdapter.discover_tools(adapter)++ assert "Status failed 500" in str(caught.value)+ assert caught.value.response.status_code == 400