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

+28
View File
@@ -339,6 +339,34 @@ A normal return from `send()` means either the visible payload was accepted by t
`send()` may run as soon as `is_running` becomes true. If a channel sets `_running` before its transport is ready, it must keep raising until delivery can be attempted safely. Small platform-specific retries are fine, but the final failure must still reach the manager.
### Optional shared proxy
Existing `__init__(config, bus)` constructors remain valid. `BaseChannel.uses_shared_proxy` defaults to `False`; only runtimes that explicitly set this class capability to `True` receive the instance-scoped top-level `NetworkConfig` as the keyword-only `network` argument. This capability is not a user setting.
To support the shared proxy, declare `use_proxy: bool = False` on your channel's config model and expose `"useProxy": ChannelFieldSpec(kind="bool", default=False)` in its setup fields. Opt in on the runtime class and forward `network` to the base constructor:
```python
from typing import Any
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.network import NetworkConfig
class WebhookChannel(BaseChannel):
uses_shared_proxy = True
def __init__(
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus, network=network)
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
```
Pass the resolved address to your platform clients. `useProxy: false` keeps the channel direct even when `network.proxy` is configured; `true` requires a shared proxy address and fails rather than silently connecting directly. Setup validators receive the same settings through `context.network`. Do not load global config or persist a proxy address in the channel config.
### Interactive Login
If your channel requires interactive authentication (e.g. QR code scan), override `login(force=False)`:
+4 -3
View File
@@ -127,7 +127,7 @@ See the [native Linear agent guide](./guides/linear-agent.md) for the complete s
1. Create a bot with `@BotFather` and copy its token.
2. Run `nanobot webui`, then open **Channels → Telegram**.
3. Paste the token. If the gateway cannot reach Telegram directly, expand **Advanced** and add an HTTP or SOCKS proxy.
3. Paste the token. If the gateway cannot reach Telegram directly, set the address in **Settings → Advanced → Shared proxy**, then enable **Use proxy** in Telegram's advanced options.
4. Save and enable Telegram, then send the bot a direct message.
The configuration badge means nanobot found a saved token. The live connection check is separate, so a temporary Telegram or proxy outage does not make an existing configuration disappear. Saved tokens and proxy URLs remain masked.
@@ -161,13 +161,14 @@ nanobot plugins enable telegram
}
```
If the gateway cannot reach Telegram directly, add a proxy to the same section:
If the gateway cannot reach Telegram directly, set the shared address and enable it for Telegram:
```json
{
"network": { "proxy": "http://127.0.0.1:7890" },
"channels": {
"telegram": {
"proxy": "http://127.0.0.1:7890"
"useProxy": true
}
}
}
+47 -13
View File
@@ -69,6 +69,41 @@ If the WebUI does not expose the option you need, start from the task below. Mos
| Run multiple isolated bots | separate `--home` directories, or `--config` and `--workspace` paths, plus distinct `gateway.port` or channel ports when processes run together | Place `--home` before the subcommand; use the same instance selectors with `status`, `agent`, `webui`, `gateway`, and `serve` | [Multiple Instances](./multiple-instances.md), [CLI Reference](./cli-reference.md) |
| Observe model calls | `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_BASE_URL` environment variables | Run one model call, then check the matching Langfuse project | [Langfuse Observability](#langfuse-observability) |
## Shared network proxy
Set one proxy address in **Settings → Advanced → Shared proxy**, then turn on **Use proxy** for each provider, Web access, channel, or remote MCP connection that needs it. The address is used by the gateway, so `127.0.0.1` refers to the machine running nanobot. Restart when Settings requests it. MCP connections can select the proxy before browser sign-in.
For proxies that require credentials, expand **Authentication (optional)** and enter the username and password, then choose **Save** to apply the address and credentials together. The same editor is available from **Configure proxy** without leaving the current form. Passwords are masked in the interface but remain part of the proxy URL in the local configuration; protect that file. If the address is a whole-URL `${ENV_VAR}` reference, include authentication in the referenced URL.
Only features with a **Use proxy** switch use this address. Turning a switch off preserves the feature's normal environment/system proxy behavior. An enabled switch without a configured address fails rather than silently connecting directly. Use a trusted proxy and keep credentials in its URL private.
<details>
<summary>Manual configuration</summary>
```json
{
"network": { "proxy": "http://127.0.0.1:7890" },
"providers": { "openai": { "useProxy": true } },
"tools": {
"web": { "useProxy": true },
"mcpServers": {
"figma-remote": {
"type": "streamableHttp",
"url": "https://mcp.figma.com/mcp",
"auth": "oauth",
"useProxy": true
}
}
}
}
```
HTTP, HTTPS, SOCKS5, and SOCKS5H URLs are accepted; individual integrations retain their transport limits. `${ENV_VAR}` references work in `network.proxy`.
</details>
On upgrade, one legacy proxy address moves to `network.proxy` and previously configured features receive `useProxy: true`. The migrated configuration is written on the next normal save, including `nanobot onboard --refresh`. If the old configuration contains different proxy addresses, choose one and set `network.proxy` explicitly before upgrading; multiple per-feature addresses are no longer supported. For Discord configurations that store the entire proxy URL in an environment variable and credentials separately, combine them into one full URL environment variable and set `network.proxy` to that reference before upgrading. Credential references inside a URL remain references when saved. Back up the original configuration before saving if you may need to downgrade.
## Environment Variables for Secrets
Instead of storing secrets directly in `config.json`, you can use `${VAR_NAME}` references that are resolved from environment variables at startup:
@@ -277,7 +312,7 @@ A Base URL is the service address nanobot sends model requests to. Change it onl
> - **Xiaomi MiMo thinking mode**: MiMo models (e.g. `mimo-v2.5-pro`) default to enabled thinking. In the preset's **Advanced options**, set reasoning effort to `none` to disable it, or `low` / `medium` / `high` to keep it on. Omitting the field preserves the provider's per-model default.
> - **Xiaomi MiMo Token Plan**: If you're on MiMo's token plan, open the xiaomi_mimo connection in **Settings → Models** and set its base URL to `https://token-plan-sgp.xiaomimimo.com/v1`.
> - **Custom providers**: Besides the built-in `custom` provider, any extra key under `providers` can define its own endpoint. For example, `providers.companyProxy.apiBase` plus `modelPresets.primary.provider: "companyProxy"` creates a separate custom provider. Set `apiBase`; set `apiKey` only when the endpoint requires it. Declare accepted protocols with `providers.<name>.api`; custom connections can use Chat Completions, Responses, or Anthropic Messages. See [custom connection APIs](#custom-connection-apis).
> - **Provider-scoped proxy**: `providers.<name>.proxy` routes only that provider through an HTTP proxy. It is supported for OpenAI-compatible providers, Anthropic Messages, `openai_codex`, and `xai_grok`. Native `bedrock`, `azure_openai`, and `github_copilot` backends reject `proxy`.
> - **Use proxy**: `providers.<name>.useProxy` opts that provider into the [shared network proxy](#shared-network-proxy). It is supported for OpenAI-compatible providers, Anthropic Messages, `openai_codex`, and `xai_grok`. Native `bedrock`, `azure_openai`, and `github_copilot` backends do not support this switch.
</details>
@@ -754,14 +789,13 @@ The default model is `xai-grok/grok-4.6` with a 500,000-token context window. Th
This is xAI subscription OAuth, not X Developer OAuth. nanobot follows the public OAuth client and proxy contract used by [Grok Build](https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/02-authentication.md). The browser flow uses a random loopback callback and PKCE. The resulting token is stored in the active instance's `auth/xai.json` (normally `~/.nanobot/auth/xai.json`), separately from Grok Build so rotating refresh tokens cannot invalidate one another.
To use a provider-specific proxy, merge this into `config.json` before login:
To use the shared proxy, configure its address and enable it for xAI before login:
```json
{
"network": { "proxy": "http://127.0.0.1:7890" },
"providers": {
"xaiGrok": {
"proxy": "http://127.0.0.1:7890"
}
"xaiGrok": { "useProxy": true }
}
}
```
@@ -1744,7 +1778,7 @@ When ripgrep (`rg`) is installed, nanobot automatically uses it in place of the
## Web Tools
Open **Settings → Capabilities → Web access** to enable or disable web tools and configure search and fetch. Use **Configure → Advanced options** for the web proxy and User-Agent, and **Settings → Advanced** for the SSRF whitelist. Follow any restart prompt.
Open **Settings → Capabilities → Web access** to enable or disable web tools and configure search and fetch. Use **Configure → Advanced options** for **Use proxy** and User-Agent, and **Settings → Advanced** for the shared proxy address and SSRF whitelist. Follow any restart prompt.
nanobot includes web search and web fetch tools. They are enabled by default. The collapsed examples below show the equivalent `tools.web` configuration.
@@ -1782,28 +1816,28 @@ nanobot uses a shared SSRF guard for built-in web fetches and HTTP/SSE MCP conne
Keep whitelist entries as narrow as possible, such as a single host CIDR (`192.168.1.50/32`). The whitelist is global for the shared SSRF guard; it is not limited to one tool or one MCP server. This guard does not filter network traffic from shell commands or stdio MCP processes. The shell sandboxes also allow network access; use host or container egress controls when you need to prevent outbound connections.
HTTP/SSE MCP connections use the same process-wide proxy environment behavior as `web_fetch`: proxied targets use the configured proxy, and URLs excluded by `NO_PROXY` remain DNS-pinned direct connections.
Web access and HTTP/SSE MCP connections can opt into the [shared network proxy](#shared-network-proxy). With **Use proxy** off, their normal environment proxy settings and `NO_PROXY` still apply.
In WebUI, open **Settings → Capabilities → Web access → Configure → Advanced options** to set the web proxy. This setting applies to the agent's web search and page reading, not model providers, MCP, or your browser. `127.0.0.1` refers to the machine that runs nanobot, not the phone or computer that opens WebUI. Clear the field to use the default network settings, which can include proxy environment variables. After saving, restart nanobot when WebUI requests it. You can configure the proxy before enabling web access.
Set the address in **Settings → Advanced → Shared proxy**, then enable **Use proxy** under **Settings → Capabilities → Web access → Configure → Advanced options**. This switch applies to web search and page reading; providers and MCP connections have their own switches. Your browser uses its own network settings. Follow any restart prompt. You can configure the proxy before enabling web access.
> [!TIP]
> Use `proxy` in `tools.web` to route web requests through a proxy:
> Set `network.proxy` once and enable `tools.web.useProxy` to route web requests through it:
> <details>
> <summary>Manual configuration</summary>
>
> ```json
> { "tools": { "web": { "proxy": "http://127.0.0.1:7890" } } }
> { "network": { "proxy": "http://127.0.0.1:7890" }, "tools": { "web": { "useProxy": true } } }
> ```
>
> </details>
> `web_fetch` applies DNS pinning for direct connections. When an explicit `tools.web.proxy` or a process-wide proxy environment variable applies to the target URL, nanobot still validates the requested URL locally, but DNS resolution for the outbound fetch happens at the proxy; configure only trusted proxies. URLs excluded by `NO_PROXY` keep the DNS-pinned direct path unless `tools.web.proxy` is configured.
> Web requests still enforce URL safety checks when using a proxy. Use only trusted proxies: the proxy controls final DNS resolution and outbound access. With **Use proxy** enabled, the shared address takes precedence over environment proxy settings, including `NO_PROXY`.
### `tools.web`
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `enable` | boolean | `true` | Enable or disable all built-in web tools (`web_search` + `web_fetch`) |
| `proxy` | string or null | `null` | Proxy for web requests, for example `http://127.0.0.1:7890`. `web_fetch` DNS pinning applies only to direct connections; proxied fetches rely on the configured proxy as the trusted network exit. |
| `useProxy` | boolean | `false` | Use the [shared network proxy](#shared-network-proxy) for web search and fetch. |
| `userAgent` | string or null | `null` | User-Agent header for all web requests. If null, a browser one will be used |
### Web Search
@@ -2098,7 +2132,7 @@ Queries are limited to 128 Unicode characters after trimming whitespace; longer
### Web Fetch
In **Settings → Capabilities → Web access**, expand the fetch options and choose whether to use Jina Reader. Save the change; use **Configure → Advanced options** in the same Web access card for network proxy settings.
In **Settings → Capabilities → Web access**, expand the fetch options and choose whether to use Jina Reader. Save the change; use **Configure → Advanced options → Use proxy** to enable the address saved in **Settings → Advanced → Shared proxy**.
> [!TIP]
> If you are having issues with JS proof-of-work or Cloudflare captchas, set a random user agent and disable Jina Reader:
+6 -5
View File
@@ -28,12 +28,12 @@ Open **Channels → Telegram**:
1. If Telegram support is not installed, turn on its switch and confirm the installation.
2. Paste the token from BotFather.
3. If the gateway cannot reach Telegram directly, expand **Advanced** and enter an HTTP or SOCKS proxy such as `http://127.0.0.1:7890`.
3. If the gateway cannot reach Telegram directly, set an address such as `http://127.0.0.1:7890` in **Settings → Advanced → Shared proxy**, then enable **Use proxy** in Telegram's advanced options.
4. Save and enable Telegram. For a first private setup, leave the sender allowlist empty: new senders must pair before they can use the agent. Do not set it to `*`.
The configuration badge appears as soon as a bot token is saved. A connection check is separate: if Telegram is temporarily unreachable, the saved configuration remains valid and the bot can continue working in environments where the gateway has network access.
Saved tokens and proxy URLs are masked. A proxy entered here is used both for the connection check and for normal Telegram traffic.
Saved tokens and proxy URLs are masked. **Use proxy** applies the shared address to both the connection check and normal Telegram traffic.
## Manual setup
@@ -50,17 +50,18 @@ Then merge this snippet into `~/.nanobot/config.json`:
```json
{
"network": { "proxy": "http://127.0.0.1:7890" },
"channels": {
"telegram": {
"enabled": true,
"token": "YOUR_BOT_TOKEN",
"proxy": "http://127.0.0.1:7890"
"useProxy": true
}
}
}
```
Omit `proxy` when the gateway can reach Telegram directly.
Leave `useProxy` off when the gateway can reach Telegram directly.
Omitting `allowFrom` enables pairing-only mode. The first DM from a new user gets a pairing code instead of agent access.
@@ -109,7 +110,7 @@ Send the message again after approval. Confirm that your private chat now receiv
## Troubleshooting
- If the channel is not listed, run `nanobot plugins enable telegram` again in the same Python environment.
- If the WebUI shows a saved configuration but the live check cannot reach Telegram, the token is still saved. Confirm the gateway can reach `api.telegram.org`, or open **Advanced → Network proxy** and enter a proxy.
- If the WebUI shows a saved configuration but the live check cannot reach Telegram, the token is still saved. Confirm the gateway can reach `api.telegram.org`, or configure **Settings → Advanced → Shared proxy** and turn on Telegram's **Use proxy** switch.
- If Telegram rejects the token, copy the current token from BotFather or regenerate it.
- If messages do not arrive, check the Telegram runtime status in **Channels** and the logs of the running gateway. Confirm it is enabled and can reach Telegram; do not start a second gateway to diagnose the first.
- If a first DM returns a pairing code, that is expected. Approve the code before testing normal agent replies.
+1 -1
View File
@@ -85,7 +85,7 @@ Provider settings reuse normal provider config fields:
| `providers.<name>.apiBase` | Optional custom base URL |
| `providers.<name>.extraHeaders` | Headers merged into provider requests |
| `providers.<name>.extraBody` | Extra JSON fields merged into provider request bodies |
| `providers.<name>.proxy` | Explicit trusted HTTP proxy for provider requests and returned image URL downloads |
| `providers.<name>.useProxy` | Use the shared `network.proxy` address for provider requests and returned image URL downloads |
For providers that return image URLs, direct downloads use DNS pinning. When an explicit provider `proxy` is configured, nanobot rejects malformed URLs and locally identifiable private/internal targets on the initial URL and every redirect. Hostnames unavailable to local DNS are delegated to that trusted proxy, which owns final DNS resolution and network egress. Process-wide proxy environment variables are not used for these downloads.
+4
View File
@@ -2,6 +2,8 @@
Open **Apps → MCP** to find a service, configure its connection, and select **Connect**. Presets save MCP server configuration; the gateway discovers and runs the tools. Each service still requires its own account access and permissions. The tables below list all built-in presets.
For a remote HTTP/SSE service that needs a proxy, first set the shared address in **Settings → Advanced → Shared proxy**, then turn on **Use proxy** in its connection dialog before selecting **Connect**. The gateway uses that route for MCP requests and authorization. The browser's sign-in page still uses your browser's own network settings. Local stdio servers keep their own networking configuration.
## Hosted services
Browser sign-in uses the service's MCP OAuth flow. API-key presets ask for the credential listed below and add it to the required HTTP header or URL parameter. Paste the token itself into the credential field.
@@ -123,6 +125,8 @@ Datadog uses the MCP endpoint for your Datadog site and a Personal or Service Ac
Figma uses the desktop app's local MCP endpoint, and Supabase starts a local server in read-only mode. Their **(remote)** variants use browser sign-in. GitHub uses Docker; **GitHub (remote)** uses a personal access token. Changes to credentials retain the connection's tool selection, timeout, and other saved settings.
Figma (remote) also requires [Figma's approval of the MCP client](https://developers.figma.com/docs/figma-mcp-server/remote-server-installation/). A client rejected during registration cannot connect until Figma approves it, even when its network connection works.
## Local servers
Local servers run on the gateway computer. Install the runtime or application listed for each service. Stdio servers use a managed working directory under the nanobot data directory so their runtime files stay outside the source checkout. Figma connects over HTTP to the local desktop app.
+1 -1
View File
@@ -72,7 +72,7 @@ These fields answer different questions:
| `model` | `modelPresets.<name>.model` | The model ID expected by that provider or gateway. |
| `apiKey` | `providers.<provider>.apiKey` | Credential for that provider. Use `${ENV_VAR}` for secrets. |
| `apiBase` | `providers.<provider>.apiBase` | HTTP base URL of the provider endpoint. |
| `proxy` | `providers.<provider>.proxy` | Optional HTTP proxy for this provider only. Supported for OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI OAuth. |
| `use_proxy` | `providers.<provider>.useProxy` | Use the shared `network.proxy` address for this provider. Supported for OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI OAuth. |
You usually omit `apiBase` for hosted built-in providers such as OpenRouter, Anthropic direct, OpenAI direct, Groq, or Bedrock because nanobot knows their default endpoints. Set `apiBase` for `custom`, local OpenAI-compatible servers, provider proxies, regional endpoints, or subscription endpoints. Include the API version path when the endpoint requires it, for example `https://api.example.com/v1` or `http://localhost:11434/v1`.
+2 -2
View File
@@ -148,12 +148,12 @@ If you need a known-good snippet instead of diagnosis, use [`provider-cookbook.m
| Local model connection refused | Ollama, vLLM, LM Studio, or another local server is not running, or `apiBase` points to the wrong port. |
| Bedrock validation error | Check AWS region, credentials, model access, model ID, and whether the model supports Converse. |
| OAuth provider fails | Run the matching login command: `openai-codex`, `xai-grok`, or `github-copilot`, normally with `--set-main`. |
| Codex OAuth needs a proxy | Set `providers.openaiCodex.proxy` before running the login command. The proxy applies to login, token refresh, and Codex API requests. |
| Codex OAuth needs a proxy | Set the address in **Settings → Advanced → Shared proxy** and enable **Use proxy** for OpenAI Codex before login. In `config.json`, use `network.proxy` and `providers.openaiCodex.useProxy: true`. This applies to login, token refresh, and Codex API requests. |
| Codex login runs on a remote/headless machine | In the WebUI, open ChatGPT in your local browser; when the localhost callback page cannot load, copy the full `http://localhost:1455/auth/callback?...` URL from the address bar and paste it into the WebUI dialog. From the CLI, open the printed URL locally and paste the same callback URL back into the terminal. |
| Codex login runs in Docker | Start the container with `docker run -it` so the OAuth flow has an interactive terminal. |
| Codex says a model is not supported with a ChatGPT account | Use provider `openai_codex` with a Codex model such as `openai-codex/gpt-5.6-sol`. Do not use the direct-API `openai/...` prefix with Codex OAuth. |
| Config says `providers.openai_codex` conflicts with the built-in provider | Under `providers`, keep only the canonical `openaiCodex` settings key and remove a duplicate `openai_codex` key. A model preset's `provider` value remains `openai_codex`. |
| xAI OAuth needs a proxy | Set `providers.xaiGrok.proxy` before login. It applies to OAuth discovery, token exchange/refresh, and Grok subscription requests. |
| xAI OAuth needs a proxy | Set `network.proxy` and `providers.xaiGrok.useProxy: true` before login, or use the shared address and provider switch in Settings. This applies to OAuth discovery, token exchange/refresh, and Grok subscription requests. |
| xAI login runs on a remote/headless machine | In the WebUI, finish sign-in in your local browser; if the loopback redirect cannot reach the server, copy the final URL from the address bar into the WebUI dialog. From the CLI, run `nanobot provider login xai-grok` interactively, open the printed URL elsewhere, and paste the final callback URL or authorization code when prompted. |
| xAI returns 403 or subscription access denied | Confirm the signed-in account has an eligible X Premium / Grok subscription, then run `nanobot provider login xai-grok` again. This provider does not use an xAI API key or X Developer OAuth. |
| xAI returns 400 `invalid-argument` | Read the bounded `Response body` appended to the provider error. Hosted `x_search` is sent only when xAI's model catalog advertises `supportsBackendSearch`; the model ID `grok-4.5` itself is valid. |