Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(mcp): OAuth login and token refresh for MCP Hub servers (#3076)

rkrkrkkda1240ac5dc1
diff --git a/core/mcp_hub/definition.py b/core/mcp_hub/definition.py
index 8ee47c70d..c6366a2cb 100644
--- a/core/mcp_hub/definition.py
+++ b/core/mcp_hub/definition.py
@@ -121,6 +121,11 @@ def definition_from_provider(name: str, server: object) -> dict[str, Any]:
"url": _validate_url(server.get("url")),
"headers": _string_map(server.get("headers"), "headers", _HEADER_NAME),
}
+ oauth = server.get("oauth")
+ if isinstance(oauth, dict):
+ selected = {key: oauth[key] for key in ("clientId", "scopes") if key in oauth and isinstance(oauth[key], str)}
+ if selected:
+ definition["oauth"] = selected
return definition
if kind not in _STDIO_TYPES:
raise _invalid("type", f"Unsupported transport type {kind!r}.")
@@ -313,6 +318,8 @@ def provider_entry(definition: dict[str, Any]) -> dict[str, Any]:
entry: dict[str, Any] = {"type": "http", "url": transport["url"]}
if transport.get("headers"):
entry["headers"] = transport["headers"]
+ if definition.get("oauth"):
+ entry["oauth"] = dict(definition["oauth"])
return entry
entry = {"command": transport["command"], "args": list(transport.get("args") or [])}
for field in ("env", "cwd"):
diff --git a/core/mcp_hub/oauth.py b/core/mcp_hub/oauth.py
new file mode 100644
index 000000000..ab12057c3
--- /dev/null
+++ b/core/mcp_hub/oauth.py
@@ -0,0 +1,155 @@
+"""Durable OAuth primitives for HTTP MCP Hub servers."""
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import time
+from pathlib import Path
+from urllib.parse import parse_qs, urlparse
+
+from config import paths
+from config.atomic_io import write_atomic
+from core.mcp_hub.errors import McpHubError
+from mcp.client.auth.oauth2 import OAuthClientProvider
+from mcp.shared.auth import OAuthClientMetadata, OAuthClientInformationFull, OAuthMetadata, OAuthToken, ProtectedResourceMetadata
+
+logger = logging.getLogger(__name__)
+
+
+def oauth_path(name: str) -> Path:
+ return paths.get_vibe_remote_dir() / "mcp" / name / "oauth.json"
+
+
+def delete_oauth(name: str) -> None:
+ try:
+ oauth_path(name).unlink()
+ except FileNotFoundError:
+ pass
+
+
+def read_state(name: str, server_url: str) -> dict:
+ try:
+ value = json.loads(oauth_path(name).read_text(encoding="utf-8"))
+ except (FileNotFoundError, OSError, ValueError):
+ return {}
+ return value if isinstance(value, dict) and value.get("serverUrl") == server_url else {}
+
+
+def _write(name: str, value: dict) -> None:
+ write_atomic(oauth_path(name), json.dumps(value, ensure_ascii=False, indent=2) + "\n", mode=0o600)
+
+
+class AvibeTokenStorage:
+ def __init__(self, name: str, server_url: str, redirect_uri: str | None = None) -> None:
+ self.name, self.server_url, self.redirect_uri = name, server_url, redirect_uri
+
+ def raw(self) -> dict:
+ return read_state(self.name, self.server_url)
+
+ async def get_tokens(self) -> OAuthToken | None:
+ value = (await asyncio.to_thread(self.raw)).get("tokens")
+ return OAuthToken.model_validate(value) if isinstance(value, dict) else None
+
+ async def set_tokens(self, tokens: OAuthToken) -> None:
+ value = await asyncio.to_thread(self.raw)
+ value.update(schemaVersion=1, serverUrl=self.server_url, tokens=tokens.model_dump(mode="json"))
+ if tokens.expires_in is not None:
+ value["expiresAt"] = int(time.time()) + int(tokens.expires_in)
+ else:
+ value.pop("expiresAt", None)
+ await asyncio.to_thread(_write, self.name, value)
+ async def get_client_info(self) -> OAuthClientInformationFull | None:
+ value = (await asyncio.to_thread(self.raw)).get("client")
+ if isinstance(value, dict) and self.redirect_uri is not None:
+ uris = [str(item) for item in value.get("redirect_uris") or []]
+ if self.redirect_uri not in uris:
+ return None
+ return OAuthClientInformationFull.model_validate(value) if isinstance(value, dict) else None
+
+ async def set_client_info(self, client_info: OAuthClientInformationFull) -> None:
+ value = await asyncio.to_thread(self.raw)
+ value.update(schemaVersion=1, serverUrl=self.server_url, client=client_info.model_dump(mode="json"))
+ await asyncio.to_thread(_write, self.name, value)
+
+ def drop_client(self) -> None:
+ value = self.raw()
+ value.pop("client", None)
+ _write(self.name, value)
+
+ async def clear_tokens(self) -> None:
+ value = await asyncio.to_thread(self.raw)
+ value.pop("tokens", None)
+ value.pop("expiresAt", None)
+ await asyncio.to_thread(_write, self.name, value)
+
+class AvibeOAuthProvider(OAuthClientProvider):
+ """SDK provider with persisted expiry, AS metadata and PRM."""
+
+ async def _initialize(self) -> None:
+ await super()._initialize()
+ raw = await asyncio.to_thread(self.context.storage.raw) if hasattr(self.context.storage, "raw") else {}
+ if raw.get("expiresAt") is not None:
+ self.context.token_expiry_time = float(raw["expiresAt"])
+ for key, attr, model in (("authServerMetadata", "oauth_metadata", OAuthMetadata), ("resourceMetadata", "protected_resource_metadata", ProtectedResourceMetadata)):
+ if isinstance(raw.get(key), dict):
+ try:
+ setattr(self.context, attr, model.model_validate(raw[key]))
+ except Exception:
+ logger.warning("Ignoring invalid stored MCP OAuth metadata")
+ configured = getattr(self, "_configured_client_info", None)
+ if configured is not None:
+ self.context.client_info = configured
+
+ async def _handle_token_response(self, response) -> None:
+ await super()._handle_token_response(response)
+ raw = await asyncio.to_thread(self.context.storage.raw)
+ if self.context.oauth_metadata is not None:
+ raw["authServerMetadata"] = self.context.oauth_metadata.model_dump(mode="json")
+ if self.context.protected_resource_metadata is not None:
+ raw["resourceMetadata"] = self.context.protected_resource_metadata.model_dump(mode="json")
+ await asyncio.to_thread(_write, self.context.storage.name, raw)
+
+ async def _handle_refresh_response(self, response) -> bool:
+ status = getattr(response, "status_code", 0)
+ ok = await super()._handle_refresh_response(response)
+ if not ok and status in {400, 401}:
+ await self.context.storage.clear_tokens()
+ return ok
+
+
+def redirect_mode(origin: str | None, *, cloud_origin: str | None = None, cli: bool = False, port: int | None = None) -> tuple[str, str]:
+ candidate = cloud_origin if cli and cloud_origin else origin
+ parsed = urlparse(candidate or "")
+ host = (parsed.hostname or "").lower()
+ direct = parsed.scheme == "https" or (parsed.scheme == "http" and host in {"localhost", "127.0.0.1", "::1"})
+ if direct:
+ return ("direct", f"{parsed.scheme}://{parsed.netloc}/api/mcp/oauth/callback")
+ if port is None:
+ raise McpHubError("usage", "A loopback setup port is required for MCP OAuth paste-mode redirects.")
+ return ("paste", f"http://127.0.0.1:{int(port)}/api/mcp/oauth/callback")
+
+
+def parse_callback_url(value: str) -> dict[str, str]:
+ parsed = urlparse(value)
+ if parsed.path != "/api/mcp/oauth/callback":
+ raise McpHubError("invalid_callback", "The callback URL is not an Avibe MCP OAuth callback.")
+ result = {key: values[0] for key, values in parse_qs(parsed.query).items() if values}
+ if not result.get("code") or not result.get("state"):
+ raise McpHubError("invalid_callback", "The callback URL is missing OAuth state or code.")
+ return result
+
+
+def make_provider(name: str, definition: dict, redirect_uri: str, *, redirect_handler, callback_handler, filter_redirect: bool = True) -> AvibeOAuthProvider:
+ transport = definition["transport"]
+ oauth = definition.get("oauth") or {}
+ provider = AvibeOAuthProvider(
+ transport["url"],
+ OAuthClientMetadata(redirect_uris=[redirect_uri], client_name="Avibe MCP Hub", application_type="native", token_endpoint_auth_method="none", scope=oauth.get("scopes")),
+ AvibeTokenStorage(name, transport["url"], redirect_uri if filter_redirect else None),
+ redirect_handler=redirect_handler, callback_handler=callback_handler,
+ )
+ if isinstance(oauth.get("clientId"), str) and oauth["clientId"]:
+ provider.context.client_info = OAuthClientInformationFull(client_id=oauth["clientId"], redirect_uris=[redirect_uri])
+ provider._configured_client_info = provider.context.client_info
+ return provider
diff --git a/core/mcp_hub/prompt.py b/core/mcp_hub/prompt.py
index dd6ac0537..3e078d675 100644
--- a/core/mcp_hub/prompt.py
+++ b/core/mcp_hub/prompt.py
@@ -29,7 +29,7 @@ def build_mcp_prompt_blocks() -> list[RenderedPromptBlock]:
except Exception:
logger.warning("MCP prompt index unavailable", exc_info=True)
return []
- entries, next_page = catalog_page_of(packages, server_row, 1)
+ entries, next_page = catalog_page_of([item for item in packages if item.get("auth") != "needs_login"], server_row, 1)
if not entries:
return []
blocks = [render_prompt_block("mcp-capabilities-prompt")]
diff --git a/core/mcp_hub/repository.py b/core/mcp_hub/repository.py
index 5b85a9f60..bdba6104a 100644
--- a/core/mcp_hub/repository.py
+++ b/core/mcp_hub/repository.py
@@ -22,6 +22,7 @@ from typing import Any, Optional
from config import paths
from config.atomic_io import write_atomic
from core.mcp_hub import native
+from core.mcp_hub import oauth as mcp_oauth
from core.mcp_hub.definition import validate_name
from core.mcp_hub.errors import McpHubError
from core.private_fs import ensure_private_directory
@@ -196,6 +197,7 @@ def remove_package(name: str) -> str:
"""Avibe source: delete artifacts. Native source: hide in Avibe only."""
validate_name(name)
+ mcp_oauth.delete_oauth(name)
if read_avibe_definition(name) is not None:
directory = package_dir(name)
if directory.exists():
@@ -362,8 +364,10 @@ def summarize(name: str, servers: Optional[dict[str, native.NativeServer]] = Non
command = " ".join([transport.get("command") or "", *(transport.get("args") or [])]).strip()
else:
url = str(transport.get("url") or "")
+ summary_auth = manifest.get("auth", "none")
return {
"name": name,
+ "auth": summary_auth,
"source": source,
"sourcePath": source_path,
"description": manifest.get("description") or "",
diff --git a/core/mcp_hub/runtime.py b/core/mcp_hub/runtime.py
index dbcdb14fa..8941b68d7 100644
--- a/core/mcp_hub/runtime.py
+++ b/core/mcp_hub/runtime.py
@@ -19,11 +19,13 @@ import threading
import time
from datetime import datetime, timezone
from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
import anyio
from core.mcp_hub import commands as mcp_commands
from core.mcp_hub import native, repository
+from core.mcp_hub import oauth as mcp_oauth
from core.mcp_hub.definition import HTTP, STDIO, definition_from_provider, normalize_description
from core.mcp_hub.errors import McpHubError
@@ -34,6 +36,7 @@ IDLE_CLOSE_SECONDS = 600
CALL_TIMEOUT_SECONDS = 120
CONNECT_TIMEOUT_SECONDS = 60
GENERATION_TIMEOUT_SECONDS = 300
+OAUTH_LOGIN_TIMEOUT_SECONDS = 600
TOOLS_PAGE_CAP = 100
# Results above this are not returned (the call still completed; see envelope).
RESULT_BYTE_CAP = 4 * 1024 * 1024
@@ -59,7 +62,7 @@ def _http_session_lost(exc: Exception) -> bool:
return message == "Session terminated"
-def _client_for(definition: dict[str, Any], stack: contextlib.AsyncExitStack, mode: str = "auto"):
+def _client_for(definition: dict[str, Any], stack: contextlib.AsyncExitStack, mode: str = "auto", auth=None):
"""Build an SDK client for a revision snapshot (never the edited top-level file)."""
from mcp import Client, StdioServerParameters
@@ -71,13 +74,12 @@ def _client_for(definition: dict[str, Any], stack: contextlib.AsyncExitStack, mo
info = Implementation(name="avibe", version="1")
if transport["type"] == STDIO:
params = StdioServerParameters(
- command=transport["command"],
- args=list(transport.get("args") or []),
- env=dict(transport.get("env") or {}) or None,
- cwd=transport.get("cwd"),
+ command=transport["command"], args=list(transport.get("args") or []),
+ env=dict(transport.get("env") or {}) or None, cwd=transport.get("cwd"),
)
return Client(params, client_info=info, mode=mode)
- http_client = create_mcp_http_client(headers=dict(transport.get("headers") or {}))
+ headers = dict(transport.get("headers") or {})
+ http_client = create_mcp_http_client(headers=headers, auth=auth)
stack.push_async_callback(http_client.aclose)
return Client(streamable_http_client(transport["url"], http_client=http_client), client_info=info, mode=mode)
@@ -92,7 +94,7 @@ def _closed_during_handshake(exc: BaseException) -> bool:
return any(_closed_during_handshake(item) for item in getattr(exc, "exceptions", ()))
-async def _enter_client(definition: dict[str, Any], stack: contextlib.AsyncExitStack):
+async def _enter_client(definition: dict[str, Any], stack: contextlib.AsyncExitStack, auth=None):
"""Enter a client; retry once with the initialize handshake for strict pre-2026 servers.
The default probe sends ``server/discover`` first, and strict legacy servers
@@ -100,11 +102,11 @@ async def _enter_client(definition: dict[str, Any], stack: contextlib.AsyncExitS
"""
try:
- return await stack.enter_async_context(_client_for(definition, stack))
+ return await stack.enter_async_context(_client_for(definition, stack, auth=auth))
except Exception as exc:
if not _closed_during_handshake(exc):
raise
- return await stack.enter_async_context(_client_for(definition, stack, mode="legacy"))
+ return await stack.enter_async_context(_client_for(definition, stack, mode="legacy", auth=auth))
def _first_sentence(text: Optional[str]) -> Optional[str]:
@@ -162,12 +164,15 @@ class _Connection:
raise
except Exception as exc:
await self.close()
+ hub = _hub_error(exc)
+ if hub is not None:
+ raise hub from None
raise McpHubError("connection", f"Could not connect to the MCP server: {_describe(exc)}") from None
async def _run(self) -> None:
try:
async with contextlib.AsyncExitStack() as stack:
- client = await _enter_client(self.definition, stack)
+ client = await _enter_client(self.definition, stack, auth=await self.runtime._oauth_provider(self.definition))
# The SDK learns every tool's output schema before the first call.
await _list_all_tools(client)
self._ready.set_result(client)
@@ -198,6 +203,80 @@ class _Connection:
self._task.cancel()
+def _hub_error(exc: BaseException, *, _seen: Optional[set[int]] = None) -> Optional[McpHubError]:
+ seen = _seen if _seen is not None else set()
+ marker = id(exc)
+ if marker in seen:
+ return None
+ seen.add(marker)
+ if isinstance(exc, McpHubError):
+ return exc
+ for item in getattr(exc, "exceptions", ()) or ():
+ if isinstance(item, BaseException):
+ nested = _hub_error(item, _seen=seen)
+ if nested is not None:
+ return nested
+ cause = getattr(exc, "__cause__", None) or getattr(exc, "__context__", None)
+ return _hub_error(cause, _seen=seen) if isinstance(cause, BaseException) else None
+
+
+def _http_status(exc: BaseException, *, _seen: Optional[set[int]] = None) -> Optional[int]:
+ """HTTP status on this exception or its cause chain, not from error text."""
+ seen = _seen if _seen is not None else set()
+ marker = id(exc)
+ if marker in seen:
+ return None
+ seen.add(marker)
+ response = getattr(exc, "response", None)
+ status = getattr(response, "status_code", None) if response is not None else getattr(exc, "status_code", None)
+ if isinstance(status, int):
+ return status
+ for item in getattr(exc, "exceptions", ()) or ():
+ if isinstance(item, BaseException):
+ nested = _http_status(item, _seen=seen)
+ if nested is not None:
+ return nested
+ cause = getattr(exc, "__cause__", None) or getattr(exc, "__context__", None)
+ return _http_status(cause, _seen=seen) if isinstance(cause, BaseException) else None
+
+
+def _explicit_authorization(definition: dict[str, Any]) -> bool:
+ headers = (definition.get("transport") or {}).get("headers") or {}
+ return any(key.lower() == "authorization" for key in headers)
+
+
+def _oauth_eligible(definition: dict[str, Any]) -> bool:
+ return (definition.get("transport") or {}).get("type") == HTTP and not _explicit_authorization(definition)
+
+
+def _oauth_challenge(exc: BaseException, *, _seen: Optional[set[int]] = None) -> bool:
+ """Recognize a protected-resource OAuth challenge through exception causes."""
+ seen = _seen if _seen is not None else set()
+ marker = id(exc)
+ if marker in seen:
+ return False
+ seen.add(marker)
+ response = getattr(exc, "response", None)
+ if response is not None and getattr(response, "status_code", None) == 401:
+ try:
+ from mcp.client.auth.utils import extract_resource_metadata_from_www_auth
+
+ if extract_resource_metadata_from_www_auth(response):
+ return True
+ except Exception:
+ headers = getattr(response, "headers", None) or {}
+ header = ""
+ if hasattr(headers, "get"):
+ header = str(headers.get("WWW-Authenticate") or headers.get("www-authenticate") or "")
+ if "resource_metadata=" in header:
+ return True
+ for item in getattr(exc, "exceptions", ()) or ():
+ if isinstance(item, BaseException) and _oauth_challenge(item, _seen=seen):
+ return True
+ cause = getattr(exc, "__cause__", None) or getattr(exc, "__context__", None)
+ return isinstance(cause, BaseException) and _oauth_challenge(cause, _seen=seen)
+
+
def _http_excerpt(response: object) -> str:
status = getattr(response, "status_code", None)
if status is None:
@@ -266,6 +345,11 @@ class McpRuntime:
self._sweeper: Optional[asyncio.Task] = None
self._discover_lock = asyncio.Lock()
self._discover_task: Optional[asyncio.Task] = None
+ self._oauth_providers: dict[str, Any] = {}
+ self._pending_logins: dict[str, dict[str, Any]] = {}
+ self._oauth_tasks: dict[str, asyncio.Task] = {}
+ self._oauth_logins: set[str] = set()
+ self._oauth_provider_locks: dict[str, asyncio.Lock] = {}
# -- thread ---------------------------------------------------------------
@@ -345,6 +429,48 @@ class McpRuntime:
if self._connections.get(connection.key) is connection:
del self._connections[connection.key]
+ @staticmethod
+ def _oauth_cache_identity(definition: dict[str, Any]) -> tuple[Any, Any, Any]:
+ transport = definition.get("transport") or {}
+ oauth = definition.get("oauth") or {}
+ return (transport.get("url"), oauth.get("clientId"), oauth.get("scopes"))
+
+ async def _oauth_provider(self, definition: dict[str, Any]):
+ transport = definition.get("transport") or {}
+ if not _oauth_eligible(definition):
+ return None
+ name = definition["name"]
+ identity = self._oauth_cache_identity(definition)
+ lock = self._oauth_provider_locks.setdefault(name, asyncio.Lock())
+ async with lock:
+ provider = self._oauth_providers.get(name)
+ if provider is not None and getattr(provider, "_cache_identity", None) != identity:
+ self._oauth_providers.pop(name, None)
+ provider = None
+ if provider is not None:
+ return provider
+ provider = await self._make_call_time_provider(name, definition, transport)
+ provider._cache_identity = identity
+ self._oauth_providers[name] = provider
+ return provider
+
+ async def _make_call_time_provider(self, name: str, definition: dict[str, Any], transport: dict[str, Any]):
+ async def _redirect(_url: str) -> None:
+ raise McpHubError("auth_required", "MCP OAuth login is required.", hint=f"vibe mcp {name} --login")
+ async def _callback():
+ raise McpHubError("auth_required", "MCP OAuth login is required.")
+ raw = await asyncio.to_thread(mcp_oauth.read_state, name, transport["url"])
+ uris = (raw.get("client") or {}).get("redirect_uris") or []
+ redirect_uri = str(uris[0]) if uris else "http://127.0.0.1/api/mcp/oauth/callback"
+ return mcp_oauth.make_provider(
+ name,
+ definition,
+ redirect_uri,
+ redirect_handler=_redirect,
+ callback_handler=_callback,
+ filter_redirect=False,
+ )
+
def _lock(self, name: str) -> asyncio.Lock:
return self._package_locks.setdefault(name, asyncio.Lock())
@@ -392,6 +518,10 @@ class McpRuntime:
"discover": self._discover_all,
"remove": self._remove,
"call": self._call,
+ "oauth_start": self._oauth_start,
+ "oauth_complete": self._oauth_complete,
+ "oauth_callback": self._oauth_callback,
+ "oauth_logout": self._oauth_logout,
}
handler = handlers.get(operation)
if handler is None:
@@ -452,12 +582,15 @@ class McpRuntime:
saved = True
body = json.loads(await self._refresh({"name": name, "waitStdio": True, "locked": True}))
if body.get("ok"):
- return {
+ result = {
"name": name,
"status": "added",
"revision": body.get("revision"),
"toolCount": body.get("toolCount"),
}
+ if body.get("auth") == "needs_login":
+ result["auth"] = "needs_login"
+ return result
error = (body.get("error") or {}).get("message") or "failed"
except McpHubError as cop:
error = cop.message
@@ -472,10 +605,14 @@ class McpRuntime:
transport = dict(definition.get("transport") or {})
if transport.get("type") == STDIO and not transport.get("cwd"):
transport["cwd"] = repository.default_cwd()
- return {
+ comparable = {
"name": definition.get("name"),
"transport": transport,
}
+ oauth = definition.get("oauth")
+ if isinstance(oauth, dict):
+ comparable["oauth"] = {key: oauth.get(key) for key in ("clientId", "scopes")}
+ return comparable
@staticmethod
def _save_one(definition: dict[str, Any], replace: bool) -> str:
@@ -515,14 +652,23 @@ class McpRuntime:
async with self._lock(name):
return await self._refresh_locked(name, wait_stdio=payload.get("waitStdio") is True, unlist_on_failure=True)
- async def _refresh_locked(self, name: str, *, wait_stdio: bool, unlist_on_failure: bool = False) -> bytes:
+ async def _refresh_locked(
+ self,
+ name: str,
+ *,
+ wait_stdio: bool,
+ unlist_on_failure: bool = False,
+ lock_publish: bool = False,
+ ) -> bytes:
definition = await asyncio.to_thread(repository.read_definition, name)
snapshot = json.loads(json.dumps(definition))
if snapshot["transport"]["type"] == STDIO and not snapshot["transport"].get("cwd"):
snapshot["transport"]["cwd"] = await asyncio.to_thread(repository.default_cwd)
stdio = snapshot["transport"]["type"] == STDIO
- deadline = time.monotonic() + GENERATION_TIMEOUT_SECONDS
+ deadline = time.monotonic() + (
+ OAUTH_LOGIN_TIMEOUT_SECONDS if name in self._oauth_logins else GENERATION_TIMEOUT_SECONDS
+ )
acquired = False
try:
if stdio:
@@ -544,19 +690,38 @@ class McpRuntime:
if unlist_on_failure:
await asyncio.to_thread(repository.unlist, name)
raise McpHubError("timeout", "Refresh timed out.") from None
- except McpHubError:
+ except McpHubError as cop:
+ if _oauth_eligible(definition) and cop.type in {"auth_required", "oauth"} and name not in self._oauth_logins:
+ revision = await asyncio.to_thread(self._publish_needs_login, name, definition)
+ return _dumps({"ok": True, "name": name, "revision": revision, "toolCount": 0, "auth": "needs_login"})
if unlist_on_failure:
await asyncio.to_thread(repository.unlist, name)
raise
except Exception as cop:
+ hub = _hub_error(cop)
+ if _oauth_eligible(definition) and name not in self._oauth_logins and (
+ (hub is not None and hub.type in {"auth_required", "oauth"}) or _oauth_challenge(cop)
+ ):
+ revision = await asyncio.to_thread(self._publish_needs_login, name, definition)
+ return _dumps({"ok": True, "name": name, "revision": revision, "toolCount": 0, "auth": "needs_login"})
if unlist_on_failure:
await asyncio.to_thread(repository.unlist, name)
+ if hub is not None:
+ raise hub from None
raise McpHubError("connection", f"Refresh failed: {_describe(cop)}") from None
finally:
if acquired:
self.release_stdio_slot()
- revision = await asyncio.to_thread(self._publish, name, snapshot, definition, tools, server_info, instructions)
- await self._retire_package(name, keep_revision=revision)
+ async def _publish_revision() -> str:
+ revision = await asyncio.to_thread(self._publish, name, snapshot, definition, tools, server_info, instructions)
+ await self._retire_package(name, keep_revision=revision)
+ return revision
+
+ if lock_publish:
+ async with self._lock(name):
+ revision = await _publish_revision()
+ else:
+ revision = await _publish_revision()
return _dumps({"ok": True, "name": name, "revision": revision, "toolCount": len(tools)})
async def _discover_all(self, payload: dict[str, Any]) -> bytes:
@@ -600,7 +765,10 @@ class McpRuntime:
await asyncio.to_thread(repository.unlist, name)
return {"name": name, "status": "failed", "error": str(cop)}
if body.get("ok"):
- return {"name": name, "status": "registered", "toolCount": body.get("toolCount")}
+ result = {"name": name, "status": "registered", "toolCount": body.get("toolCount")}
+ if body.get("auth") == "needs_login":
+ result["auth"] = "needs_login"
+ return result
error = (body.get("error") or {}).get("message") or "failed"
logger.warning("MCP discover %s failed: %s", name, error)
await asyncio.to_thread(repository.unlist, name)
@@ -608,13 +776,27 @@ class McpRuntime:
return list(await asyncio.gather(*(one(name) for name in sorted(names))))
- @staticmethod
- async def _discover(snapshot: dict[str, Any]) -> tuple[list, Any, Optional[str]]:
+ async def _discover(self, snapshot: dict[str, Any]) -> tuple[list, Any, Optional[str]]:
async with contextlib.AsyncExitStack() as stack:
- client = await _enter_client(snapshot, stack)
+ client = await _enter_client(snapshot, stack, auth=await self._oauth_provider(snapshot))
return await _list_all_tools(client), client.server_info, client.instructions
@staticmethod
+ def _publish_needs_login(name: str, definition: dict[str, Any]) -> str:
+ return repository.publish(name, definition=definition, manifest={"description": "", "auth": "needs_login"}, tools=[], commands=[])
+
+ async def _publish_call_time_needs_login(self, name: str, revision: str, definition: dict[str, Any]) -> None:
+ async with self._lock(name):
+ def _maybe() -> None:
+ published = repository.read_published(name)
+ if published is None or published.get("revision") != revision:
+ return
+ if (published.get("manifest") or {}).get("auth") == "needs_login":
+ return
+ self._publish_needs_login(name, definition)
+
+ await asyncio.to_thread(_maybe)
+ @staticmethod
def _publish(name, snapshot, definition, tools, server_info, instructions=None) -> str:
descriptors, diagnostics, seen = [], [], set()
for tool in tools:
@@ -636,6 +818,8 @@ class McpRuntime:
"generatedAt": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
version = getattr(server_info, "version", None)
+ if _oauth_eligible(snapshot):
+ manifest["auth"] = "ok"
if version:
manifest["serverInfo"] = {"version": str(version)}
if diagnostics:
@@ -649,14 +833,160 @@ class McpRuntime:
)
return revision
+ async def _oauth_start(self, payload: dict[str, Any]) -> bytes:
+ name = payload.get("name")
+ definition = await asyncio.to_thread(repository.read_definition, name)
+ transport = definition.get("transport") or {}
+ if not _oauth_eligible(definition):
+ raise McpHubError("usage", "OAuth login is only available for HTTP MCP servers without an Authorization header.", usage=True)
+ port = payload.get("port")
+ mode, redirect_uri = mcp_oauth.redirect_mode(
+ payload.get("origin"),
+ cloud_origin=payload.get("cloudOrigin"),
+ cli=payload.get("cli") is True,
+ port=int(port) if port is not None else None,
+ )
+ async with self._lock(name):
+ previous = self._oauth_tasks.pop(name, None)
+ for state, item in list(self._pending_logins.items()):
+ if item.get("name") == name:
+ self._pending_logins.pop(state, None)
+ future = item.get("callback")
+ if future is not None and not future.done():
+ future.cancel()
+ if previous is not None and not previous.done():
+ previous.cancel()
+ await asyncio.gather(previous, return_exceptions=True)
+ stored_client = (await asyncio.to_thread(mcp_oauth.read_state, name, transport["url"])).get("client")
+ if isinstance(stored_client, dict) and redirect_uri not in [str(item) for item in stored_client.get("redirect_uris") or []]:
+ await asyncio.to_thread(mcp_oauth.AvibeTokenStorage(name, transport["url"]).drop_client)
+ url_future = asyncio.get_running_loop().create_future()
+ callback_future = asyncio.get_running_loop().create_future()
+ origin = str(payload.get("origin") or "").rstrip("/")
+ record = {
+ "name": name,
+ "callback": callback_future,
+ "url": url_future,
+ "redirect_uri": redirect_uri,
+ "mode": mode,
+ "returnUrl": f"{origin}/skills?mcp={name}&oauth=success" if origin else f"/skills?mcp={name}&oauth=success",
+ }
+
+ async def redirect_handler(url: str) -> None:
+ parsed = urlparse(url)
+ query = parse_qs(parsed.query)
+ state = query.get("state", [""])[0]
+ if not state:
+ raise McpHubError("oauth", "OAuth authorization URL did not contain state.")
+ self._pending_logins[state] = record
+ if not url_future.done():
+ url_future.set_result(url)
+
+ async def callback_handler():
+ with anyio.fail_after(OAUTH_LOGIN_TIMEOUT_SECONDS):
+ return await callback_future
+
+ login_provider = mcp_oauth.make_provider(name, definition, redirect_uri, redirect_handler=redirect_handler, callback_handler=callback_handler)
+ login_provider._cache_identity = self._oauth_cache_identity(definition)
+ cached = self._oauth_providers.get(name)
+ self._oauth_providers[name] = login_provider
+ self._oauth_logins.add(name)
+ async def run_login() -> None:
+ try:
+ await self._refresh_locked(name, wait_stdio=False, unlist_on_failure=False, lock_publish=True)
+ except asyncio.CancelledError:
+ if not url_future.done():
+ url_future.set_exception(McpHubError("oauth", "OAuth authorization URL was not created."))
+ raise
+ except Exception as cop:
+ if not url_future.done():
+ url_future.set_exception(cop)
+ logger.info("MCP OAuth login %s ended: %s", name, _describe(cop))
+ raise
+ finally:
+ self._oauth_logins.discard(name)
+ if self._oauth_providers.get(name) is login_provider:
+ if cached is not None:
+ cached._initialized = False
+ self._oauth_providers[name] = cached
+ else:
+ self._oauth_providers.pop(name, None)
+ for state, item in list(self._pending_logins.items()):
+ if item is record:
+ self._pending_logins.pop(state, None)
+ task = asyncio.create_task(run_login(), name=f"mcp-oauth-{name}")
+ self._oauth_tasks[name] = task
+ try:
+ url = await asyncio.wait_for(url_future, 30)
+ except TimeoutError:
+ raise McpHubError("oauth", "OAuth authorization URL was not created.") from None
+ return _dumps({"ok": True, "name": name, "authorizeUrl": url, "mode": mode})
+
+ async def _oauth_callback(self, payload: dict[str, Any]) -> bytes:
+ state = payload.get("state")
+ item = self._pending_logins.get(state)
+ if item is None or item["callback"].done():
+ raise McpHubError("invalid_callback", "This OAuth callback is unknown or already used.")
+ from mcp.shared.auth import AuthorizationCodeResult
+ item["callback"].set_result(AuthorizationCodeResult(code=payload.get("code"), state=state, iss=payload.get("iss")))
+ task = self._oauth_tasks.get(item.get("name"))
+ if task is not None:
+ try:
+ await asyncio.wait_for(asyncio.shield(task), OAUTH_LOGIN_TIMEOUT_SECONDS)
+ except Exception as cop:
+ raise McpHubError("oauth", "MCP OAuth login failed.") from cop
+ return _dumps({"ok": True, "redirect": item.get("returnUrl")})
+
+ async def _oauth_complete(self, payload: dict[str, Any]) -> bytes:
+ values = mcp_oauth.parse_callback_url(str(payload.get("callbackUrl") or ""))
+ return await self._oauth_callback(values)
+
+ async def _cancel_login(self, name: str) -> None:
+ task = self._oauth_tasks.pop(name, None)
+ for state, item in list(self._pending_logins.items()):
+ if item.get("name") == name:
+ self._pending_logins.pop(state, None)
+ future = item.get("callback")
+ if future is not None and not future.done():
+ future.cancel()
+ if task is not None and not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ self._oauth_logins.discard(name)
+ self._oauth_providers.pop(name, None)
+
+ async def _oauth_logout(self, payload: dict[str, Any]) -> bytes:
+ name = payload.get("name")
+ definition = await asyncio.to_thread(repository.read_definition, name)
+ if not _oauth_eligible(definition):
+ raise McpHubError("usage", "OAuth logout is only available for HTTP MCP servers without an Authorization header.", usage=True)
+ async with self._lock(name):
+ await self._cancel_login(name)
+ await self._retire_package(name)
+ for connection in list(self._connections.values()):
+ if connection.key[0] == name:
+ connection.retired = True
+ self.forget(connection)
+ await connection.close()
+ await asyncio.to_thread(self._publish_needs_login, name, definition)
+ await asyncio.to_thread(mcp_oauth.delete_oauth, name)
+ return _dumps({"ok": True, "name": name})
+
async def _remove(self, payload: dict[str, Any]) -> bytes:
name = payload.get("name")
async with self._lock(name):
+ await self._cancel_login(name)
kind = await asyncio.to_thread(repository.remove_package, name)
await self._retire_package(name)
+ for connection in list(self._connections.values()):
+ if connection.key[0] == name:
+ connection.retired = True
+ self.forget(connection)
+ await connection.close()
+ await asyncio.to_thread(mcp_oauth.delete_oauth, name)
return _dumps({"ok": True, "name": name, "removed": True, "kind": kind})
- # -- calls ----------------------------------------------------------------
+
@staticmethod
def _admit(name: str, tool: str, arguments: Any) -> dict[str, Any]:
@@ -664,6 +994,8 @@ class McpRuntime:
if published is None:
repository.read_definition(name)
raise McpHubError("not_generated", f"MCP server {name!r} has not been generated.", hint="vibe mcp --list")
+ if published["manifest"].get("auth") == "needs_login":
+ raise McpHubError("auth_required", "MCP OAuth login is required.", hint=f"vibe mcp {name} --login")
descriptor = next((item for item in published["tools"] if item.get("name") == tool), None)
if descriptor is None:
raise McpHubError("not_found", f"{name} has no tool {tool!r}.", hint=f"vibe mcp {name} --list")
@@ -691,9 +1023,17 @@ class McpRuntime:
if not http or attempt:
raise McpHubError("unknown_outcome", "The MCP HTTP session was lost; do not retry blindly.") from None
continue
+ except Exception as cop:
+ hub = _hub_error(cop)
+ if hub is not None:
+ raise hub from None
+ raise
return await asyncio.to_thread(self._result_envelope, name, revision, tool, result)
- except McpHubError as exc:
- return _dumps(self._envelope(name, revision, tool, error=exc))
+ except McpHubError as cop:
+ if cop.type == "auth_required" and definition["transport"]["type"] == HTTP:
+ with contextlib.suppress(Exception):
+ await self._publish_call_time_needs_login(name, revision, definition)
+ return _dumps(self._envelope(name, revision, tool, error=cop))
raise AssertionError("unreachable")
async def _call_once(self, name, revision, session_id, definition, tool, arguments):
@@ -726,8 +1066,22 @@ class McpRuntime:
f"The tool did not answer within {CALL_TIMEOUT_SECONDS}s; it may have acted. Do not retry blindly.",
) from None
except Exception as exc:
+ if isinstance(exc, McpHubError):
+ raise
+ hub = _hub_error(exc)
+ if hub is not None:
+ raise hub from None
from mcp import MCPError
+ if _oauth_eligible(definition) and (
+ _http_status(exc) == 401 or (isinstance(exc, MCPError) and getattr(exc.error, "code", None) == 401)
+ ):
+ raise McpHubError(
+ "auth_required",
+ "MCP OAuth login is required.",
+ hint=f"vibe mcp {name} --login",
+ ) from None
+
if (
isinstance(exc, MCPError)
and exc.error.code not in _CLIENT_SIDE_CODES
diff --git a/docs/MCP_HUB.md b/docs/MCP_HUB.md
index ef9f0400b..744d45f38 100644
--- a/docs/MCP_HUB.md
+++ b/docs/MCP_HUB.md
@@ -41,7 +41,7 @@ vibe mcp-add local-tools --env MODE=readonly -- python server.py
vibe mcp-add --json-stdin < servers.json
```
-- Supported transports are stdio and Streamable HTTP. SSE and OAuth are not supported.
+- Supported transports are stdio and Streamable HTTP. SSE is not supported. HTTP servers that advertise OAuth can be logged in from the Skills & MCP page or with `vibe mcp <name> --login`.
- Add never writes Claude/Codex/OpenCode files.
- A Hub-entered `cwd` must be absolute.
- `${VAR}` placeholders are not expanded.
@@ -55,7 +55,20 @@ vibe mcp-add --json-stdin < servers.json
vibe mcp docs --remove
```
-## Credentials are plaintext
+## OAuth login
+
+HTTP definitions may include Claude-format OAuth options such as `"oauth": {"scopes": "offline_access"}`. When a server requires OAuth it remains visible as **needs login**, but its tools are not added to the Agent prompt until login succeeds.
+
+Use **Log in** in the Skills & MCP page, or:
+
+```bash
+vibe mcp suno --login
+vibe mcp suno --login-complete '<callback URL>'
+vibe mcp suno --logout
+```
+
+Avibe uses a direct callback for HTTPS and loopback HTTP: the browser stays in the current tab and returns to the MCP page after login. LAN or other plain-HTTP access uses paste mode: authorize in the new tab, copy the callback URL from the address bar, and paste it into the small login dialog or `--login-complete`. Tokens and the dynamic client registration are stored in `<avibe-home>/mcp/<name>/oauth.json`, an owner-private plaintext file with mode `0600`; it is never shown in lists, help, API responses, or logs. Removing or logging out deletes it.
+
Env and header values are stored as given. URLs with `user:pass@` are rejected; put credentials in an `Authorization` header.
diff --git a/docs/plans/mcp-hub-mvp.md b/docs/plans/mcp-hub-mvp.md
index 1c63b0906..e77f7af81 100644
--- a/docs/plans/mcp-hub-mvp.md
+++ b/docs/plans/mcp-hub-mvp.md
@@ -1,6 +1,6 @@
# Avibe MCP Hub MVP design
-> Status: implemented (instance-global Hub). Official latest stable Python MCP SDK, no OAuth, no generated Skills.
+> Status: implemented (instance-global Hub). Official latest stable Python MCP SDK, no generated Skills. OAuth: see `docs/plans/mcp-hub-oauth.md`.
> Model: auto-discover reachable servers and register them; no draft/enable lifecycle.
> Principle: smallest complete design; reuse existing caller context, IPC, credentials, i18n and owner lifecycle; no speculative defenses.
> Design source of truth: `avibe-docs/design.pen`, frames `avibe — Skills & MCP · …`.
@@ -24,7 +24,7 @@ vibe mcp-add → Avibe store + refresh that name
In scope: stdio and Streamable HTTP, auto-discovery, plaintext env/header configuration, static help/list, shared runtime, structured/multimodal results.
-Out of scope: OAuth, SSE (explicit `unsupported_transport_sse` error), project scope, Skill generation, resources/prompts, sampling, update detection, auto-install/upgrade of server software, package sharing/import.
+Out of scope: OAuth (now `docs/plans/mcp-hub-oauth.md`), SSE (explicit `unsupported_transport_sse` error), project scope, Skill generation, resources/prompts, sampling, update detection, auto-install/upgrade of server software, package sharing/import.
## 2. Package on disk
diff --git a/docs/plans/mcp-hub-oauth.md b/docs/plans/mcp-hub-oauth.md
new file mode 100644
index 000000000..0e2279cf7
--- /dev/null
+++ b/docs/plans/mcp-hub-oauth.md
@@ -0,0 +1,248 @@
+# MCP Hub OAuth
+
+> Status: spec, owner decisions recorded 2026-10-30; design review (advisor, codex-astra) folded in §11.
+> Extends `docs/plans/mcp-hub-mvp.md`.
+> Reference server: `{"mcpServers": {"suno": {"url": "https://api.suno.com/mcp"}}}`.
+
+## 1. Background
+
+MCP Hub (`docs/MCP_HUB.md`) treats an HTTP 401 as an ordinary refresh failure, so an
+OAuth-protected server such as Suno is never listed. The pinned SDK (`mcp>=2.3.0,<3`)
+already ships `mcp.client.auth.OAuthClientProvider` (discovery, DCR/CIMD, PKCE, refresh,
+SEP-2352 issuer binding); Avibe supplies only `TokenStorage`, `redirect_handler` and
+`callback_handler`.
+
+Probed Suno (2026-10-30):
+
+- `POST /mcp` → `401`, `WWW-Authenticate: Bearer resource_metadata=".../.well-known/oauth-protected-resource/mcp"`.
+- PRM → AS `https://studio-api-prod.suno.com/api/v2/external/oauth`; scopes include `credits:spend`, `offline_access`.
+- AS: PKCE S256, `token_endpoint_auth_method: none`, `refresh_token`, DCR and CIMD.
+- DCR redirect acceptance: `https://<any>/…` ✅, `http://127.0.0.1:<port>/…` ✅, `http://localhost/…` ✅,
+ `http://192.168.1.20:5123/…` ❌, `http://myhost.lan:5123/…` ❌ (`invalid_redirect_uri`).
+ This is the OAuth 2.1 rule (plain HTTP only on loopback) and must be assumed for every AS.
+
+Prior art: Claude Code (401/403 → "needs authentication", `/mcp` or `claude mcp login`, random
+loopback port, keychain/credentials file, paste-the-callback fallback), Codex (`codex mcp login`,
+`--no-browser`, `mcp_oauth_callback_url` for remote ingress, file/keyring store), OpenCode
+(`mcp-auth.json`; known bug: concurrent flows overwrite tokens and re-register clients),
+Claude.ai (hosted HTTPS callback registered through DCR).
+
+## 2. Decisions (owner, 2026-10-30)
+
+1. **Needs-login is a visible state.** Page and `vibe mcp --list` show it; the Agent prompt
+ index omits it (no tools yet). A published server whose token later fails stays listed;
+ calls return `auth_required`.
+2. **Scopes:** request what the SDK selects by spec (challenge → PRM `scopes_supported`), like
+ Claude Code / Codex. Optional `oauth.scopes` narrows it.
+3. **Token storage:** a 0600 file aligned with Claude Code's credentials-file behavior, not Vault.
+4. **Pre-registered clients deferred.** Phase 1 accepts Claude-format `oauth.clientId` and
+ `oauth.scopes` only; no fixed callback port.
+5. **DCR only.** No CIMD in phase 1 (each instance has a different origin; one hosted metadata
+ document cannot list them).
+
+## 3. Callback: the Web UI may be remote
+
+The redirect URI must be registered (DCR), sent at authorize, and sent again at token
+exchange, byte-identical. Avibe's UI is reached through several origins, and only some are
+legal redirect targets:
+
+| How the browser reaches Avibe | Origin (`vibe/ui_server.py` `_current_origin()`) | Legal redirect? | Mode |
+|---|---|---|---|
+| Same machine, `http://127.0.0.1:5123` / `localhost` | loopback | ✅ | direct |
+| SSH tunnel to loopback | loopback (on the browser's machine) | ✅ | direct |
+| Avibe Cloud `public_url` | `https://…` | ✅ | direct |
+| Reverse proxy listed in `ui.trusted_public_origins` | `https://…` | ✅ | direct |
+| Same, but proxy serves plain HTTP | `http://<host>` | ❌ | paste |
+| LAN IP / hostname `http://192.168.x.x:5123` | `http://<lan>` | ❌ | paste |
+
+**Rule.** A login gets one redirect URI chosen at start and kept with the pending login:
+
+- **direct** — origin is `https`, or `http` on a loopback host (`127.0.0.1`, `localhost`, `[::1]`):
+ `redirect_uri = <origin>/api/mcp/oauth/callback`. The AS redirects that tab there. Avibe itself stays in the original tab.
+- **paste** — anything else: `redirect_uri = http://127.0.0.1:<ui.setup_port>/api/mcp/oauth/callback`.
+ If the browser happens to run on the Avibe host it completes directly. Otherwise the browser
+ lands on an unreachable page; paste mode tells the user to copy that address-bar URL
+ and paste it into the dialog. This is the Claude Code / Codex `--no-browser` fallback.
+- **CLI/IM start** (no browser origin): Avibe Cloud `public_url` when remote access is enabled,
+ else paste mode. The CLI always prints the URL and accepts a pasted callback.
+
+Consequences:
+
+- **Origin derivation** reuses `_current_origin()`; no new trust in `Host`/`X-Forwarded-*`.
+- **One stored client.** Storage returns the saved DCR client only when its `redirect_uris`
+ contains this login's URI; otherwise it returns none, the SDK re-registers, and the new client
+ replaces the old one. A redirect change always comes with a new login, so no client list.
+- **Callback auth = the pending `state`.** `GET /api/mcp/oauth/callback` is exempt from the UI
+ session, like the existing Cloud `/auth/callback` (`vibe/ui_server.py` `_remote_auth_exempt_path`
+ and its unauthenticated rate limit): a login started from CLI/IM, or opened on another device,
+ has no browser session. The route only forwards `code`/`state`/`iss` over IPC; the runtime
+ accepts it only for a live pending login with that exact `state` (SDK-generated, 32 bytes), and
+ the PKCE verifier never leaves the runtime. Unknown/expired/used `state` → generic error page.
+ Starting, pasting and logging out stay Owner-only.
+- **The pasted URL is validated** against the pending login: same `state`, path
+ `/api/mcp/oauth/callback`; `code`, `state`, `iss` are extracted from its query. Host/port are not
+ required to match (the user may paste from another device).
+- Regression/Incus: environments reached through Cloud use direct mode.
+
+## 4. Flow (Suno)
+
+```text
+add {"suno":{"url":"https://api.suno.com/mcp"}}
+ → refresh: 401 + resource_metadata → status needs_login (definition saved, not "failed")
+Owner: page "Log in" | `vibe mcp suno --login`
+ → controller: new pending login {state, redirect_uri, mode}, SDK provider runs discovery + DCR,
+ redirect_handler yields the authorize URL → returned to caller
+browser authorizes → AS redirects to redirect_uri?code&state&iss
+ → direct: UI route → IPC → controller resolves the pending login
+ → paste: dialog / `vibe mcp suno --login-complete '<url>'` → same IPC
+ → SDK exchanges token → storage saves → refresh → tools published
+call → shared per-server provider (§5) attaches Bearer per request, refreshes before expiry
+ → refresh token rejected → envelope error.type = auth_required, hint `vibe mcp suno --login`
+```
+
+- The SDK's grant suspends inside `callback_handler`; it awaits a Future (with
+ `anyio.fail_after(600)`) that the callback/paste IPC resolves. Pending logins are a
+ `dict[state → Future]` in the **MCP runtime loop** (`core/mcp_hub/runtime.py`; the Future must be
+ created on that loop), single-use, one per server (a new start cancels the previous).
+- **needs_login fits the publish model** (`_refresh_locked` currently unlists on failure, and
+ `summarize`/`list_packages`/prompt read published snapshots): a 401 carrying an OAuth challenge
+ publishes a **zero-tool snapshot whose manifest has `auth: "needs_login"`**. Lists show it with a
+ login action; `core/mcp_hub/prompt.py` skips it; calls return `auth_required`. A successful
+ login republishes normally.
+
+## 5. Token refresh
+
+### 5.1 Prior art (read from source, 2026-10-30)
+
+| | Claude Code 2.1.314 (bundled JS) | Codex (`openai/codex@d7b77a5`, `codex-rs/rmcp-client`, rmcp `e5698cb`) | OpenCode (`anomalyco/opencode@f29e281`, `packages/core/src/mcp/oauth.ts`) |
+|---|---|---|---|
+| Persisted expiry | absolute `expiresAt` | absolute `expires_at` (ms) | absolute `expires`, converted back to `expires_in` on load |
+| AS metadata after restart | persisted `discoveryState` (AS URL + metadata) | re-resolved at connection start | SDK discovery state |
+| When | proactive inside `tokens()` when <= 300 s left | before every client operation, 30 s skew | SDK |
+| In-process dedupe | one `_refreshInProgress` promise | `RefreshCredentialLock` | single-flight keyed by token URL + client_id + refresh_token |
+| Cross-process | `mcp-refresh-<key>.lock` (stale 60 s), then re-read for a winner's fresh tokens | `mcp-oauth-locks/<sha>.lock`, then authoritative re-read | none |
+| Request 401 | needs-auth; remembers the rejected access token and stops sending it | rmcp: one silent refresh, retry once only if the token changed, else challenge; Codex then returns "Authentication required" without replaying | SDK; `UnauthorizedError` → needs_auth |
+| Refresh rejected | needs-auth (`mcp_oauth_token_refresh_failed`) | retire refresh token **only if it still matches the one presented** | delete credential **only if it still holds the presented refresh token** |
+| Transient failure | keep and return current tokens | propagate, retry later | SDK |
+| Caller cancellation | — | refresh runs in an owned task so cancellation cannot lose a rotated token; 45 s timeout | — |
+| Background timer | no | no | no |
+| Logout | revokes at the AS revocation endpoint | — | — |
+
+The Python SDK's own provider is not usable as-is across restarts (`mcp` 2.3.0
+`client/auth/oauth2.py`): expiry lives only in memory; a 401 triggers full re-authorization
+instead of a refresh; without in-memory AS metadata, refresh falls back to `<server origin>/token`
+(Suno: `https://api.suno.com/token` → 404; real endpoint
+`https://studio-api-prod.suno.com/api/v2/external/oauth/token/`). Claude Code and Codex both
+wrap their SDKs for the same reasons.
+
+### 5.2 Avibe design
+
+Reuse the SDK provider for everything; fix its three restart gaps in a thin subclass.
+
+- `AvibeOAuthProvider(OAuthClientProvider)`, **one instance per server**, shared by every HTTP
+ connection of that server (`_client_for` passes it as `auth=` to `create_mcp_http_client`).
+ Its `context.lock` already serializes the auth flow, so N concurrent requests cause one refresh;
+ a provider is an httpx `Auth`, so the token is attached per request and long-lived Session
+ connections pick up refreshed tokens.
+- Override `_initialize()` to restore from `oauth.json`: tokens, client, absolute `expiresAt` →
+ `context.token_expiry_time`, AS metadata → `context.oauth_metadata`, PRM →
+ `context.protected_resource_metadata`. Proactive refresh then uses the real `token_endpoint`
+ (SDK refreshes when expired; the SDK's own RFC 6749 §6 carry-forward of `refresh_token`/`scope`
+ and save-before-use apply as is).
+- `TokenStorage.set_tokens` writes absolute `expiresAt` (from `expires_in`) plus the current AS
+ metadata / PRM via `write_atomic` (0600). A write failure is logged and raised; no retry state.
+- Override `_handle_refresh_response`: on `400 invalid_grant` / `invalid_client` / `401` from the
+ token endpoint, also delete the tokens from `oauth.json` (keep the client), so the next call does
+ not hit the token endpoint again; status becomes `needs_login`. Network / `5xx` / `429`: keep tokens.
+- Call-time providers have a `redirect_handler` that raises `McpHubError("auth_required")`. A 401
+ at call time (revoked or unrefreshable token) therefore ends as `auth_required` with the hint
+ `vibe mcp <name> --login`; **no automatic replay of `tools/call`** (a 401 is not guaranteed to
+ precede side effects). The pre-dispatch `Session not found` retry in `runtime.py` is unchanged.
+- No background timer, no owned refresh task, no write-retry, no token revocation at logout
+ (phase 1 `--logout` deletes `oauth.json`), no rejected-token memory, no cross-process lock
+ (only the Controller's MCP runtime touches `oauth.json`).
+- These overrides touch SDK private members; `mcp` is pinned `<3`, and the hermetic test
+ (§10) exercises restart → refresh so an SDK change fails CI rather than users.
+- Logs carry status and OAuth `error` code only, never token values.
+
+## 6. Storage
+
+`<avibe-home>/mcp/<name>/oauth.json`, mode 0600, `write_atomic`:
+
+```json
+{"schemaVersion": 1, "serverUrl": "https://api.suno.com/mcp",
+ "tokens": {"access_token": "…", "refresh_token": "…", "scope": "…", "token_type": "Bearer"},
+ "expiresAt": 1793345230,
+ "client": {"client_id": "…", "redirect_uris": ["…"], "issuer": "…"},
+ "authServerMetadata": {"issuer": "…", "token_endpoint": "…", "…": "…"},
+ "resourceMetadata": {"resource": "https://api.suno.com/mcp", "authorization_servers": ["…"]}}
+```
+
+`tokens` / `client` / metadata are the SDK models' own JSON (`OAuthToken`,
+`OAuthClientInformationFull`, `OAuthMetadata`, `ProtectedResourceMetadata`).
+
+- Not in `definition.json` or `revisions/`; never printed by list/help/API.
+- Ignored (treated as absent) when `serverUrl` differs from the definition URL, so a changed
+ native URL never receives the old bearer token.
+- Deleted on `--remove` / hide, and by `--logout`.
+- Native-source OAuth servers get their own Avibe login; native token stores are not read.
+
+## 7. Precedence
+
+A definition with an explicit `Authorization` header never uses OAuth. Otherwise HTTP servers
+attach the OAuth provider; a server that never returns 401 never triggers it.
+
+## 8. Surfaces
+
+CLI (Owner for login/logout, like refresh/remove):
+
+```bash
+vibe mcp suno --login # prints authorize URL (+ paste hint), returns
+vibe mcp suno --login-complete '<callback URL>'
+vibe mcp suno --logout
+```
+
+API: `POST /api/mcp/{name}/oauth/start` (body carries nothing; origin from request) →
+`{authorizeUrl, mode}`; `GET /api/mcp/oauth/callback` (session-exempt, §3); `POST /api/mcp/{name}/oauth/complete`
+`{callbackUrl}`; `POST /api/mcp/{name}/oauth/logout`. Summary gains `auth: none|needs_login|ok`.
+
+UI: needs-login rows show a login action. Direct and paste both open the authorize URL in a **new tab** (preallocate `about:blank` synchronously on click, then `location.replace` after start returns — never `window.location.assign` on the Avibe tab, never raw `window.open` after `await`). Avibe stays in the original tab; the callback 302s the authorize tab back to Skills & MCP. Adding an HTTP server that returns `auth: needs_login` starts this login immediately. Paste mode still shows a dialog with a paste box. Strings via i18n.
+
+Definition: accept Claude-format `oauth: {clientId?, scopes?}` on HTTP entries; other `oauth`
+keys ignored (not rejected), per native extras policy.
+
+## 9. Out of scope (phase 1)
+
+Pre-registered secrets and fixed callback port, CIMD, token revocation at logout, keychain/Vault storage, OAuth for SSE,
+client-credentials grant, step-up UX beyond the SDK default, borrowing native clients' tokens.
+
+## 10. Acceptance
+
+1. Add Suno → listed as needs-login; not in the Agent prompt index.
+2. Log in from localhost UI → completes without paste; tools published; a call succeeds.
+3. Log in from Avibe Cloud UI → direct callback on the Cloud origin completes.
+4. Log in from `http://<LAN IP>:5123` → paste mode; pasting the address-bar URL completes.
+5. `vibe mcp suno --login` / `--login-complete` work from CLI and from an Agent in IM.
+6. Expired access token refreshes transparently, including after a Controller restart and on a
+ Session connection held open past expiry; rejected refresh token → tokens deleted, status
+ `needs_login`, call `auth_required`; token-endpoint outage → tokens kept.
+7. N concurrent calls across Sessions on an expired token cause exactly one token-endpoint request;
+ a rotated refresh token is persisted before use. A call-time 401 never replays `tools/call`.
+8. `--logout` / `--remove` delete `oauth.json`; tokens never appear in logs, list, help, or API.
+9. Tests: hermetic loopback AS + MCP fixture covering 401→login→call, redirect-mode selection
+ table, per-redirect client reuse, pasted-URL validation, refresh-failure mapping, restart-then-refresh, session-exempt callback state check.
+
+## 11. Design review (2026-10-30)
+
+advisor and codex-astra both returned approve-with-cuts. Applied:
+
+- Reuse the SDK provider for refresh via `_initialize` / `_handle_refresh_response` overrides
+ instead of a separate token manager (advisor; codex-astra had judged a manager necessary only
+ because the SDK does not restore expiry/metadata, which the override solves).
+- Cut: owned refresh task, write-failure retry, logout revocation, compare-before-retire,
+ rejected-token memory, 401 resend, per-redirect client list.
+- Fixed: callback must be session-exempt and bound by `state` (codex-astra); pending logins live on
+ the MCP runtime loop and needs_login is a zero-tool published snapshot (advisor).
+- Kept against one cut proposal: `serverUrl` binding (codex-astra) — one comparison prevents
+ sending a bearer token to a changed URL.
+
diff --git a/tests/fixtures/member_management_existing_read_roles.json b/tests/fixtures/member_management_existing_read_roles.json
index af49937b8..3af7bb023 100644
--- a/tests/fixtures/member_management_existing_read_roles.json
+++ b/tests/fixtures/member_management_existing_read_roles.json
@@ -37,6 +37,7 @@
"GET /api/inbox": "viewer",
"GET /api/mcp": "editor",
"GET /api/mcp/example": "editor",
+ "GET /api/mcp/oauth/callback": "viewer",
"GET /api/media/example": "viewer",
"GET /api/media/example/meta": "viewer",
"GET /api/models/agents/example/models": "editor",
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index f265e25cc..b17ec7e9e 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -641,4 +641,11 @@ scenarios:
- tests/test_avault_agent.py
- tests/test_local_deps.py
- ui/src/components/ui/avault-authorization-notice.test.tsx
+ - id: AUTH-SETUP-135
+ name: MCP Hub HTTP OAuth login publishes needs_login then completes through the owner callback
+ status: covered
+ kind: happy_path
+ layer: scenario
+ backend: shared
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_mcp_hub_oauth_login_completes_through_owner_callback
next_priority: []
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index e9c55e03c..5b03b65ac 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -177,6 +177,47 @@ def test_auth_setup_catalog_priorities_reference_live_scenarios():
assert set(catalog.get("next_priority", [])) <= live_ids
+def test_mcp_hub_oauth_login_completes_through_owner_callback(tmp_path):
+ """Scenario: AUTH-SETUP-135 — add publishes needs_login, login grant completes, tools appear."""
+ from tests.scenario_harness.core import BaseScenarioHarness, ScenarioExpect, ScenarioRunner
+ from tests.test_mcp_hub_oauth import _LoopbackOauth, _run
+ from core.mcp_hub import repository
+ from core.mcp_hub.runtime import McpRuntime
+ from tests.ui_server_test_helpers import save_config
+
+ save_config(tmp_path).save()
+ loopback = _LoopbackOauth()
+ loopback.start()
+ runtime = McpRuntime()
+ harness = BaseScenarioHarness()
+ runner = ScenarioRunner(harness)
+ started = {}
+
+ def start(_h):
+ added = _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": f"{loopback.origin}/mcp"}}]})
+ assert added["ok"] and added["added"][0]["auth"] == "needs_login"
+ assert repository.list_packages()[0]["auth"] == "needs_login"
+ started.update(_run(runtime, "oauth_start", {"name": "suno", "origin": "http://127.0.0.1:5123", "port": 5123}))
+ assert started["ok"] and started["mode"] == "direct"
+
+ def complete(_h):
+ query = urllib.parse.parse_qs(urllib.parse.urlparse(started["authorizeUrl"]).query)
+ done = _run(runtime, "oauth_callback", {"state": query["state"][0], "code": "code-1", "iss": loopback.origin})
+ assert done["ok"]
+ listed = repository.list_packages()[0]
+ assert listed["auth"] == "ok" and listed["toolCount"] == 1
+
+ try:
+ start(harness)
+ runner.history.append("start")
+ complete(harness)
+ runner.history.append("complete")
+ ScenarioExpect.step_history(runner, ["start", "complete"])
+ finally:
+ runtime.stop()
+ loopback.stop()
+
+
@pytest.mark.parametrize("vendor", ["openai", "anthropic", "gemini", "kimi", "xai"])
@pytest.mark.parametrize("identity_case", ["valid", "invalid_utf8", "token_whitespace"])
def test_subscription_identity_survives_oauth_completion_and_http_replay(monkeypatch, tmp_path, vendor, identity_case):
diff --git a/tests/test_mcp_hub_api.py b/tests/test_mcp_hub_api.py
index ab30cc326..b75d276cc 100644
--- a/tests/test_mcp_hub_api.py
+++ b/tests/test_mcp_hub_api.py
@@ -104,6 +104,46 @@ def test_all_failed_batch_returns_per_server_reasons_and_identical_readd_is_unch
assert "Unexpected MCP Hub response" not in json.dumps(none_body)
+def test_needs_login_package_lists_and_details_without_500(owner):
+ definition = {
+ "name": "suno",
+ "transport": {"type": "http", "url": "https://api.example/mcp"},
+ }
+ repository.write_definition(definition)
+ repository.publish(
+ "suno",
+ definition=definition,
+ manifest={"description": "", "auth": "needs_login"},
+ tools=[],
+ commands=[],
+ )
+ client = app.test_client()
+ listed = client.get("/api/mcp")
+ assert listed.status_code == 200
+ body = listed.get_json()
+ assert body["ok"] is True
+ assert body["servers"][0]["auth"] == "needs_login"
+ detail = client.get("/api/mcp/suno")
+ assert detail.status_code == 200
+ payload = detail.get_json()
+ assert payload["ok"] is True
+ assert payload["server"]["auth"] == "needs_login"
+ assert payload.get("tools") == []
+
+
+def test_mcp_run_wraps_unexpected_errors_as_internal_object():
+ from vibe import mcp_api
+
+ async def boom():
+ raise RuntimeError("disk full")
+
+ body, status = __import__("asyncio").run(mcp_api.run(boom))
+ assert status == 500
+ assert body["ok"] is False
+ assert body["error"]["type"] == "internal"
+ assert "disk full" in body["error"]["message"]
+
+
def test_malformed_json_add_returns_top_level_error_without_batch_arrays(owner):
client = app.test_client()
headers = csrf_headers(client)
@@ -121,10 +161,14 @@ def test_malformed_json_add_returns_top_level_error_without_batch_arrays(owner):
[
("GET", "/api/mcp", "editor"),
("GET", "/api/mcp/echo", "editor"),
+ ("GET", "/api/mcp/oauth/callback", "viewer"),
("POST", "/api/mcp", "owner"),
("POST", "/api/mcp/discover", "owner"),
("POST", "/api/mcp/echo/refresh", "owner"),
("DELETE", "/api/mcp/echo", "owner"),
+ ("POST", "/api/mcp/echo/oauth/start", "owner"),
+ ("POST", "/api/mcp/echo/oauth/complete", "owner"),
+ ("POST", "/api/mcp/echo/oauth/logout", "owner"),
],
)
def test_route_roles(method, path, role):
diff --git a/tests/test_mcp_hub_oauth.py b/tests/test_mcp_hub_oauth.py
new file mode 100644
index 000000000..0b3753ca1
--- /dev/null
+++ b/tests/test_mcp_hub_oauth.py
@@ -0,0 +1,615 @@
+"""Hermetic MCP Hub OAuth contracts owned by the runtime/storage boundary."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import sys
+import threading
+import time
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from starlette.applications import Starlette
+from starlette.requests import Request
+from starlette.responses import JSONResponse, Response
+from starlette.routing import Route
+import uvicorn
+
+from core.mcp_hub import oauth, repository
+from core.mcp_hub.definition import definition_from_provider
+from core.mcp_hub.prompt import build_mcp_prompt_blocks
+from core.mcp_hub.runtime import McpRuntime
+from tests.ui_server_test_helpers import save_config
+
+
+class _LoopbackOauth:
+ """One process serving AS metadata, token, and a streamable-http MCP resource."""
+
+ def __init__(self) -> None:
+ self.access = "access-1"
+ self.refresh = "refresh-1"
+ self.token_posts = 0
+ self.mcp_posts = 0
+ self.resource_status = 200
+ self.refresh_status = 200
+ self.refresh_error = "invalid_grant"
+ self.tool_error: str | None = None
+ self.codes: dict[str, str] = {}
+ self._server: uvicorn.Server | None = None
+ self._thread: threading.Thread | None = None
+ self.origin = ""
+
+ def start(self) -> str:
+ app = Starlette(routes=[
+ Route("/.well-known/oauth-protected-resource", self._prm),
+ Route("/.well-known/oauth-authorization-server", self._as_meta),
+ Route("/register", self._register, methods=["POST"]),
+ Route("/authorize", self._authorize),
+ Route("/token", self._token, methods=["POST"]),
+ Route("/mcp", self._mcp, methods=["POST", "GET", "DELETE"]),
+ ])
+ config = uvicorn.Config(app, host="127.0.0.1", port=0, log_level="error")
+ self._server = uvicorn.Server(config)
+ self._thread = threading.Thread(target=self._server.run, daemon=True)
+ self._thread.start()
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ if self._server.started:
+ break
+ time.sleep(0.02)
+ port = self._server.servers[0].sockets[0].getsockname()[1]
+ self.origin = f"http://127.0.0.1:{port}"
+ return self.origin
+
+ def stop(self) -> None:
+ if self._server is not None:
+ self._server.should_exit = True
+ if self._thread is not None:
+ self._thread.join(timeout=5)
+
+ async def _prm(self, request: Request) -> JSONResponse:
+ return JSONResponse({
+ "resource": f"{self.origin}/mcp",
+ "authorization_servers": [self.origin],
+ })
+
+ async def _as_meta(self, request: Request) -> JSONResponse:
+ return JSONResponse({
+ "issuer": self.origin,
+ "authorization_endpoint": f"{self.origin}/authorize",
+ "token_endpoint": f"{self.origin}/token",
+ "registration_endpoint": f"{self.origin}/register",
+ "code_challenge_methods_supported": ["S256"],
+ "grant_types_supported": ["authorization_code", "refresh_token"],
+ "token_endpoint_auth_methods_supported": ["none"],
+ })
+
+ async def _register(self, request: Request) -> JSONResponse:
+ body = await request.json()
+ return JSONResponse({
+ "client_id": "loop-client",
+ "redirect_uris": body.get("redirect_uris") or [],
+ "token_endpoint_auth_method": "none",
+ }, status_code=201)
+
+ async def _authorize(self, request: Request) -> Response:
+ query = dict(request.query_params)
+ code = f"code-{len(self.codes) + 1}"
+ self.codes[code] = query.get("state", "")
+ redirect = f"{query['redirect_uri']}?code={code}&state={query['state']}&iss={self.origin}"
+ return Response(status_code=302, headers={"location": redirect})
+
+ async def _token(self, request: Request) -> JSONResponse:
+ self.token_posts += 1
+ form = await request.form()
+ grant = form.get("grant_type")
+ if grant == "refresh_token":
+ if self.refresh_status != 200:
+ return JSONResponse({"error": self.refresh_error}, status_code=self.refresh_status)
+ self.access = f"access-{self.token_posts}"
+ self.refresh = f"refresh-{self.token_posts}"
+ elif grant == "authorization_code":
+ self.access = f"access-{self.token_posts}"
+ self.refresh = f"refresh-{self.token_posts}"
+ else:
+ return JSONResponse({"error": "unsupported_grant_type"}, status_code=400)
+ return JSONResponse({
+ "access_token": self.access,
+ "refresh_token": self.refresh,
+ "token_type": "Bearer",
+ "expires_in": 3600,
+ })
+
+ async def _mcp(self, request: Request) -> Response:
+ self.mcp_posts += 1
+ if self.resource_status == 401:
+ return Response(
+ status_code=401,
+ headers={"WWW-Authenticate": f'Bearer resource_metadata="{self.origin}/.well-known/oauth-protected-resource"'},
+ )
+ auth = request.headers.get("authorization") or ""
+ if auth != f"Bearer {self.access}":
+ return Response(
+ status_code=401,
+ headers={"WWW-Authenticate": f'Bearer resource_metadata="{self.origin}/.well-known/oauth-protected-resource"'},
+ )
+ payload = await request.json()
+ method = payload.get("method")
+ rpc_id = payload.get("id")
+ if method == "initialize":
+ result = {
+ "protocolVersion": payload.get("params", {}).get("protocolVersion"),
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "loop", "version": "0.1.0"},
+ }
+ elif method in {"notifications/initialized", "notifications/cancelled"}:
+ return Response(status_code=202)
+ elif method == "tools/list":
+ result = {"tools": [{"name": "echo", "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}}}]}
+ elif method == "tools/call":
+ if self.tool_error:
+ return JSONResponse({"jsonrpc": "2.0", "id": rpc_id, "error": {"code": -32002, "message": self.tool_error}})
+ result = {"content": [{"type": "text", "text": payload.get("params", {}).get("arguments", {}).get("text", "")}]}
+ else:
+ result = {}
+ return JSONResponse({"jsonrpc": "2.0", "id": rpc_id, "result": result})
+
+
+def _run(runtime: McpRuntime, operation: str, payload: dict) -> dict:
+ status, body = asyncio.run(runtime.submit(operation, payload))
+ assert status == 200
+ return json.loads(body)
+
+
+def _seed_tokens(name: str, url: str, *, expires_at: float, access: str = "access-1", refresh: str = "refresh-1") -> None:
+ from mcp.shared.auth import OAuthClientInformationFull, OAuthMetadata, OAuthToken, ProtectedResourceMetadata
+
+ storage = oauth.AvibeTokenStorage(name, url)
+ origin = url.rsplit("/", 1)[0]
+ asyncio.run(storage.set_tokens(OAuthToken(access_token=access, refresh_token=refresh, expires_in=1, token_type="Bearer")))
+ asyncio.run(storage.set_client_info(OAuthClientInformationFull(client_id="loop-client", redirect_uris=["http://127.0.0.1:5123/api/mcp/oauth/callback"])))
+ raw = storage.raw()
+ raw["expiresAt"] = expires_at
+ raw["authServerMetadata"] = OAuthMetadata(
+ issuer=origin,
+ authorization_endpoint=f"{origin}/authorize",
+ token_endpoint=f"{origin}/token",
+ registration_endpoint=f"{origin}/register",
+ ).model_dump(mode="json")
+ raw["resourceMetadata"] = ProtectedResourceMetadata(
+ resource=url,
+ authorization_servers=[origin],
+ ).model_dump(mode="json")
+ oauth._write(name, raw)
+
+
+def runtime(tmp_path):
+ config = save_config(tmp_path)
+ config.save()
+ owner = McpRuntime()
+ yield owner
+ owner.stop()
+
+
+def loopback():
+ server = _LoopbackOauth()
+ server.start()
+ try:
+ yield server
+ finally:
+ server.stop()
+
+
+def test_redirect_mode_obeys_oauth_loopback_rule():
+ cases = [
+ ("http://127.0.0.1:5123", "direct", "http://127.0.0.1:5123/api/mcp/oauth/callback"),
+ ("http://localhost:5123", "direct", "http://localhost:5123/api/mcp/oauth/callback"),
+ ("https://cloud.example", "direct", "https://cloud.example/api/mcp/oauth/callback"),
+ ("http://192.168.1.20:5123", "paste", "http://127.0.0.1:5123/api/mcp/oauth/callback", 5123),
+ ("http://host.lan:5123", "paste", "http://127.0.0.1:5123/api/mcp/oauth/callback", 5123),
+ (None, "paste", "http://127.0.0.1:5123/api/mcp/oauth/callback", 5123),
+ ]
+ for origin, mode, redirect, *port in cases:
+ kwargs = {"port": port[0]} if port else {}
+ assert oauth.redirect_mode(origin, **kwargs) == (mode, redirect)
+
+
+def test_redirect_mode_uses_configured_loopback_port():
+ assert oauth.redirect_mode("http://192.168.1.20:9000", port=7777)[1] == "http://127.0.0.1:7777/api/mcp/oauth/callback"
+
+
+def test_redirect_mode_requires_port_for_paste():
+ with pytest.raises(Exception, match="loopback setup port"):
+ oauth.redirect_mode("http://192.168.1.20:9000")
+
+
+def test_definition_accepts_only_phase_one_oauth_options():
+ definition = definition_from_provider("suno", {"url": "https://api.example/mcp", "oauth": {"clientId": "ignored", "scopes": "offline_access", "secret": "ignored"}})
+ assert definition["oauth"] == {"clientId": "ignored", "scopes": "offline_access"}
+
+
+def test_storage_filters_client_by_provider_redirect_and_client_id_is_used(tmp_path):
+ save_config(tmp_path).save()
+
+ async def exercise():
+ storage = oauth.AvibeTokenStorage("suno", "https://api.example/mcp", "https://cloud.example/api/mcp/oauth/callback")
+ from mcp.shared.auth import OAuthClientInformationFull
+ await storage.set_client_info(OAuthClientInformationFull(client_id="registered", redirect_uris=["http://127.0.0.1/api/mcp/oauth/callback"]))
+ assert await storage.get_client_info() is None
+ call_time = oauth.AvibeTokenStorage("suno", "https://api.example/mcp")
+ stored = await call_time.get_client_info()
+ assert stored is not None and stored.client_id == "registered"
+ definition = definition_from_provider("suno", {"url": "https://api.example/mcp", "oauth": {"clientId": "fixed"}})
+ provider = oauth.make_provider("suno", definition, "https://cloud.example/api/mcp/oauth/callback", redirect_handler=lambda _: None, callback_handler=lambda: None)
+ assert provider.context.client_info.client_id == "fixed"
+ await provider._initialize()
+ assert provider.context.client_info.client_id == "fixed"
+
+ asyncio.run(exercise())
+
+
+def test_runtime_caches_one_provider_per_server(runtime):
+ definition = definition_from_provider("suno", {"url": "https://api.example/mcp"})
+
+ async def exercise():
+ first, second = await asyncio.gather(runtime._oauth_provider(definition), runtime._oauth_provider(definition))
+ third = await runtime._oauth_provider(definition)
+ assert first is second is third
+
+ asyncio.run(exercise())
+
+
+def test_readd_with_new_oauth_client_id_is_exists_not_unchanged(runtime, loopback):
+ url = f"{loopback.origin}/mcp"
+ first = _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": url, "oauth": {"clientId": "old"}}}]})
+ assert first["ok"] is True
+ blocked = _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": url, "oauth": {"clientId": "new"}}}]})
+ assert blocked["ok"] is False
+ assert blocked["failed"][0]["type"] == "exists"
+ replaced = _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": url, "oauth": {"clientId": "new"}}}], "replace": True})
+ assert replaced["ok"] is True
+ saved = repository.read_avibe_definition("suno")
+ assert saved["oauth"]["clientId"] == "new"
+
+ async def cached_client():
+ provider = await runtime._oauth_provider(saved)
+ return provider.context.client_info.client_id
+
+ assert asyncio.run(cached_client()) == "new"
+
+
+def test_oauth_provider_cache_invalidates_on_client_id_change(runtime):
+ first_def = definition_from_provider("suno", {"url": "https://api.example/mcp", "oauth": {"clientId": "old"}})
+ second_def = definition_from_provider("suno", {"url": "https://api.example/mcp", "oauth": {"clientId": "new"}})
+
+ async def exercise():
+ first = await runtime._oauth_provider(first_def)
+ same = await runtime._oauth_provider(first_def)
+ second = await runtime._oauth_provider(second_def)
+ assert first is same
+ assert second is not first
+ assert second.context.client_info.client_id == "new"
+
+ asyncio.run(exercise())
+
+
+def test_oauth_storage_is_url_bound_and_private(tmp_path):
+ save_config(tmp_path).save()
+ storage = oauth.AvibeTokenStorage("suno", "https://api.example/mcp")
+ from mcp.shared.auth import OAuthToken
+
+ asyncio.run(storage.set_tokens(OAuthToken(access_token="secret", refresh_token="refresh", expires_in=60)))
+ path = oauth.oauth_path("suno")
+ assert path.stat().st_mode & 0o777 == 0o600
+ assert storage.raw()["serverUrl"] == "https://api.example/mcp"
+ assert oauth.AvibeTokenStorage("suno", "https://changed.example/mcp").raw() == {}
+
+
+def test_needs_login_is_listed_but_omitted_from_prompt(tmp_path):
+ save_config(tmp_path).save()
+ definition = definition_from_provider("suno", {"url": "https://api.example/mcp", "oauth": {"scopes": "offline_access"}})
+ repository.write_definition(definition)
+ repository.publish("suno", definition=definition, manifest={"description": "", "auth": "needs_login"}, tools=[], commands=[])
+ assert repository.list_packages()[0]["auth"] == "needs_login"
+ assert "suno" not in "".join(block.text for block in build_mcp_prompt_blocks())
+
+
+def test_callback_state_is_single_use_on_runtime_loop(runtime):
+ async def exercise():
+ loop = asyncio.get_running_loop()
+ future = loop.create_future()
+ runtime._pending_logins["state"] = {"callback": future}
+ first = json.loads(await runtime._oauth_callback({"state": "state", "code": "code"}))
+ assert first["ok"]
+ with pytest.raises(Exception, match="unknown or already used"):
+ await runtime._oauth_callback({"state": "state", "code": "again"})
+
+ asyncio.run(exercise())
+
+
+def test_callback_url_validation_rejects_wrong_path_or_missing_code():
+ with pytest.raises(Exception, match="not an Avibe"):
+ oauth.parse_callback_url("https://example.test/wrong?code=x&state=y")
+ with pytest.raises(Exception, match="missing OAuth"):
+ oauth.parse_callback_url("https://example.test/api/mcp/oauth/callback?state=y")
+
+
+def test_first_contact_oauth_401_publishes_needs_login(runtime, loopback):
+ added = _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": f"{loopback.origin}/mcp"}}]})
+ assert added["ok"]
+ assert added["added"][0]["toolCount"] == 0
+ assert added["added"][0]["auth"] == "needs_login"
+ listed = repository.list_packages()[0]
+ assert listed["auth"] == "needs_login"
+ assert "suno" not in "".join(block.text for block in build_mcp_prompt_blocks())
+
+
+def test_authorization_header_skips_oauth(runtime, loopback):
+ added = _run(runtime, "add", {"servers": [{"name": "suno", "server": {
+ "url": f"{loopback.origin}/mcp",
+ "headers": {"Authorization": f"Bearer {loopback.access}"},
+ }}]})
+ assert added["ok"] and added["added"][0]["toolCount"] == 1
+ assert loopback.token_posts == 0
+ listed = json.dumps(repository.list_packages())
+ assert "access-1" not in listed and "refresh-1" not in listed
+
+
+def test_expired_access_token_refreshes_once_on_real_token_endpoint(runtime, loopback):
+ url = f"{loopback.origin}/mcp"
+ definition = definition_from_provider("suno", {"url": url})
+ repository.write_definition(definition)
+ _seed_tokens("suno", url, expires_at=time.time() - 10)
+ refreshed = _run(runtime, "refresh", {"name": "suno"})
+ assert refreshed["ok"] and refreshed["toolCount"] == 1
+ assert loopback.token_posts == 1
+ called = _run(runtime, "call", {"name": "suno", "tool": "echo", "arguments": {"text": "hi"}})
+ assert called["status"] == "ok"
+ assert loopback.token_posts == 1
+
+
+def test_restart_then_refresh_uses_stored_token_endpoint(runtime, loopback):
+ url = f"{loopback.origin}/mcp"
+ repository.write_definition(definition_from_provider("suno", {"url": url}))
+ _seed_tokens("suno", url, expires_at=time.time() - 10)
+ runtime.stop()
+ again = McpRuntime()
+ try:
+ refreshed = _run(again, "refresh", {"name": "suno"})
+ assert refreshed["ok"]
+ assert loopback.token_posts == 1
+ finally:
+ again.stop()
+
+
+def test_rejected_refresh_deletes_tokens_and_call_is_auth_required(runtime, loopback):
+ url = f"{loopback.origin}/mcp"
+ repository.write_definition(definition_from_provider("suno", {"url": url}))
+ _seed_tokens("suno", url, expires_at=time.time() - 10)
+ loopback.refresh_status = 400
+ refreshed = _run(runtime, "refresh", {"name": "suno"})
+ assert refreshed.get("auth") == "needs_login"
+ assert "tokens" not in oauth.read_state("suno", url)
+ called = _run(runtime, "call", {"name": "suno", "tool": "echo", "arguments": {"text": "hi"}})
+ assert called["error"]["type"] == "auth_required"
+ assert "vibe mcp suno --login" in called["error"]["hint"]
+
+
+def test_call_time_resource_401_is_auth_required_without_replay(runtime, loopback):
+ url = f"{loopback.origin}/mcp"
+ repository.write_definition(definition_from_provider("suno", {"url": url}))
+ _seed_tokens("suno", url, expires_at=time.time() + 3600)
+ assert _run(runtime, "refresh", {"name": "suno"})["ok"]
+ before = loopback.mcp_posts
+ loopback.resource_status = 401
+ called = _run(runtime, "call", {"name": "suno", "tool": "echo", "arguments": {"text": "hi"}})
+ assert called["error"]["type"] == "auth_required"
+ assert loopback.mcp_posts == before + 1
+ assert repository.list_packages()[0]["auth"] == "needs_login"
+
+
+def test_concurrent_call_time_auth_required_keeps_valid_package(runtime, loopback, monkeypatch):
+ url = f"{loopback.origin}/mcp"
+ repository.write_definition(definition_from_provider("suno", {"url": url}))
+ _seed_tokens("suno", url, expires_at=time.time() + 3600)
+ assert _run(runtime, "refresh", {"name": "suno"})["ok"]
+ loopback.resource_status = 401
+ original = repository.publish
+ needs_login = []
+
+ def counted(*args, **kwargs):
+ revision = original(*args, **kwargs)
+ if (kwargs.get("manifest") or {}).get("auth") == "needs_login":
+ needs_login.append(revision)
+ return revision
+
+ monkeypatch.setattr(repository, "publish", counted)
+
+ async def many():
+ results = await asyncio.gather(*[
+ runtime.submit("call", {"name": "suno", "tool": "echo", "arguments": {"text": "hi"}, "sessionId": f"s{i}"})
+ for i in range(8)
+ ])
+ return [json.loads(body) for _, body in results]
+
+ bodies = asyncio.run(many())
+ assert all(body["error"]["type"] == "auth_required" for body in bodies)
+ assert len(needs_login) == 1
+ published = repository.read_published("suno")
+ assert published is not None
+ assert published["manifest"]["auth"] == "needs_login"
+ assert repository.list_packages()[0]["auth"] == "needs_login"
+
+
+def test_concurrent_calls_share_one_token_refresh(runtime, loopback):
+ url = f"{loopback.origin}/mcp"
+ repository.write_definition(definition_from_provider("suno", {"url": url}))
+ _seed_tokens("suno", url, expires_at=time.time() + 3600)
+ assert _run(runtime, "refresh", {"name": "suno"})["ok"]
+ _seed_tokens("suno", url, expires_at=time.time() - 10, access=loopback.access, refresh=loopback.refresh)
+ provider = asyncio.run(runtime._oauth_provider(definition_from_provider("suno", {"url": url})))
+ provider._initialized = False
+ loopback.token_posts = 0
+
+ async def many():
+ await asyncio.gather(*(
+ runtime.submit("call", {"name": "suno", "tool": "echo", "arguments": {"text": str(i)}})
+ for i in range(4)
+ ))
+
+ asyncio.run(many())
+ assert loopback.token_posts == 1
+
+
+def test_login_drives_grant_and_callback_redirects_to_skills(runtime, loopback):
+ _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": f"{loopback.origin}/mcp"}}]})
+ started = _run(runtime, "oauth_start", {"name": "suno", "origin": "http://127.0.0.1:5123", "port": 5123})
+ assert started["ok"] and started["mode"] == "direct"
+ parsed = urlparse(started["authorizeUrl"])
+ query = parse_qs(parsed.query)
+ state = query["state"][0]
+ done = _run(runtime, "oauth_callback", {"state": state, "code": "code-1", "iss": loopback.origin})
+ assert done["ok"]
+ assert done["redirect"] == "http://127.0.0.1:5123/skills?mcp=suno&oauth=success"
+ listed = repository.list_packages()[0]
+ assert listed["auth"] == "ok" and listed["toolCount"] == 1
+
+
+def test_new_login_rejects_old_callback_state(runtime, loopback):
+ _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": f"{loopback.origin}/mcp"}}]})
+ first = _run(runtime, "oauth_start", {"name": "suno", "origin": "http://127.0.0.1:5123"})
+ old_state = parse_qs(urlparse(first["authorizeUrl"]).query)["state"][0]
+ second = _run(runtime, "oauth_start", {"name": "suno", "origin": "http://127.0.0.1:5123"})
+ new_state = parse_qs(urlparse(second["authorizeUrl"]).query)["state"][0]
+ rejected = _run(runtime, "oauth_callback", {"state": old_state, "code": "late"})
+ assert rejected["ok"] is False
+ assert rejected["error"]["type"] == "invalid_callback"
+ accepted = _run(runtime, "oauth_callback", {"state": new_state, "code": "code-2", "iss": loopback.origin})
+ assert accepted["ok"]
+
+
+def test_overlapping_oauth_start_keeps_only_latest_grant(runtime, loopback):
+ _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": f"{loopback.origin}/mcp"}}]})
+ payload = {"name": "suno", "origin": "http://127.0.0.1:5123", "port": 5123}
+
+ async def both():
+ first, second = await asyncio.wait_for(
+ asyncio.gather(
+ runtime.submit("oauth_start", payload),
+ runtime.submit("oauth_start", payload),
+ ),
+ 5,
+ )
+ return json.loads(first[1]), json.loads(second[1])
+
+ first, second = asyncio.run(both())
+ assert first["ok"] and second["ok"]
+ first_state = parse_qs(urlparse(first["authorizeUrl"]).query)["state"][0]
+ second_state = parse_qs(urlparse(second["authorizeUrl"]).query)["state"][0]
+ pending = list(runtime._pending_logins)
+ assert len(pending) == 1
+ winner = pending[0]
+ loser = first_state if winner == second_state else second_state
+ rejected = _run(runtime, "oauth_callback", {"state": loser, "code": "late"})
+ assert rejected["ok"] is False
+ assert rejected["error"]["type"] == "invalid_callback"
+ accepted = _run(runtime, "oauth_callback", {"state": winner, "code": "code-2", "iss": loopback.origin})
+ assert accepted["ok"]
+
+
+def test_login_completion_serializes_publish_with_refresh(runtime, loopback, monkeypatch):
+ _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": f"{loopback.origin}/mcp"}}]})
+ started = _run(runtime, "oauth_start", {"name": "suno", "origin": "http://127.0.0.1:5123", "port": 5123})
+ state = parse_qs(urlparse(started["authorizeUrl"]).query)["state"][0]
+ original = repository.publish
+ concurrent = 0
+ peak = 0
+
+ def counted(*args, **kwargs):
+ nonlocal concurrent, peak
+ concurrent += 1
+ peak = max(peak, concurrent)
+ try:
+ return original(*args, **kwargs)
+ finally:
+ concurrent -= 1
+
+ monkeypatch.setattr(repository, "publish", counted)
+
+ async def both():
+ return await asyncio.gather(
+ runtime.submit("oauth_callback", {"state": state, "code": "code-1", "iss": loopback.origin}),
+ runtime.submit("refresh", {"name": "suno"}),
+ )
+
+ asyncio.run(both())
+ assert peak == 1
+ published = repository.read_published("suno")
+ assert published is not None
+ current = repository.package_dir("suno") / "revisions"
+ survivors = [path for path in current.iterdir() if path.is_dir()]
+ assert len(survivors) == 1
+ assert survivors[0].name == published["revision"]
+
+
+def test_logout_republishes_needs_login_without_tokens(runtime, loopback):
+ url = f"{loopback.origin}/mcp"
+ repository.write_definition(definition_from_provider("suno", {"url": url}))
+ _seed_tokens("suno", url, expires_at=time.time() + 3600)
+ assert _run(runtime, "refresh", {"name": "suno"})["ok"]
+ logged_out = _run(runtime, "oauth_logout", {"name": "suno"})
+ assert logged_out["ok"]
+ listed = repository.list_packages()[0]
+ assert listed["auth"] == "needs_login"
+ assert listed["toolCount"] == 0
+ assert not oauth.oauth_path("suno").exists()
+ dump = json.dumps(listed)
+ assert "access-" not in dump and "refresh-" not in dump
+
+
+def test_stdio_logout_is_rejected(runtime, tmp_path):
+ definition = definition_from_provider("echo", {"command": sys.executable, "args": ["-c", "pass"]})
+ repository.write_definition(definition)
+ logged_out = _run(runtime, "oauth_logout", {"name": "echo"})
+ assert logged_out["ok"] is False
+ assert logged_out["error"]["type"] == "usage"
+
+
+def test_authorization_header_logout_is_rejected(runtime, loopback):
+ added = _run(runtime, "add", {"servers": [{"name": "suno", "server": {
+ "url": f"{loopback.origin}/mcp",
+ "headers": {"Authorization": f"Bearer {loopback.access}"},
+ }}]})
+ assert added["ok"] and added["added"][0]["toolCount"] == 1
+ before = repository.list_packages()[0]
+ assert before.get("auth") != "needs_login"
+ logged_out = _run(runtime, "oauth_logout", {"name": "suno"})
+ assert logged_out["ok"] is False
+ assert logged_out["error"]["type"] == "usage"
+ after = repository.list_packages()[0]
+ assert after.get("auth") != "needs_login"
+ assert after["toolCount"] == 1
+
+
+def test_remove_cancels_pending_login(runtime, loopback):
+ _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": f"{loopback.origin}/mcp"}}]})
+ started = _run(runtime, "oauth_start", {"name": "suno", "origin": "http://127.0.0.1:5123", "port": 5123})
+ state = parse_qs(urlparse(started["authorizeUrl"]).query)["state"][0]
+ removed = _run(runtime, "remove", {"name": "suno"})
+ assert removed["ok"]
+ rejected = _run(runtime, "oauth_callback", {"state": state, "code": "late"})
+ assert rejected["ok"] is False
+ assert rejected["error"]["type"] == "invalid_callback"
+
+
+def test_tool_error_containing_auth_stays_tool_error(runtime, loopback):
+ url = f"{loopback.origin}/mcp"
+ repository.write_definition(definition_from_provider("suno", {"url": url}))
+ _seed_tokens("suno", url, expires_at=time.time() + 3600)
+ assert _run(runtime, "refresh", {"name": "suno"})["ok"]
+ loopback.tool_error = "auth failed for user"
+ called = _run(runtime, "call", {"name": "suno", "tool": "echo", "arguments": {"text": "hi"}})
+ assert called["error"]["type"] == "tool_error"
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index bfa0a2f9e..d043c669f 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -98,6 +98,9 @@ _RETAINED_OWNER_ROUTES = {
("POST", "/api/mcp/discover"),
("POST", "/api/mcp/{name}/refresh"),
("DELETE", "/api/mcp/{name}"),
+ ("POST", "/api/mcp/{name}/oauth/start"),
+ ("POST", "/api/mcp/{name}/oauth/complete"),
+ ("POST", "/api/mcp/{name}/oauth/logout"),
("PUT", "/api/permissions/authorized-users"),
("PUT", "/api/permissions/projects/{project_id}/access"),
("PUT", "/api/permissions/resources/{resource_kind}/{resource_id}/access"),
@@ -123,7 +126,7 @@ def test_complete_registered_api_management_inventory():
for method in (getattr(route, "methods", None) or ())
if method not in {"HEAD", "OPTIONS"}
}
- assert len(endpoints) == 303 # master 297 + 6 MCP Hub routes, classified in tests/test_mcp_hub_api.py
+ assert len(endpoints) == 307 # master 297 + 10 MCP Hub routes, classified in tests/test_mcp_hub_api.py
# Editors who use Vault read avault's authorization state; the handler admits only
# instance managers to raise the Keychain dialog on the host.
for method in ("GET", "POST"):
diff --git a/ui/src/components/workbench/ShowPageLaunchControl.tsx b/ui/src/components/workbench/ShowPageLaunchControl.tsx
index 7a4cca712..313723843 100644
--- a/ui/src/components/workbench/ShowPageLaunchControl.tsx
+++ b/ui/src/components/workbench/ShowPageLaunchControl.tsx
@@ -20,6 +20,7 @@ import {
type ViewportPoint,
} from '../../lib/showPageLaunch';
import { isDesktopShell } from '../../lib/desktopShell';
+import { navigatePreparedTab, openPreparedTab } from '../../lib/pwaNavigation';
import { isDesktopViewport } from '../../lib/useIsDesktop';
import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';
import { Button } from '../ui/button';
@@ -123,18 +124,13 @@ export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({
if (!linkHref) return;
// Open synchronously inside the click gesture, then navigate after ensure;
// otherwise popup blockers reject window.open after the awaited request.
- const tab = window.open('about:blank', '_blank');
+ const tab = openPreparedTab();
if (!tab) return;
- try {
- tab.opener = null;
- } catch {
- // Some browser WindowProxy implementations expose a read-only opener.
- }
if (!(await prepare())) {
tab.close();
return;
}
- if (!tab.closed) tab.location.replace(linkHref);
+ navigatePreparedTab(tab, linkHref);
}, [clearHoverTimer, linkHref, prepare]);
const pinToDock = useCallback(async () => {
diff --git a/ui/src/components/workbench/skills/McpHubSection.tsx b/ui/src/components/workbench/skills/McpHubSection.tsx
index 7f198c63e..f70ac3d11 100644
--- a/ui/src/components/workbench/skills/McpHubSection.tsx
+++ b/ui/src/components/workbench/skills/McpHubSection.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronDown, ChevronRight, Globe, Loader2, Plus, RefreshCw, Search, Terminal, Trash2, X } from 'lucide-react';
import clsx from 'clsx';
@@ -11,6 +11,8 @@ import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogTitle } from '../../ui/dialog';
import { Textarea } from '../../ui/textarea';
+import { pasteMayNeedOAuthLogin, preparedTabNeedsAuthorizeFallback } from '../../../lib/mcpPaste';
+import { navigatePreparedTab, openLinkInNewContext, openPreparedTab } from '../../../lib/pwaNavigation';
const SOURCE_CHIP: Record<string, string> = {
avibe: 'border-gold/40 bg-gold/[0.12] text-gold-ink',
@@ -82,21 +84,35 @@ export const McpHubSection: React.FC = () => {
const canManage = capabilities.is_instance_owner;
const [servers, setServers] = useState<McpServerSummary[]>([]);
const [search, setSearch] = useState('');
- const [selected, setSelected] = useState<string | null>(null);
+ const [selected, setSelected] = useState<string | null>(() => new URLSearchParams(window.location.search).get('mcp'));
const [expandedFor, setExpandedFor] = useState<string | null>(null);
const [expandedTools, setExpandedTools] = useState<Record<string, boolean>>({});
const [busy, setBusy] = useState<string | null>(null);
const [showAdd, setShowAdd] = useState(false);
const [addText, setAddText] = useState('');
const [addError, setAddError] = useState<string | null>(null);
+ const [loginFor, setLoginFor] = useState<{ name: string } | null>(null);
+ const [authorizeUrl, setAuthorizeUrl] = useState<string | null>(null);
+ const [callbackText, setCallbackText] = useState('');
const [confirmDelete, setConfirmDelete] = useState<McpServerSummary | null>(null);
+ const loginInFlight = useRef(false);
+
if (expandedFor !== selected) {
setExpandedFor(selected);
setExpandedTools({});
}
const describe = useCallback(
- (error?: McpError) => (error ? t(`mcpHub.errors.${error.type}`, { defaultValue: error.message, message: error.message }) : t('mcpHub.failed')),
+ (error?: McpError | string) => {
+ if (typeof error === 'string' && error.trim()) return error;
+ if (error && typeof error === 'object') {
+ const type = typeof error.type === 'string' ? error.type.trim() : '';
+ const message = typeof error.message === 'string' ? error.message : '';
+ if (type) return t(`mcpHub.errors.${type}`, { defaultValue: message || t('mcpHub.failed'), message });
+ if (message) return message;
+ }
+ return t('mcpHub.failed');
+ },
[t],
);
@@ -110,6 +126,13 @@ export const McpHubSection: React.FC = () => {
}
}, [api, describe, showToast, t]);
+ useEffect(() => {
+ const params = new URLSearchParams(window.location.search);
+ if (params.get('oauth') === 'success') {
+ showToast(t('mcpHub.loginComplete'), 'success');
+ window.history.replaceState({}, '', window.location.pathname);
+ }
+ }, [load, showToast, t]);
const [listed, setListed] = useState(false);
if (!listed) {
setListed(true);
@@ -151,7 +174,74 @@ export const McpHubSection: React.FC = () => {
}
};
+ const startLogin = async (server: Pick<McpServerSummary, 'name'>, tab: Window | null) => {
+ setBusy(`login:${server.name}`);
+ loginInFlight.current = true;
+ try {
+ const res = await api.loginMcp(server.name);
+ if (!res.ok) {
+ navigatePreparedTab(tab, null);
+ showToast(describe(res.error), 'error');
+ loginInFlight.current = false;
+ return;
+ }
+ const authorize = res.authorizeUrl ?? null;
+ if (authorize && !preparedTabNeedsAuthorizeFallback(tab)) {
+ navigatePreparedTab(tab, authorize);
+ } else {
+ navigatePreparedTab(tab, null);
+ }
+ if (authorize && preparedTabNeedsAuthorizeFallback(tab)) {
+ setLoginFor({ name: server.name });
+ setAuthorizeUrl(authorize);
+ showToast(t('mcpHub.authorizeFallback'), 'error', {
+ label: t('mcpHub.openAuthorize'),
+ onClick: () => openLinkInNewContext(authorize, 'noopener,noreferrer'),
+ });
+ } else if (res.mode !== 'direct') {
+ setLoginFor({ name: server.name });
+ setAuthorizeUrl(authorize);
+ }
+ } catch {
+ navigatePreparedTab(tab, null);
+ showToast(t('mcpHub.failed'), 'error');
+ loginInFlight.current = false;
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const onLogin = (server: McpServerSummary) => {
+ const tab = openPreparedTab();
+ void startLogin(server, tab);
+ };
+
+ useEffect(() => {
+ const refreshIfWaiting = () => {
+ if (!loginInFlight.current || document.visibilityState !== 'visible') return;
+ loginInFlight.current = false;
+ void load();
+ };
+ window.addEventListener('focus', refreshIfWaiting);
+ document.addEventListener('visibilitychange', refreshIfWaiting);
+ return () => {
+ window.removeEventListener('focus', refreshIfWaiting);
+ document.removeEventListener('visibilitychange', refreshIfWaiting);
+ };
+ }, [load]);
+
+ const onCompleteLogin = async () => {
+ if (!loginFor) return;
+ setBusy(`login:${loginFor.name}`);
+ try {
+ const res = await api.completeMcpLogin(loginFor.name, callbackText);
+ if (!res.ok) { showToast(describe(res.error), 'error'); return; }
+ setLoginFor(null); setAuthorizeUrl(null); setCallbackText(''); await load();
+ showToast(t('mcpHub.loginComplete'), 'success');
+ } finally { setBusy(null); }
+ };
const onAdd = async () => {
+ const tab = pasteMayNeedOAuthLogin(addText) ? openPreparedTab() : null;
setBusy('add');
setAddError(null);
try {
@@ -174,6 +264,7 @@ export const McpHubSection: React.FC = () => {
const toast = inline;
const hasBatch = Boolean(res.added || res.unchanged || res.failed);
if (!succeeded) {
+ navigatePreparedTab(tab, null);
setAddError(hasBatch ? inline : describe(res.error));
return;
}
@@ -184,7 +275,17 @@ export const McpHubSection: React.FC = () => {
} else {
showToast(t('mcpHub.succeededCount', { count: succeeded }), 'success');
}
+ const needsLogin = [...added, ...unchanged].find((item) => item.auth === 'needs_login');
+ if (needsLogin) {
+ await startLogin(needsLogin, tab);
+ await load();
+ return;
+ }
+ navigatePreparedTab(tab, null);
await load();
+ } catch {
+ navigatePreparedTab(tab, null);
+ showToast(t('mcpHub.failed'), 'error');
} finally {
setBusy(null);
}
@@ -279,7 +380,24 @@ export const McpHubSection: React.FC = () => {
{t('mcpHub.toolMeta', { count: server.toolCount ?? 0, transport: transportLabel(server) })}
</span>
</span>
- <ChevronRight className="size-3.5 text-muted" />
+ {server.auth === 'needs_login' ? (
+ <span
+ role="button"
+ tabIndex={0}
+ className="inline-flex h-6 items-center rounded-md border border-border bg-surface px-2 font-mono text-[10px] font-semibold uppercase text-foreground hover:bg-surface-2"
+ onClick={(event) => { event.stopPropagation(); void onLogin(server); }}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ event.stopPropagation();
+ void onLogin(server);
+ }
+ }}
+ >
+ {t('mcpHub.login')}
+ </span>
+ ) : null}
+ <ChevronRight className="size-3.5 text-muted" />
</button>
))
)}
@@ -330,6 +448,7 @@ export const McpHubSection: React.FC = () => {
? t('mcpHub.serverVersion', { version: current.serverVersion })
: null}
</div>
+ {current.auth === 'needs_login' ? <Button type="button" variant="brand" size="sm" onClick={() => void onLogin(current)}>{t('mcpHub.login')}</Button> : null}
{canManage ? (
<div className="flex items-center gap-2 pt-1">
<Button type="button" variant="outline" size="xs" disabled={busy !== null} onClick={() => void onRefreshOne(current.name)}>
@@ -346,6 +465,16 @@ export const McpHubSection: React.FC = () => {
) : null}
</div>
+ <Dialog open={loginFor !== null} onOpenChange={(open) => (!open ? setLoginFor(null) : undefined)}>
+ <DialogContent className="max-w-lg" closeLabel={t('common.close')}>
+ <DialogTitle>{t('mcpHub.loginTitle')}</DialogTitle>
+ <DialogDescription>{t('mcpHub.loginHint')}</DialogDescription>
+ {authorizeUrl ? <Button type="button" variant="outline" onClick={() => openLinkInNewContext(authorizeUrl, 'noopener,noreferrer')}>{t('mcpHub.openAuthorize')}</Button> : null}
+ <Textarea value={callbackText} onChange={(event) => setCallbackText(event.target.value)} className="min-h-20 font-mono text-[12px]" placeholder={t('mcpHub.callbackPlaceholder')} />
+ <DialogFooter><Button type="button" variant="outline" onClick={() => setLoginFor(null)}>{t('common.cancel')}</Button><Button type="button" disabled={!callbackText.trim() || busy !== null} onClick={() => void onCompleteLogin()}>{t('mcpHub.completeLogin')}</Button></DialogFooter>
+ </DialogContent>
+ </Dialog>
+
<Dialog open={showAdd} onOpenChange={(open) => (!open ? setShowAdd(false) : undefined)}>
<DialogContent className="max-w-lg" closeLabel={t('common.close')}>
<DialogTitle>{t('mcpHub.addTitle')}</DialogTitle>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 626a8df67..8fb2aa916 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -569,6 +569,7 @@ export interface McpServerSummary {
revision?: string | null;
generatedAt?: string;
serverVersion?: string;
+ auth?: 'none' | 'needs_login' | 'ok';
toolCount?: number;
tools?: { name: string; description?: string }[];
diagnostics?: string[];
@@ -591,7 +592,8 @@ export interface McpDefinition {
};
}
export interface McpResult { ok: boolean; error?: McpError }
-export interface McpParsedServer { name: string; exists: boolean; transport?: { type: string } }
+export type McpOAuthStartResult = McpResult & { authorizeUrl?: string; mode?: 'direct' | 'paste' };
+export type McpOAuthMutationResult = McpResult & { name?: string };
export interface McpTool { name: string; description?: string; inputSchema?: unknown; flags: { flag: string; kind: string; required: boolean }[] }
export type ApiContextType = {
@@ -945,13 +947,15 @@ export type ApiContextType = {
saved?: string[];
name?: string;
toolCount?: number;
- added?: { name: string; toolCount?: number }[];
- unchanged?: { name: string }[];
+ added?: { name: string; toolCount?: number; auth?: McpServerSummary['auth'] }[];
+ unchanged?: { name: string; auth?: McpServerSummary['auth'] }[];
failed?: { name: string; error?: string; type?: string }[];
}>;
discoverMcp: () => Promise<McpResult & { results?: { name: string; status: string; error?: string; toolCount?: number }[] }>;
refreshMcp: (name: string) => Promise<McpResult & { name?: string; toolCount?: number }>;
removeMcp: (name: string) => Promise<McpResult>;
+ loginMcp: (name: string) => Promise<McpOAuthStartResult>;
+ completeMcpLogin: (name: string, callbackUrl: string) => Promise<McpOAuthMutationResult>;
getMcpServer: (name: string) => Promise<McpResult & { server?: McpServerSummary; tools?: McpTool[] }>;
previewSkillSource: (source: string, params?: { projectId?: string }) => Promise<SkillsPreviewResult>;
addSkill: (payload: { source: string; scope: SkillScope; projectId?: string; backends?: string[]; all?: boolean; skill?: string; copy?: boolean }) => Promise<SkillsMutationResult>;
@@ -4336,6 +4340,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
discoverMcp: () => postJson('/api/mcp/discover', {}, { handleError: false }),
refreshMcp: (name) => postJson(`/api/mcp/${encodeURIComponent(name)}/refresh`, {}, { handleError: false }),
removeMcp: (name) => deleteJson(`/api/mcp/${encodeURIComponent(name)}`, undefined, { handleError: false }),
+ loginMcp: (name) => postJson(`/api/mcp/${encodeURIComponent(name)}/oauth/start`, {}, { handleError: false }),
+ completeMcpLogin: (name, callbackUrl) => postJson(`/api/mcp/${encodeURIComponent(name)}/oauth/complete`, { callbackUrl }, { handleError: false }),
getMcpServer: (name) => getJson(`/api/mcp/${encodeURIComponent(name)}`, { handleError: false }),
previewSkillSource: (source, params) =>
postJson('/api/skills/preview', { source, project_id: params?.projectId }),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 7a89b01f1..71c1a6633 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -6516,7 +6516,14 @@
"timeout": "The MCP server timed out.",
"capacity": "Too many MCP server processes are running; try again later.",
"not_found": "Unknown MCP server.",
- "unsupported_transport_sse": "SSE is not supported; use a Streamable HTTP URL."
+ "unsupported_transport_sse": "SSE is not supported; use a Streamable HTTP URL.",
+ "invalid_callback": "This OAuth callback is invalid or expired.",
+ "auth_required": "MCP login is required.",
+ "oauth": "MCP login could not be completed: {{message}}",
+ "usage": "{{message}}",
+ "add_failed": "{{message}}",
+ "add_partial": "{{message}}",
+ "internal": "MCP operation failed."
},
"addedCount": "Added {{count}} MCP servers.",
"addedPartial": "Added {{count}}; failed: {{failed}}",
@@ -6525,6 +6532,14 @@
"succeededCount": "{{count}} succeeded",
"failedCount": "{{count}} failed:",
"failedLine": "{{name}} — {{error}}",
- "callHint": "vibe mcp {{name}} <tool>"
+ "callHint": "vibe mcp {{name}} <tool>",
+ "login": "Log in",
+ "loginTitle": "Log in to MCP server",
+ "loginHint": "Authorize in the new tab, then paste the callback URL here when needed.",
+ "openAuthorize": "Open authorization",
+ "authorizeFallback": "The authorization tab could not be opened. Use Open authorization to continue.",
+ "callbackPlaceholder": "Paste the callback URL",
+ "completeLogin": "Complete login",
+ "loginComplete": "MCP login completed"
}
}
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index accc4a2f6..c42709e15 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -6516,7 +6516,14 @@
"timeout": "MCP 服务器超时。",
"capacity": "运行中的 MCP 服务器进程过多,请稍后重试。",
"not_found": "未知 MCP 服务器。",
- "unsupported_transport_sse": "不支持 SSE;请使用 Streamable HTTP 地址。"
+ "unsupported_transport_sse": "不支持 SSE;请使用 Streamable HTTP 地址。",
+ "invalid_callback": "OAuth 回调无效或已过期。",
+ "auth_required": "需要登录 MCP。",
+ "oauth": "MCP 登录未完成:{{message}}",
+ "usage": "{{message}}",
+ "add_failed": "{{message}}",
+ "add_partial": "{{message}}",
+ "internal": "MCP 操作失败。"
},
"addedCount": "已添加 {{count}} 个。",
"addedPartial": "已添加 {{count}} 个;失败:{{failed}}",
@@ -6525,6 +6532,14 @@
"succeededCount": "成功 {{count}} 个",
"failedCount": "失败 {{count}} 个:",
"failedLine": "{{name}} — {{error}}",
- "callHint": "vibe mcp {{name}} <tool>"
+ "callHint": "vibe mcp {{name}} <tool>",
+ "login": "登录",
+ "loginTitle": "登录 MCP 服务器",
+ "loginHint": "在新标签页中授权;如有需要,将回调 URL 粘贴到这里。",
+ "openAuthorize": "打开授权页面",
+ "authorizeFallback": "无法打开授权标签页。请点击「打开授权页面」继续。",
+ "callbackPlaceholder": "粘贴回调 URL",
+ "completeLogin": "完成登录",
+ "loginComplete": "MCP 登录完成"
}
}
diff --git a/ui/src/lib/mcpPaste.test.ts b/ui/src/lib/mcpPaste.test.ts
new file mode 100644
index 000000000..b4f5508d5
--- /dev/null
+++ b/ui/src/lib/mcpPaste.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest';
+
+import { pasteMayNeedOAuthLogin, preparedTabNeedsAuthorizeFallback } from './mcpPaste';
+
+describe('pasteMayNeedOAuthLogin', () => {
+ it('is true for an HTTP URL server without Authorization', () => {
+ expect(
+ pasteMayNeedOAuthLogin(
+ JSON.stringify({ mcpServers: { suno: { url: 'https://api.example/mcp' } } }),
+ ),
+ ).toBe(true);
+ });
+
+ it('is false for stdio command servers', () => {
+ expect(
+ pasteMayNeedOAuthLogin(
+ JSON.stringify({ mcpServers: { echo: { command: 'npx', args: ['-y', 'echo'] } } }),
+ ),
+ ).toBe(false);
+ });
+
+ it('is false when Authorization is already set', () => {
+ expect(
+ pasteMayNeedOAuthLogin(
+ JSON.stringify({
+ mcpServers: {
+ github: {
+ url: 'https://api.githubcopilot.com/mcp/',
+ headers: { Authorization: 'Bearer tok' },
+ },
+ },
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it('treats authorization header names case-insensitively', () => {
+ expect(
+ pasteMayNeedOAuthLogin(
+ JSON.stringify({
+ mcpServers: { github: { url: 'https://api.example/mcp', headers: { authorization: 'Bearer tok' } } },
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it('is true when a batch mixes stdio with one OAuth-eligible URL server', () => {
+ expect(
+ pasteMayNeedOAuthLogin(
+ JSON.stringify({
+ mcpServers: {
+ echo: { command: 'npx' },
+ suno: { url: 'https://api.example/mcp' },
+ },
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it('is false when JSON cannot be parsed', () => {
+ expect(pasteMayNeedOAuthLogin('{not json')).toBe(false);
+ });
+});
+
+describe('preparedTabNeedsAuthorizeFallback', () => {
+ it('falls back when the popup was blocked', () => {
+ expect(preparedTabNeedsAuthorizeFallback(null)).toBe(true);
+ });
+
+ it('falls back when the prepared tab was closed before navigation', () => {
+ expect(preparedTabNeedsAuthorizeFallback({ closed: true } as Window)).toBe(true);
+ });
+
+ it('does not fall back for an open prepared tab', () => {
+ expect(preparedTabNeedsAuthorizeFallback({ closed: false } as Window)).toBe(false);
+ });
+});
diff --git a/ui/src/lib/mcpPaste.ts b/ui/src/lib/mcpPaste.ts
new file mode 100644
index 000000000..f5e33e4a0
--- /dev/null
+++ b/ui/src/lib/mcpPaste.ts
@@ -0,0 +1,29 @@
+/** True when paste includes an HTTP MCP server that Hub can OAuth-login. */
+export function pasteMayNeedOAuthLogin(text: string): boolean {
+ try {
+ const parsed: unknown = JSON.parse(text);
+ if (!parsed || typeof parsed !== 'object') return false;
+ const servers = (parsed as { mcpServers?: unknown }).mcpServers;
+ const entries =
+ servers && typeof servers === 'object' && !Array.isArray(servers)
+ ? Object.values(servers as Record<string, unknown>)
+ : [parsed];
+ return entries.some(isOAuthEligiblePasteServer);
+ } catch {
+ return false;
+ }
+}
+
+function isOAuthEligiblePasteServer(value: unknown): boolean {
+ if (!value || typeof value !== 'object') return false;
+ const server = value as Record<string, unknown>;
+ const url = typeof server.url === 'string' && server.url.trim();
+ if (!url || server.command) return false;
+ const headers = server.headers;
+ if (!headers || typeof headers !== 'object' || Array.isArray(headers)) return true;
+ return !Object.keys(headers as Record<string, unknown>).some((key) => key.toLowerCase() === 'authorization');
+}
+
+export function preparedTabNeedsAuthorizeFallback(tab: Window | null): boolean {
+ return tab == null || tab.closed;
+}
diff --git a/ui/src/lib/pwaNavigation.test.ts b/ui/src/lib/pwaNavigation.test.ts
index 3dcce006d..77c473272 100644
--- a/ui/src/lib/pwaNavigation.test.ts
+++ b/ui/src/lib/pwaNavigation.test.ts
@@ -6,7 +6,9 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import {
internalPwaLinkTarget,
+ navigatePreparedTab,
openLinkInNewContext,
+ openPreparedTab,
shouldBlockPwaLoopbackLink,
} from './pwaNavigation';
@@ -246,10 +248,26 @@ describe('programmatic PWA navigation', () => {
.sort((left, right) => left.path.localeCompare(right.path));
expect(directCalls).toEqual([
- { path: 'components/workbench/ShowPageLaunchControl.tsx', count: 1 },
- { path: 'lib/pwaNavigation.ts', count: 1 },
+ { path: 'lib/pwaNavigation.ts', count: 2 },
]);
+ });
+
+ it('does not navigate the Avibe tab for MCP OAuth', () => {
+ const text = readFileSync(new URL('../components/workbench/skills/McpHubSection.tsx', import.meta.url), 'utf8');
+ expect(text).not.toMatch(/location\.assign/);
+ });
+ it('preallocates a blank tab and severs opener before later navigation', () => {
+ const tab = { opener: {} as Window, closed: false, close: vi.fn(), location: { replace: vi.fn() } };
+ const nativeOpen = vi.fn(() => tab);
+ vi.stubGlobal('window', { open: nativeOpen });
+ expect(openPreparedTab()).toBe(tab);
+ expect(nativeOpen).toHaveBeenCalledWith('about:blank', '_blank');
+ expect(tab.opener).toBeNull();
+ navigatePreparedTab(tab as unknown as Window, 'https://as.example/authorize');
+ expect(tab.location.replace).toHaveBeenCalledWith('https://as.example/authorize');
+ navigatePreparedTab(tab as unknown as Window, null);
+ expect(tab.close).toHaveBeenCalled();
});
it('severs the opener of every preallocated blank tab', () => {
diff --git a/ui/src/lib/pwaNavigation.ts b/ui/src/lib/pwaNavigation.ts
index e3ce064f5..eccf8b04c 100644
--- a/ui/src/lib/pwaNavigation.ts
+++ b/ui/src/lib/pwaNavigation.ts
@@ -82,3 +82,28 @@ export function openLinkInNewContext(href: string, features?: string): Window |
if (window.__AVIBE_PWA_NAVIGATE_SAME_ORIGIN__?.(href)) return null;
return window.open(href, '_blank', features);
}
+
+/**
+ * Open a blank tab inside the click gesture so a later awaited request can
+ * still navigate it. Popup blockers reject `window.open` after `await`.
+ */
+export function openPreparedTab(): Window | null {
+ if (typeof window === 'undefined') return null;
+ const tab = window.open('about:blank', '_blank');
+ if (!tab) return null;
+ try {
+ tab.opener = null;
+ } catch {
+ // Some WindowProxy implementations expose a read-only opener.
+ }
+ return tab;
+}
+
+export function navigatePreparedTab(tab: Window | null, href: string | null | undefined): void {
+ if (!tab || tab.closed) return;
+ if (!href) {
+ tab.close();
+ return;
+ }
+ tab.location.replace(href);
+}
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 8142e8de1..56d468638 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -465,6 +465,7 @@ _VIEWER_HTTP_RULES = tuple(
r"^/api/show-pages$",
r"^/api/show-pages/[^/]+/access$",
r"^/api/show-pages/[^/]+/icon$",
+ r"^/api/mcp/oauth/callback$",
)
)
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 7e72f12f1..8dce407f6 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1796,5 +1796,7 @@
"unsupported": "The reference image {path} is {mime}, which cannot be sent."
}
}
- }
+ },
+ "mcp_oauth_callback_success": "MCP OAuth login completed. You can close this tab.",
+ "mcp_oauth_callback_failure": "MCP OAuth login could not be completed. Return to Avibe and try again."
}
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 2a79be6e6..5a7512d1a 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1796,5 +1796,7 @@
"unsupported": "参考图片 {path} 是 {mime},无法发送。"
}
}
- }
+ },
+ "mcp_oauth_callback_success": "MCP OAuth 登录已完成,可以关闭此标签页。",
+ "mcp_oauth_callback_failure": "MCP OAuth 登录未完成,请返回 Avibe 重试。"
}
diff --git a/vibe/mcp_api.py b/vibe/mcp_api.py
index 5b0ca90fe..aadc50011 100644
--- a/vibe/mcp_api.py
+++ b/vibe/mcp_api.py
@@ -13,7 +13,7 @@ from core.mcp_hub import repository
from core.mcp_hub.definition import parse_provider_json, provider_entry
from core.mcp_hub.errors import McpHubError
-_STATUS = {"usage": 400, "not_found": 404, "exists": 409, "unavailable": 503, "unknown_outcome": 502}
+_STATUS = {"usage": 400, "not_found": 404, "exists": 409, "unavailable": 503, "unknown_outcome": 502, "auth_required": 401, "invalid_callback": 400, "oauth": 400, "internal": 500}
def _error(exc: McpHubError) -> tuple[dict[str, Any], int]:
@@ -49,6 +49,8 @@ async def run(handler, *args) -> tuple[dict[str, Any], int]:
return await handler(*args), 200
except McpHubError as cop:
return _error(cop)
+ except Exception as exc: # noqa: BLE001 - Web MCP must not leak a string envelope
+ return _error(McpHubError("internal", str(exc) or "Unexpected MCP Hub error."))
async def list_servers() -> dict[str, Any]:
@@ -97,3 +99,24 @@ async def refresh(name: str) -> dict[str, Any]:
async def remove(name: str) -> dict[str, Any]:
return await _owner("remove", {"name": name})
+async def oauth_start(name: str, body: dict[str, Any], origin: str | None = None) -> dict[str, Any]:
+ payload: dict[str, Any] = {"name": name, "origin": origin}
+ if body.get("port") is not None:
+ payload["port"] = body["port"]
+ if body.get("cli") is True:
+ payload["cli"] = True
+ if body.get("cloudOrigin"):
+ payload["cloudOrigin"] = body["cloudOrigin"]
+ return await _owner("oauth_start", payload)
+
+
+async def oauth_callback(body: dict[str, Any]) -> dict[str, Any]:
+ return await _owner("oauth_callback", body)
+
+
+async def oauth_complete(name: str, callback_url: str) -> dict[str, Any]:
+ return await _owner("oauth_complete", {"name": name, "callbackUrl": callback_url})
+
+
+async def oauth_logout(name: str) -> dict[str, Any]:
+ return await _owner("oauth_logout", {"name": name})
diff --git a/vibe/mcp_cli.py b/vibe/mcp_cli.py
index e56f9ccbb..11668bbf1 100644
--- a/vibe/mcp_cli.py
+++ b/vibe/mcp_cli.py
@@ -24,6 +24,8 @@ usage:
vibe mcp <server> --list [--format json]
vibe mcp <server> --refresh
vibe mcp <server> --remove
+ vibe mcp <server> --login-complete '<callback URL>'
+ vibe mcp <server> --logout
vibe mcp <server> <tool> --help
vibe mcp <server> <tool> [--<key> <value> ...]
vibe mcp <server> <tool> --args-json '<object>' | --args-file <path> | --args-stdin
@@ -240,6 +242,30 @@ def _server(name: str, args: list[str]) -> int:
validate_name(name)
except McpHubError:
raise McpHubError("not_found", f"Unknown MCP server {name!r}.", hint="vibe mcp --list") from None
+ if args and args[0] in {"--login", "--logout", "--login-complete"}:
+ denied = _admit("owner")
+ if denied is not None:
+ return denied
+ option = args[0]
+ if option == "--login":
+ if len(args) != 1:
+ raise McpHubError("usage", "usage: vibe mcp <server> --login", usage=True)
+ payload = {"name": name, "cli": True}
+ from config.v2_config import V2Config
+ loaded = V2Config.load()
+ cloud = loaded.remote_access.vibe_cloud
+ if cloud.enabled and cloud.public_url:
+ payload["cloudOrigin"] = str(cloud.public_url).rstrip("/")
+ payload["port"] = int(loaded.ui.setup_port)
+ return _oauth_owner("oauth_start", payload)
+ if option == "--login-complete":
+ if len(args) != 2:
+ raise McpHubError("usage", "usage: vibe mcp <server> --login-complete '<callback URL>'", usage=True)
+ return _oauth_owner("oauth_complete", {"name": name, "callbackUrl": args[1]})
+ if len(args) != 1:
+ raise McpHubError("usage", "usage: vibe mcp <server> --logout", usage=True)
+ return _oauth_owner("oauth_logout", {"name": name})
+
if args and args[0] == "--refresh":
denied = _admit("owner")
if denied is not None:
@@ -282,6 +308,23 @@ def _server(name: str, args: list[str]) -> int:
return _call(name, tool, arguments)
+def _oauth_owner(operation: str, payload: dict[str, Any]) -> int:
+ from vibe import internal_client
+ try:
+ response = internal_client.mcp_request_sync(operation, payload)
+ except internal_client.InternalServerUnavailable:
+ raise McpHubError("unavailable", "The Avibe service is not running.", hint="vibe start") from None
+ if not response.get("ok"):
+ raise McpHubError.from_payload(response.get("error"))
+ if operation == "oauth_start":
+ print(response.get("authorizeUrl", ""))
+ if response.get("mode") == "paste":
+ print("After authorization, paste the callback URL with --login-complete.", file=sys.stderr)
+ elif operation == "oauth_complete":
+ print("MCP OAuth login completed.")
+ else:
+ print("MCP OAuth tokens removed.")
+ return 0
def _server_list(name: str, args: list[str]) -> int:
as_json = _format_json(args, {"--list", "--help", "-h"})
published = _published(name)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index cf4d51684..f41bfdc33 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1687,6 +1687,7 @@ def _remote_auth_exempt_path() -> bool:
path == "/health"
or path == "/auth/login"
or path == "/auth/callback"
+ or path == "/api/mcp/oauth/callback"
or path == "/auth/show-identity/callback"
or path == "/auth/logout"
or path == "/api/session"
@@ -1710,6 +1711,7 @@ def _remote_auth_exempt_before_host_validation() -> bool:
request.path
in {
"/auth/callback",
+ "/api/mcp/oauth/callback",
"/auth/logout",
"/api/session",
"/api/csrf-token",
@@ -9545,10 +9547,46 @@ async def mcp_refresh(name: str, starlette_request: FastAPIRequest):
@app.delete("/api/mcp/{name}", include_in_schema=False)
async def mcp_remove(name: str, starlette_request: FastAPIRequest):
from vibe import mcp_api
-
return await _mcp_route(starlette_request, mcp_api.remove, name)
[email protected]("/api/mcp/{name}/oauth/start", include_in_schema=False)
+async def mcp_oauth_start(name: str, starlette_request: FastAPIRequest):
+ from vibe import mcp_api
+ def start():
+ body = _mcp_body()
+ from config.v2_config import V2Config
+ body["port"] = int(V2Config.load().ui.setup_port)
+ return mcp_api.oauth_start(name, body, _current_origin())
+ return await _mcp_route(starlette_request, start)
+
+
[email protected]("/api/mcp/oauth/callback", include_in_schema=False)
+async def mcp_oauth_callback(starlette_request: FastAPIRequest):
+ from vibe import mcp_api
+ query = {key: value for key, value in starlette_request.query_params.items()}
+ body, status = await mcp_api.run(mcp_api.oauth_callback, query)
+ if body.get("redirect"):
+ from starlette.responses import RedirectResponse
+ return RedirectResponse(body["redirect"], status_code=302)
+ from vibe.i18n import t as i18n_t
+ message = i18n_t("mcp_oauth_callback_success" if body.get("ok") else "mcp_oauth_callback_failure")
+ return Response(content=f"<!doctype html><title>MCP OAuth</title><main><p>{message}</p></main>", status_code=status, media_type="text/html")
+
+
[email protected]("/api/mcp/{name}/oauth/complete", include_in_schema=False)
+async def mcp_oauth_complete(name: str, starlette_request: FastAPIRequest):
+ from vibe import mcp_api
+ body = await starlette_request.json()
+ return await _mcp_route(starlette_request, lambda: mcp_api.oauth_complete(name, str(body.get("callbackUrl") or "")))
+
+
[email protected]("/api/mcp/{name}/oauth/logout", include_in_schema=False)
+async def mcp_oauth_logout(name: str, starlette_request: FastAPIRequest):
+ from vibe import mcp_api
+ return await _mcp_route(starlette_request, mcp_api.oauth_logout, name)
+
+
# Agent Skills — thin shells over api.* (which wraps the askill CLI). Pure
# data CRUD, so it stays in the UI-server process via core/services (no
# dispatch-socket round-trip). See docs/plans/workbench-skills-page.md.