feat(network): centralize proxy settings and add MCP routing (NAN-315) (#6372)
* feat(network): share proxy settings across features and MCP (NAN-315) * fix(network): address shared proxy review regressions * test(network): align rebased OAuth fixtures with runtime admission * fix(webui): configure shared proxy without leaving connection drafts * feat(webui): add optional shared proxy authentication editor * fix(webui): align proxy save tests and loading skeleton
This commit is contained in:
1 parent
872a83340d
commit
084b6bb394
181 files changed
+3740
-807
No files matched your search
@@ -9,6 +9,7 @@ import pytest
|
||||
|
||||
from nanobot.agent.tools.image_generation import ImageGenerationTool, ImageGenerationToolConfig
|
||||
from nanobot.config.loader import set_config_path
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import Config, ProviderConfig
|
||||
from nanobot.providers.image_generation import GeneratedImageResponse, image_gen_provider_configs
|
||||
|
||||
@@ -188,7 +189,8 @@ def test_image_generation_tool_passes_provider_proxy_to_client(
|
||||
provider="openai_codex",
|
||||
model="openai-codex/gpt-image-2",
|
||||
),
|
||||
provider_configs={"openai_codex": ProviderConfig(proxy=proxy)},
|
||||
provider_configs={"openai_codex": ProviderConfig(use_proxy=True)},
|
||||
network=NetworkConfig(proxy=proxy),
|
||||
)
|
||||
|
||||
client = tool._provider_client()
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import socket
|
||||
from unittest.mock import MagicMock, patch
|
||||
from unittest.mock import patch
|
||||
from urllib.request import getproxies_environment
|
||||
|
||||
import httpx
|
||||
@@ -79,7 +79,8 @@ async def test_probe_returns_false_when_validated_target_refuses_connection(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_probe_rejects_public_name_resolving_to_loopback():
|
||||
@pytest.mark.parametrize("proxy", [None, "http://shared-proxy.example:8080"])
|
||||
async def test_probe_rejects_public_name_resolving_to_loopback(proxy):
|
||||
def _resolver(hostname, port, family=0, type_=0):
|
||||
return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 0))]
|
||||
|
||||
@@ -87,7 +88,7 @@ async def test_probe_rejects_public_name_resolving_to_loopback():
|
||||
patch("nanobot.security.network.socket.getaddrinfo", _resolver),
|
||||
patch("nanobot.agent.tools.mcp.asyncio.open_connection") as open_connection,
|
||||
):
|
||||
assert await _probe_http_url("http://example.com:8765/mcp") is False
|
||||
assert await _probe_http_url("http://example.com:8765/mcp", proxy=proxy) is False
|
||||
open_connection.assert_not_called()
|
||||
|
||||
|
||||
@@ -145,22 +146,13 @@ async def test_probe_tries_next_validated_ip_when_first_is_unreachable(monkeypat
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_http_cfg(url: str, transport: str = "streamableHttp"):
|
||||
cfg = MagicMock()
|
||||
cfg.type = transport
|
||||
cfg.url = url
|
||||
cfg.command = None
|
||||
cfg.args = []
|
||||
cfg.env = {}
|
||||
cfg.headers = None
|
||||
cfg.tool_timeout = 30
|
||||
cfg.enabled_tools = ["*"]
|
||||
return cfg
|
||||
return MCPServerConfig(type=transport, url=url)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_skips_unreachable_streamable_http():
|
||||
"""Unreachable streamableHttp server should be skipped with a warning, no crash."""
|
||||
async def _unreachable(_url: str) -> bool:
|
||||
async def _unreachable(_url: str, *, proxy: str | None = None) -> bool:
|
||||
return False
|
||||
|
||||
registry = ToolRegistry()
|
||||
@@ -174,7 +166,7 @@ async def test_connect_skips_unreachable_streamable_http():
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_skips_unreachable_sse():
|
||||
"""Unreachable SSE server should be skipped with a warning, no crash."""
|
||||
async def _unreachable(_url: str) -> bool:
|
||||
async def _unreachable(_url: str, *, proxy: str | None = None) -> bool:
|
||||
return False
|
||||
|
||||
registry = ToolRegistry()
|
||||
@@ -190,7 +182,7 @@ async def test_connect_isolates_streamable_http_status_failure(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A reachable endpoint returning HTTP 530 must not poison the event loop."""
|
||||
async def _reachable(_url: str) -> bool:
|
||||
async def _reachable(_url: str, *, proxy: str | None = None) -> bool:
|
||||
return True
|
||||
|
||||
def _return_http_530(request: httpx.Request) -> httpx.Response:
|
||||
@@ -249,16 +241,22 @@ async def test_probe_not_called_for_stdio():
|
||||
return await original_probe(url, **kw)
|
||||
|
||||
with patch("nanobot.agent.tools.mcp._probe_http_url", _spy_probe):
|
||||
cfg = MagicMock()
|
||||
cfg.type = "stdio"
|
||||
cfg.url = None
|
||||
cfg.command = "nonexistent-command-xyz"
|
||||
cfg.args = []
|
||||
cfg.env = None
|
||||
cfg.headers = None
|
||||
cfg.tool_timeout = 30
|
||||
cfg.enabled_tools = ["*"]
|
||||
cfg = MCPServerConfig(type="stdio", command="nonexistent-command-xyz")
|
||||
registry = ToolRegistry()
|
||||
await connect_mcp_servers({"s": cfg}, registry)
|
||||
|
||||
assert not called, "probe should not be called for stdio transport"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_explicit_proxy_skips_direct_probe_even_when_no_proxy_env_matches(monkeypatch):
|
||||
monkeypatch.setenv("NO_PROXY", "mcp.example.com")
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.tools.mcp.resolve_url_target",
|
||||
lambda _url: (True, "", ("93.184.216.34",)),
|
||||
)
|
||||
with patch("nanobot.agent.tools.mcp.asyncio.open_connection") as open_connection:
|
||||
assert await _probe_http_url(
|
||||
"https://mcp.example.com/mcp", proxy="http://shared-proxy.example:8080"
|
||||
) is True
|
||||
open_connection.assert_not_called()
|
||||
@@ -0,0 +1,275 @@
|
||||
"""Shared MCP routing exercised through a real loopback HTTP recording proxy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
from urllib.request import getproxies_environment
|
||||
|
||||
import aiohttp
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from aiohttp import web
|
||||
|
||||
from nanobot.agent.tools.mcp import MCPProvider, MCPToolWrapper, connect_mcp_servers
|
||||
from nanobot.agent.tools.mcp_oauth import MCPOAuthStorage
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
from nanobot.security import network as security_network
|
||||
from nanobot.webui.mcp_oauth_api import McpOAuthManager
|
||||
|
||||
_PROXY_ENV_VARS = (
|
||||
"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
|
||||
"http_proxy", "https_proxy", "all_proxy", "no_proxy",
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _RecordingMCPProxy:
|
||||
origin: str = ""
|
||||
proxy: str = ""
|
||||
proxy_requests: list[tuple[str, str]] = field(default_factory=list)
|
||||
origin_requests: list[tuple[str, str, str | None]] = field(default_factory=list)
|
||||
rpc_methods: list[str] = field(default_factory=list)
|
||||
token_grants: list[str] = field(default_factory=list)
|
||||
proxy_fails: bool = False
|
||||
terminate_next_call: bool = False
|
||||
initialized: int = 0
|
||||
|
||||
async def serve_origin(self, request: web.Request) -> web.Response:
|
||||
self.origin_requests.append((request.method, request.path, request.headers.get("X-Test-Proxy")))
|
||||
if request.path == "/.well-known/oauth-protected-resource":
|
||||
return web.json_response({
|
||||
"resource": f"{self.origin}/mcp",
|
||||
"authorization_servers": [self.origin],
|
||||
})
|
||||
if request.path == "/.well-known/oauth-authorization-server":
|
||||
return web.json_response({
|
||||
"issuer": self.origin,
|
||||
# Browser navigation is not performed by this fixture or the gateway.
|
||||
"authorization_endpoint": "https://8.8.8.8/authorize",
|
||||
"token_endpoint": f"{self.origin}/token",
|
||||
"registration_endpoint": f"{self.origin}/register",
|
||||
"response_types_supported": ["code"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
})
|
||||
if request.path == "/register":
|
||||
registration = await request.json()
|
||||
return web.json_response({
|
||||
"client_id": "local-test-client",
|
||||
"redirect_uris": registration["redirect_uris"],
|
||||
"token_endpoint_auth_method": "none",
|
||||
}, status=201)
|
||||
if request.path == "/token":
|
||||
token_request = parse_qs(await request.text())
|
||||
grant = token_request["grant_type"][0]
|
||||
self.token_grants.append(grant)
|
||||
if grant == "authorization_code":
|
||||
assert token_request["code"] == ["local-test-code"]
|
||||
assert len(token_request["code_verifier"][0]) >= 43
|
||||
else:
|
||||
assert grant == "refresh_token"
|
||||
assert token_request["refresh_token"] == ["local-refresh-token"]
|
||||
return web.json_response({
|
||||
"access_token": "local-access-token", "refresh_token": "local-refresh-token",
|
||||
"token_type": "Bearer", "expires_in": 3600,
|
||||
})
|
||||
if request.path != "/mcp":
|
||||
return web.Response(status=404)
|
||||
if request.headers.get("Authorization") != "Bearer local-access-token":
|
||||
return web.Response(status=401, headers={
|
||||
"WWW-Authenticate": (
|
||||
f'Bearer resource_metadata="{self.origin}/.well-known/oauth-protected-resource"'
|
||||
),
|
||||
})
|
||||
if request.method == "DELETE":
|
||||
return web.Response(status=200)
|
||||
if request.method != "POST":
|
||||
return web.Response(status=405)
|
||||
payload = await request.json()
|
||||
method = payload["method"]
|
||||
self.rpc_methods.append(method)
|
||||
if "id" not in payload:
|
||||
return web.Response(status=202)
|
||||
headers = {}
|
||||
if method == "initialize":
|
||||
self.initialized += 1
|
||||
headers["Mcp-Session-Id"] = f"test-session-{self.initialized}"
|
||||
result = {
|
||||
"protocolVersion": payload["params"]["protocolVersion"],
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "local-proxy-test", "version": "1"},
|
||||
}
|
||||
elif method == "tools/list":
|
||||
result = {"tools": [{
|
||||
"name": "echo", "description": "Echo over the selected route",
|
||||
"inputSchema": {"type": "object", "properties": {}},
|
||||
}]}
|
||||
elif method == "tools/call":
|
||||
if self.terminate_next_call:
|
||||
self.terminate_next_call = False
|
||||
return web.json_response({
|
||||
"jsonrpc": "2.0", "id": payload["id"],
|
||||
"error": {"code": -32000, "message": "Session terminated"},
|
||||
})
|
||||
result = {"content": [{"type": "text", "text": "through-shared-proxy"}]}
|
||||
else:
|
||||
raise AssertionError(f"Unexpected MCP method: {method}")
|
||||
return web.json_response({"jsonrpc": "2.0", "id": payload["id"], "result": result}, headers=headers)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def recording_mcp_proxy(tmp_path, monkeypatch: pytest.MonkeyPatch):
|
||||
for name in _PROXY_ENV_VARS:
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
monkeypatch.setattr(security_network, "getproxies", getproxies_environment)
|
||||
monkeypatch.setattr("nanobot.agent.tools.mcp_oauth.get_data_dir", lambda: tmp_path)
|
||||
previous_whitelist = [str(cidr) for cidr in security_network._allowed_networks]
|
||||
security_network.configure_ssrf_whitelist(["127.0.0.1/32"])
|
||||
fixture = _RecordingMCPProxy()
|
||||
runners: list[web.AppRunner] = []
|
||||
|
||||
async def serve(handler) -> str:
|
||||
app = web.Application()
|
||||
app.router.add_route("*", "/{tail:.*}", handler)
|
||||
runner = web.AppRunner(app)
|
||||
runners.append(runner)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
port = site._server.sockets[0].getsockname()[1]
|
||||
return f"http://127.0.0.1:{port}"
|
||||
|
||||
try:
|
||||
fixture.origin = await serve(fixture.serve_origin)
|
||||
async with aiohttp.ClientSession(trust_env=False) as forwarding_client:
|
||||
async def forward(request: web.Request) -> web.Response:
|
||||
target = request.raw_path
|
||||
fixture.proxy_requests.append((request.method, target))
|
||||
assert target.startswith(f"{fixture.origin}/"), "test proxy must never forward externally"
|
||||
if fixture.proxy_fails:
|
||||
return web.Response(status=502, text="controlled proxy failure")
|
||||
headers = {
|
||||
key: value for key, value in request.headers.items()
|
||||
if key.lower() not in {"host", "content-length", "connection", "proxy-connection"}
|
||||
}
|
||||
headers["X-Test-Proxy"] = "shared"
|
||||
async with forwarding_client.request(
|
||||
request.method, target, headers=headers, data=await request.read(),
|
||||
allow_redirects=False,
|
||||
) as response:
|
||||
body = await response.read()
|
||||
response_headers = {
|
||||
key: value for key, value in response.headers.items()
|
||||
if key.lower() not in {"content-length", "transfer-encoding", "connection"}
|
||||
}
|
||||
return web.Response(body=body, status=response.status, headers=response_headers)
|
||||
|
||||
fixture.proxy = await serve(forward)
|
||||
yield fixture
|
||||
finally:
|
||||
for runner in reversed(runners):
|
||||
await runner.cleanup()
|
||||
security_network.configure_ssrf_whitelist(previous_whitelist)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_oauth_discovery_tokens_reconnect_and_tool_calls_share_real_proxy(
|
||||
recording_mcp_proxy,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
fixture = recording_mcp_proxy
|
||||
# Even an ambient proxy or NO_PROXY=* cannot override an explicitly selected route.
|
||||
monkeypatch.setenv("HTTP_PROXY", "http://127.0.0.1:9")
|
||||
monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:9")
|
||||
monkeypatch.setenv("NO_PROXY", "*")
|
||||
cfg = MCPServerConfig(
|
||||
type="streamableHttp", auth="oauth", url=f"{fixture.origin}/mcp",
|
||||
use_proxy=True, enabled_tools=["echo"],
|
||||
)
|
||||
network = NetworkConfig(proxy=fixture.proxy)
|
||||
registry = ToolRegistry()
|
||||
provider = MCPProvider({"local": cfg}, registry, network=network)
|
||||
manager = McpOAuthManager(RuntimeAdmission())
|
||||
|
||||
async def reload_mcp():
|
||||
await provider.connect()
|
||||
return {"ok": provider.connected_server_names == {"local"}, "connected": ["local"]}
|
||||
|
||||
started = await asyncio.wait_for(manager.start(
|
||||
"local", cfg, "http://127.0.0.1:8765/auth/mcp/callback",
|
||||
reload_mcp=reload_mcp, network=network,
|
||||
), timeout=10)
|
||||
try:
|
||||
assert started["status"] == "authorization_required"
|
||||
state = parse_qs(urlsplit(started["authorization_url"]).query)["state"][0]
|
||||
manager.submit_callback(state=state, code="local-test-code", error=None)
|
||||
async with asyncio.timeout(10):
|
||||
while (await manager.status(started["flow_id"]))["status"] == "connecting":
|
||||
await asyncio.sleep(0.01)
|
||||
assert (await manager.status(started["flow_id"]))["status"] == "connected"
|
||||
tool = registry.get("mcp_local_echo")
|
||||
assert isinstance(tool, MCPToolWrapper)
|
||||
assert await tool.execute() == "through-shared-proxy"
|
||||
fixture.terminate_next_call = True
|
||||
assert await tool.execute() == "through-shared-proxy"
|
||||
assert registry.get("mcp_local_echo") is not tool
|
||||
assert fixture.initialized == 3 # Browser flow, activation, terminated-session recovery.
|
||||
assert fixture.rpc_methods.count("tools/call") == 3
|
||||
storage = MCPOAuthStorage("local", cfg.url)
|
||||
snapshot = await storage.get_snapshot()
|
||||
assert snapshot.tokens is not None
|
||||
assert snapshot.tokens.access_token == "local-access-token"
|
||||
# A later runtime loads an expired saved token and must refresh over the same route.
|
||||
await storage.set_tokens(snapshot.tokens.model_copy(update={"expires_in": -1}))
|
||||
await provider.aclose()
|
||||
registry = ToolRegistry()
|
||||
provider = MCPProvider({"local": cfg}, registry, network=network)
|
||||
await provider.connect()
|
||||
refreshed_tool = registry.get("mcp_local_echo")
|
||||
assert isinstance(refreshed_tool, MCPToolWrapper)
|
||||
assert await refreshed_tool.execute() == "through-shared-proxy"
|
||||
assert fixture.token_grants == ["authorization_code", "refresh_token"]
|
||||
assert ("POST", f"{fixture.origin}/register") in fixture.proxy_requests
|
||||
assert ("POST", f"{fixture.origin}/token") in fixture.proxy_requests
|
||||
assert ("GET", f"{fixture.origin}/.well-known/oauth-protected-resource") in fixture.proxy_requests
|
||||
assert ("GET", f"{fixture.origin}/.well-known/oauth-authorization-server") in fixture.proxy_requests
|
||||
assert fixture.origin_requests
|
||||
assert all(route == "shared" for _, _, route in fixture.origin_requests)
|
||||
finally:
|
||||
await manager.cancel(started["flow_id"])
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("transport", ["sse", "streamableHttp"])
|
||||
async def test_failing_shared_proxy_never_retries_reachable_origin_directly(recording_mcp_proxy, transport) -> None:
|
||||
fixture = recording_mcp_proxy
|
||||
fixture.proxy_fails = True
|
||||
registry = ToolRegistry()
|
||||
connections = await asyncio.wait_for(connect_mcp_servers(
|
||||
{"local": MCPServerConfig(type=transport, url=f"{fixture.origin}/mcp", use_proxy=True)},
|
||||
registry, network=NetworkConfig(proxy=fixture.proxy),
|
||||
), timeout=5)
|
||||
assert connections == {}
|
||||
assert registry.tool_names == []
|
||||
assert fixture.proxy_requests
|
||||
assert fixture.origin_requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("transport", ["sse", "streamableHttp"])
|
||||
async def test_missing_shared_address_does_not_open_http_connection(recording_mcp_proxy, transport) -> None:
|
||||
fixture = recording_mcp_proxy
|
||||
registry = ToolRegistry()
|
||||
connections = await connect_mcp_servers(
|
||||
{"local": MCPServerConfig(type=transport, url=f"{fixture.origin}/mcp", use_proxy=True)},
|
||||
registry, network=NetworkConfig(),
|
||||
)
|
||||
assert connections == {}
|
||||
assert registry.tool_names == []
|
||||
assert fixture.proxy_requests == []
|
||||
assert fixture.origin_requests == []
|
||||
@@ -7,12 +7,14 @@ from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
from urllib.parse import unquote
|
||||
from urllib.request import getproxies_environment
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
import nanobot.agent.tools.mcp as mcp_mod
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.mcp import (
|
||||
MCPPromptWrapper,
|
||||
MCPProvider,
|
||||
@@ -24,6 +26,7 @@ from nanobot.agent.tools.mcp import (
|
||||
connect_mcp_servers,
|
||||
)
|
||||
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
|
||||
_PROXY_ENV_VARS = ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy")
|
||||
@@ -163,7 +166,9 @@ def _make_wrapper(session: object, *, timeout: float = 0.1) -> MCPToolWrapper:
|
||||
async def test_mcp_provider_connect_propagates_external_cancellation(monkeypatch) -> None:
|
||||
started = asyncio.Event()
|
||||
|
||||
async def connect_mcp_servers(_servers: dict, _registry: ToolRegistry) -> dict:
|
||||
async def connect_mcp_servers(
|
||||
_servers: dict, _registry: ToolRegistry, *, network
|
||||
) -> dict:
|
||||
started.set()
|
||||
await asyncio.sleep(60)
|
||||
return {}
|
||||
@@ -211,7 +216,7 @@ async def test_saved_oauth_http_403_projects_failed_runtime_without_details(
|
||||
)
|
||||
yield object(), object(), object()
|
||||
|
||||
async def reachable(_url: str) -> bool:
|
||||
async def reachable(_url: str, *, proxy: str | None = None) -> bool:
|
||||
return True
|
||||
|
||||
oauth_mod = ModuleType("nanobot.agent.tools.mcp_oauth")
|
||||
@@ -1117,6 +1122,160 @@ def test_unexpected_connection_failure_keeps_error_trace() -> None:
|
||||
assert not any(record["level"].name == "WARNING" for record in records)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("transport", ["sse", "streamableHttp"])
|
||||
@pytest.mark.parametrize("log_content", [True, False])
|
||||
async def test_proxy_constructor_failure_diagnostics_never_render_live_locals(
|
||||
monkeypatch: pytest.MonkeyPatch, transport: str, log_content: bool,
|
||||
) -> None:
|
||||
proxy = "http://diagnostic-user:diagnostic-secret@\u2603.example:8080"
|
||||
network = NetworkConfig(proxy=proxy)
|
||||
with pytest.raises(httpx.InvalidURL):
|
||||
httpx.AsyncHTTPTransport(proxy=network.proxy)
|
||||
|
||||
@asynccontextmanager
|
||||
async def sse_client(_url, *, httpx_client_factory):
|
||||
async with httpx_client_factory():
|
||||
yield object(), object()
|
||||
|
||||
monkeypatch.setattr(sys.modules["mcp.client.sse"], "sse_client", sse_client)
|
||||
monkeypatch.setattr(mcp_mod, "validate_url_target", lambda _url: (True, ""))
|
||||
monkeypatch.setattr(mcp_mod, "_probe_http_url", AsyncMock(return_value=True))
|
||||
messages: list[str] = []
|
||||
sink = mcp_mod.logger.add(
|
||||
lambda message: messages.append(str(message)), level="DEBUG",
|
||||
format="{level} {message}", diagnose=True, backtrace=True,
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
try:
|
||||
with request_context(RequestContext(channel="test", chat_id="proxy", log_content=log_content)):
|
||||
connections = await connect_mcp_servers(
|
||||
{"remote": MCPServerConfig(
|
||||
type=transport, url="https://mcp.example.invalid/mcp", use_proxy=True,
|
||||
)}, registry, network=network,
|
||||
)
|
||||
finally:
|
||||
mcp_mod.logger.remove(sink)
|
||||
|
||||
assert connections == {}
|
||||
assert registry.tool_names == []
|
||||
output = "\n".join(messages)
|
||||
assert "diagnostic-secret" not in output
|
||||
assert "diagnostic-user" not in output
|
||||
assert "failed to connect" in output
|
||||
if log_content:
|
||||
assert "InvalidURL" in output
|
||||
assert "Invalid IDNA hostname" in output
|
||||
assert "Traceback (most recent call last)" in output
|
||||
assert "in _pinned_transport_kwargs" in output
|
||||
else:
|
||||
assert "InvalidURL" not in output
|
||||
assert "Traceback" not in output
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failure_stage", ["open", "cleanup"])
|
||||
@pytest.mark.parametrize("userinfo", ["diagnostic-user:diagnostic%3Asecret", "e:p", "e"])
|
||||
async def test_connection_failure_redacts_resolved_proxy_in_exception_chain_and_group(
|
||||
fake_mcp_runtime, monkeypatch: pytest.MonkeyPatch, failure_stage: str, userinfo: str,
|
||||
) -> None:
|
||||
proxy = f"http://{userinfo}@proxy.example.invalid:8080"
|
||||
authority = proxy.removeprefix("http://")
|
||||
monkeypatch.setenv("MCP_DIAGNOSTIC_PROXY", proxy)
|
||||
network = NetworkConfig(proxy="${MCP_DIAGNOSTIC_PROXY}")
|
||||
session = _make_fake_session(["demo"])
|
||||
session.initialize = AsyncMock(side_effect=RuntimeError("initialize failed"))
|
||||
fake_mcp_runtime["session"] = session
|
||||
|
||||
@asynccontextmanager
|
||||
async def failing_sse(_url, *, httpx_client_factory):
|
||||
if failure_stage == "cleanup":
|
||||
yield object(), object()
|
||||
try:
|
||||
raise ValueError(f"proxy handshake rejected {proxy}")
|
||||
except ValueError as cause:
|
||||
raise ExceptionGroup("MCP transport setup failed", [
|
||||
httpx.ProxyError(
|
||||
f"authentication rejected {authority} / {unquote(authority)} / {unquote(proxy)}"
|
||||
),
|
||||
]) from cause
|
||||
yield # pragma: no cover
|
||||
|
||||
monkeypatch.setattr(sys.modules["mcp.client.sse"], "sse_client", failing_sse)
|
||||
monkeypatch.setattr(mcp_mod, "validate_url_target", lambda _url: (True, ""))
|
||||
monkeypatch.setattr(mcp_mod, "_probe_http_url", AsyncMock(return_value=True))
|
||||
messages: list[str] = []
|
||||
sink = mcp_mod.logger.add(
|
||||
lambda message: messages.append(str(message)), level="DEBUG",
|
||||
format="{level} {message}", diagnose=True, backtrace=True,
|
||||
)
|
||||
try:
|
||||
assert await connect_mcp_servers(
|
||||
{"remote": MCPServerConfig(type="sse", url="https://mcp.example.invalid/sse", use_proxy=True)},
|
||||
ToolRegistry(), network=network,
|
||||
) == {}
|
||||
finally:
|
||||
mcp_mod.logger.remove(sink)
|
||||
|
||||
output = "\n".join(messages)
|
||||
for credential_context in (proxy, unquote(proxy), f"{userinfo}@", f"{unquote(userinfo)}@"):
|
||||
assert credential_context not in output
|
||||
assert "Traceback (most recent call last)" in output
|
||||
assert "httpx.ProxyError: authentication rejected" in output
|
||||
assert "ValueError: proxy handshake rejected" in output
|
||||
assert "ExceptionGroup: MCP transport setup failed" in output
|
||||
assert "http://proxy.example.invalid:8080" in output
|
||||
assert "[redacted]@proxy.example.invalid:8080" in output
|
||||
assert "direct cause" in output
|
||||
assert "in failing_sse" in output
|
||||
if failure_stage == "cleanup":
|
||||
assert "initialize failed" in output
|
||||
|
||||
|
||||
@pytest.mark.parametrize("transient", [False, True])
|
||||
def test_connection_failure_retains_useful_trace_without_local_values(transient: bool) -> None:
|
||||
messages: list[str] = []
|
||||
records: list[dict] = []
|
||||
|
||||
def capture(message):
|
||||
messages.append(str(message))
|
||||
records.append(message.record)
|
||||
|
||||
sink = mcp_mod.logger.add(
|
||||
capture, level="DEBUG", format="{level} {message}", diagnose=True, backtrace=True,
|
||||
)
|
||||
|
||||
def fail_transport():
|
||||
local_credential = "unrelated-local-credential"
|
||||
error = httpx.ConnectError if transient else RuntimeError
|
||||
raise error(f"handshake failed (credential length {len(local_credential)})")
|
||||
|
||||
try:
|
||||
try:
|
||||
fail_transport()
|
||||
except Exception as exc:
|
||||
mcp_mod._log_mcp_connection_failure("remote", exc, " check server configuration")
|
||||
finally:
|
||||
mcp_mod.logger.remove(sink)
|
||||
|
||||
output = "\n".join(messages)
|
||||
assert "unrelated-local-credential" not in output
|
||||
assert "handshake failed (credential length 26)" in output
|
||||
assert "in fail_transport" in output
|
||||
assert "Traceback (most recent call last)" in output
|
||||
detail = next(record for record in records if record["exception"] is not None)
|
||||
assert detail["exception"].traceback is None
|
||||
assert detail["exception"].value.__traceback__ is None
|
||||
assert detail["exception"].value.__context__ is None
|
||||
assert detail["level"].name == ("DEBUG" if transient else "ERROR")
|
||||
if transient:
|
||||
assert "ConnectError" in output
|
||||
assert "transient connection failure" in output
|
||||
else:
|
||||
assert "RuntimeError" in output
|
||||
assert "check server configuration" in output
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"config",
|
||||
@@ -1127,7 +1286,9 @@ def test_unexpected_connection_failure_keeps_error_trace() -> None:
|
||||
MCPServerConfig(type="streamableHttp", url="http://169.254.169.254/mcp"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("use_proxy", [False, True])
|
||||
async def test_connect_mcp_servers_rejects_unsafe_http_urls_before_probe(
|
||||
use_proxy: bool,
|
||||
config: MCPServerConfig,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
@@ -1145,7 +1306,11 @@ async def test_connect_mcp_servers_rejects_unsafe_http_urls_before_probe(
|
||||
monkeypatch.setattr("nanobot.agent.tools.mcp.logger.warning", _warning)
|
||||
|
||||
registry = ToolRegistry()
|
||||
stacks = await connect_mcp_servers({"local": config}, registry)
|
||||
stacks = await connect_mcp_servers(
|
||||
{"local": config.model_copy(update={"use_proxy": use_proxy})},
|
||||
registry,
|
||||
network=NetworkConfig(proxy="http://shared-proxy.example:8080"),
|
||||
)
|
||||
|
||||
assert stacks == {}
|
||||
assert registry.tool_names == []
|
||||
@@ -1180,7 +1345,7 @@ async def test_connect_mcp_servers_env_proxy_adds_proxy_mounts_and_keeps_pinned_
|
||||
fake_mcp_runtime["session"] = _make_fake_session(["demo"])
|
||||
client_kwargs: list[dict[str, object]] = []
|
||||
|
||||
async def _reachable(_url: str) -> bool:
|
||||
async def _reachable(_url: str, *, proxy: str | None = None) -> bool:
|
||||
return True
|
||||
|
||||
def _validate(_url: str) -> tuple[bool, str]:
|
||||
@@ -1273,7 +1438,9 @@ def test_mcp_http_clients_no_proxy_env_keeps_pinned_direct_route(monkeypatch):
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("use_proxy", [False, True])
|
||||
async def test_connect_mcp_servers_http_clients_reject_unsafe_redirect_targets(
|
||||
use_proxy: bool,
|
||||
config: MCPServerConfig,
|
||||
expected_transport: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
@@ -1288,7 +1455,7 @@ async def test_connect_mcp_servers_http_clients_reject_unsafe_redirect_targets(
|
||||
return False, "loopback blocked"
|
||||
return True, ""
|
||||
|
||||
async def _reachable(_url: str) -> bool:
|
||||
async def _reachable(_url: str, *, proxy: str | None = None) -> bool:
|
||||
return True
|
||||
|
||||
def _handler(request: httpx.Request) -> httpx.Response:
|
||||
@@ -1329,6 +1496,11 @@ async def test_connect_mcp_servers_http_clients_reject_unsafe_redirect_targets(
|
||||
"PinnedDNSAsyncTransport",
|
||||
lambda **_kwargs: httpx.MockTransport(_handler),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
mcp_mod.httpx,
|
||||
"AsyncHTTPTransport",
|
||||
lambda **_kwargs: httpx.MockTransport(_handler),
|
||||
)
|
||||
monkeypatch.setattr(mcp_mod.httpx, "AsyncClient", _async_client_with_mock_transport)
|
||||
monkeypatch.setattr(sys.modules["mcp.client.sse"], "sse_client", _fake_sse_client)
|
||||
monkeypatch.setattr(
|
||||
@@ -1338,7 +1510,11 @@ async def test_connect_mcp_servers_http_clients_reject_unsafe_redirect_targets(
|
||||
)
|
||||
|
||||
registry = ToolRegistry()
|
||||
stacks = await connect_mcp_servers({"remote": config}, registry)
|
||||
stacks = await connect_mcp_servers(
|
||||
{"remote": config.model_copy(update={"use_proxy": use_proxy})},
|
||||
registry,
|
||||
network=NetworkConfig(proxy="http://shared-proxy.example:8080"),
|
||||
)
|
||||
|
||||
assert stacks == {}
|
||||
assert registry.tool_names == []
|
||||
@@ -1503,7 +1679,7 @@ async def test_connect_mcp_servers_streamable_http_uses_finite_timeout(
|
||||
fake_mcp_runtime["session"] = _make_fake_session(["demo"])
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
async def _reachable(_url: str) -> bool:
|
||||
async def _reachable(_url: str, *, proxy: str | None = None) -> bool:
|
||||
return True
|
||||
|
||||
def _validate(_url: str) -> tuple[bool, str]:
|
||||
@@ -1558,7 +1734,7 @@ async def test_connect_mcp_servers_attaches_oauth_to_remote_http_client(
|
||||
oauth_handlers = object()
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
async def _reachable(_url: str) -> bool:
|
||||
async def _reachable(_url: str, *, proxy: str | None = None) -> bool:
|
||||
return True
|
||||
|
||||
def _validate(_url: str) -> tuple[bool, str]:
|
||||
@@ -1642,7 +1818,7 @@ async def test_connect_mcp_servers_skips_background_oauth_without_credentials(
|
||||
|
||||
probe_called = False
|
||||
|
||||
async def _probe(_url: str) -> bool:
|
||||
async def _probe(_url: str, *, proxy: str | None = None) -> bool:
|
||||
nonlocal probe_called
|
||||
probe_called = True
|
||||
return True
|
||||
@@ -2342,3 +2518,88 @@ async def test_optional_mcp_filters_reach_server_unchanged(params, error):
|
||||
else:
|
||||
assert result == "ok"
|
||||
session.call_tool.assert_awaited_once_with("list_issues", arguments=params)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("transport", ["sse", "streamableHttp"])
|
||||
@pytest.mark.parametrize("use_proxy", [False, True], ids=["environment-route", "shared-route"])
|
||||
async def test_mcp_http_requests_use_selected_transport_without_route_fallback(
|
||||
fake_mcp_runtime,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
transport: str,
|
||||
use_proxy: bool,
|
||||
) -> None:
|
||||
fake_mcp_runtime["session"] = _make_fake_session(["demo"])
|
||||
routes: list[str] = []
|
||||
constructed_proxies: list[str] = []
|
||||
shared_proxy = "http://shared.example:8080"
|
||||
|
||||
def recording_transport(route: str) -> httpx.MockTransport:
|
||||
def respond(request: httpx.Request) -> httpx.Response:
|
||||
routes.append(route)
|
||||
return httpx.Response(200, json={"ok": True}, request=request)
|
||||
return httpx.MockTransport(respond)
|
||||
|
||||
def proxy_transport(*, proxy: str) -> httpx.MockTransport:
|
||||
constructed_proxies.append(proxy)
|
||||
return recording_transport("shared")
|
||||
|
||||
async def probe(_url, *, proxy):
|
||||
assert proxy == (shared_proxy if use_proxy else None)
|
||||
return True
|
||||
|
||||
@asynccontextmanager
|
||||
async def sse_client(url, *, httpx_client_factory):
|
||||
async with httpx_client_factory() as client:
|
||||
response = await client.get(url)
|
||||
assert response.json() == {"ok": True}
|
||||
yield object(), object()
|
||||
|
||||
@asynccontextmanager
|
||||
async def streamable_client(url, *, http_client):
|
||||
response = await http_client.get(url)
|
||||
assert response.json() == {"ok": True}
|
||||
yield object(), object(), object()
|
||||
|
||||
monkeypatch.setenv("HTTPS_PROXY", "http://environment.example:8888")
|
||||
monkeypatch.setattr(mcp_mod, "validate_url_target", lambda _url: (True, ""))
|
||||
monkeypatch.setattr(mcp_mod, "_probe_http_url", probe)
|
||||
monkeypatch.setattr(mcp_mod, "PinnedDNSAsyncTransport", lambda: recording_transport("direct"))
|
||||
monkeypatch.setattr(
|
||||
mcp_mod, "httpx_env_proxy_mounts", lambda: {"all://": recording_transport("environment")},
|
||||
)
|
||||
monkeypatch.setattr(mcp_mod.httpx, "AsyncHTTPTransport", proxy_transport)
|
||||
monkeypatch.setattr(sys.modules["mcp.client.sse"], "sse_client", sse_client)
|
||||
monkeypatch.setattr(sys.modules["mcp.client.streamable_http"], "streamable_http_client", streamable_client)
|
||||
|
||||
registry = ToolRegistry()
|
||||
connections = await connect_mcp_servers(
|
||||
{"remote": MCPServerConfig(
|
||||
type=transport, url="https://93.184.216.34/mcp", use_proxy=use_proxy,
|
||||
)},
|
||||
registry,
|
||||
network=NetworkConfig(proxy=shared_proxy),
|
||||
)
|
||||
try:
|
||||
assert set(connections) == {"remote"}
|
||||
assert registry.has("mcp_remote_demo")
|
||||
assert routes == (["shared"] if use_proxy else ["environment"])
|
||||
assert constructed_proxies == ([shared_proxy] if use_proxy else [])
|
||||
finally:
|
||||
for connection in connections.values():
|
||||
await connection.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stdio_cannot_opt_into_shared_proxy(monkeypatch) -> None:
|
||||
stdio_client = AsyncMock()
|
||||
monkeypatch.setattr(sys.modules["mcp.client.stdio"], "stdio_client", stdio_client)
|
||||
registry = ToolRegistry()
|
||||
connections = await connect_mcp_servers(
|
||||
{"local": MCPServerConfig(command="must-not-launch", use_proxy=True)},
|
||||
registry,
|
||||
network=NetworkConfig(proxy="http://shared.example:8080"),
|
||||
)
|
||||
assert connections == {}
|
||||
assert registry.tool_names == []
|
||||
stdio_client.assert_not_called()
|
||||
@@ -337,7 +337,7 @@ def test_web_search_tool_create():
|
||||
mock_config = MagicMock()
|
||||
mock_config.web.enable = True
|
||||
mock_config.web.search = MagicMock()
|
||||
mock_config.web.proxy = None
|
||||
mock_config.web.use_proxy = False
|
||||
mock_config.web.user_agent = None
|
||||
ctx = ToolContext(config=mock_config, workspace="/tmp")
|
||||
tool = WebSearchTool.create(ctx)
|
||||
@@ -349,7 +349,7 @@ def test_web_fetch_tool_create():
|
||||
mock_config = MagicMock()
|
||||
mock_config.web.enable = True
|
||||
mock_config.web.fetch = MagicMock()
|
||||
mock_config.web.proxy = None
|
||||
mock_config.web.use_proxy = False
|
||||
mock_config.web.user_agent = None
|
||||
ctx = ToolContext(config=mock_config, workspace="/tmp")
|
||||
tool = WebFetchTool.create(ctx)
|
||||
@@ -442,7 +442,7 @@ def test_loader_registers_builtin_tools():
|
||||
mock_config.web.enable = True
|
||||
mock_config.web.search = MagicMock()
|
||||
mock_config.web.fetch = MagicMock()
|
||||
mock_config.web.proxy = None
|
||||
mock_config.web.use_proxy = False
|
||||
mock_config.web.user_agent = None
|
||||
mock_config.image_generation.enabled = False
|
||||
mock_config.my.enable = True
|
||||
|
||||
Reference in new issue
Block a user