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:
chengyongru authored and GitHub committed 2026-10-22 15:49:27 +08:00
1 parent 872a83340d
commit 084b6bb394
181 files changed
+3740 -807

No files matched your search

+112 -13
View File
@@ -20,7 +20,8 @@ from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.mcp import MCPProvider, MCPResourceWrapper, MCPToolWrapper
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.config.loader import load_config, save_config
from nanobot.config.schema import MCPServerConfig
from nanobot.config.network import NetworkConfig
from nanobot.config.schema import Config, MCPServerConfig
def _mcp_notification(method: str, params: dict[str, Any] | None = None) -> SessionMessage:
@@ -144,7 +145,7 @@ async def test_connect_mcp_retries_when_no_servers_connect(tmp_path, monkeypatch
provider, _registry = _make_provider()
attempts = 0
async def _fake_connect(_servers, _registry):
async def _fake_connect(_servers, _registry, *, network):
nonlocal attempts
attempts += 1
return {}
@@ -203,7 +204,7 @@ async def test_mcp_provider_closes_connections_independently_from_agent_loop(
closed_tasks.append(asyncio.current_task())
assert asyncio.current_task() is self.owner
async def _fake_connect(servers, _registry):
async def _fake_connect(servers, _registry, *, network):
stacks = {name: _OwnerCheckedStack() for name in servers}
return stacks
@@ -333,7 +334,7 @@ async def test_reload_mcp_servers_adds_and_removes_tools_without_restart(
async def _mark_closed(name: str) -> None:
closed.append(name)
async def _fake_connect(servers, registry):
async def _fake_connect(servers, registry, *, network):
stacks = {}
for name in servers:
registry.register(_FakeMcpTool(f"mcp_{name}_navigate"))
@@ -382,7 +383,7 @@ async def test_reload_is_a_direct_provider_operation_without_an_agent_loop(
async def _mark_closed(name: str) -> None:
closed.append(name)
async def _fake_connect(servers, registry):
async def _fake_connect(servers, registry, *, network):
stacks = {}
for name in servers:
registry.register(_FakeMcpTool(f"mcp_{name}_navigate"))
@@ -394,7 +395,7 @@ async def test_reload_is_a_direct_provider_operation_without_an_agent_loop(
monkeypatch.setattr("nanobot.agent.tools.mcp.connect_mcp_servers", _fake_connect)
registry = ToolRegistry()
provider = MCPProvider({}, registry, server_loader=lambda: configured)
provider = MCPProvider({}, registry, server_loader=lambda: (configured, NetworkConfig()))
result = await provider.reload()
@@ -422,7 +423,7 @@ async def test_reload_timeout_marks_attempted_server_failed_and_allows_retry(
started = asyncio.Event()
attempts = 0
async def _fake_connect(servers, _registry):
async def _fake_connect(servers, _registry, *, network):
nonlocal attempts
attempts += 1
if attempts == 1:
@@ -436,7 +437,7 @@ async def test_reload_timeout_marks_attempted_server_failed_and_allows_retry(
provider = MCPProvider(
{"test": server},
ToolRegistry(),
server_loader=lambda: {"test": server},
server_loader=lambda: ({"test": server}, NetworkConfig()),
)
reload_task = asyncio.create_task(provider.reload())
@@ -469,7 +470,7 @@ async def test_reload_mcp_servers_retries_configured_server_without_live_stack(
)
save_config(config)
async def _fake_connect(servers, registry):
async def _fake_connect(servers, registry, *, network):
stacks = {}
for name in servers:
registry.register(_FakeMcpTool(f"mcp_{name}_navigate"))
@@ -516,7 +517,7 @@ async def test_reload_mcp_servers_skips_oauth_server_waiting_for_authorization(
attempted: list[str] = []
async def _fake_connect(servers, _registry):
async def _fake_connect(servers, _registry, *, network):
attempted.extend(servers)
stack = AsyncExitStack()
await stack.__aenter__()
@@ -568,7 +569,7 @@ async def test_mcp_tool_reconnects_after_session_terminated(
content=[mcp_types.TextContent(type="text", text="recovered")]
)
async def _fake_connect(servers, registry):
async def _fake_connect(servers, registry, *, network):
nonlocal connect_count
stacks = {}
for name in servers:
@@ -626,7 +627,7 @@ async def test_mcp_reconnect_handler_uses_sanitized_server_prefix(
content=[mcp_types.TextContent(type="text", text="recovered")]
)
async def _fake_connect(servers, registry):
async def _fake_connect(servers, registry, *, network):
nonlocal connect_count
stacks = {}
for name in servers:
@@ -685,7 +686,7 @@ async def test_concurrent_mcp_reconnect_reuses_fresh_session(
]
)
async def _fake_connect(servers, registry):
async def _fake_connect(servers, registry, *, network):
nonlocal connect_count
stacks = {}
for name in servers:
@@ -717,3 +718,101 @@ async def test_concurrent_mcp_reconnect_reuses_fresh_session(
assert outputs == ["fresh:alpha", "fresh:beta"]
assert connect_count == 2
assert closed == ["remote"]
@pytest.mark.asyncio
async def test_shared_proxy_snapshot_survives_reconnect_and_reloads_only_opted_in_servers(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
):
config = Config()
config.agents.defaults.workspace = str(tmp_path / "workspace")
config.network.proxy = "http://proxy-a.example:8080"
config.tools.mcp_servers = {
"proxied": MCPServerConfig(url="https://mcp.example.com/mcp", use_proxy=True),
"independent": MCPServerConfig(url="https://other.example.com/mcp"),
}
next_network = NetworkConfig(proxy="http://proxy-b.example:8080")
attempts: list[tuple[str, str | None, str | None]] = []
closed: list[str] = []
sessions: dict[str, Any] = {}
class Session:
expired = False
async def call_tool(self, _name: str, arguments: dict[str, Any]) -> Any:
if self.expired:
raise McpError(ErrorData(code=-32000, message="Session terminated"))
return SimpleNamespace(content=[mcp_types.TextContent(type="text", text="ok")])
async def mark_closed(name: str) -> None:
closed.append(name)
async def connect(servers, registry, *, network):
connections = {}
for name, cfg in servers.items():
attempts.append((name, network.proxy, network.resolve_proxy(cfg.use_proxy)))
sessions[name] = Session()
registry.register(MCPToolWrapper(sessions[name], name, SimpleNamespace(
name="echo", description="echo", inputSchema={"type": "object"},
)))
stack = AsyncExitStack()
await stack.__aenter__()
stack.push_async_callback(mark_closed, name)
connections[name] = stack
return connections
monkeypatch.setattr(mcp_runtime, "connect_mcp_servers", connect)
registry = ToolRegistry()
provider = MCPProvider.from_config(
config,
registry,
server_loader=lambda: (config.tools.mcp_servers, next_network),
)
try:
await provider.connect()
independent_tool = registry.get("mcp_independent_echo")
assert attempts == [
("proxied", "http://proxy-a.example:8080", "http://proxy-a.example:8080"),
("independent", "http://proxy-a.example:8080", None),
]
# Mutating the caller's config must not reroute a live provider's reconnect.
config.network.proxy = "http://not-live.example:8080"
sessions["proxied"].expired = True
old_tool = registry.get("mcp_proxied_echo")
assert isinstance(old_tool, MCPToolWrapper)
assert await old_tool.execute() == "ok"
assert attempts[-1] == (
"proxied", "http://proxy-a.example:8080", "http://proxy-a.example:8080"
)
result = await provider.reload()
assert result["ok"] is True
assert result["changed"] == ["proxied"]
assert result["connected"] == ["independent", "proxied"]
assert result["tools_removed"] == 1
assert attempts[-1] == (
"proxied", "http://proxy-b.example:8080", "http://proxy-b.example:8080"
)
assert closed == ["proxied", "proxied"]
assert registry.get("mcp_independent_echo") is independent_tool
# Reload also captures a copy, rather than retaining the loader's mutable model.
next_network.proxy = "http://proxy-c.example:8080"
sessions["proxied"].expired = True
current_tool = registry.get("mcp_proxied_echo")
assert isinstance(current_tool, MCPToolWrapper)
assert await current_tool.execute() == "ok"
assert attempts[-1] == (
"proxied", "http://proxy-b.example:8080", "http://proxy-b.example:8080"
)
result = await provider.reload()
assert result["changed"] == ["proxied"]
assert attempts[-1] == (
"proxied", "http://proxy-c.example:8080", "http://proxy-c.example:8080"
)
assert registry.get("mcp_independent_echo") is independent_tool
assert closed == ["proxied"] * 4
finally:
await provider.aclose()
+6 -3
View File
@@ -1090,7 +1090,8 @@ class TestMainMenuInteraction:
config = Config()
config.providers.openai.api_key = "${UNRELATED_MISSING_KEY}"
config.providers.openai_codex.proxy = "${CODEX_PROXY}"
config.network.proxy = "${CODEX_PROXY}"
config.providers.openai_codex.use_proxy = True
token = SimpleNamespace(access="existing-token", account_id="account-123")
token_proxies: list[str | None] = []
login_calls: list[object] = []
@@ -1113,7 +1114,8 @@ class TestMainMenuInteraction:
assert token_proxies == ["http://127.0.0.1:8080"]
assert login_calls == []
assert config.providers.openai.api_key == "${UNRELATED_MISSING_KEY}"
assert config.providers.openai_codex.proxy == "${CODEX_PROXY}"
assert config.network.proxy == "${CODEX_PROXY}"
assert config.providers.openai_codex.use_proxy is True
def test_quick_start_openai_codex_reports_incomplete_installation(self, monkeypatch):
import oauth_cli_kit
@@ -1139,7 +1141,8 @@ class TestMainMenuInteraction:
import oauth_cli_kit
config = Config()
config.providers.openai_codex.proxy = "http://127.0.0.1:8080"
config.network.proxy = "http://127.0.0.1:8080"
config.providers.openai_codex.use_proxy = True
prompts: list[str] = []
printed: list[tuple[tuple[object, ...], dict[str, object]]] = []
+3 -2
View File
@@ -93,7 +93,8 @@ def test_agent_loop_assembles_my_tool_with_runtime_control(tmp_path: Path) -> No
def test_runtime_snapshot_has_exact_allowlist_and_redacts_secrets(tmp_path: Path) -> None:
loop = _make_loop(tmp_path)
loop.web_config.search.api_key = "search-secret"
loop.web_config.proxy = "http://proxy-user:proxy-secret@proxy.example"
loop.network_config.proxy = "http://proxy-user:proxy-secret@proxy.example"
loop.web_config.use_proxy = True
loop.unlisted_secret = "loop-secret"
snapshot = _my_tool(loop)._runtime_control.snapshot()
@@ -132,7 +133,7 @@ def test_runtime_snapshot_has_exact_allowlist_and_redacts_secrets(tmp_path: Path
assert "search-secret" not in rendered
assert "proxy-secret" not in rendered
assert "loop-secret" not in rendered
assert snapshot.web_config["proxy"] == "<configured>"
assert snapshot.web_config["use_proxy"] is True
def test_runtime_snapshot_is_detached_from_mutable_config(tmp_path: Path) -> None:
+4 -2
View File
@@ -912,11 +912,13 @@ def test_discover_enabled_warns_for_enabled_package_import_errors():
# Manager _init_channels with dict config
# ---------------------------------------------------------------------------
def test_manager_loads_plugin_from_dict_config(monkeypatch):
"""ChannelManager should instantiate a channel package from a raw dict config."""
@pytest.mark.parametrize("proxy", ["", "http://127.0.0.1:7890"])
def test_manager_loads_plugin_from_dict_config(monkeypatch, proxy):
"""Existing two-argument plugins work with or without a shared proxy configured."""
from nanobot.channels.manager import ChannelManager
fake_config = Config.model_validate({
"network": {"proxy": proxy},
"channels": {
"fakeplugin": {"enabled": True, "allowFrom": ["*"]},
}
+1 -1
View File
@@ -130,7 +130,7 @@ def test_webui_forms_have_writable_mattermost_and_whatsapp_contracts() -> None:
assert whatsapp is not None
assert mattermost.route_field_types["serverUrl"] == "string"
assert mattermost.route_field_types["token"] == "secret"
assert whatsapp.route_field_types["proxy"] == "string"
assert whatsapp.route_field_types["useProxy"] == "bool"
assert whatsapp.route_field_types["allowFrom"] == "list"
assert whatsapp.route_field_types["groupPolicy"] == (
"enum",
+8 -7
View File
@@ -911,7 +911,7 @@ def test_provider_login_openai_codex_passes_configured_proxy(monkeypatch):
proxy = "http://127.0.0.1:23458"
monkeypatch.setattr(
"nanobot.config.loader.load_config",
lambda: Config.model_validate({"providers": {"openaiCodex": {"proxy": proxy}}}),
lambda: Config.model_validate({"network": {"proxy": proxy}, "providers": {"openaiCodex": {"useProxy": True}}}),
)
import oauth_cli_kit
@@ -954,7 +954,7 @@ def test_provider_login_openai_codex_uses_explicit_config_proxy(tmp_path, monkey
path = config_path or active_path.get("path")
if path is None:
return Config.model_validate(
{"providers": {"openaiCodex": {"proxy": "http://default-proxy:8080"}}}
{"network": {"proxy": "http://default-proxy:8080"}, "providers": {"openaiCodex": {"useProxy": True}}}
)
return real_load_config(path)
@@ -987,7 +987,7 @@ def test_provider_login_openai_codex_resolves_proxy_env_ref(monkeypatch):
monkeypatch.setattr(
"nanobot.config.loader.load_config",
lambda: Config.model_validate(
{"providers": {"openaiCodex": {"proxy": "${CODEX_PROXY_FOR_TEST}"}}}
{"network": {"proxy": "${CODEX_PROXY_FOR_TEST}"}, "providers": {"openaiCodex": {"useProxy": True}}}
),
)
@@ -1011,7 +1011,7 @@ def test_provider_login_xai_grok_runs_browser_flow_with_configured_proxy(monkeyp
proxy = "http://127.0.0.1:23458"
monkeypatch.setattr(
"nanobot.config.loader.load_config",
lambda: Config.model_validate({"providers": {"xaiGrok": {"proxy": proxy}}}),
lambda: Config.model_validate({"network": {"proxy": proxy}, "providers": {"xaiGrok": {"useProxy": True}}}),
)
monkeypatch.setattr(
"nanobot.providers.xai_oauth.get_xai_oauth_token",
@@ -1326,7 +1326,8 @@ def test_openai_codex_proxy_config_affects_provider_and_signature():
"model": "openai-codex/gpt-5.5",
}
},
"providers": {"openaiCodex": {"proxy": proxy}},
"network": {"proxy": proxy},
"providers": {"openaiCodex": {"useProxy": True}},
}
)
@@ -1355,13 +1356,13 @@ def test_provider_proxy_rejects_unsupported_backend():
"azureOpenai": {
"apiKey": "sk-test",
"apiBase": "https://azure.example/openai/v1",
"proxy": "http://127.0.0.1:23458",
"useProxy": True,
}
},
}
)
with pytest.raises(ValueError, match=r"providers\.azure_openai\.proxy"):
with pytest.raises(ValueError, match=r"providers\.azure_openai\.use_proxy"):
make_provider(config)
+13 -8
View File
@@ -159,10 +159,11 @@ class TestResolveConfig:
proxy = "http://127.0.0.1:23458"
config = Config.model_validate(
{
"network": {"proxy": proxy},
"providers": {
"openaiCodex": {
"apiKey": "codex-secret",
"proxy": proxy,
"useProxy": True,
"extraBody": {"service_tier": "priority"},
},
"groq": {"apiKey": "groq-secret"},
@@ -175,12 +176,13 @@ class TestResolveConfig:
saved = json.loads(config_path.read_text(encoding="utf-8"))
assert saved["providers"]["openaiCodex"] == {
"extraBody": {"service_tier": "priority"},
"proxy": proxy,
"useProxy": True,
}
assert saved["providers"]["groq"]["apiKey"] == "groq-secret"
reloaded = load_config(config_path)
assert reloaded.providers.openai_codex.proxy == proxy
assert reloaded.network.proxy == proxy
assert reloaded.providers.openai_codex.use_proxy is True
assert reloaded.providers.openai_codex.extra_body == {"service_tier": "priority"}
assert reloaded.providers.openai_codex.api_key is None
@@ -189,10 +191,11 @@ class TestResolveConfig:
proxy = "http://127.0.0.1:23458"
config = Config.model_validate(
{
"network": {"proxy": proxy},
"providers": {
"xaiGrok": {
"apiKey": "must-not-be-saved",
"proxy": proxy,
"useProxy": True,
"extraBody": {"parallel_tool_calls": False},
}
}
@@ -204,12 +207,13 @@ class TestResolveConfig:
saved = json.loads(config_path.read_text(encoding="utf-8"))
assert saved["providers"]["xaiGrok"] == {
"extraBody": {"parallel_tool_calls": False},
"proxy": proxy,
"useProxy": True,
}
assert "must-not-be-saved" not in config_path.read_text(encoding="utf-8")
reloaded = load_config(config_path)
assert reloaded.providers.xai_grok.proxy == proxy
assert reloaded.network.proxy == proxy
assert reloaded.providers.xai_grok.use_proxy is True
assert reloaded.providers.xai_grok.extra_body == {"parallel_tool_calls": False}
assert reloaded.providers.xai_grok.api_key is None
@@ -217,6 +221,7 @@ class TestResolveConfig:
config_path = tmp_path / "config.json"
config = Config.model_validate(
{
"network": {"proxy": "http://127.0.0.1:7890"},
"providers": {
"openaiCodex": {
"apiKey": "codex-secret",
@@ -224,7 +229,7 @@ class TestResolveConfig:
},
"xaiGrok": {
"apiKey": "xai-secret",
"proxy": "http://127.0.0.1:7890",
"useProxy": True,
"extraBody": {"parallel_tool_calls": False},
},
}
@@ -239,7 +244,7 @@ class TestResolveConfig:
}
assert saved["providers"]["xaiGrok"] == {
"extraBody": {"parallel_tool_calls": False},
"proxy": "http://127.0.0.1:7890",
"useProxy": True,
}
assert "codex-secret" not in config_path.read_text(encoding="utf-8")
assert "xai-secret" not in config_path.read_text(encoding="utf-8")
+267
View File
@@ -0,0 +1,267 @@
"""One shared address, explicit feature opt-in, and legacy config migration."""
import json
import httpx
import pytest
from nanobot.config.loader import ConfigLoadError, load_config, resolve_config_env_vars, save_config
from nanobot.config.network import NetworkConfig
from nanobot.config.schema import Config
@pytest.mark.parametrize("address", ["http://127.0.0.1:7890", "socks5://user:pass@localhost:1080", "${SHARED_PROXY}"])
def test_legacy_proxy_migrates_once_across_features(tmp_path, address):
path = tmp_path / "config.json"
original = {
"providers": {"openai": {"proxy": address}, "openaiCodex": {"proxy": address}},
"tools": {"web": {"proxy": address}},
"channels": {"telegram": {"proxy": address}, "slack": {"proxy": ""}},
}
path.write_text(json.dumps(original), encoding="utf-8")
config = load_config(path)
assert json.loads(path.read_text(encoding="utf-8")) == original
assert config.network.proxy == address
assert config.providers.openai.use_proxy is True
assert config.providers.openai_codex.use_proxy is True
assert config.tools.web.use_proxy is True
assert config.channels.telegram["useProxy"] is True
assert "useProxy" not in config.channels.slack
config.providers.openai.use_proxy = False
save_config(config, path)
saved = json.loads(path.read_text(encoding="utf-8"))
assert saved["network"]["proxy"] == address
assert "proxy" not in saved["providers"]["openai"]
assert "proxy" not in saved["tools"]["web"]
assert "proxy" not in saved["channels"]["telegram"]
assert load_config(path).providers.openai.use_proxy is False
def test_multiple_legacy_addresses_require_one_explicit_global_address(tmp_path):
path = tmp_path / "config.json"
original = {"tools": {"web": {"proxy": "http://secret:password@localhost:7890"}}, "channels": {"discord": {"proxy": "http://localhost:7891"}}}
path.write_text(json.dumps(original), encoding="utf-8")
with pytest.raises(ConfigLoadError, match="Multiple legacy proxy addresses") as caught:
load_config(path)
assert "secret" not in str(caught.value)
assert json.loads(path.read_text(encoding="utf-8")) == original
original["network"] = {"proxy": "http://localhost:7892"}
path.write_text(json.dumps(original), encoding="utf-8")
config = load_config(path)
assert config.network.proxy == "http://localhost:7892"
assert config.tools.web.use_proxy is True
assert config.channels.discord["useProxy"] is True
def test_discord_proxy_credentials_move_into_the_shared_url(tmp_path):
path = tmp_path / "config.json"
path.write_text(json.dumps({"channels": {"discord": {"proxy": "localhost:7890", "proxyUsername": "user@host", "proxyPassword": "pass:word"}}}), encoding="utf-8")
config = load_config(path)
assert config.network.proxy == "http://user%40host:pass%3Aword@localhost:7890"
assert config.channels.discord == {"useProxy": True}
def test_proxy_opt_in_does_not_fall_back_when_unconfigured():
network = NetworkConfig()
assert network.resolve_proxy(False) is None
with pytest.raises(ValueError, match="Advanced"):
network.resolve_proxy(True)
def test_shared_proxy_environment_reference_stays_unresolved_on_disk(tmp_path, monkeypatch):
monkeypatch.setenv("SHARED_PROXY", "http://localhost:7890")
config = Config(network=NetworkConfig(proxy="${SHARED_PROXY}"))
config.tools.web.use_proxy = True
resolved = resolve_config_env_vars(config)
assert resolved.network.resolve_proxy(True) == "http://localhost:7890"
assert config.network.proxy == "${SHARED_PROXY}"
path = tmp_path / "config.json"
save_config(config, path)
assert load_config(path).network.proxy == "${SHARED_PROXY}"
@pytest.mark.parametrize("address", ["file:///tmp/proxy", "http://host:99999", "http://host/path", "http://user:secret@["])
def test_invalid_shared_proxy_has_a_safe_error(address):
with pytest.raises(ValueError, match="proxy URL") as caught:
NetworkConfig.normalize_proxy(address)
assert address not in str(caught.value)
@pytest.mark.parametrize("file_present", [False, True])
def test_environment_legacy_proxy_migrates_after_source_merge(tmp_path, monkeypatch, file_present):
proxy = "http://localhost:7890"
monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({"openai": {"proxy": proxy}}))
monkeypatch.setenv("NANOBOT_TOOLS", json.dumps({"web": {"proxy": proxy}}))
monkeypatch.setenv("NANOBOT_CHANNELS", json.dumps({"telegram": {"proxy": proxy}}))
path = tmp_path / "config.json"
if file_present:
path.write_text(json.dumps({"providers": {"openai": {"apiKey": "test-key"}}}), encoding="utf-8")
config = load_config(path)
assert config.network.proxy == proxy
assert config.providers.openai.use_proxy is True
assert config.tools.web.use_proxy is True
assert config.channels.telegram == {"useProxy": True}
save_config(config, path)
saved = json.loads(path.read_text(encoding="utf-8"))
assert saved["network"]["proxy"] == proxy
assert "proxy" not in saved["providers"]["openai"]
config.providers.openai.use_proxy = False
save_config(config, path)
assert load_config(path).providers.openai.use_proxy is False
def test_file_proxy_and_opt_out_take_precedence_over_environment(tmp_path, monkeypatch):
monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({"openai": {"proxy": "http://environment:7890"}}))
path = tmp_path / "config.json"
path.write_text(json.dumps({"providers": {"openai": {"proxy": "http://file:7891", "useProxy": False}}}), encoding="utf-8")
config = load_config(path)
assert config.network.proxy == "http://file:7891"
assert config.providers.openai.use_proxy is False
@pytest.mark.parametrize("password", ["a/b", "a#b?c", "a@b:c%"])
def test_discord_credential_references_are_escaped_without_persisting_secrets(tmp_path, monkeypatch, password):
from urllib.parse import unquote, urlsplit
monkeypatch.setenv("PROXY_USER", "alice@example")
monkeypatch.setenv("PROXY_PASSWORD", password)
path = tmp_path / "config.json"
path.write_text(json.dumps({"channels": {"discord": {"proxy": "http://localhost:7890", "proxyUsername": "${PROXY_USER}", "proxyPassword": "${PROXY_PASSWORD}"}}}), encoding="utf-8")
config = load_config(path)
for network in (config.network, resolve_config_env_vars(config).network):
proxy = network.resolve_proxy(True)
parsed = urlsplit(proxy)
assert parsed.hostname == "localhost"
assert parsed.port == 7890
assert unquote(parsed.username) == "alice@example"
assert unquote(parsed.password) == password
save_config(config, path)
saved = json.loads(path.read_text(encoding="utf-8"))
assert saved["network"]["proxy"] == "http://${PROXY_USER}:${PROXY_PASSWORD}@localhost:7890"
assert "alice@example" not in path.read_text(encoding="utf-8")
assert load_config(path).network.resolve_proxy(True) == config.network.resolve_proxy(True)
def test_whole_discord_url_reference_with_separate_credentials_requires_consolidation(tmp_path, monkeypatch):
monkeypatch.setenv("DISCORD_PROXY", "http://localhost:7890")
original = {"channels": {"discord": {"proxy": "${DISCORD_PROXY}", "proxyUsername": "alice", "proxyPassword": "secret-password"}}}
path = tmp_path / "config.json"
path.write_text(json.dumps(original), encoding="utf-8")
with pytest.raises(ConfigLoadError, match="one full URL environment variable") as caught:
load_config(path)
assert "secret-password" not in str(caught.value)
assert json.loads(path.read_text(encoding="utf-8")) == original
original["network"] = {"proxy": "${SHARED_PROXY}"}
path.write_text(json.dumps(original), encoding="utf-8")
config = load_config(path)
assert config.network.proxy == "${SHARED_PROXY}"
assert config.channels.discord == {"useProxy": True}
@pytest.mark.parametrize("alias, attribute", [("openaiCodex", "openai_codex"), ("xaiGrok", "xai_grok")])
@pytest.mark.parametrize("saved_opt_out", [True, False], ids=["refresh", "changed-setting"])
def test_oauth_proxy_opt_out_survives_save_with_legacy_environment(tmp_path, monkeypatch, alias, attribute, saved_opt_out):
proxy = "http://proxy.example:8080"
monkeypatch.setenv("NANOBOT_PROVIDERS", json.dumps({alias: {"proxy": proxy, "apiKey": "oauth-secret"}}))
original = {"network": {"proxy": proxy}, "providers": {alias: {"useProxy": False} if saved_opt_out else {}}}
path = tmp_path / "config.json"
path.write_text(json.dumps(original), encoding="utf-8")
config = load_config(path)
provider = getattr(config.providers, attribute)
assert provider.use_proxy is (not saved_opt_out)
assert json.loads(path.read_text(encoding="utf-8")) == original
if not saved_opt_out:
provider.use_proxy = False
save_config(config, path)
saved = json.loads(path.read_text(encoding="utf-8"))
assert saved["providers"][alias] == {"useProxy": False}
assert "oauth-secret" not in path.read_text(encoding="utf-8")
assert getattr(load_config(path).providers, attribute).use_proxy is False
@pytest.mark.parametrize("legacy", [False, True], ids=["shared", "legacy"])
@pytest.mark.parametrize(
"userinfo, environment, expected_auth",
[
("${PROXY_AUTH}", {"PROXY_AUTH": "alice:pw"}, (b"alice", b"pw")),
("${PROXY_AUTH}", {"PROXY_AUTH": "alice%40mail:p%2Fa%23b%3Fc%40d%3Ae%2525f"}, (b"alice@mail", b"p/a#b?c@d:e%25f")),
("${PROXY_AUTH}", {"PROXY_AUTH": "alice:p/a#b?c@d:e%f"}, (b"alice", b"p/a#b?c@d:e%f")),
(
"${PROXY_USER}:${PROXY_PASSWORD}",
{"PROXY_USER": "alice/a#b?c@d:e%25f", "PROXY_PASSWORD": "p/a#b?c@d:e%25f"},
(b"alice/a#b?c@d:e%25f", b"p/a#b?c@d:e%25f"),
),
],
ids=["combined-auth", "combined-encoded-auth", "combined-special-password", "credential-components"],
)
def test_proxy_userinfo_references_round_trip_with_httpx_auth(tmp_path, monkeypatch, legacy, userinfo, environment, expected_auth):
for name, value in environment.items():
monkeypatch.setenv(name, value)
template = f"http://{userinfo}@proxy.example:8080"
original = {"providers": {"openai": {"proxy": template}}} if legacy else {
"network": {"proxy": template}, "providers": {"openai": {"useProxy": True}},
}
path = tmp_path / "config.json"
path.write_text(json.dumps(original), encoding="utf-8")
config = load_config(path)
assert config.network.proxy == template
assert config.providers.openai.use_proxy is True
for current in (config, resolve_config_env_vars(config)):
assert httpx.Proxy(current.network.resolve_proxy(current.providers.openai.use_proxy)).raw_auth == expected_auth
assert json.loads(path.read_text(encoding="utf-8")) == original
save_config(config, path)
saved_text = path.read_text(encoding="utf-8")
assert json.loads(saved_text)["network"]["proxy"] == template
for value in environment.values():
assert value not in saved_text
reloaded = load_config(path)
assert reloaded.network.proxy == template
assert httpx.Proxy(resolve_config_env_vars(reloaded).network.resolve_proxy(True)).raw_auth == expected_auth
@pytest.mark.parametrize("address", ["${PROXY_SCHEME}://proxy.example:8080", "${PROXY_SCHEME}://${PROXY_HOST}:8080", "http://${PROXY_HOST}:8080"])
@pytest.mark.parametrize("credential_refs", [False, True], ids=["literal-auth", "referenced-auth"])
def test_discord_partial_url_reference_migrates_without_resolving_on_disk(tmp_path, monkeypatch, address, credential_refs):
from urllib.parse import quote
username = "alice/a#b?c@d:e%25f"
password = "p/a#b?c@d:e%25f"
monkeypatch.setenv("PROXY_SCHEME", "http")
monkeypatch.setenv("PROXY_HOST", "proxy.example")
monkeypatch.setenv("PROXY_USER", username)
monkeypatch.setenv("PROXY_PASSWORD", password)
user_template = "${PROXY_USER}" if credential_refs else quote(username, safe="")
password_template = "${PROXY_PASSWORD}" if credential_refs else quote(password, safe="")
scheme, host = address.split("://", 1)
expected_template = f"{scheme}://{user_template}:{password_template}@{host}"
original = {"channels": {"discord": {
"proxy": address,
"proxyUsername": "${PROXY_USER}" if credential_refs else username,
"proxyPassword": "${PROXY_PASSWORD}" if credential_refs else password,
}}}
path = tmp_path / "config.json"
path.write_text(json.dumps(original), encoding="utf-8")
config = load_config(path)
assert config.network.proxy == expected_template
assert config.channels.discord == {"useProxy": True}
assert json.loads(path.read_text(encoding="utf-8")) == original
for network in (config.network, resolve_config_env_vars(config).network):
proxy = httpx.Proxy(network.resolve_proxy(True))
assert proxy.url.host == "proxy.example"
assert proxy.url.port == 8080
assert proxy.raw_auth == (username.encode(), password.encode())
save_config(config, path)
saved_text = path.read_text(encoding="utf-8")
assert json.loads(saved_text)["network"]["proxy"] == expected_template
if credential_refs:
assert username not in saved_text
assert password not in saved_text
reloaded = load_config(path)
assert reloaded.network.proxy == expected_template
assert httpx.Proxy(resolve_config_env_vars(reloaded).network.resolve_proxy(True)).raw_auth == (username.encode(), password.encode())
+3 -2
View File
@@ -602,7 +602,8 @@ async def test_custom_messages_uses_its_proxy_and_does_not_inherit_native_creden
config = _config()
connection = config.get_provider(preset=config.model_presets["messages"])
connection.api_key = None
connection.proxy = "http://proxy.test:8080"
config.network.proxy = "http://proxy.test:8080"
connection.use_proxy = True
monkeypatch.setenv("ANTHROPIC_API_KEY", "native-key")
monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "native-token")
requests = []
@@ -612,7 +613,7 @@ async def test_custom_messages_uses_its_proxy_and_does_not_inherit_native_creden
return _answer(request)
def transport(**kwargs):
assert kwargs.pop("proxy") == connection.proxy
assert kwargs.pop("proxy") == config.network.proxy
assert kwargs["trust_env"] is False
return DefaultAsyncHttpxClient(transport=httpx.MockTransport(handler), **kwargs)
+2 -1
View File
@@ -417,9 +417,10 @@ async def test_factory_builds_xai_provider_and_applies_explicit_body_overrides(m
"provider": "xai_grok",
}
},
"network": {"proxy": "http://127.0.0.1:7890"},
"providers": {
"xaiGrok": {
"proxy": "http://127.0.0.1:7890",
"useProxy": True,
"extraBody": {
"parallel_tool_calls": False,
"max_turns": 2,
+3 -1
View File
@@ -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()
+23 -25
View File
@@ -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()
+275
View File
@@ -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 == []
+270 -9
View File
@@ -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()
+3 -3
View File
@@ -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
@@ -34,7 +34,8 @@
"tools.max_session_messages_per_minute",
"tools.webui_allow_remote_package_install",
"tools.web.enable",
"tools.web.proxy",
"network.proxy",
"tools.web.use_proxy",
"tools.web.user_agent",
"tools.image_generation.save_dir",
"api.host",
+20 -7
View File
@@ -4,6 +4,7 @@ import asyncio
import pytest
from nanobot.config.network import NetworkConfig
from nanobot.config.schema import MCPServerConfig
from nanobot.runtime_admission import RuntimeAdmission, RuntimeBusyError, RuntimeMaintenanceError
from nanobot.webui.mcp_oauth_api import (
@@ -50,14 +51,19 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_
connection = _Connection()
received: dict[str, object] = {}
reload_calls = 0
cfg = _config()
cfg.use_proxy = True
network_config = NetworkConfig(proxy="http://proxy-a.example:8080")
monkeypatch.setattr(
"nanobot.webui.mcp_oauth_api.validate_url_target",
lambda _url: (True, ""),
)
async def connect(servers, _registry, *, oauth_handlers):
async def connect(servers, _registry, *, oauth_handlers, network):
assert set(servers) == {"xmind"}
received["cfg"] = servers["xmind"]
received["network"] = network
handlers = oauth_handlers["xmind"]
await handlers.redirect_handler(
"https://accounts.example.com/authorize?client_id=test&state=state-123"
@@ -86,13 +92,20 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_
started = await manager.start(
"xmind",
_config(),
cfg,
"https://agent.example.com/auth/mcp/callback",
reload_mcp=reload_mcp,
network=network_config,
)
assert started["status"] == "authorization_required"
assert started["authorization_url"].startswith("https://accounts.example.com/authorize?")
cfg.use_proxy = False
network_config.proxy = "http://proxy-b.example:8080"
assert received["cfg"] is not cfg
assert received["cfg"].use_proxy is True
assert received["network"] is not network_config
assert received["network"].proxy == "http://proxy-a.example:8080"
manager.submit_callback(state="state-123", code="oauth-code", error=None)
with pytest.raises(McpOAuthError, match="expired"):
manager.submit_callback(state="state-123", code="replayed-code", error=None)
@@ -135,7 +148,7 @@ async def test_browser_flow_activates_tools_before_probe_cleanup_completes(
lambda _url: (True, ""),
)
async def connect(_servers, _registry, *, oauth_handlers):
async def connect(_servers, _registry, *, oauth_handlers, network):
handlers = oauth_handlers["linear"]
await handlers.redirect_handler(
"https://accounts.example.com/authorize?client_id=test&state=blocked-close"
@@ -202,7 +215,7 @@ async def test_browser_flow_remains_busy_through_cancelled_or_expired_cleanup(
if expire:
monkeypatch.setattr("nanobot.webui.mcp_oauth_api._FLOW_TTL_S", 0)
async def connect(_servers, _registry, *, oauth_handlers):
async def connect(_servers, _registry, *, oauth_handlers, network):
handlers = oauth_handlers["linear"]
await handlers.redirect_handler("https://accounts.example.com/auth?state=pending")
try:
@@ -256,7 +269,7 @@ async def test_remote_http_flow_accepts_a_pasted_loopback_callback(
lambda _url: (True, ""),
)
async def connect(_servers, _registry, *, oauth_handlers):
async def connect(_servers, _registry, *, oauth_handlers, network):
handlers = oauth_handlers["linear"]
received["redirect_uri"] = handlers.redirect_uri
await handlers.redirect_handler(
@@ -329,7 +342,7 @@ async def test_browser_flow_surfaces_provider_denial_without_callback_descriptio
lambda _url: (True, ""),
)
async def connect(_servers, _registry, *, oauth_handlers):
async def connect(_servers, _registry, *, oauth_handlers, network):
handlers = oauth_handlers["notion"]
await handlers.redirect_handler("https://accounts.example.com/auth?state=deny-state")
await handlers.callback_handler()
@@ -375,7 +388,7 @@ async def test_browser_flow_blocks_unsafe_authorization_url(
lambda _url: (url_is_safe, "private address"),
)
async def connect(_servers, _registry, *, oauth_handlers):
async def connect(_servers, _registry, *, oauth_handlers, network):
await oauth_handlers["linear"].redirect_handler(authorization_url)
return {}
+149 -5
View File
@@ -359,11 +359,12 @@ def test_instance_oauth_setup_saves_endpoint_before_authorization(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_use_config(tmp_path, monkeypatch)
name, cfg = ensure_mcp_oauth_server(
name, cfg, network = ensure_mcp_oauth_server(
{"name": ["metabase"], "mcp_url": ["https://analytics.example.com/api/metabase-mcp"]}
)
assert name == "metabase"
assert cfg.auth == "oauth"
assert network == load_config().network
assert cfg.url == "https://analytics.example.com/api/metabase-mcp"
row = next(item for item in mcp_presets_payload()["presets"] if item["name"] == name)
assert row["installed"] is True
@@ -372,7 +373,7 @@ def test_instance_oauth_setup_saves_endpoint_before_authorization(
config = load_config()
config.tools.mcp_servers[name].enabled_tools = ["search"]
save_config(config)
_, updated = ensure_mcp_oauth_server(
_, updated, _network = ensure_mcp_oauth_server(
{"name": [name], "mcp_url": ["https://other.example.com/api/metabase-mcp"]}
)
assert updated.url == "https://other.example.com/api/metabase-mcp"
@@ -615,7 +616,7 @@ def test_test_mcp_preset_connects_and_reports_tools(
async def aclose(self) -> None:
return None
async def fake_connect(servers, registry):
async def fake_connect(servers, registry, *, network):
assert list(servers) == ["playwright"]
class FakeTool:
@@ -652,7 +653,7 @@ def test_test_mcp_preset_inspects_tools_outside_the_enabled_allowlist(
async def aclose(self) -> None:
return None
async def fake_connect(servers, registry):
async def fake_connect(servers, registry, *, network):
assert servers["playwright"].enabled_tools == ["*"]
class FakeTool:
@@ -689,7 +690,7 @@ def test_test_mcp_preset_scrubs_connection_errors(
},
)
async def fake_connect(_servers, _registry):
async def fake_connect(_servers, _registry, *, network):
raise RuntimeError("failed https://mcp.browserbase.com/mcp?browserbaseApiKey=bb_live_secret")
monkeypatch.setattr("nanobot.agent.tools.mcp.connect_mcp_servers", fake_connect)
@@ -930,3 +931,146 @@ def test_normalize_mcp_mentions_uses_explicit_gateway_config(
)
assert payload == [{"name": "gateway-docs", "display_name": "Gateway docs"}]
@pytest.mark.parametrize("installed", [False, True], ids=["first-authorization", "existing-preset"])
def test_oauth_setup_persists_proxy_choice_without_credential_fields(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
installed: bool,
) -> None:
_use_config(tmp_path, monkeypatch)
config = load_config()
config.network.proxy = "http://shared.example:8080"
save_config(config)
if installed:
mcp_presets_action("enable", {"name": ["xmind"]})
name, cfg, network = ensure_mcp_oauth_server({
"name": ["xmind"], "use_proxy": ["true"],
})
assert name == "xmind"
assert cfg.use_proxy is True
assert cfg.auth == "oauth"
assert network.proxy == "http://shared.example:8080"
assert load_config().tools.mcp_servers[name].use_proxy is True
payload = mcp_presets_payload()
row = next(item for item in payload["presets"] if item["name"] == name)
assert row["use_proxy"] is True
assert row["status"] == "authorization_required"
assert payload["proxy_configured"] is True
assert "shared.example" not in json.dumps(payload)
_, updated, _ = ensure_mcp_oauth_server({"name": [name], "use_proxy": ["false"]})
assert updated.use_proxy is False
assert load_config().tools.mcp_servers[name].use_proxy is False
@pytest.mark.parametrize("name", ["xmind", "custom-docs"])
def test_proxy_action_preserves_existing_server_and_materializes_presets(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
name: str,
) -> None:
_use_config(tmp_path, monkeypatch)
config = load_config()
config.network.proxy = "http://shared.example:8080"
save_config(config)
if name == "custom-docs":
custom_mcp_action("custom", {
"name": [name], "url": ["https://docs.example.com/mcp"],
"headers": ['{"Authorization": "Bearer preserved-secret"}'],
"enabled_tools": ['["search"]'], "tool_timeout": ["90"],
})
payload = mcp_presets_action("proxy", {"name": [name], "use_proxy": ["true"]})
before = load_config().tools.mcp_servers[name]
assert before.use_proxy is True
assert payload["requires_restart"] is True
assert next(row for row in payload["presets"] if row["name"] == name)["use_proxy"] is True
mcp_presets_action("proxy", {"name": [name], "use_proxy": ["false"]})
after = load_config().tools.mcp_servers[name]
assert after.use_proxy is False
assert after.model_dump(exclude={"use_proxy"}) == before.model_dump(exclude={"use_proxy"})
if name == "custom-docs":
assert after.headers == {"Authorization": "Bearer preserved-secret"}
assert after.enabled_tools == ["search"]
assert after.tool_timeout == 90
@pytest.mark.parametrize("transport", ["sse", "streamableHttp"])
def test_custom_server_saves_explicit_proxy_flag(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
transport: str,
) -> None:
_use_config(tmp_path, monkeypatch)
config = load_config()
config.network.proxy = "http://shared.example:8080"
save_config(config)
payload = custom_mcp_action("custom", {
"name": ["company-docs"], "transport": [transport],
"url": ["https://docs.example.com/mcp"], "use_proxy": ["true"],
})
assert load_config().tools.mcp_servers["company-docs"].use_proxy is True
assert next(row for row in payload["presets"] if row["name"] == "company-docs")["use_proxy"] is True
@pytest.mark.parametrize("use_proxy", [False, True])
def test_import_preserves_boolean_proxy_flag(tmp_path, monkeypatch, use_proxy: bool) -> None:
_use_config(tmp_path, monkeypatch)
config = load_config()
config.network.proxy = "http://shared.example:8080"
save_config(config)
custom_mcp_action("import", {"config": [json.dumps({"mcpServers": {
"company-docs": {"url": "https://docs.example.com/mcp", "useProxy": use_proxy},
}})]})
assert load_config().tools.mcp_servers["company-docs"].use_proxy is use_proxy
@pytest.mark.parametrize("invalid", ["true", "false", 1, None])
def test_import_rejects_nonboolean_proxy_flag_without_saving(tmp_path, monkeypatch, invalid) -> None:
_use_config(tmp_path, monkeypatch)
with pytest.raises(McpPresetError, match="useProxy must be a boolean"):
custom_mcp_action("import", {"config": [json.dumps({"mcpServers": {
"valid-first": {"url": "https://docs.example.com/mcp"},
"bad-flag": {"url": "https://docs.example.com/mcp", "useProxy": invalid},
}})]})
assert load_config().tools.mcp_servers == {}
@pytest.mark.parametrize("action", ["enable", "proxy", "oauth", "custom", "import"])
def test_explicit_proxy_requires_shared_address_before_saving(tmp_path, monkeypatch, action) -> None:
_use_config(tmp_path, monkeypatch)
with pytest.raises(McpPresetError, match="Configure the shared proxy"):
if action == "oauth":
ensure_mcp_oauth_server({"name": ["xmind"], "use_proxy": ["true"]})
elif action == "custom":
custom_mcp_action("custom", {
"name": ["company-docs"], "url": ["https://docs.example.com/mcp"],
"use_proxy": ["true"],
})
elif action == "import":
custom_mcp_action("import", {"config": [json.dumps({
"company-docs": {"url": "https://docs.example.com/mcp", "useProxy": True},
})]})
else:
mcp_presets_action(action, {"name": ["xmind"], "use_proxy": ["true"]})
assert load_config().tools.mcp_servers == {}
assert mcp_presets_payload()["proxy_configured"] is False
def test_enable_preset_preserves_proxy_choice_on_later_enable(tmp_path, monkeypatch) -> None:
_use_config(tmp_path, monkeypatch)
config = load_config()
config.network.proxy = "http://shared.example:8080"
save_config(config)
mcp_presets_action("enable", {"name": ["xmind"], "use_proxy": ["true"]})
assert load_config().tools.mcp_servers["xmind"].use_proxy is True
mcp_presets_action("enable", {"name": ["xmind"]})
assert load_config().tools.mcp_servers["xmind"].use_proxy is True
mcp_presets_action("enable", {"name": ["xmind"], "use_proxy": ["false"]})
assert load_config().tools.mcp_servers["xmind"].use_proxy is False
+22 -18
View File
@@ -906,7 +906,8 @@ def test_create_provider_settings_persists_custom_advanced_options(
monkeypatch: pytest.MonkeyPatch,
) -> None:
config_path = tmp_path / "config.json"
save_config(Config(), config_path)
config = Config.model_validate({"network": {"proxy": "http://127.0.0.1:7890"}})
save_config(config, config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
payload = create_provider_settings(
@@ -914,7 +915,7 @@ def test_create_provider_settings_persists_custom_advanced_options(
"name": ["Company Gateway"],
"apiBase": ["https://gateway.example/v1"],
"apiKey": ["sk-company"],
"proxy": ["http://127.0.0.1:7890"],
"use_proxy": ["true"],
"extraHeaders": [json.dumps({"X-Tenant": "engineering"})],
"extraBody": [json.dumps({"service_tier": "priority"})],
"extraQuery": [json.dumps({"api-version": "2026-01-01"})],
@@ -930,7 +931,7 @@ def test_create_provider_settings_persists_custom_advanced_options(
"extra_headers",
"extra_body",
"extra_query",
"proxy",
"use_proxy",
"thinking_style",
]
assert row["extra_headers"] == {"X-Tenant": "engineering"}
@@ -941,7 +942,8 @@ def test_create_provider_settings_persists_custom_advanced_options(
assert saved.display_name == "Company Gateway"
assert saved.api_key == "sk-company"
assert saved.api_base == "https://gateway.example/v1"
assert saved.proxy == "http://127.0.0.1:7890"
assert saved.use_proxy is True
assert load_config(config_path).network.proxy == "http://127.0.0.1:7890"
assert saved.extra_headers == {"X-Tenant": "engineering"}
assert saved.extra_body == {"service_tier": "priority"}
assert saved.extra_query == {"api-version": "2026-01-01"}
@@ -1023,6 +1025,7 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(
config_path = tmp_path / "config.json"
config = Config()
config.providers.openai.api_key = "sk-openai"
config.network.proxy = "http://127.0.0.1:7890"
save_config(config, config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
@@ -1030,7 +1033,7 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(
{
"provider": ["openai"],
"apiType": ["responses"],
"proxy": ["http://127.0.0.1:7890"],
"use_proxy": ["true"],
"extraHeaders": [json.dumps({"X-Trace": "enabled"})],
"extraBody": [json.dumps({"service_tier": "priority"})],
"extraQuery": [json.dumps({"trace": "true"})],
@@ -1047,7 +1050,8 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(
saved = load_config(config_path)
assert saved.providers.openai.api.to_capabilities().preferred_api == "responses"
assert saved.providers.openai.proxy == "http://127.0.0.1:7890"
assert saved.providers.openai.use_proxy is True
assert saved.network.proxy == "http://127.0.0.1:7890"
assert saved.providers.openai.extra_headers == {"X-Trace": "enabled"}
assert saved.providers.openai.extra_body == {"service_tier": "priority"}
assert saved.providers.openai.extra_query == {"trace": "true"}
@@ -1071,7 +1075,7 @@ def test_update_provider_settings_updates_and_clears_oauth_proxy(
) -> None:
config_path = tmp_path / "config.json"
config = Config()
getattr(config.providers, config_attr).proxy = "http://127.0.0.1:7000"
config.network.proxy = "http://127.0.0.1:7890"
save_config(config, config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
monkeypatch.setattr(
@@ -1087,24 +1091,24 @@ def test_update_provider_settings_updates_and_clears_oauth_proxy(
payload = update_provider_settings(
{
"provider": [provider_name],
"proxy": [" http://127.0.0.1:7890 "],
"use_proxy": ["true"],
"extraBody": [json.dumps({"tools": []})],
}
)
providers = {row["name"]: row for row in payload["providers"]}
assert providers[provider_name]["proxy"] == "http://127.0.0.1:7890"
assert getattr(load_config(config_path).providers, config_attr).proxy == (
"http://127.0.0.1:7890"
)
assert providers[provider_name]["use_proxy"] is True
assert getattr(load_config(config_path).providers, config_attr).use_proxy is True
assert load_config(config_path).network.proxy == "http://127.0.0.1:7890"
assert providers[provider_name]["extra_body"] == {"tools": []}
assert getattr(load_config(config_path).providers, config_attr).extra_body == {"tools": []}
cleared = update_provider_settings({"provider": [provider_name], "proxy": [" "]})
cleared = update_provider_settings({"provider": [provider_name], "use_proxy": ["false"]})
providers = {row["name"]: row for row in cleared["providers"]}
assert providers[provider_name]["proxy"] is None
assert getattr(load_config(config_path).providers, config_attr).proxy is None
assert providers[provider_name]["use_proxy"] is False
assert getattr(load_config(config_path).providers, config_attr).use_proxy is False
assert load_config(config_path).network.proxy == "http://127.0.0.1:7890"
def test_update_provider_settings_keeps_oauth_credentials_read_only(
@@ -1115,7 +1119,7 @@ def test_update_provider_settings_keeps_oauth_credentials_read_only(
save_config(Config(), config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
with pytest.raises(WebUISettingsError, match="only supports proxy and extra_body settings"):
with pytest.raises(WebUISettingsError, match="only supports use_proxy and extra_body settings"):
update_provider_settings({"provider": ["openai_codex"], "apiKey": ["not-allowed"]})
@@ -1930,7 +1934,7 @@ def test_openai_codex_oauth_login_passes_configured_proxy(
proxy = "http://127.0.0.1:23458"
config_path = tmp_path / "config.json"
save_config(
Config.model_validate({"providers": {"openaiCodex": {"proxy": "${CODEX_PROXY_TEST}"}}}),
Config.model_validate({"network": {"proxy": "${CODEX_PROXY_TEST}"}, "providers": {"openaiCodex": {"useProxy": True}}}),
config_path,
)
monkeypatch.setenv("CODEX_PROXY_TEST", proxy)
@@ -2112,7 +2116,7 @@ def test_xai_grok_login_starts_fresh_browser_flow_with_proxy(
) -> None:
proxy = "http://127.0.0.1:23458"
config_path = tmp_path / "config.json"
save_config(Config.model_validate({"providers": {"xaiGrok": {"proxy": proxy}}}), config_path)
save_config(Config.model_validate({"network": {"proxy": proxy}, "providers": {"xaiGrok": {"useProxy": True}}}), config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
captured: dict[str, object] = {}
+106 -3
View File
@@ -14,6 +14,7 @@ from websockets.datastructures import Headers
from nanobot.bus.queue import MessageBus
from nanobot.config.loader import get_config_path
from nanobot.config.network import NetworkConfig
from nanobot.config.schema import MCPServerConfig
from nanobot.runtime_admission import RuntimeBusyError
from nanobot.webui.http_utils import http_json_response
@@ -413,12 +414,12 @@ async def test_settings_shutdown_joins_browser_authorization_and_releases_admiss
config = MCPServerConfig(type="streamableHttp", auth="oauth", url="https://mcp.example/mcp")
monkeypatch.setattr(
"nanobot.webui.settings_routes.ensure_mcp_oauth_server",
lambda _query, *, config_path=None: ("linear", config),
lambda _query, *, config_path=None: ("linear", config, NetworkConfig()),
)
monkeypatch.setattr("nanobot.webui.mcp_oauth_api.validate_url_target", lambda _: (True, ""))
cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event()
async def connect(_servers, _registry, *, oauth_handlers):
async def connect(_servers, _registry, *, oauth_handlers, network):
handlers = oauth_handlers["linear"]
await handlers.redirect_handler("https://accounts.example/authorize?state=settings")
try:
@@ -457,9 +458,10 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke
auth="oauth",
url="https://app.xmind.com/api/mcp",
)
network = SimpleNamespace(proxy="http://shared.example:8080")
monkeypatch.setattr(
"nanobot.webui.settings_routes.ensure_mcp_oauth_server",
lambda _query, *, config_path=None: ("xmind", config),
lambda _query, *, config_path=None: ("xmind", config, network),
)
router = _router()
start = AsyncMock(return_value={
@@ -484,6 +486,7 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke
config,
"https://gateway.example/auth/mcp/callback",
reload_mcp=ANY,
network=network,
reset_credentials=False,
)
@@ -1040,3 +1043,103 @@ async def test_image_switch_round_trip_clears_restart(tmp_path, enabled):
reverted = await router.dispatch(None, _mutation_request(path, {"enabled": enabled}), path)
assert json.loads(reverted.body)["requires_restart"] is False
assert json.loads(reverted.body)["restart_required_sections"] == []
@pytest.mark.asyncio
async def test_first_mcp_oauth_request_saves_proxy_flag_before_starting_flow(tmp_path) -> None:
from nanobot.config.loader import load_config
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps({
"network": {"proxy": "http://shared.example:8080"},
"agents": {"defaults": {"workspace": str(tmp_path / "workspace")}},
}), encoding="utf-8")
router = _router(config_path=config_path)
captured = {}
async def start(name, cfg, redirect_uri, *, reload_mcp, network, reset_credentials):
saved = load_config(config_path)
assert name == "xmind"
assert cfg.auth == "oauth"
assert cfg.use_proxy is True
assert saved.tools.mcp_servers[name].use_proxy is True
assert network == saved.network
captured["network"] = network.proxy
return {"status": "authorization_required", "name": name, "flow_id": "first-flow"}
router._mcp_oauth = SimpleNamespace(start=start)
request = _mutation_request(
"/api/settings/mcp-oauth/start",
{"name": "xmind", "use_proxy": True},
)
response = await router.dispatch(None, request, "/api/settings/mcp-oauth/start")
assert response is not None
assert response.status_code == 200
assert json.loads(response.body)["flow_id"] == "first-flow"
assert captured == {"network": "http://shared.example:8080"}
@pytest.mark.asyncio
@pytest.mark.parametrize("use_proxy", [True, False])
async def test_mcp_proxy_mutation_persists_reloads_and_keeps_oauth_credentials(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, use_proxy: bool,
) -> None:
from mcp.shared.auth import OAuthToken
from websockets.http11 import Request
from nanobot.agent.tools.mcp_oauth import MCPOAuthStorage
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.config.loader import load_config, save_config
from nanobot.config.schema import Config
from nanobot.webui.gateway_services import build_gateway_services
monkeypatch.setattr("nanobot.agent.tools.mcp_oauth.get_data_dir", lambda: tmp_path)
config_path = tmp_path / "config.json"
config = Config.model_validate({
"network": {"proxy": "http://proxy.example:8080"},
"tools": {"mcpServers": {"team-docs": {
"type": "streamableHttp", "auth": "oauth",
"url": "https://mcp.example.com/mcp", "useProxy": not use_proxy,
"headers": {"X-Organization": "team"}, "enabledTools": ["read"],
}}},
})
save_config(config, config_path)
original = config.tools.mcp_servers["team-docs"].model_copy(deep=True)
storage = MCPOAuthStorage("team-docs", original.url)
await storage.set_tokens(OAuthToken(access_token="synthetic-access", token_type="Bearer"))
async def reload_mcp() -> dict[str, object]:
assert load_config(config_path).tools.mcp_servers["team-docs"].use_proxy is use_proxy
return {"ok": True, "connected": ["team-docs"], "requires_restart": False}
reload = AsyncMock(side_effect=reload_mcp)
gateway = build_gateway_services(
config=WebSocketConfig(), bus=MessageBus(), session_manager=None,
static_dist_path=None, workspace_path=tmp_path, config_path=config_path,
default_restrict_to_workspace=True, runtime_model_name=None,
runtime_surface="browser", runtime_capabilities_overrides=None, mcp_reload=reload,
)
connection = SimpleNamespace(
remote_address=("127.0.0.1", 12345),
request=Request("/", Headers({"Host": "127.0.0.1:8765"})),
)
path = "/api/settings/mcp-presets/proxy"
try:
http_response = await gateway.http.dispatch(connection, Request(path, Headers()))
assert http_response.status_code == 405
response = await gateway.http.dispatch_webui_mutation(
connection, "settings.mcp.proxy", {"name": "team-docs", "use_proxy": str(use_proxy).lower()},
)
assert response.status_code == 200
payload = json.loads(response.body)
assert payload["hot_reload"]["ok"] is True
assert payload["requires_restart"] is False
row = next(row for row in payload["presets"] if row["name"] == "team-docs")
assert row["use_proxy"] is use_proxy
assert load_config(config_path).tools.mcp_servers["team-docs"] == original.model_copy(update={"use_proxy": use_proxy})
assert storage.has_credentials() is True
reload.assert_awaited_once()
finally:
await gateway.http.settings_routes.close()
+20 -8
View File
@@ -16,20 +16,32 @@ from nanobot.webui.settings_runtime import (
from nanobot.webui.settings_services import WebUISettingsServices
def test_web_proxy_roundtrip_while_disabled_preserves_model_proxy(tmp_path):
def test_shared_proxy_roundtrip_preserves_independent_feature_switches(tmp_path):
path = tmp_path / "config.json"
config = Config()
config.tools.web.enable = False
config.providers.openai.proxy = "http://model-proxy.example:8080"
config.providers.openai.use_proxy = True
save_config(config, path)
for proxy in ("http://web-proxy.example:7890", None):
payload = update_runtime_config_settings({"tools.web.proxy": proxy}, local_browser=True, config_path=path)
assert payload["runtime_config"]["tools.web.proxy"] == proxy
for proxy in ("http://shared-proxy.example:7890", "http://shared-proxy.example:7891"):
payload = update_runtime_config_settings({"network.proxy": proxy}, local_browser=True, config_path=path)
assert payload["runtime_config"]["network.proxy"] == proxy
assert payload["requires_restart"]
saved = load_config(path)
assert saved.tools.web.proxy == proxy
assert saved.network.proxy == proxy
assert saved.tools.web.enable is False
assert saved.providers.openai.proxy == "http://model-proxy.example:8080"
assert saved.tools.web.use_proxy is False
assert saved.providers.openai.use_proxy is True
update_runtime_config_settings({"tools.web.use_proxy": True}, config_path=path)
assert load_config(path).tools.web.use_proxy is True
def test_enabling_web_proxy_without_an_address_preserves_config(tmp_path):
path = tmp_path / "config.json"
save_config(Config(), path)
before = path.read_bytes()
with pytest.raises(WebUISettingsError, match="Advanced"):
update_runtime_config_settings({"tools.web.use_proxy": True}, config_path=path)
assert path.read_bytes() == before
def test_runtime_patch_persists_and_preserves_other_domains(tmp_path):
@@ -158,7 +170,7 @@ def test_timezone_auto_and_nullable_fields():
}}})
assert update_runtime_config(config, {
"agents.defaults.timezone_mode": "auto",
"tools.web.proxy": None,
"network.proxy": None,
}, local_browser=True)
assert config.agents.defaults.timezone_mode == "auto"
assert config.agents.defaults.dream.cron == "0 2 * * *"