Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(tests): bypass proxies for loopback MCP fixtures

Miranda7a1c7c9d4293
diff --git a/agent/tests/mcp_http_test_helpers.py b/agent/tests/mcp_http_test_helpers.py
index c8b44ada9..0f76a55a0 100644
--- a/agent/tests/mcp_http_test_helpers.py
+++ b/agent/tests/mcp_http_test_helpers.py
@@ -3,18 +3,57 @@
from __future__ import annotations
import json
+import os
import socket
import subprocess
import sys
import tempfile
import time
from contextlib import contextmanager
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Iterator
import requests
_PYTHON = sys.executable
+_DIAGNOSTIC_BODY_LIMIT = 500
+_NO_PROXY_ENV_VARS = ("NO_PROXY", "no_proxy")
+_LOOPBACK_NO_PROXY_HOSTS = ("127.0.0.1", "localhost")
+
+
+@dataclass(frozen=True)
+class HttpMCPServerHandle:
+ """Running HTTP MCP fixture plus context useful when remote discovery fails."""
+
+ process: subprocess.Popen[str]
+ port: int
+ command: tuple[str, ...]
+ ready_url: str
+ ready_request_kwargs: dict[str, Any]
+ last_ready_probe: str = ""
+
+ def __iter__(self) -> Iterator[Any]:
+ yield self.process
+ yield self.port
+
+ def diagnostics(self) -> str:
+ """Return non-blocking diagnostics for assertion messages."""
+ lines = [
+ "HTTP MCP fixture diagnostics:",
+ f" command: {' '.join(self.command)}",
+ f" selected_port: {self.port}",
+ f" ready_url: {self.ready_url}",
+ f" process_exit_code: {self.process.poll()}",
+ ]
+ if self.last_ready_probe:
+ lines.append(f" last_ready_probe: {self.last_ready_probe}")
+ lines.append(f" live_probe: {_probe_ready_url(self.ready_url, self.ready_request_kwargs)}")
+ if self.process.poll() is None:
+ lines.append(" stdout/stderr: unavailable while fixture process is running")
+ else:
+ lines.append(f" stdout/stderr: {_collect_process_output(self.process).strip() or '<empty>'}")
+ return "\n".join(lines)
def make_single_server_agent_json(
@@ -67,6 +106,79 @@ def _collect_process_output(proc: subprocess.Popen[str]) -> str:
return proc.stdout.read() if proc.stdout is not None else ""
+def _probe_ready_url(ready_url: str, request_kwargs: dict[str, Any] | None = None) -> str:
+ request_kwargs = dict(request_kwargs or {})
+ stream = bool(request_kwargs.get("stream"))
+ try:
+ response = requests.get(ready_url, timeout=0.5, **request_kwargs)
+ except requests.RequestException as exc:
+ return f"{type(exc).__name__}: {exc}"
+
+ try:
+ return _summarize_response(response, stream=stream)
+ finally:
+ response.close()
+
+
+def _summarize_response(response: requests.Response, *, stream: bool = False) -> str:
+ content_type = response.headers.get("content-type", "")
+ if stream:
+ body = "<streaming response body omitted>"
+ else:
+ body = response.text[:_DIAGNOSTIC_BODY_LIMIT]
+ return f"status={response.status_code} content-type={content_type!r} body={body!r}"
+
+
+def _format_start_failure(
+ service_name: str,
+ proc: subprocess.Popen[str],
+ *,
+ command: list[str],
+ ready_url: str,
+ port: int | None = None,
+ last_probe: str = "",
+ reason: str,
+) -> RuntimeError:
+ output = _collect_process_output(proc)
+ lines = [
+ f"{service_name} {reason}",
+ f"command: {' '.join(command)}",
+ f"selected_port: {port if port is not None else '<unknown>'}",
+ f"ready_url: {ready_url}",
+ f"process_exit_code: {proc.returncode}",
+ ]
+ if last_probe:
+ lines.append(f"last_ready_probe: {last_probe}")
+ lines.append(f"stdout/stderr: {output.strip() or '<empty>'}")
+ return RuntimeError("\n".join(lines))
+
+
+def _merge_loopback_no_proxy(value: str | None) -> str:
+ entries = [entry.strip() for entry in (value or "").split(",") if entry.strip()]
+ lowered = {entry.lower() for entry in entries}
+ for host in _LOOPBACK_NO_PROXY_HOSTS:
+ if host not in lowered:
+ entries.append(host)
+ return ",".join(entries)
+
+
+@contextmanager
+def _loopback_proxy_bypass() -> Iterator[None]:
+ """Keep local FastMCP fixture traffic out of developer/system HTTP proxies."""
+ original = {name: os.environ.get(name) for name in _NO_PROXY_ENV_VARS}
+ merged = _merge_loopback_no_proxy(original.get("NO_PROXY") or original.get("no_proxy"))
+ for name in _NO_PROXY_ENV_VARS:
+ os.environ[name] = merged
+ try:
+ yield
+ finally:
+ for name, value in original.items():
+ if value is None:
+ os.environ.pop(name, None)
+ else:
+ os.environ[name] = value
+
+
def start_http_mcp_server(
fixture_server: Path,
*,
@@ -77,31 +189,47 @@ def start_http_mcp_server(
ready_request_kwargs: dict[str, Any] | None = None,
) -> subprocess.Popen[str]:
"""Start an HTTP MCP subprocess and wait until the endpoint is reachable."""
+ command = [_PYTHON, str(fixture_server), *extra_args]
proc = subprocess.Popen(
- [_PYTHON, str(fixture_server), *extra_args],
+ command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
request_kwargs = dict(ready_request_kwargs or {})
accepted_statuses = set(ready_statuses or {200})
+ last_probe = ""
for _ in range(40):
if proc.poll() is not None:
- output = proc.stdout.read() if proc.stdout is not None else ""
- raise RuntimeError(f"{service_name} failed to start with exit code {proc.returncode}: {output}")
+ raise _format_start_failure(
+ service_name,
+ proc,
+ command=command,
+ ready_url=ready_url,
+ last_probe=last_probe,
+ reason=f"failed to start with exit code {proc.returncode}",
+ )
try:
response = requests.get(ready_url, timeout=0.5, **request_kwargs)
+ last_probe = _summarize_response(response, stream=bool(request_kwargs.get("stream")))
if response.status_code in accepted_statuses:
response.close()
return proc
response.close()
- except requests.RequestException:
+ except requests.RequestException as exc:
+ last_probe = f"{type(exc).__name__}: {exc}"
time.sleep(0.2)
stop_http_mcp_server(proc)
- output = proc.stdout.read() if proc.stdout is not None else ""
- raise RuntimeError(f"{service_name} did not become ready within 8 seconds: {output}")
+ raise _format_start_failure(
+ service_name,
+ proc,
+ command=command,
+ ready_url=ready_url,
+ last_probe=last_probe,
+ reason="did not become ready within 8 seconds",
+ )
def start_http_mcp_server_on_random_port(
@@ -113,29 +241,40 @@ def start_http_mcp_server_on_random_port(
ready_statuses: set[int] | None = None,
ready_request_kwargs: dict[str, Any] | None = None,
max_attempts: int = 5,
-) -> tuple[subprocess.Popen[str], int]:
+) -> HttpMCPServerHandle:
"""Start an HTTP MCP subprocess on an OS-assigned port."""
last_error: RuntimeError | None = None
for _ in range(max_attempts):
with tempfile.TemporaryDirectory(prefix="mcp-port-") as temp_dir:
port_file = Path(temp_dir) / "port.txt"
+ command = [_PYTHON, str(fixture_server), *extra_args_builder(0), "--port-file", str(port_file)]
proc = subprocess.Popen(
- [_PYTHON, str(fixture_server), *extra_args_builder(0), "--port-file", str(port_file)],
+ command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
try:
port = _wait_for_server_port(proc, port_file, service_name=service_name)
- _wait_for_http_ready(
+ ready_url = ready_url_builder(port)
+ last_probe = _wait_for_http_ready(
proc,
- ready_url=ready_url_builder(port),
+ ready_url=ready_url,
service_name=service_name,
ready_statuses=ready_statuses,
ready_request_kwargs=ready_request_kwargs,
+ command=command,
+ port=port,
+ )
+ return HttpMCPServerHandle(
+ process=proc,
+ port=port,
+ command=tuple(command),
+ ready_url=ready_url,
+ ready_request_kwargs=dict(ready_request_kwargs or {}),
+ last_ready_probe=last_probe,
)
- return proc, port
except RuntimeError as exc:
last_error = exc
stop_http_mcp_server(proc)
@@ -174,30 +313,49 @@ def _wait_for_http_ready(
*,
ready_url: str,
service_name: str,
+ command: list[str],
+ port: int,
ready_statuses: set[int] | None = None,
ready_request_kwargs: dict[str, Any] | None = None,
timeout_seconds: float = 8.0,
-) -> None:
+) -> str:
"""Poll the fixture endpoint until it is reachable."""
request_kwargs = dict(ready_request_kwargs or {})
accepted_statuses = set(ready_statuses or {200})
deadline = time.time() + timeout_seconds
+ last_probe = ""
while time.time() < deadline:
if proc.poll() is not None:
- output = _collect_process_output(proc)
- raise RuntimeError(f"{service_name} failed to start with exit code {proc.returncode}: {output}")
+ raise _format_start_failure(
+ service_name,
+ proc,
+ command=command,
+ ready_url=ready_url,
+ port=port,
+ last_probe=last_probe,
+ reason=f"failed to start with exit code {proc.returncode}",
+ )
try:
response = requests.get(ready_url, timeout=0.5, **request_kwargs)
+ last_probe = _summarize_response(response, stream=bool(request_kwargs.get("stream")))
if response.status_code in accepted_statuses:
response.close()
- return
+ return last_probe
response.close()
- except requests.RequestException:
+ except requests.RequestException as exc:
+ last_probe = f"{type(exc).__name__}: {exc}"
time.sleep(0.2)
- output = _collect_process_output(proc)
- raise RuntimeError(f"{service_name} did not become ready within 8 seconds: {output}")
+ raise _format_start_failure(
+ service_name,
+ proc,
+ command=command,
+ ready_url=ready_url,
+ port=port,
+ last_probe=last_probe,
+ reason="did not become ready within 8 seconds",
+ )
@contextmanager
@@ -211,18 +369,19 @@ def running_http_mcp_server(
ready_request_kwargs: dict[str, Any] | None = None,
) -> Iterator[subprocess.Popen[str]]:
"""Context manager that runs a FastMCP HTTP server for one test."""
- proc = start_http_mcp_server(
- fixture_server,
- ready_url=ready_url,
- service_name=service_name,
- extra_args=extra_args,
- ready_statuses=ready_statuses,
- ready_request_kwargs=ready_request_kwargs,
- )
- try:
- yield proc
- finally:
- stop_http_mcp_server(proc)
+ with _loopback_proxy_bypass():
+ proc = start_http_mcp_server(
+ fixture_server,
+ ready_url=ready_url,
+ service_name=service_name,
+ extra_args=extra_args,
+ ready_statuses=ready_statuses,
+ ready_request_kwargs=ready_request_kwargs,
+ )
+ try:
+ yield proc
+ finally:
+ stop_http_mcp_server(proc)
@contextmanager
@@ -235,18 +394,19 @@ def running_http_mcp_server_on_random_port(
ready_statuses: set[int] | None = None,
ready_request_kwargs: dict[str, Any] | None = None,
max_attempts: int = 5,
-) -> Iterator[tuple[subprocess.Popen[str], int]]:
+) -> Iterator[HttpMCPServerHandle]:
"""Context manager that runs a FastMCP HTTP server on a retryable free port."""
- proc, port = start_http_mcp_server_on_random_port(
- fixture_server,
- service_name=service_name,
- ready_url_builder=ready_url_builder,
- extra_args_builder=extra_args_builder,
- ready_statuses=ready_statuses,
- ready_request_kwargs=ready_request_kwargs,
- max_attempts=max_attempts,
- )
- try:
- yield proc, port
- finally:
- stop_http_mcp_server(proc)
\ No newline at end of file
+ with _loopback_proxy_bypass():
+ handle = start_http_mcp_server_on_random_port(
+ fixture_server,
+ service_name=service_name,
+ ready_url_builder=ready_url_builder,
+ extra_args_builder=extra_args_builder,
+ ready_statuses=ready_statuses,
+ ready_request_kwargs=ready_request_kwargs,
+ max_attempts=max_attempts,
+ )
+ try:
+ yield handle
+ finally:
+ stop_http_mcp_server(handle.process)
diff --git a/agent/tests/test_mcp_sse_integration.py b/agent/tests/test_mcp_sse_integration.py
index 53c7b1607..d1c1dd65c 100644
--- a/agent/tests/test_mcp_sse_integration.py
+++ b/agent/tests/test_mcp_sse_integration.py
@@ -51,12 +51,12 @@ def test_remote_sse_tool_appears_in_registry(tmp_path: Path) -> None:
ready_url_builder=_sse_url,
extra_args_builder=lambda port: ["--port", str(port)],
ready_request_kwargs={"stream": True},
- ) as (_, port):
- cfg_path = _make_agent_json(tmp_path, "fake_sse", port=port)
+ ) as server:
+ cfg_path = _make_agent_json(tmp_path, "fake_sse", port=server.port)
agent_config = load_agent_config(config_path=cfg_path)
registry = build_registry(agent_config=agent_config)
- assert "mcp_fake_sse_echo" in registry.tool_names
+ assert "mcp_fake_sse_echo" in registry.tool_names, server.diagnostics()
def test_remote_sse_tool_is_callable_and_returns_expected_result(tmp_path: Path) -> None:
@@ -69,13 +69,13 @@ def test_remote_sse_tool_is_callable_and_returns_expected_result(tmp_path: Path)
ready_url_builder=_sse_url,
extra_args_builder=lambda port: ["--port", str(port)],
ready_request_kwargs={"stream": True},
- ) as (_, port):
- cfg_path = _make_agent_json(tmp_path, "fake_sse", port=port)
+ ) as server:
+ cfg_path = _make_agent_json(tmp_path, "fake_sse", port=server.port)
agent_config = load_agent_config(config_path=cfg_path)
registry = build_registry(agent_config=agent_config)
echo_tool = registry.get("mcp_fake_sse_echo")
- assert echo_tool is not None, "mcp_fake_sse_echo not found in registry"
+ assert echo_tool is not None, f"mcp_fake_sse_echo not found in registry\n{server.diagnostics()}"
result = echo_tool.execute(message="hello")
assert "echo: hello" in result
@@ -91,13 +91,13 @@ def test_enabled_tools_filter_limits_remote_sse_tools(tmp_path: Path) -> None:
ready_url_builder=_sse_url,
extra_args_builder=lambda port: ["--port", str(port)],
ready_request_kwargs={"stream": True},
- ) as (_, port):
- cfg_path = _make_agent_json(tmp_path, "fake_sse", port=port, enabledTools=["echo"])
+ ) as server:
+ cfg_path = _make_agent_json(tmp_path, "fake_sse", port=server.port, enabledTools=["echo"])
agent_config = load_agent_config(config_path=cfg_path)
registry = build_registry(agent_config=agent_config)
mcp_names = [name for name in registry.tool_names if name.startswith("mcp_fake_sse_")]
- assert "mcp_fake_sse_echo" in mcp_names
+ assert "mcp_fake_sse_echo" in mcp_names, server.diagnostics()
assert "mcp_fake_sse_add" not in mcp_names, (
"mcp_fake_sse_add should be excluded by enabledTools filter"
)
diff --git a/agent/tests/test_mcp_streamable_http_integration.py b/agent/tests/test_mcp_streamable_http_integration.py
index b5ede38df..a3196232f 100644
--- a/agent/tests/test_mcp_streamable_http_integration.py
+++ b/agent/tests/test_mcp_streamable_http_integration.py
@@ -55,12 +55,12 @@ def test_remote_streamable_http_tool_appears_in_registry(tmp_path: Path) -> None
ready_url_builder=_http_url,
extra_args_builder=lambda port: ["--port", str(port), "--path", HTTP_PATH],
ready_statuses={200, 400, 405, 406},
- ) as (_, port):
- cfg_path = _make_agent_json(tmp_path, "fake_http", port=port)
+ ) as server:
+ cfg_path = _make_agent_json(tmp_path, "fake_http", port=server.port)
agent_config = load_agent_config(config_path=cfg_path)
registry = build_registry(agent_config=agent_config)
- assert "mcp_fake_http_echo" in registry.tool_names
+ assert "mcp_fake_http_echo" in registry.tool_names, server.diagnostics()
def test_remote_streamable_http_tool_is_callable_and_returns_expected_result(tmp_path: Path) -> None:
@@ -73,13 +73,13 @@ def test_remote_streamable_http_tool_is_callable_and_returns_expected_result(tmp
ready_url_builder=_http_url,
extra_args_builder=lambda port: ["--port", str(port), "--path", HTTP_PATH],
ready_statuses={200, 400, 405, 406},
- ) as (_, port):
- cfg_path = _make_agent_json(tmp_path, "fake_http", port=port)
+ ) as server:
+ cfg_path = _make_agent_json(tmp_path, "fake_http", port=server.port)
agent_config = load_agent_config(config_path=cfg_path)
registry = build_registry(agent_config=agent_config)
echo_tool = registry.get("mcp_fake_http_echo")
- assert echo_tool is not None, "mcp_fake_http_echo not found in registry"
+ assert echo_tool is not None, f"mcp_fake_http_echo not found in registry\n{server.diagnostics()}"
result = echo_tool.execute(message="hello")
assert "echo: hello" in result
@@ -95,13 +95,13 @@ def test_enabled_tools_filter_limits_remote_streamable_http_tools(tmp_path: Path
ready_url_builder=_http_url,
extra_args_builder=lambda port: ["--port", str(port), "--path", HTTP_PATH],
ready_statuses={200, 400, 405, 406},
- ) as (_, port):
- cfg_path = _make_agent_json(tmp_path, "fake_http", port=port, enabledTools=["echo"])
+ ) as server:
+ cfg_path = _make_agent_json(tmp_path, "fake_http", port=server.port, enabledTools=["echo"])
agent_config = load_agent_config(config_path=cfg_path)
registry = build_registry(agent_config=agent_config)
mcp_names = [name for name in registry.tool_names if name.startswith("mcp_fake_http_")]
- assert "mcp_fake_http_echo" in mcp_names
+ assert "mcp_fake_http_echo" in mcp_names, server.diagnostics()
assert "mcp_fake_http_add" not in mcp_names, (
"mcp_fake_http_add should be excluded by enabledTools filter"
)
@@ -134,4 +134,4 @@ def test_unreachable_streamable_http_server_does_not_block_local_tools(tmp_path:
assert mcp_names == []
assert any("bad-http" in warning for warning in warnings), (
f"Expected a warning mentioning 'bad-http', got: {warnings}"
- )
\ No newline at end of file
+ )