feat(mcp): add browser OAuth for remote servers (#5316)

This commit is contained in:
chengyongru authored and GitHub committed 2026-08-10 23:44:37 +08:00
1 parent b3b0517611
commit 8e77f3f8a4
33 files changed
+4099 -198

No files matched your search

+415
View File
@@ -0,0 +1,415 @@
"""Gateway-owned browser authorization flows for remote MCP servers."""
from __future__ import annotations
import asyncio
import re
import secrets
import time
from collections.abc import Awaitable, Callable
from contextlib import suppress
from dataclasses import dataclass, field
from typing import Any
from urllib.parse import SplitResult, parse_qs, urlsplit, urlunsplit
from nanobot.agent.tools.mcp import MCPConnection, connect_mcp_servers
from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH, MCPOAuthHandlers
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.config.schema import MCPServerConfig
from nanobot.security.network import validate_url_target
from nanobot.webui.http_utils import is_loopback_host
McpReload = Callable[[], Awaitable[dict[str, Any]]]
_FLOW_TTL_S = 300
_START_WAIT_S = 20
_OAUTH_ERROR_RE = re.compile(r"^[a-zA-Z0-9_.-]{1,80}$")
class McpOAuthError(Exception):
"""Safe WebUI error for an MCP OAuth request."""
def __init__(self, message: str, status: int = 400) -> None:
super().__init__(message)
self.message = message
self.status = status
class _OAuthCallbackError(RuntimeError):
pass
@dataclass
class _McpOAuthFlow:
flow_id: str
name: str
cfg: MCPServerConfig
redirect_uri: str
manual_callback: bool
expires_at: float
authorization_ready: asyncio.Event = field(default_factory=asyncio.Event)
callback_result: asyncio.Future[tuple[str, str | None]] | None = None
task: asyncio.Task[bool] | None = None
authorization_url: str | None = None
state: str | None = None
callback_received: bool = False
error: str | None = None
reload_result: dict[str, Any] | None = None
def _parse_mcp_oauth_redirect_uri(redirect_uri: str) -> tuple[str, SplitResult, int | None]:
cleaned = redirect_uri.strip()
parsed = urlsplit(cleaned)
try:
port = parsed.port
except ValueError as exc:
raise McpOAuthError("Invalid MCP OAuth callback URL") from exc
if (
not parsed.netloc
or not parsed.hostname
or parsed.path != MCP_OAUTH_CALLBACK_PATH
or parsed.query
or parsed.fragment
or parsed.username is not None
or parsed.password is not None
):
raise McpOAuthError("Invalid MCP OAuth callback URL")
return cleaned, parsed, port
def validate_mcp_oauth_redirect_uri(redirect_uri: str) -> str:
"""Allow HTTPS callbacks, plus loopback HTTP for a local gateway."""
cleaned, parsed, _port = _parse_mcp_oauth_redirect_uri(redirect_uri)
if parsed.scheme == "https":
return cleaned
if parsed.scheme == "http" and is_loopback_host(parsed.netloc):
return cleaned
raise McpOAuthError("MCP OAuth callbacks must use HTTPS or localhost")
def prepare_mcp_oauth_redirect_uri(redirect_uri: str) -> tuple[str, bool]:
"""Use a pasteable loopback callback when a remote WebUI is served over HTTP."""
cleaned, parsed, port = _parse_mcp_oauth_redirect_uri(redirect_uri)
if parsed.scheme != "http" or is_loopback_host(parsed.netloc):
return validate_mcp_oauth_redirect_uri(cleaned), False
loopback = "127.0.0.1" if port is None else f"127.0.0.1:{port}"
manual_redirect_uri = urlunsplit(("http", loopback, parsed.path, "", ""))
return validate_mcp_oauth_redirect_uri(manual_redirect_uri), True
class McpOAuthManager:
"""Own short-lived browser flows while the gateway process is running."""
def __init__(self) -> None:
self._flows: dict[str, _McpOAuthFlow] = {}
self._states: dict[str, str] = {}
async def start(
self,
name: str,
cfg: MCPServerConfig,
redirect_uri: str,
*,
reload_mcp: McpReload,
reset_credentials: bool = False,
) -> dict[str, Any]:
self._prune()
redirect_uri, manual_callback = prepare_mcp_oauth_redirect_uri(redirect_uri)
await self._cancel_name(name)
loop = asyncio.get_running_loop()
now = time.monotonic()
flow = _McpOAuthFlow(
flow_id=secrets.token_urlsafe(24),
name=name,
cfg=cfg,
redirect_uri=redirect_uri,
manual_callback=manual_callback,
expires_at=now + _FLOW_TTL_S,
callback_result=loop.create_future(),
)
self._flows[flow.flow_id] = flow
handlers = MCPOAuthHandlers(
redirect_uri=redirect_uri,
redirect_handler=lambda url: self._receive_authorization_url(flow, url),
callback_handler=lambda: self._wait_for_callback(flow),
reset_credentials=reset_credentials,
)
flow.task = asyncio.create_task(
self._connect_and_reload(flow, handlers, reload_mcp),
name=f"mcp-oauth:{name}",
)
ready_waiter = asyncio.create_task(flow.authorization_ready.wait())
try:
await asyncio.wait(
{ready_waiter, flow.task},
timeout=_START_WAIT_S,
return_when=asyncio.FIRST_COMPLETED,
)
finally:
ready_waiter.cancel()
with suppress(asyncio.CancelledError):
await ready_waiter
return self._payload(flow)
async def status(self, flow_id: str) -> dict[str, Any]:
self._prune()
flow = self._flow(flow_id)
return self._payload(flow)
def submit_callback(
self,
*,
state: str,
code: str | None,
error: str | None,
) -> str:
self._prune()
flow_id = self._states.pop(state, None)
if flow_id is None:
raise McpOAuthError("This MCP authorization request has expired", status=410)
flow = self._flow(flow_id)
callback_result = flow.callback_result
if callback_result is None or callback_result.done():
raise McpOAuthError("This MCP authorization callback was already used", status=409)
flow.callback_received = True
if error:
safe_error = error if _OAUTH_ERROR_RE.fullmatch(error) else "authorization_failed"
flow.error = f"Authorization was not completed ({safe_error})."
callback_result.set_exception(_OAuthCallbackError(flow.error))
raise McpOAuthError(flow.error)
elif not code or len(code) > 8192:
flow.error = "The MCP server did not return an authorization code."
callback_result.set_exception(_OAuthCallbackError(flow.error))
raise McpOAuthError(flow.error)
else:
callback_result.set_result((code, state))
return flow.name
def submit_callback_url(self, *, flow_id: str, callback_url: str) -> dict[str, Any]:
"""Complete a flow from a full browser callback URL pasted into the WebUI."""
self._prune()
flow = self._flow(flow_id)
parsed = urlsplit(callback_url.strip())
expected = urlsplit(flow.redirect_uri)
if (
not parsed.query
or parsed.fragment
or parsed.username is not None
or parsed.password is not None
or parsed.scheme != expected.scheme
or parsed.netloc != expected.netloc
or parsed.path != expected.path
):
raise McpOAuthError(
"Paste the complete callback URL from the browser address bar."
)
try:
query = parse_qs(parsed.query, keep_blank_values=True, max_num_fields=16)
except ValueError as exc:
raise McpOAuthError(
"Paste the complete callback URL from the browser address bar."
) from exc
states = query.get("state", [])
state = states[0] if len(states) == 1 else ""
if not state or state != flow.state:
raise McpOAuthError(
"This callback belongs to a different or expired authorization request. "
"Start again.",
status=410,
)
codes = query.get("code", [])
errors = query.get("error", [])
if len(codes) > 1 or len(errors) > 1 or (codes and errors):
raise McpOAuthError(
"Paste the complete callback URL from the browser address bar."
)
code = codes[0] if len(codes) == 1 else None
error = errors[0] if len(errors) == 1 else None
if (not code and not error) or (code is not None and len(code) > 8192):
raise McpOAuthError(
"Paste the complete callback URL from the browser address bar."
)
self.submit_callback(state=state, code=code, error=error)
return self._payload(flow)
async def cancel(self, flow_id: str) -> dict[str, Any]:
self._prune()
flow = self._flow(flow_id)
await self._cancel_flow(flow)
return self._payload(flow)
async def _receive_authorization_url(
self,
flow: _McpOAuthFlow,
authorization_url: str,
) -> None:
parsed = urlsplit(authorization_url)
if (
parsed.scheme != "https"
or not parsed.netloc
or parsed.username is not None
or parsed.password is not None
or parsed.fragment
):
flow.error = "The MCP server returned an unsafe authorization URL."
raise McpOAuthError(flow.error)
ok, _error = validate_url_target(authorization_url)
if not ok:
flow.error = "The MCP server returned an unsafe authorization URL."
raise McpOAuthError(flow.error)
states = parse_qs(parsed.query).get("state", [])
state = states[0] if len(states) == 1 else ""
if not state or len(state) > 512:
flow.error = "The MCP server returned an invalid authorization URL."
raise McpOAuthError(flow.error)
if state in self._states:
flow.error = "The MCP server reused an OAuth state value."
raise McpOAuthError(flow.error)
flow.authorization_url = authorization_url
flow.state = state
self._states[state] = flow.flow_id
flow.authorization_ready.set()
async def _wait_for_callback(self, flow: _McpOAuthFlow) -> tuple[str, str | None]:
callback_result = flow.callback_result
if callback_result is None:
raise _OAuthCallbackError("MCP OAuth callback is unavailable")
remaining = max(0.1, flow.expires_at - time.monotonic())
try:
return await asyncio.wait_for(asyncio.shield(callback_result), timeout=remaining)
except asyncio.TimeoutError as exc:
flow.error = "MCP authorization timed out."
raise _OAuthCallbackError(flow.error) from exc
async def _connect(self, flow: _McpOAuthFlow, handlers: MCPOAuthHandlers) -> bool:
connections: dict[str, MCPConnection] = {}
try:
connections = await connect_mcp_servers(
{flow.name: flow.cfg},
ToolRegistry(),
oauth_handlers={flow.name: handlers},
)
succeeded = flow.name in connections
if not succeeded and flow.error is None:
flow.error = "Could not complete the MCP OAuth connection."
return succeeded
except asyncio.CancelledError:
raise
except Exception:
if flow.error is None:
flow.error = "Could not complete the MCP OAuth connection."
return False
finally:
for connection in connections.values():
with suppress(Exception):
await connection.aclose()
async def _connect_and_reload(
self,
flow: _McpOAuthFlow,
handlers: MCPOAuthHandlers,
reload_mcp: McpReload,
) -> bool:
succeeded = await self._connect(flow, handlers)
if not succeeded:
return False
try:
flow.reload_result = await reload_mcp()
failed = flow.reload_result.get("failed")
if (
not flow.reload_result.get("ok")
and not flow.reload_result.get("requires_restart")
and isinstance(failed, list)
and flow.name in failed
):
flow.reload_result = await reload_mcp()
except Exception:
flow.reload_result = {
"ok": False,
"message": "Signed in, but nanobot could not activate the MCP tools.",
"requires_restart": True,
}
return True
def _flow(self, flow_id: str) -> _McpOAuthFlow:
flow = self._flows.get(flow_id)
if flow is None:
raise McpOAuthError("Unknown or expired MCP OAuth flow", status=404)
return flow
def _payload(self, flow: _McpOAuthFlow) -> dict[str, Any]:
task = flow.task
connected = flow.reload_result.get("connected") if flow.reload_result is not None else None
if task is not None and task.cancelled():
status = "cancelled"
elif task is not None and task.done():
try:
succeeded = task.result()
except Exception:
succeeded = False
if not succeeded:
status = "failed"
elif flow.reload_result is None:
status = "authorized"
elif flow.reload_result.get("ok") or (
isinstance(connected, list) and flow.name in connected
):
status = "connected"
else:
status = "authorized"
elif flow.callback_received:
status = "connecting"
elif flow.authorization_url:
status = "authorization_required"
else:
status = "starting"
payload: dict[str, Any] = {
"flow_id": flow.flow_id,
"name": flow.name,
"status": status,
"expires_in": max(0, int(flow.expires_at - time.monotonic())),
}
if flow.manual_callback:
payload["completion_input"] = "callback_url"
if flow.authorization_url and status == "authorization_required":
payload["authorization_url"] = flow.authorization_url
if flow.error:
payload["error"] = flow.error
if flow.reload_result is not None:
payload["hot_reload"] = flow.reload_result
return payload
async def _cancel_name(self, name: str) -> None:
for flow in list(self._flows.values()):
if flow.name == name and flow.task is not None and not flow.task.done():
await self._cancel_flow(flow)
async def _cancel_flow(self, flow: _McpOAuthFlow) -> None:
if flow.state:
self._states.pop(flow.state, None)
task = flow.task
if task is not None and not task.done():
task.cancel()
with suppress(BaseException):
await task
def _prune(self) -> None:
now = time.monotonic()
for flow_id, flow in list(self._flows.items()):
if flow.expires_at > now:
continue
if flow.state:
self._states.pop(flow.state, None)
if flow.task is not None and not flow.task.done():
flow.task.cancel()
callback_result = flow.callback_result
if callback_result is not None and not callback_result.done():
callback_result.cancel()
self._flows.pop(flow_id, None)
+160 -6
View File
@@ -16,6 +16,10 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Mapping, cast
from nanobot.agent.tools.mcp_oauth import (
delete_mcp_oauth_credentials,
mcp_oauth_has_credentials,
)
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.apps.protocol import app_manifest, compact_dict
from nanobot.config.loader import load_config, resolve_config_env_vars, save_config
@@ -337,6 +341,63 @@ MCP_PRESETS: tuple[McpPreset, ...] = (
),
note="Requires Figma Desktop Dev Mode MCP to be running locally.",
),
McpPreset(
name="xmind",
display_name="Xmind",
category="productivity",
description="Create, read, and edit cloud mind maps through Xmind.",
docs_url="https://xmind.com/user-guide/xmind-mcp",
transport="streamableHttp",
install_supported=True,
brand_domain="xmind.com",
brand_color="#F4B41A",
requires="Xmind account",
server=MCPServerConfig(
type="streamableHttp",
auth="oauth",
url="https://app.xmind.com/api/mcp",
tool_timeout=60,
),
note="Connects securely in your browser with Xmind OAuth.",
),
McpPreset(
name="notion",
display_name="Notion",
category="productivity",
description="Read and update your Notion workspace through Notion MCP.",
docs_url="https://developers.notion.com/guides/mcp/get-started-with-mcp",
transport="streamableHttp",
install_supported=True,
brand_domain="notion.so",
brand_color="#111111",
requires="Notion account",
server=MCPServerConfig(
type="streamableHttp",
auth="oauth",
url="https://mcp.notion.com/mcp",
tool_timeout=60,
),
note="Connects securely in your browser with Notion OAuth.",
),
McpPreset(
name="linear",
display_name="Linear",
category="productivity",
description="Find and manage Linear issues, projects, and comments.",
docs_url="https://linear.app/docs/mcp",
transport="streamableHttp",
install_supported=True,
brand_domain="linear.app",
brand_color="#5E6AD2",
requires="Linear account",
server=MCPServerConfig(
type="streamableHttp",
auth="oauth",
url="https://mcp.linear.app/mcp",
tool_timeout=60,
),
note="Connects securely in your browser with Linear OAuth.",
),
McpPreset(
name="github",
display_name="GitHub",
@@ -657,6 +718,8 @@ def _status_for(preset: McpPreset, cfg: MCPServerConfig | None) -> str:
return "not_installed" if preset.install_supported else "coming_soon"
if any(field.required and not _field_configured(field, cfg) for field in preset.fields):
return "missing_credentials"
if cfg.auth == "oauth" and not mcp_oauth_has_credentials(preset.name, cfg.url):
return "authorization_required"
if cfg.command and not _command_available(cfg.command):
return "missing_dependency"
return "configured"
@@ -702,6 +765,7 @@ def _preset_manifest(preset: McpPreset, *, logo_url: str) -> dict[str, Any]:
compact_dict({
"type": "mcp",
"transport": preset.transport,
"auth": server.auth if server and server.auth else None,
"command": server.command if server and server.command else None,
"args": list(server.args) if server and server.command else None,
"url": _connection_summary(server) if server and server.url else None,
@@ -752,6 +816,7 @@ def _custom_manifest(name: str, cfg: MCPServerConfig) -> dict[str, Any]:
compact_dict({
"type": "mcp",
"transport": transport,
"auth": cfg.auth,
"command": cfg.command or None,
"url": _connection_summary(cfg) if cfg.url else None,
})
@@ -779,7 +844,7 @@ def _custom_manifest(name: str, cfg: MCPServerConfig) -> dict[str, Any]:
def _preset_payload(preset: McpPreset, configured_servers: dict[str, MCPServerConfig]) -> dict[str, Any]:
cfg = configured_servers.get(preset.name)
status = _status_for(preset, cfg)
configured = cfg is not None and status not in {"missing_credentials"}
configured = cfg is not None and status not in {"missing_credentials", "authorization_required"}
logo_url = _favicon_url(preset.brand_domain)
return {
"name": preset.name,
@@ -788,6 +853,7 @@ def _preset_payload(preset: McpPreset, configured_servers: dict[str, MCPServerCo
"description": preset.description,
"docs_url": preset.docs_url,
"transport": preset.transport,
"auth": (cfg.auth if cfg is not None else (preset.server.auth if preset.server else None)),
"requires": preset.requires,
"note": preset.note,
"install_supported": preset.install_supported,
@@ -814,7 +880,11 @@ def _custom_payload(
transport = cfg.type
if not transport:
transport = "stdio" if cfg.command else ("sse" if cfg.url.rstrip("/").endswith("/sse") else "streamableHttp")
status = "missing_dependency" if cfg.command and not _command_available(cfg.command) else "configured"
if cfg.auth == "oauth" and not mcp_oauth_has_credentials(name, cfg.url):
status = "authorization_required"
else:
status = "missing_dependency" if cfg.command and not _command_available(cfg.command) else "configured"
configured = status != "authorization_required"
return {
"name": name,
"display_name": name,
@@ -822,12 +892,13 @@ def _custom_payload(
"description": "Custom MCP server from nanobot config.",
"docs_url": "",
"transport": transport,
"auth": cfg.auth,
"requires": "",
"note": "",
"install_supported": True,
"installed": True,
"configured": True,
"available": _config_available(cfg),
"configured": configured,
"available": configured and _config_available(cfg),
"status": status,
"logo_url": None,
"brand_color": "#64748B",
@@ -1127,6 +1198,32 @@ def _normalize_transport(value: str | None, *, command: str = "", url: str = "")
return normalized # type: ignore[return-value]
def _normalize_auth(
value: object,
*,
transport: Literal["stdio", "sse", "streamableHttp"],
url: str,
headers: Mapping[str, str],
) -> Literal["oauth"] | None:
raw = str(value or "").strip().lower()
if not raw and url and not headers:
normalized_url = url.rstrip("/")
if any(
preset.server is not None
and preset.server.auth == "oauth"
and preset.server.url.rstrip("/") == normalized_url
for preset in MCP_PRESETS
):
raw = "oauth"
if not raw:
return None
if raw != "oauth":
raise McpPresetError("unsupported MCP auth type")
if transport == "stdio":
raise McpPresetError("MCP OAuth requires a remote HTTP transport")
return "oauth"
def _validated_server_name(name: str) -> str:
if not name or _MCP_PRESET_NAME_RE.match(name) is None:
raise McpPresetError("invalid MCP server name")
@@ -1142,6 +1239,13 @@ def _custom_server_from_query(query: QueryParams) -> tuple[str, MCPServerConfig]
raise McpPresetError("stdio MCP servers require a command")
if transport in {"sse", "streamableHttp"} and not url:
raise McpPresetError("remote MCP servers require a URL")
headers = _parse_string_map(_query_first(query, "headers"))
auth = _normalize_auth(
_query_first(query, "auth"),
transport=transport,
url=url,
headers=headers,
)
raw_timeout = (_query_first(query, "tool_timeout") or "").strip()
tool_timeout = _DEFAULT_CUSTOM_TIMEOUT
if raw_timeout:
@@ -1151,12 +1255,13 @@ def _custom_server_from_query(query: QueryParams) -> tuple[str, MCPServerConfig]
raise McpPresetError("tool_timeout must be an integer") from exc
cfg = MCPServerConfig(
type=transport,
auth=auth,
command=command if transport == "stdio" else "",
args=_parse_string_list(_query_first(query, "args")),
env=_parse_string_map(_query_first(query, "env")),
cwd=(_query_first(query, "cwd") or "").strip() if transport == "stdio" else "",
url=url if transport in {"sse", "streamableHttp"} else "",
headers=_parse_string_map(_query_first(query, "headers")),
headers=headers,
tool_timeout=tool_timeout,
enabled_tools=_parse_enabled_tools(_query_first(query, "enabled_tools")),
)
@@ -1201,6 +1306,13 @@ def _mcp_server_config(name: str, raw: Any) -> tuple[str, MCPServerConfig]:
headers = cast(dict[object, object], headers_value)
if not all(isinstance(k, str) and isinstance(v, str) for k, v in headers.items()):
raise McpPresetError(f"MCP server '{server_name}' headers must be a string object")
typed_headers = cast(dict[str, str], headers)
auth = _normalize_auth(
server.get("auth"),
transport=transport,
url=url,
headers=typed_headers,
)
if not isinstance(enabled_tools_value, list):
enabled_tools_value = ["*"]
else:
@@ -1209,12 +1321,13 @@ def _mcp_server_config(name: str, raw: Any) -> tuple[str, MCPServerConfig]:
enabled_tools_value = ["*"]
return server_name, MCPServerConfig(
type=transport,
auth=auth,
command=command if transport == "stdio" else "",
args=cast(list[str], args),
env=cast(dict[str, str], env),
cwd=cwd if transport == "stdio" else "",
url=url if transport in {"sse", "streamableHttp"} else "",
headers=cast(dict[str, str], headers),
headers=typed_headers,
tool_timeout=timeout_int,
enabled_tools=cast(list[str], enabled_tools_value),
)
@@ -1239,6 +1352,15 @@ def _import_mcp_servers(raw_json: str | None) -> dict[str, MCPServerConfig]:
return out
def _oauth_credentials_replaced(
previous: MCPServerConfig | None,
replacement: MCPServerConfig,
) -> bool:
if previous is None or previous.auth != "oauth":
return False
return replacement.auth != "oauth" or replacement.url != previous.url
def custom_mcp_action(
action: str,
query: QueryParams,
@@ -1248,8 +1370,11 @@ def custom_mcp_action(
config = load_config(config_path) if config_path is not None else load_config()
if action == "custom":
name, cfg = _custom_server_from_query(query)
delete_credentials = _oauth_credentials_replaced(config.tools.mcp_servers.get(name), cfg)
config.tools.mcp_servers[name] = cfg
save_config(config, config_path)
if delete_credentials:
delete_mcp_oauth_credentials(name)
payload = mcp_presets_payload(
last_action=_server_action_message(action, name),
config_path=config_path,
@@ -1259,8 +1384,15 @@ def custom_mcp_action(
if action in {"import", "import-cursor"}:
servers = _import_mcp_servers(_query_first(query, "config"))
delete_credentials = [
name
for name, cfg in servers.items()
if _oauth_credentials_replaced(config.tools.mcp_servers.get(name), cfg)
]
config.tools.mcp_servers.update(servers)
save_config(config, config_path)
for name in delete_credentials:
delete_mcp_oauth_credentials(name)
payload = mcp_presets_payload(
last_action={
"ok": True,
@@ -1289,6 +1421,27 @@ def custom_mcp_action(
raise McpPresetError(f"unknown MCP action '{action}'", status=404)
def ensure_mcp_oauth_server(
query: QueryParams,
*,
config_path: Path | None = None,
) -> tuple[str, MCPServerConfig]:
"""Materialize an OAuth preset on first click and return its saved config."""
name = _validated_server_name((_query_first(query, "name") or "").strip())
config = load_config(config_path) if config_path is not None else load_config()
cfg = config.tools.mcp_servers.get(name)
if cfg is None:
preset = _preset_by_name(name)
if preset.server is None or preset.server.auth != "oauth":
raise McpPresetError("MCP server does not support browser authorization", status=409)
cfg = _materialize_server(preset, query, None)
config.tools.mcp_servers[name] = cfg
save_config(config, config_path)
if cfg.auth != "oauth" or cfg.type not in {"sse", "streamableHttp"} or not cfg.url:
raise McpPresetError("MCP server is not configured for OAuth", status=409)
return name, cfg
def mcp_presets_action(
action: str,
query: QueryParams,
@@ -1328,6 +1481,7 @@ def mcp_presets_action(
cleanup_error = str(exc)
del config.tools.mcp_servers[name]
save_config(config, config_path)
delete_mcp_oauth_credentials(name)
last_action = (
_action_message(action, preset)
if preset is not None
+163 -1
View File
@@ -8,6 +8,7 @@ request mapping and response shaping.
from __future__ import annotations
import asyncio
import html
import inspect
import json
import time
@@ -19,6 +20,7 @@ from websockets.http11 import Response
from nanobot.agent.tools.image_generation import request_image_generation_reload
from nanobot.agent.tools.mcp import request_mcp_reload
from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH
from nanobot.api.runtime import ApiRuntime, ApiStartOptions, api_runtime_paths
from nanobot.bus.queue import MessageBus
from nanobot.channels._setup import channel_setup_spec
@@ -39,9 +41,11 @@ from nanobot.optional_features import (
)
from nanobot.pairing import approve_code, deny_code, list_pending
from nanobot.webui.cli_apps_api import cli_apps_action, cli_apps_payload
from nanobot.webui.http_utils import http_response as _http_response
from nanobot.webui.http_utils import is_local_browser_request as _is_local_browser_request
from nanobot.webui.http_utils import query_first as _query_first
from nanobot.webui.mcp_presets_api import mcp_presets_settings_action
from nanobot.webui.mcp_oauth_api import McpOAuthManager
from nanobot.webui.mcp_presets_api import ensure_mcp_oauth_server, mcp_presets_settings_action
from nanobot.webui.nanobot_features_api import (
nanobot_feature_instance_target,
nanobot_features_action,
@@ -80,6 +84,7 @@ _WEBUI_MUTATION_REQUEST_ATTR = "_nanobot_webui_mutation_request"
_SKIP_FIELD = object()
_CHANNEL_CONNECT_ACTIONS = frozenset({"start", "poll", "cancel"})
_MCP_OAUTH_CALLBACK_URL_MAX_BYTES = 8 * 1024
def _channel_connect_route(path: str) -> tuple[str, str] | None:
@@ -130,6 +135,9 @@ _SETTINGS_MUTATION_PATHS = frozenset({
"/api/settings/channels/configure",
"/api/settings/pairing/approve",
"/api/settings/pairing/deny",
"/api/settings/mcp-oauth/start",
"/api/settings/mcp-oauth/complete",
"/api/settings/mcp-oauth/cancel",
*_MCP_PRESET_ACTIONS_BY_PATH,
})
@@ -177,6 +185,7 @@ class WebUISettingsRouter:
runtime_capabilities: dict[str, Any],
channel_feature_action: Callable[..., Any] | None = None,
channel_runtime_status: Callable[[], dict[str, Any]] | None = None,
mcp_oauth_redirect_uri: Callable[[WsRequest], str] | None = None,
) -> None:
self.settings = settings
self.bus = bus
@@ -189,6 +198,8 @@ class WebUISettingsRouter:
self._runtime_capabilities = runtime_capabilities
self._channel_feature_action = channel_feature_action
self._channel_runtime_status = channel_runtime_status
self._mcp_oauth_redirect_uri = mcp_oauth_redirect_uri
self._mcp_oauth = McpOAuthManager()
self._restart_sections: set[str] = set()
self._channel_connectors: dict[str, Any] = {}
@@ -202,6 +213,8 @@ class WebUISettingsRouter:
405,
"WebUI mutations require an authenticated WebSocket",
)
if path == MCP_OAUTH_CALLBACK_PATH:
return self._handle_mcp_oauth_callback(request)
if path == "/api/settings":
return self._handle_settings(request)
if path == "/api/settings/usage":
@@ -281,6 +294,14 @@ class WebUISettingsRouter:
return self._handle_settings_pairing_action(request, "deny")
if path == "/api/settings/mcp-presets":
return await self._handle_settings_mcp_presets(request)
if path == "/api/settings/mcp-oauth/start":
return await self._handle_mcp_oauth_start(request)
if path == "/api/settings/mcp-oauth/status":
return await self._handle_mcp_oauth_status(request)
if path == "/api/settings/mcp-oauth/complete":
return self._handle_mcp_oauth_complete(request)
if path == "/api/settings/mcp-oauth/cancel":
return await self._handle_mcp_oauth_cancel(request)
if path == "/api/settings/version-check":
return await self._handle_settings_version_check(request)
mcp_action = _MCP_PRESET_ACTIONS_BY_PATH.get(path)
@@ -1230,6 +1251,147 @@ class WebUISettingsRouter:
return self._json_response(payload)
return self._json_response(self._with_restart_state(payload, section="runtime"))
async def _handle_mcp_oauth_start(self, request: WsRequest) -> Response:
if not self._authorized(request):
return self._unauthorized()
if self._mcp_oauth_redirect_uri is None:
return self._error_response(500, "MCP OAuth callback is not configured")
query = self._parse_mcp_settings_query(request)
try:
name, cfg = await asyncio.to_thread(
self.settings.mutate,
ensure_mcp_oauth_server,
query,
)
redirect_uri = self._mcp_oauth_redirect_uri(request)
reset = (_query_first(query, "reset") or "").lower() in {"1", "true", "yes"}
payload = await self._mcp_oauth.start(
name,
cfg,
redirect_uri,
reload_mcp=lambda: request_mcp_reload(self.bus),
reset_credentials=reset,
)
except Exception as exc:
return self._mcp_oauth_error_response(exc, action="start")
return self._json_response(payload)
async def _handle_mcp_oauth_status(self, request: WsRequest) -> Response:
if not self._authorized(request):
return self._unauthorized()
flow_id = (_query_first(self._query(request), "flow_id") or "").strip()
if not flow_id:
return self._error_response(400, "missing MCP OAuth flow ID")
try:
payload = await self._mcp_oauth.status(flow_id)
except Exception as exc:
return self._mcp_oauth_error_response(exc, action="status")
return self._json_response(payload)
def _handle_mcp_oauth_complete(self, request: WsRequest) -> Response:
if not self._authorized(request):
return self._unauthorized()
query = self._query(request)
flow_id = (_query_first(query, "flow_id") or "").strip()
if not flow_id:
return self._error_response(400, "missing MCP OAuth flow ID")
callback_url = (_query_first(query, "callback_url") or "").strip()
if not callback_url:
return self._error_response(400, "Paste the complete callback URL to continue")
if len(callback_url.encode("utf-8")) > _MCP_OAUTH_CALLBACK_URL_MAX_BYTES:
return self._error_response(400, "The MCP OAuth callback URL is too long")
try:
payload = self._mcp_oauth.submit_callback_url(
flow_id=flow_id,
callback_url=callback_url,
)
except Exception as exc:
return self._mcp_oauth_error_response(exc, action="complete")
return self._json_response(payload)
async def _handle_mcp_oauth_cancel(self, request: WsRequest) -> Response:
if not self._authorized(request):
return self._unauthorized()
flow_id = (_query_first(self._query(request), "flow_id") or "").strip()
if not flow_id:
return self._error_response(400, "missing MCP OAuth flow ID")
try:
payload = await self._mcp_oauth.cancel(flow_id)
except Exception as exc:
return self._mcp_oauth_error_response(exc, action="cancel")
return self._json_response(payload)
def _handle_mcp_oauth_callback(self, request: WsRequest) -> Response:
query = self._query(request)
state = (_query_first(query, "state") or "").strip()
if not state:
return self._mcp_oauth_callback_page(
ok=False,
message="This authorization request is missing its security state.",
status=400,
)
try:
name = self._mcp_oauth.submit_callback(
state=state,
code=_query_first(query, "code"),
error=_query_first(query, "error"),
)
except Exception as exc:
status = int(getattr(exc, "status", 400))
message = str(getattr(exc, "message", "Could not complete MCP authorization"))
return self._mcp_oauth_callback_page(ok=False, message=message, status=status)
return self._mcp_oauth_callback_page(
ok=True,
message=f"Authorization received for {name}. Return to nanobot to finish connecting.",
)
def _mcp_oauth_error_response(self, exc: Exception, *, action: str) -> Response:
raw_status = getattr(exc, "status", 500)
status = raw_status if isinstance(raw_status, int) and 400 <= raw_status <= 599 else 500
if status >= 500:
self.logger.exception("MCP OAuth '{}' failed", action)
message = f"MCP OAuth {action} failed"
else:
raw_message = getattr(exc, "message", None)
message = raw_message if isinstance(raw_message, str) else "MCP OAuth request failed"
return self._error_response(status, message)
@staticmethod
def _mcp_oauth_callback_page(
*,
ok: bool,
message: str,
status: int = 200,
) -> Response:
title = "Authorization received" if ok else "Connection failed"
safe_title = html.escape(title)
safe_message = html.escape(message)
close_script = "<script>setTimeout(() => window.close(), 700)</script>" if ok else ""
body = (
"<!doctype html><html><head><meta charset='utf-8'>"
"<meta name='viewport' content='width=device-width,initial-scale=1'>"
f"<title>{safe_title}</title><style>"
"body{font:16px system-ui;margin:0;min-height:100vh;display:grid;place-items:center;"
"background:#f7f7f6;color:#171717}.card{max-width:34rem;margin:2rem;padding:2rem;"
"border:1px solid #ddd;border-radius:16px;background:white}h1{font-size:1.35rem}"
"p{line-height:1.55;color:#555}</style></head><body><main class='card'>"
f"<h1>{safe_title}</h1><p>{safe_message}</p></main>{close_script}</body></html>"
).encode("utf-8")
return _http_response(
body,
status=status,
content_type="text/html; charset=utf-8",
extra_headers=[
("Cache-Control", "no-store"),
("Referrer-Policy", "no-referrer"),
(
"Content-Security-Policy",
"default-src 'none'; base-uri 'none'; form-action 'none'; "
"frame-ancestors 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'",
),
],
)
async def _handle_settings_version_check(self, request: WsRequest) -> Response:
if not self._authorized(request):
return self._unauthorized()
+13 -1
View File
@@ -17,7 +17,7 @@ import time
from collections.abc import Callable
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
from urllib.parse import quote, unquote
from urllib.parse import quote, unquote, urlsplit, urlunsplit
from loguru import logger
from websockets.datastructures import Headers
@@ -166,6 +166,9 @@ _WEBUI_MUTATION_PATHS = {
"settings.mcp.import": "/api/settings/mcp-presets/import",
"settings.mcp.import_cursor": "/api/settings/mcp-presets/import-cursor",
"settings.mcp.tools": "/api/settings/mcp-presets/tools",
"settings.mcp.oauth_start": "/api/settings/mcp-oauth/start",
"settings.mcp.oauth_complete": "/api/settings/mcp-oauth/complete",
"settings.mcp.oauth_cancel": "/api/settings/mcp-oauth/cancel",
}
_WEBUI_CHANNEL_CONNECT_ACTIONS = {
@@ -344,6 +347,7 @@ class GatewayHTTPHandler:
runtime_capabilities=self._capabilities,
channel_feature_action=channel_feature_action,
channel_runtime_status=channel_runtime_status,
mcp_oauth_redirect_uri=self._mcp_oauth_redirect_uri,
)
def workspace_controls_available(self, connection: Any) -> bool:
@@ -617,6 +621,14 @@ class GatewayHTTPHandler:
expected_path = _normalize_config_path(self.config.path)
return f"{scheme}://{host}{expected_path}"
def _mcp_oauth_redirect_uri(self, request: WsRequest) -> str:
"""Derive the browser callback from the same public origin as WebSocket bootstrap."""
from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH
public_ws_url = urlsplit(self._bootstrap_ws_url(request))
scheme = "https" if public_ws_url.scheme == "wss" else "http"
return urlunsplit((scheme, public_ws_url.netloc, MCP_OAUTH_CALLBACK_PATH, "", ""))
# -- Session routes -----------------------------------------------------
async def _dispatch_session_routes(self, request: WsRequest, got: str) -> Response | None: