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
@@ -61,6 +61,7 @@ from nanobot.bus.outbound_events import (
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands
|
||||
from nanobot.command.router import command_text
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import AgentDefaults, ModelPresetConfig
|
||||
from nanobot.events import NO_EVENTS, AgentEvent, EventSink
|
||||
from nanobot.llm_usage.context import source_from_request
|
||||
@@ -301,6 +302,7 @@ class AgentLoop:
|
||||
unified_session: bool = False,
|
||||
disabled_skills: list[str] | None = None,
|
||||
tools_config: ToolsConfig | None = None,
|
||||
network_config: NetworkConfig | None = None,
|
||||
provider_snapshot_loader: Callable[..., ProviderSnapshot] | None = None,
|
||||
provider_signature: tuple[object, ...] | None = None,
|
||||
model_presets: dict[str, ModelPresetConfig] | None = None,
|
||||
@@ -367,6 +369,7 @@ class AgentLoop:
|
||||
else defaults.tool_hint_max_length
|
||||
)
|
||||
self.tools_config = _tc
|
||||
self.network_config = network_config or NetworkConfig()
|
||||
self.web_config = _tc.web
|
||||
self.exec_config = _tc.exec
|
||||
self.cron_service = cron_service
|
||||
@@ -406,6 +409,7 @@ class AgentLoop:
|
||||
workspace=workspace,
|
||||
bus=bus,
|
||||
tools_config=_tc,
|
||||
network_config=self.network_config,
|
||||
max_tool_result_chars=self.max_tool_result_chars,
|
||||
restrict_to_workspace=restrict_to_workspace,
|
||||
disabled_skills=disabled_skills,
|
||||
@@ -519,6 +523,7 @@ class AgentLoop:
|
||||
session_ttl_minutes=defaults.session_ttl_minutes,
|
||||
idle_compact_check_interval_seconds=defaults.idle_compact_check_interval_seconds,
|
||||
tools_config=config.tools,
|
||||
network_config=config.network,
|
||||
model_presets=preset_helpers.configured_model_presets(config),
|
||||
model_preset=defaults.model_preset,
|
||||
dream_model_preset=defaults.dream.model_override,
|
||||
@@ -656,6 +661,7 @@ class AgentLoop:
|
||||
self.register_runtime_context_provider(runtime_control.workspace_context)
|
||||
ctx = ToolContext(
|
||||
config=self.tools_config,
|
||||
network=self.network_config,
|
||||
workspace=str(self.workspace),
|
||||
bus=self.bus,
|
||||
subagent_manager=self.subagents,
|
||||
|
||||
@@ -38,6 +38,7 @@ from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import RuntimeEventContext, SubagentTaskChanged
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import AgentDefaults, ToolsConfig
|
||||
from nanobot.events import AgentEvent, EventSink
|
||||
from nanobot.llm_usage.context import LLMUsageSource, current_llm_usage_source
|
||||
@@ -220,6 +221,7 @@ class SubagentManager:
|
||||
max_concurrent_subagents: int | None = None,
|
||||
*,
|
||||
consolidator: Consolidator,
|
||||
network_config: NetworkConfig | None = None,
|
||||
session_manager: SessionManager | None = None,
|
||||
):
|
||||
if cast(object, consolidator) is None:
|
||||
@@ -252,6 +254,7 @@ class SubagentManager:
|
||||
self.workspace = workspace
|
||||
self.bus = bus
|
||||
self.tools_config = tools_config or ToolsConfig()
|
||||
self.network_config = network_config or NetworkConfig()
|
||||
self.max_tool_result_chars = max_tool_result_chars
|
||||
self.restrict_to_workspace = restrict_to_workspace
|
||||
self.disabled_skills = set(disabled_skills or [])
|
||||
@@ -526,6 +529,7 @@ class SubagentManager:
|
||||
cfg = tools_config if tools_config is not None else self._subagent_tools_config()
|
||||
ctx = ToolContext(
|
||||
config=cfg,
|
||||
network=self.network_config,
|
||||
workspace=str(root.resolve()),
|
||||
exec_session_manager=exec_manager or self._exec_session_manager,
|
||||
file_state_store=FileStates(),
|
||||
|
||||
@@ -7,6 +7,8 @@ from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Callable, Protocol, runtime_checkable
|
||||
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.exec_session import ExecSessionManager
|
||||
@@ -92,6 +94,7 @@ def current_request_session_key() -> str | None:
|
||||
class ToolContext:
|
||||
config: ToolsConfig
|
||||
workspace: str
|
||||
network: NetworkConfig = field(default_factory=NetworkConfig)
|
||||
bus: MessageBus | None = None
|
||||
subagent_manager: SubagentManager | None = None
|
||||
cron_service: CronService | None = None
|
||||
|
||||
@@ -17,6 +17,7 @@ from nanobot.agent.tools.schema import (
|
||||
StringSchema,
|
||||
tool_parameters_schema,
|
||||
)
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.providers.image_generation import (
|
||||
ImageGenerationError,
|
||||
@@ -81,6 +82,7 @@ class ImageGenerationTool(Tool):
|
||||
workspace=ctx.workspace,
|
||||
config=ctx.config.image_generation,
|
||||
provider_configs=image_gen_provider_configs(ctx.providers_config),
|
||||
network=ctx.network,
|
||||
)
|
||||
|
||||
def __init__(
|
||||
@@ -90,9 +92,11 @@ class ImageGenerationTool(Tool):
|
||||
config: ImageGenerationToolConfig,
|
||||
provider_config: ProviderConfig | None = None,
|
||||
provider_configs: dict[str, ProviderConfig] | None = None,
|
||||
network: NetworkConfig | None = None,
|
||||
) -> None:
|
||||
self.workspace = Path(workspace).expanduser()
|
||||
self.config = config
|
||||
self.network = network or NetworkConfig()
|
||||
self.provider_configs = dict(provider_configs or {})
|
||||
if provider_config is not None and "openrouter" not in self.provider_configs:
|
||||
self.provider_configs["openrouter"] = provider_config
|
||||
@@ -126,7 +130,7 @@ class ImageGenerationTool(Tool):
|
||||
"api_base": provider.api_base if provider and isinstance(provider.api_base, str) else None,
|
||||
"extra_headers": headers or None,
|
||||
"extra_body": body or None,
|
||||
"proxy": provider.proxy if provider and isinstance(provider.proxy, str) else None,
|
||||
"proxy": self.network.resolve_proxy(provider.use_proxy) if provider else None,
|
||||
}
|
||||
return cls(**kwargs)
|
||||
|
||||
@@ -218,6 +222,7 @@ def register_image_generation_tool(
|
||||
|
||||
ctx = ToolContext(
|
||||
config=config.tools,
|
||||
network=config.network,
|
||||
workspace=str(workspace),
|
||||
providers_config=config.providers,
|
||||
)
|
||||
|
||||
+56
-17
@@ -8,6 +8,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import traceback
|
||||
import urllib.parse
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Mapping
|
||||
from contextlib import AsyncExitStack, suppress
|
||||
@@ -19,6 +20,7 @@ from loguru import logger
|
||||
from nanobot.agent.tools.base import Tool, ToolResult
|
||||
from nanobot.agent.tools.context import tool_log_content_allowed
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.security.network import (
|
||||
PinnedDNSAsyncTransport,
|
||||
env_proxy_applies_to_url,
|
||||
@@ -60,7 +62,7 @@ _HTTP_READ_TIMEOUT = 300.0
|
||||
# Replace anything outside [a-zA-Z0-9_-] with underscore and collapse runs.
|
||||
_SANITIZE_RE = re.compile(r"_+")
|
||||
_ReconnectCallback = Callable[[str, str, Tool], Awaitable[Tool | None]]
|
||||
MCPServerLoader = Callable[[], Mapping[str, "MCPServerConfig"]]
|
||||
MCPServerLoader = Callable[[], tuple[Mapping[str, "MCPServerConfig"], NetworkConfig]]
|
||||
MCPRuntimeStatus = Literal["connecting", "connected", "failed"]
|
||||
|
||||
|
||||
@@ -216,8 +218,26 @@ def _is_transient_connection_failure(exc: BaseException) -> bool:
|
||||
return isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)) or _is_transient(exc)
|
||||
|
||||
|
||||
def _log_mcp_connection_failure(name: str, exc: BaseException, hint: str = "") -> None:
|
||||
exception = exc if tool_log_content_allowed() else False
|
||||
def _log_mcp_connection_failure(
|
||||
name: str, exc: BaseException, hint: str = "", *, proxy: str | None = None,
|
||||
) -> None:
|
||||
exception: Exception | bool = False
|
||||
if tool_log_content_allowed():
|
||||
details = "".join(traceback.TracebackException.from_exception(
|
||||
exc, capture_locals=False,
|
||||
).format())
|
||||
if proxy:
|
||||
for value in (proxy, urllib.parse.unquote(proxy)):
|
||||
details = details.replace(value, _redact_url(proxy))
|
||||
# Match userinfo only with its URL delimiter, never isolated short
|
||||
# credentials that could rewrite exception types or stack text.
|
||||
userinfo = urllib.parse.urlsplit(proxy).netloc.rpartition("@")[0]
|
||||
if userinfo:
|
||||
for value in (userinfo, urllib.parse.unquote(userinfo)):
|
||||
details = details.replace(f"{value}@", "[redacted]@")
|
||||
# Keep exception-aware sinks, but never give Loguru live frames or a raw
|
||||
# exception chain: diagnose=True would render credential-bearing locals.
|
||||
exception = Exception("\n" + details.rstrip())
|
||||
if _is_transient_connection_failure(exc):
|
||||
logger.warning("MCP server '{}': transient connection failure", name)
|
||||
logger.opt(exception=exception).debug(
|
||||
@@ -242,7 +262,7 @@ def _is_session_terminated(exc: BaseException) -> bool:
|
||||
)
|
||||
|
||||
|
||||
async def _probe_http_url(url: str, timeout: float = 3.0) -> bool:
|
||||
async def _probe_http_url(url: str, timeout: float = 3.0, *, proxy: str | None = None) -> bool:
|
||||
"""Quick TCP probe to check if an HTTP MCP server is reachable.
|
||||
|
||||
Avoids entering ``streamable_http_client`` / ``sse_client`` when the port is
|
||||
@@ -258,7 +278,7 @@ async def _probe_http_url(url: str, timeout: float = 3.0) -> bool:
|
||||
ok, _, resolved_ips = resolve_url_target(url)
|
||||
if not ok:
|
||||
return False
|
||||
if env_proxy_applies_to_url(url):
|
||||
if proxy or env_proxy_applies_to_url(url):
|
||||
return True
|
||||
for target_host in resolved_ips or (host,):
|
||||
try:
|
||||
@@ -294,7 +314,9 @@ def _redact_url(url: str) -> str:
|
||||
return "<redacted-url>"
|
||||
|
||||
|
||||
def _pinned_transport_kwargs() -> dict[str, Any]:
|
||||
def _pinned_transport_kwargs(proxy: str | None = None) -> dict[str, Any]:
|
||||
if proxy:
|
||||
return {"transport": httpx.AsyncHTTPTransport(proxy=proxy), "trust_env": False}
|
||||
kwargs: dict[str, Any] = {"transport": PinnedDNSAsyncTransport()}
|
||||
mounts = httpx_env_proxy_mounts()
|
||||
if mounts:
|
||||
@@ -1008,6 +1030,7 @@ async def connect_mcp_servers(
|
||||
registry: ToolRegistry,
|
||||
*,
|
||||
oauth_handlers: Mapping[str, MCPOAuthHandlers] | None = None,
|
||||
network: NetworkConfig | None = None,
|
||||
) -> dict[str, MCPConnection]:
|
||||
"""Connect to configured MCP servers and register their tools, resources, prompts.
|
||||
|
||||
@@ -1020,6 +1043,10 @@ async def connect_mcp_servers(
|
||||
from mcp.client.stdio import stdio_client
|
||||
from mcp.client.streamable_http import streamable_http_client
|
||||
|
||||
# Stack-exit failures are logged outside open_single_server; retain the exact
|
||||
# selected value there too, including credentials resolved from environment refs.
|
||||
selected_proxies: dict[str, str | None] = {}
|
||||
|
||||
async def open_single_server(
|
||||
name: str, cfg: MCPServerConfig, server_stack: AsyncExitStack
|
||||
) -> bool:
|
||||
@@ -1047,6 +1074,10 @@ async def connect_mcp_servers(
|
||||
)
|
||||
return False
|
||||
|
||||
if cfg.use_proxy and transport_type == "stdio":
|
||||
raise ValueError("The shared proxy is available for HTTP and SSE MCP connections")
|
||||
proxy = (network or NetworkConfig()).resolve_proxy(cfg.use_proxy)
|
||||
selected_proxies[name] = proxy
|
||||
oauth_auth: httpx.Auth | None = None
|
||||
if cfg.auth == "oauth":
|
||||
if transport_type not in {"sse", "streamableHttp"}:
|
||||
@@ -1084,7 +1115,7 @@ async def connect_mcp_servers(
|
||||
)
|
||||
read, write = await server_stack.enter_async_context(stdio_client(params))
|
||||
elif transport_type == "sse":
|
||||
if not await _probe_http_url(cfg.url):
|
||||
if not await _probe_http_url(cfg.url, proxy=proxy):
|
||||
logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))
|
||||
return False
|
||||
|
||||
@@ -1104,7 +1135,7 @@ async def connect_mcp_servers(
|
||||
follow_redirects=True,
|
||||
timeout=timeout,
|
||||
auth=auth,
|
||||
**_pinned_transport_kwargs(),
|
||||
**_pinned_transport_kwargs(proxy),
|
||||
)
|
||||
|
||||
sse_kwargs: dict[str, Any] = {
|
||||
@@ -1116,7 +1147,7 @@ async def connect_mcp_servers(
|
||||
sse_client(cfg.url, **sse_kwargs)
|
||||
)
|
||||
elif transport_type == "streamableHttp":
|
||||
if not await _probe_http_url(cfg.url):
|
||||
if not await _probe_http_url(cfg.url, proxy=proxy):
|
||||
logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))
|
||||
return False
|
||||
|
||||
@@ -1131,7 +1162,7 @@ async def connect_mcp_servers(
|
||||
connect=10.0,
|
||||
read=max(_HTTP_READ_TIMEOUT, cfg.tool_timeout),
|
||||
),
|
||||
**_pinned_transport_kwargs(),
|
||||
**_pinned_transport_kwargs(proxy),
|
||||
}
|
||||
if oauth_auth is not None:
|
||||
http_client_kwargs["auth"] = oauth_auth
|
||||
@@ -1300,7 +1331,7 @@ async def connect_mcp_servers(
|
||||
" Hint: this looks like stdio protocol pollution. Make sure the MCP server writes "
|
||||
"only JSON-RPC to stdout and sends logs/debug output to stderr instead."
|
||||
)
|
||||
_log_mcp_connection_failure(name, e, hint)
|
||||
_log_mcp_connection_failure(name, e, hint, proxy=selected_proxies.get(name))
|
||||
return False
|
||||
|
||||
async def connect_single_server(
|
||||
@@ -1350,7 +1381,7 @@ async def connect_mcp_servers(
|
||||
try:
|
||||
result = await connect_single_server(name, cfg)
|
||||
except Exception as e:
|
||||
_log_mcp_connection_failure(name, e)
|
||||
_log_mcp_connection_failure(name, e, proxy=selected_proxies.get(name))
|
||||
continue
|
||||
if result[1] is not None:
|
||||
server_stacks[result[0]] = result[1]
|
||||
@@ -1384,10 +1415,11 @@ def _configured_servers(config: Config) -> dict[str, MCPServerConfig]:
|
||||
)
|
||||
|
||||
|
||||
def _load_current_servers() -> dict[str, MCPServerConfig]:
|
||||
def _load_current_servers() -> tuple[dict[str, MCPServerConfig], NetworkConfig]:
|
||||
from nanobot.config.loader import load_config, resolve_config_env_vars
|
||||
|
||||
return _configured_servers(resolve_config_env_vars(load_config()))
|
||||
config = resolve_config_env_vars(load_config())
|
||||
return _configured_servers(config), config.network
|
||||
|
||||
|
||||
class MCPProvider:
|
||||
@@ -1399,8 +1431,10 @@ class MCPProvider:
|
||||
registry: ToolRegistry,
|
||||
*,
|
||||
server_loader: MCPServerLoader | None = None,
|
||||
network: NetworkConfig | None = None,
|
||||
) -> None:
|
||||
self._servers = dict(servers)
|
||||
self._network = (network or NetworkConfig()).model_copy(deep=True)
|
||||
self._registry = registry
|
||||
self._server_loader = server_loader or _load_current_servers
|
||||
self._connections: dict[str, MCPConnection] = {}
|
||||
@@ -1420,6 +1454,7 @@ class MCPProvider:
|
||||
_configured_servers(config),
|
||||
registry,
|
||||
server_loader=server_loader,
|
||||
network=config.network,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -1491,7 +1526,7 @@ class MCPProvider:
|
||||
return
|
||||
self._set_runtime_status(missing_servers, "connecting")
|
||||
try:
|
||||
connected = await connect_mcp_servers(missing_servers, self._registry)
|
||||
connected = await connect_mcp_servers(missing_servers, self._registry, network=self._network)
|
||||
if self._closing:
|
||||
await _close_mcp_connections(connected)
|
||||
return
|
||||
@@ -1526,7 +1561,8 @@ class MCPProvider:
|
||||
if self._closing:
|
||||
return self._closing_result()
|
||||
try:
|
||||
next_servers = dict(self._server_loader())
|
||||
loaded_servers, next_network = self._server_loader()
|
||||
next_servers = dict(loaded_servers)
|
||||
except Exception as exc:
|
||||
logger.warning("MCP hot reload could not read config: {}", exc)
|
||||
return {
|
||||
@@ -1553,6 +1589,7 @@ class MCPProvider:
|
||||
for name in current_names & next_names
|
||||
if _server_signature(current_servers[name])
|
||||
!= _server_signature(next_servers[name])
|
||||
or (next_servers[name].use_proxy and self._network.proxy != next_network.proxy)
|
||||
)
|
||||
|
||||
tools_removed = 0
|
||||
@@ -1564,6 +1601,7 @@ class MCPProvider:
|
||||
self._runtime_statuses.pop(name, None)
|
||||
|
||||
self._servers = next_servers
|
||||
self._network = next_network.model_copy(deep=True)
|
||||
retry_missing = sorted(
|
||||
name
|
||||
for name in next_names
|
||||
@@ -1580,7 +1618,7 @@ class MCPProvider:
|
||||
if to_connect:
|
||||
self._set_runtime_status(to_connect, "connecting")
|
||||
try:
|
||||
connected = await connect_mcp_servers(to_connect, self._registry)
|
||||
connected = await connect_mcp_servers(to_connect, self._registry, network=self._network)
|
||||
except BaseException:
|
||||
self._set_runtime_status(to_connect, "failed")
|
||||
raise
|
||||
@@ -1695,6 +1733,7 @@ class MCPProvider:
|
||||
connected = await connect_mcp_servers(
|
||||
{server_name: cfg},
|
||||
self._registry,
|
||||
network=self._network,
|
||||
)
|
||||
if self._closing:
|
||||
await _close_mcp_connections(connected)
|
||||
|
||||
@@ -282,8 +282,7 @@ def _snapshot_model_presets(
|
||||
def _snapshot_web_config(config: WebToolsConfig) -> dict[str, object]:
|
||||
return {
|
||||
"enable": config.enable,
|
||||
# Proxy URLs may embed credentials. Presence is enough for diagnosis.
|
||||
"proxy": "<configured>" if config.proxy else config.proxy,
|
||||
"use_proxy": config.use_proxy,
|
||||
"user_agent": config.user_agent,
|
||||
"search": {
|
||||
"provider": config.search.provider,
|
||||
|
||||
@@ -416,7 +416,7 @@ class WebSearchTool(Tool):
|
||||
config_loader = _load_search_config
|
||||
return cls(
|
||||
config=ctx.config.web.search,
|
||||
proxy=ctx.config.web.proxy,
|
||||
proxy=ctx.network.resolve_proxy(ctx.config.web.use_proxy),
|
||||
user_agent=ctx.config.web.user_agent,
|
||||
config_loader=config_loader,
|
||||
)
|
||||
@@ -1296,7 +1296,7 @@ class WebFetchTool(Tool):
|
||||
def create(cls, ctx: ToolContext) -> Tool:
|
||||
return cls(
|
||||
config=ctx.config.web.fetch,
|
||||
proxy=ctx.config.web.proxy,
|
||||
proxy=ctx.network.resolve_proxy(ctx.config.web.use_proxy),
|
||||
user_agent=ctx.config.web.user_agent,
|
||||
)
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ class WebFetchConfig(Base):
|
||||
class WebToolsConfig(Base):
|
||||
"""Web tools configuration."""
|
||||
enable: bool = True
|
||||
proxy: str | None = None
|
||||
use_proxy: bool = False
|
||||
user_agent: str | None = None
|
||||
search: WebSearchConfig = Field(default_factory=WebSearchConfig)
|
||||
fetch: WebFetchConfig = Field(default_factory=WebFetchConfig)
|
||||
Reference in new issue
Block a user