From c4ba9211433814080d3b56672ce6222d2ccd70fa Mon Sep 17 00:00:00 2001 From: Totoro Date: Sat, 21 Nov 2026 09:32:32 +0800 Subject: [PATCH] feat(mcp): add per-user browser OAuth for remote servers (#8425) * feat(mcp): add per-user browser OAuth for remote servers * fix(mcp): let users clear grants after server removal --------- Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com> --- backend/app/gateway/app.py | 2 + backend/app/gateway/deps.py | 2 + backend/app/gateway/routers/mcp.py | 2 + backend/app/gateway/routers/mcp_user_oauth.py | 143 +++++++++ backend/app/gateway/routers/personal_mcp.py | 3 + backend/app/gateway/services.py | 16 +- backend/docs/MCP_SERVER.md | 59 +++- .../deerflow/agents/lead_agent/agent.py | 2 + .../harness/deerflow/capabilities/runtime.py | 10 +- .../deerflow/config/extensions_config.py | 55 ++++ .../harness/deerflow/mcp/agent_auth.py | 7 + .../harness/deerflow/mcp/browser_oauth.py | 284 ++++++++++++++++++ .../packages/harness/deerflow/mcp/cache.py | 4 +- .../packages/harness/deerflow/mcp/client.py | 2 +- .../harness/deerflow/mcp/oauth_store.py | 169 ++++++++++- .../harness/deerflow/mcp/personal_network.py | 15 +- .../packages/harness/deerflow/mcp/tools.py | 96 +++++- .../harness/deerflow/mcp/user_config.py | 4 +- .../persistence/mcp_oauth_tokens/__init__.py | 3 +- .../persistence/mcp_oauth_tokens/model.py | 40 ++- .../persistence/mcp_oauth_tokens/sql.py | 223 +++++++++++++- .../versions/0058_mcp_browser_oauth.py | 45 +++ .../harness/deerflow/runtime/context_keys.py | 2 + .../harness/deerflow/runtime/runs/worker.py | 12 + .../tools/builtins/invoke_acp_agent_tool.py | 2 +- .../packages/harness/deerflow/tools/tools.py | 9 +- backend/tests/test_invoke_acp_agent_tool.py | 14 + .../tests/test_mcp_browser_oauth_protocol.py | 137 +++++++++ backend/tests/test_mcp_cache_discovery.py | 30 ++ .../tests/test_mcp_config_error_details.py | 26 +- backend/tests/test_mcp_oauth_token_store.py | 141 ++++++++- backend/tests/test_mcp_session_pool.py | 31 +- .../test_migration_0047_mcp_oauth_tokens.py | 52 +++- backend/tests/test_plugin_tools.py | 3 +- config.example.yaml | 3 + docs/guide/mcp.md | 4 +- .../capabilities/mcp-user-connections.tsx | 122 ++++++++ .../workspace/capabilities/plugin-gallery.tsx | 9 + frontend/src/core/i18n/locales/en-US.ts | 15 + frontend/src/core/i18n/locales/types.ts | 15 + frontend/src/core/i18n/locales/zh-CN.ts | 15 + frontend/src/core/mcp/user-oauth.ts | 56 ++++ .../tests/e2e/platform-mcp-controls.spec.ts | 77 +++++ 43 files changed, 1879 insertions(+), 82 deletions(-) create mode 100644 backend/app/gateway/routers/mcp_user_oauth.py create mode 100644 backend/packages/harness/deerflow/mcp/browser_oauth.py create mode 100644 backend/packages/harness/deerflow/persistence/migrations/versions/0058_mcp_browser_oauth.py create mode 100644 backend/tests/test_mcp_browser_oauth_protocol.py create mode 100644 frontend/src/components/workspace/capabilities/mcp-user-connections.tsx create mode 100644 frontend/src/core/mcp/user-oauth.ts diff --git a/backend/app/gateway/app.py b/backend/app/gateway/app.py index e5348c1895..68fdae0049 100644 --- a/backend/app/gateway/app.py +++ b/backend/app/gateway/app.py @@ -41,6 +41,7 @@ from app.gateway.routers import ( knowledge, mcp, mcp_tasks, + mcp_user_oauth, memory, models, personal_mcp, @@ -1356,6 +1357,7 @@ This gateway provides runtime endpoints for agent runs plus custom endpoints for app.include_router(capabilities.router) app.include_router(mcp.router) app.include_router(personal_mcp.router) + app.include_router(mcp_user_oauth.router) # Durable MCP tasks are scoped to their owning thread. app.include_router(mcp_tasks.router) diff --git a/backend/app/gateway/deps.py b/backend/app/gateway/deps.py index 57e45c3da4..f9c48c1dd7 100644 --- a/backend/app/gateway/deps.py +++ b/backend/app/gateway/deps.py @@ -337,6 +337,8 @@ def credentials_key_consumers(config: AppConfig) -> list[str]: if extensions is not None: # deerflow.mcp.oauth_store keeps rotating refresh tokens in the database. for name, server in extensions.get_enabled_mcp_servers().items(): + if server.uses_browser_oauth: + consumers.append(f"mcpServers.{name}.user_oauth.enabled=true") oauth = server.oauth if oauth is not None and oauth.enabled and oauth.grant_type == "refresh_token": consumers.append(f"mcpServers.{name}.oauth.enabled=true") diff --git a/backend/app/gateway/routers/mcp.py b/backend/app/gateway/routers/mcp.py index 6e91c1260e..d5c50bdb6e 100644 --- a/backend/app/gateway/routers/mcp.py +++ b/backend/app/gateway/routers/mcp.py @@ -1134,6 +1134,8 @@ def _merge_preserving_secrets( # it and silently detach an Agent's capability selection. if isinstance(existing_extra.get("capability"), dict): update["capability"] = existing_extra["capability"] + if "user_oauth" not in incoming_extra and "user_oauth" in existing_extra: + update["user_oauth"] = existing_extra["user_oauth"] merged = incoming.model_copy(update=update) _ensure_no_masked_secrets(merged) return merged diff --git a/backend/app/gateway/routers/mcp_user_oauth.py b/backend/app/gateway/routers/mcp_user_oauth.py new file mode 100644 index 0000000000..29bd6d74a0 --- /dev/null +++ b/backend/app/gateway/routers/mcp_user_oauth.py @@ -0,0 +1,143 @@ +"""Browser-owned grants for operator-configured MCP connections.""" + +import asyncio +import hashlib +import logging +import re +import secrets + +from fastapi import APIRouter, Depends, HTTPException, Request, Response +from fastapi.responses import JSONResponse, RedirectResponse +from pydantic import BaseModel + +from app.gateway.auth.session_cookie import ACCESS_TOKEN_COOKIE_NAME +from app.gateway.csrf_middleware import is_secure_request +from app.gateway.deps import get_current_user_from_request +from app.gateway.routers.auth import require_session_source +from deerflow.config.extensions_config import MCP_USER_OAUTH_CALLBACK_PATH +from deerflow.mcp import browser_oauth as oauth +from deerflow.mcp.oauth_store import McpOAuthTokenKey, McpOAuthTokenStoreUnavailable, get_mcp_oauth_token_store + +logger = logging.getLogger(__name__) +router = APIRouter(prefix="/api/mcp/user-oauth", tags=["mcp"]) +_STATE = re.compile(r"[A-Za-z0-9_-]{43}\Z") +_LANDING = "/workspace/capabilities?tab=plugins&mcp_oauth={status}#my-mcp-connections" + + +class Connection(BaseModel): + server_key: str + display_name: str + status: str + + +class Connections(BaseModel): + connections: list[Connection] + + +async def _owner(request: Request) -> str: + require_session_source(request) + user = await get_current_user_from_request(request) + return str(user.id) + + +def _browser_binding(request: Request, nonce: str) -> str: + # Bind this browser attempt to the exact authenticated login session. + session = request.cookies[ACCESS_TOKEN_COOKIE_NAME] + return hashlib.sha256(f"{session}:{nonce}".encode()).hexdigest() + + +def _store(): + store = get_mcp_oauth_token_store() + if store is None: + raise HTTPException(503, "MCP user OAuth requires shared SQL storage.") + return store + + +async def _servers(): + try: + return await asyncio.to_thread(oauth.configured_servers) + except Exception: + raise HTTPException(503, "MCP server configuration is unavailable.") from None + + +async def _server(name): + server = (await _servers()).get(name) + if server is None: + raise HTTPException(404, "This MCP server does not offer user authorization.") + return server + + +@router.get("", response_model=Connections) +async def list_connections(response: Response, owner: str = Depends(_owner)): + servers = await _servers() + + def list_rows(): + result = [] + for name, server in servers.items(): + try: + state = oauth.connection_state(name, server, owner) + except McpOAuthTokenStoreUnavailable: + state = "unavailable" + result.append(Connection(server_key=name, display_name=name, status=state)) + store = get_mcp_oauth_token_store() + if store is not None: + try: + saved = store.list_delegated_servers(owner) + except McpOAuthTokenStoreUnavailable: + raise HTTPException(503, "MCP authorization storage is unavailable.") from None + result.extend(Connection(server_key=name, display_name=name, status="removed") for name in saved if name not in servers) + return result + + response.headers["Cache-Control"] = "no-store" + return Connections(connections=await asyncio.to_thread(list_rows)) + + +@router.post("/{server_key}/connect") +async def connect(server_key: str, request: Request, owner: str = Depends(_owner)): + _store() + server = await _server(server_key) + state, binding = secrets.token_urlsafe(32), secrets.token_urlsafe(32) + try: + destination = await oauth.begin_connection(server_key, server, owner, _browser_binding(request, binding), state) + except oauth.BrowserOAuthError as exc: + raise HTTPException(502, str(exc)) from None + except McpOAuthTokenStoreUnavailable: + raise HTTPException(503, "MCP authorization storage is unavailable.") from None + except Exception: + raise HTTPException(502, "Could not start MCP authorization. Check the server configuration.") from None + response = JSONResponse({"authorization_url": destination}, headers={"Cache-Control": "no-store"}) + response.set_cookie("df_mcp_" + state, binding, max_age=300, path=MCP_USER_OAUTH_CALLBACK_PATH, httponly=True, samesite="lax", secure=is_secure_request(request)) + return response + + +@router.get("/callback", response_class=RedirectResponse) +async def callback(request: Request, owner: str = Depends(_owner)): + state = request.query_params.get("state", "") + valid_state = bool(_STATE.fullmatch(state)) + cookie = "df_mcp_" + state if valid_state else "" + binding = request.cookies.get(cookie) if cookie else None + ok = False + if binding: + try: + attempt = await asyncio.to_thread(_store().consume_delegated, state, owner_user_id=owner, browser_binding=_browser_binding(request, binding)) + code = request.query_params.get("code") + issued_by = request.query_params.get("iss") + if attempt and code and len(code) <= 8192 and not request.query_params.get("error") and (issued_by is None or issued_by == attempt.context.issuer): + server = await _server(attempt.key.server_key) + ok = await oauth.finish_connection(attempt, server, code) + except Exception as exc: + # Provider and storage exceptions may contain credentials. + logger.warning("MCP user OAuth callback failed (%s)", type(exc).__name__) + response = RedirectResponse(_LANDING.format(status="connected" if ok else "failed"), status_code=303, headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"}) + if cookie: + response.delete_cookie(cookie, path=MCP_USER_OAUTH_CALLBACK_PATH, httponly=True, samesite="lax", secure=is_secure_request(request)) + return response + + +@router.delete("/{server_key}", status_code=204) +async def disconnect(server_key: str, owner: str = Depends(_owner)): + try: + await asyncio.to_thread(_store().disconnect_delegated, McpOAuthTokenKey.for_delegated(server_key, owner)) + except McpOAuthTokenStoreUnavailable: + raise HTTPException(503, "MCP authorization storage is unavailable.") from None + return Response(status_code=204, headers={"Cache-Control": "no-store"}) diff --git a/backend/app/gateway/routers/personal_mcp.py b/backend/app/gateway/routers/personal_mcp.py index c0bad49cc9..5a8744e807 100644 --- a/backend/app/gateway/routers/personal_mcp.py +++ b/backend/app/gateway/routers/personal_mcp.py @@ -47,6 +47,9 @@ def _read_personal_config(user_id: str) -> dict: def _validate_personal_server(server: mcp.McpServerConfigResponse, *, admin: bool) -> None: if server.agent_auth: raise HTTPException(422, "agent_auth is available only for deployment MCP servers") + delegated = (server.model_extra or {}).get("user_oauth") + if delegated is not None: + raise HTTPException(422, "user_oauth is available only for deployment MCP servers") # A personal store must not grant ordinary users the deployment operator's # ability to launch arbitrary host packages or query internal services. if not admin: diff --git a/backend/app/gateway/services.py b/backend/app/gateway/services.py index ed67c3a9b6..f53ad7c18a 100644 --- a/backend/app/gateway/services.py +++ b/backend/app/gateway/services.py @@ -28,7 +28,8 @@ from langchain_core.messages import BaseMessage, ChatMessage, HumanMessage, Syst from langchain_core.messages.utils import convert_to_messages from langgraph.types import Command -from app.gateway.auth_disabled import AUTH_DISABLED_USER_ID, AUTH_SOURCE_INTERNAL, get_auth_disabled_user, is_auth_disabled +from app.gateway.auth.session_cookie import ACCESS_TOKEN_COOKIE_NAME +from app.gateway.auth_disabled import AUTH_DISABLED_USER_ID, AUTH_SOURCE_INTERNAL, AUTH_SOURCE_SESSION, get_auth_disabled_user, is_auth_disabled from app.gateway.authz import require_cancel_permission_if, resolve_route_permissions from app.gateway.deps import get_checkpointer, get_local_provider, get_run_context, get_run_manager, get_run_store, get_stream_bridge from app.gateway.history_seed import reserve_history_seed, write_history_seed @@ -93,7 +94,7 @@ from deerflow.runtime.checkpoint_mode import ( ) from deerflow.runtime.checkpoint_state import graph_state_schema from deerflow.runtime.client_context import sanitize_client_context -from deerflow.runtime.context_keys import AGENT_AUTH_CONTEXT_KEY, PROJECT_CONTEXT_KEY +from deerflow.runtime.context_keys import AGENT_AUTH_CONTEXT_KEY, MCP_BROWSER_USER_CONTEXT_KEY, PROJECT_CONTEXT_KEY from deerflow.runtime.events.message_identity import MESSAGE_SEQ_KEY from deerflow.runtime.goal import goal_thread_lock from deerflow.runtime.journal import build_checkpoint_history_seed_events @@ -1243,6 +1244,7 @@ _SERVER_OWNED_RUNTIME_CONTEXT_KEYS: frozenset[str] = ( # never survive in either run-config section. PROJECT_CONTEXT_KEY, AGENT_AUTH_CONTEXT_KEY, + MCP_BROWSER_USER_CONTEXT_KEY, KNOWLEDGE_SCOPE_KEY, KNOWLEDGE_SCOPE_RUNTIME_KEY, } @@ -2794,6 +2796,16 @@ async def start_run( request_context=getattr(body, "context", None), ) + if ( + user is not None + and getattr(request.state, "auth_source", None) == AUTH_SOURCE_SESSION + and bool(getattr(request, "cookies", {}).get(ACCESS_TOKEN_COOKIE_NAME)) + and origin is None + and admitted_origin == "interactive" + and body.multitask_strategy != "enqueue" + ): + run_ctx = replace(run_ctx, mcp_browser_user=str(user.id)) + if agent_config is not None and getattr(run_ctx.app_config, "mcp_agent_auth", None): from deerflow.mcp.agent_auth import McpAgentAuthorizationError, capture_agent_authority diff --git a/backend/docs/MCP_SERVER.md b/backend/docs/MCP_SERVER.md index 6b63a1a306..34a64c8062 100644 --- a/backend/docs/MCP_SERVER.md +++ b/backend/docs/MCP_SERVER.md @@ -835,12 +835,63 @@ material already retained by those systems. Restarting or upgrading DeerFlow doe not rotate credentials or perform historical cleanup; operators must complete both actions explicitly. +### Browser authorization for deployment MCP + +An operator can opt a Streamable HTTP server into per-user browser authorization +by setting its `user_oauth` block in `extensions_config.json`. Register the +exact public Gateway callback URL `/api/mcp/user-oauth/callback` with the +provider before enabling the server. Configure access logs to omit the query +string for this callback, which carries the one-time code and state. + +```json +{ + "mcpServers": { + "tickets": { + "type": "http", + "url": "https://mcp.example.com/mcp", + "user_oauth": { + "issuer": "https://identity.example.com", + "client_id": "deerflow", + "client_secret": "$TICKETS_OAUTH_CLIENT_SECRET", + "redirect_uri": "https://deerflow.example.com/api/mcp/user-oauth/callback", + "scope": "tickets:read" + } + } + } +} +``` + +Omit `client_secret` for a registered public client. The authorization server +must support authorization code with S256 PKCE and publish MCP resource and +authorization server metadata. Discovered authorization and token endpoints +must share the configured issuer origin. For explicitly trusted private MCP or +issuer addresses, set `allow_private_addresses: true` in `user_oauth`; both +origins still require HTTPS. Local browser callbacks may use loopback HTTP. + +Sign in and open **Capability Center → Tools & integrations → My MCP connections** to connect +or disconnect your account. Browsing and invoking the tools uses your upstream +permissions. An existing conversation picks up the connection on the next +run. Disconnect takes effect before the next dispatch, including in existing +runs on another Gateway. A request already accepted by the remote server +may finish. If an operator disables the server or removes its browser authorization +configuration, you can still disconnect your saved grant in My MCP connections. +Foreground lead-agent chat supports these connections. Subagents, +scheduled runs, IM, and other background runs use their existing credential modes. + +This mode requires SQLite or PostgreSQL and the existing credentials key. +Multiple Gateway hosts need shared PostgreSQL and the same credentials key. +A server using browser authorization has a single authorization source: omit +`agent_auth`, `user_auth`, deployment `oauth`, any static or per-request +`Authorization` header, and durable MCP task toolsets for that server. Increase +`grant_revision` when deliberately invalidating grants, including if an old +issuer or server configuration is restored. + ## Tool Discovery Cache -MCP tool discovery is cached per server. The cache is keyed by server name and -holds, for each server, the discovered tools together with a canonical snapshot -of that server's configuration, the normalized global interceptor chain and the -pooled stdio session binding they were discovered against. +Deployment servers that do not require a browser grant use a shared discovery +cache keyed by server name. Entries contain the tools, server configuration +snapshot, normalized interceptor chain, and any pooled stdio session binding. +Browser-authorized tools are discovered for the signed-in user within each run. - **Reuse.** On every (re)initialization, a server's cached tools are reused only when its configuration snapshot and global interceptor chain are unchanged diff --git a/backend/packages/harness/deerflow/agents/lead_agent/agent.py b/backend/packages/harness/deerflow/agents/lead_agent/agent.py index 7c9f1eb25c..8c1014dd27 100644 --- a/backend/packages/harness/deerflow/agents/lead_agent/agent.py +++ b/backend/packages/harness/deerflow/agents/lead_agent/agent.py @@ -75,6 +75,7 @@ from deerflow.runtime.checkpoint_mode import ( frozen_checkpoint_channel_mode, inject_checkpoint_mode, ) +from deerflow.runtime.context_keys import MCP_BROWSER_USER_CONTEXT_KEY from deerflow.scheduler.runtime import SCHEDULER_CAPABILITY_CONTEXT_KEY, is_scheduler_capability from deerflow.skills.types import Skill from deerflow.subagents.capacity import configured_subagent_max_running @@ -1367,6 +1368,7 @@ def _assemble_lead_agent(config: RunnableConfig, *, app_config: AppConfig) -> Le mcp_plugins=getattr(agent_config, "mcp_plugins", None), subagent_enabled=subagent_enabled, include_conversation_reader=callable(cfg.get(CONVERSATION_READER_CONTEXT_KEY)) and not bool(cfg.get("is_subagent")), + **({"mcp_browser_user": runtime_context[MCP_BROWSER_USER_CONTEXT_KEY]} if isinstance(runtime_context, Mapping) and runtime_context.get(MCP_BROWSER_USER_CONTEXT_KEY) and not cfg.get("is_subagent") else {}), **({"scheduler_capability": scheduler_capability} if scheduler_capability is not None else {}), app_config=resolved_app_config, chat_model=chat_model, diff --git a/backend/packages/harness/deerflow/capabilities/runtime.py b/backend/packages/harness/deerflow/capabilities/runtime.py index 960a0ccd77..1977f80c30 100644 --- a/backend/packages/harness/deerflow/capabilities/runtime.py +++ b/backend/packages/harness/deerflow/capabilities/runtime.py @@ -29,10 +29,14 @@ def ambiguous_installation_ids(servers: Mapping[str, Mapping[str, Any]]) -> set[ return ambiguous +def selected_mcp_server_names(selected: list[str], config: ExtensionsConfig) -> set[str]: + ambiguous = ambiguous_installation_ids({name: server.model_dump() for name, server in config.mcp_servers.items()}) + wanted = set(selected) - ambiguous + return {name for name, server in config.get_enabled_mcp_servers().items() if installation_id(name, server.model_dump()) in wanted} + + def filter_mcp_plugins(tools: list[Any], selected: list[str] | None, config: ExtensionsConfig) -> list[Any]: if selected is None: return tools - ambiguous = ambiguous_installation_ids({name: server.model_dump() for name, server in config.mcp_servers.items()}) - wanted = set(selected) - ambiguous - servers = {name for name, server in config.get_enabled_mcp_servers().items() if installation_id(name, server.model_dump()) in wanted} + servers = selected_mcp_server_names(selected, config) return [tool for tool in tools if not is_mcp_tool(tool) or (get_mcp_source(tool) or {}).get("server_name") in servers] diff --git a/backend/packages/harness/deerflow/config/extensions_config.py b/backend/packages/harness/deerflow/config/extensions_config.py index a835789cb1..ddee3bce1f 100644 --- a/backend/packages/harness/deerflow/config/extensions_config.py +++ b/backend/packages/harness/deerflow/config/extensions_config.py @@ -13,6 +13,7 @@ from contextlib import contextmanager from datetime import date, datetime, time from pathlib import Path from typing import Any, Literal +from urllib.parse import urlsplit from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator, model_validator @@ -215,6 +216,41 @@ class McpOAuthConfig(BaseModel): model_config = ConfigDict(extra="allow") +MCP_USER_OAUTH_CALLBACK_PATH = "/api/mcp/user-oauth/callback" + + +def _browser_oauth_url(value: str, *, callback: bool = False, issuer: bool = False) -> str: + """Validate configuration shape here; IP/egress policy is checked again at dispatch.""" + parts = urlsplit(value) + _ = parts.port # Reject malformed ports before publishing config. + loopback_callback = callback and parts.hostname in {"localhost", "127.0.0.1", "::1"} and parts.scheme == "http" + if not parts.hostname or (parts.scheme != "https" and not loopback_callback) or parts.username is not None or parts.password is not None or "#" in value or any(c.isspace() for c in value) or "\\" in value: + raise ValueError("Invalid MCP browser OAuth URL; HTTPS is required except for a loopback callback") + if (issuer or callback) and "?" in value or callback and parts.path != MCP_USER_OAUTH_CALLBACK_PATH: + raise ValueError("Invalid MCP OAuth issuer or registered callback URI") + return value + + +class McpUserOAuthConfig(BaseModel): + """Pre-registered OAuth client for delegated browser connections.""" + + model_config = ConfigDict(extra="forbid") + + enabled: bool = True + client_id: str = Field(min_length=1) + client_secret: str | None = Field(default=None, repr=False) + issuer: str + redirect_uri: str + scope: str | None = None + allow_private_addresses: bool = False + grant_revision: str = Field(default="1", min_length=1) + + @field_validator("issuer", "redirect_uri") + @classmethod + def _validate_oauth_urls(cls, value: str, info: ValidationInfo) -> str: + return _browser_oauth_url(value, issuer=info.field_name == "issuer", callback=info.field_name == "redirect_uri") + + class McpServerConfig(BaseModel): """Configuration for a single MCP server.""" @@ -228,6 +264,7 @@ class McpServerConfig(BaseModel): headers: dict[str, str] = Field(default_factory=dict, description="HTTP headers to send (for sse or http type)") oauth: McpOAuthConfig | None = Field(default=None, description="OAuth configuration (for sse or http type)") agent_auth: bool = Field(default=False, description="Require an administrator-granted agent identity for calls to this deployment HTTP server") + user_oauth: McpUserOAuthConfig | None = Field(default=None, description="Browser-based OAuth for the caller of a deployment HTTP server") user_auth: McpUserScopedAuthConfig | None = Field( default=None, description="Per-user credential injection (for sse or http type): map DeerFlow user ids to per-user credential header values", @@ -274,6 +311,16 @@ class McpServerConfig(BaseModel): @model_validator(mode="after") def _validate_agent_credentials(self) -> "McpServerConfig": + if self.uses_browser_oauth: + if self.type != "http" or not self.url or self.task_toolsets: + raise ValueError("user_oauth requires Streamable HTTP without durable task toolsets") + _browser_oauth_url(self.url) + if self.agent_auth or (self.user_auth and self.user_auth.enabled) or (self.oauth and self.oauth.enabled): + raise ValueError("user_oauth is mutually exclusive with other MCP credential modes") + if any(name.lower() == "authorization" for name in self.headers): + raise ValueError("user_oauth conflicts with a static Authorization header") + if self.headers_from_context and self.headers_from_context.enabled and any(name.lower() == "authorization" for name in self.headers_from_context.headers): + raise ValueError("user_oauth conflicts with headers_from_context for Authorization") if self.agent_auth: if self.type != "http": raise ValueError("agent_auth requires an HTTP MCP server") @@ -284,6 +331,10 @@ class McpServerConfig(BaseModel): raise ValueError("agent_auth conflicts with headers_from_context for Authorization") return self + @property + def uses_browser_oauth(self) -> bool: + return self.user_oauth is not None and self.user_oauth.enabled + @field_validator("headers") @classmethod def _validate_header_names(cls, value: dict[str, str]) -> dict[str, str]: @@ -621,6 +672,10 @@ class ExtensionsConfig(BaseModel): """ return {name: config for name, config in self.mcp_servers.items() if config.enabled} + def get_discoverable_mcp_servers(self) -> dict[str, McpServerConfig]: + """Return servers that can be discovered without a user's browser grant.""" + return {name: server for name, server in self.get_enabled_mcp_servers().items() if not server.uses_browser_oauth} + def is_skill_enabled(self, skill_name: str, skill_category: str) -> bool: """Check if a skill is enabled. diff --git a/backend/packages/harness/deerflow/mcp/agent_auth.py b/backend/packages/harness/deerflow/mcp/agent_auth.py index b697e16aff..75adc1a2bc 100644 --- a/backend/packages/harness/deerflow/mcp/agent_auth.py +++ b/backend/packages/harness/deerflow/mcp/agent_auth.py @@ -227,6 +227,13 @@ def build_agent_auth_interceptor(extensions_config: ExtensionsConfig) -> Any | N return await handler(request) if not server.agent_auth: current = await asyncio.to_thread(_current_server, request.server_name) + try: + deployed = await asyncio.to_thread(get_extensions_config) + except Exception: + raise ToolException("MCP credential policy is unavailable") from None + browser_server = deployed.mcp_servers.get(request.server_name) + if browser_server is not None and browser_server.uses_browser_oauth: + raise ToolException(f"MCP server '{request.server_name}' now requires a browser connection. Start a new run to reload its tools.") if current is not None and current.agent_auth: # The old chain may still contain user/context auth writers. # Require rediscovery instead of injecting into that chain. diff --git a/backend/packages/harness/deerflow/mcp/browser_oauth.py b/backend/packages/harness/deerflow/mcp/browser_oauth.py new file mode 100644 index 0000000000..d40a537f38 --- /dev/null +++ b/backend/packages/harness/deerflow/mcp/browser_oauth.py @@ -0,0 +1,284 @@ +"""Split browser MCP authorization across requests; only the SQL store owns the grant.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import re +import secrets +import ssl +import time +from datetime import UTC, datetime, timedelta +from urllib.parse import quote_plus + +import httpx +from langchain_core.tools import ToolException +from mcp.client.auth.oauth2 import PKCEParameters +from mcp.client.auth.utils import ( + build_oauth_authorization_server_metadata_discovery_urls, + build_protected_resource_metadata_discovery_urls, + extract_resource_metadata_from_www_auth, + extract_scope_from_www_auth, + issuers_match, + validate_metadata_issuer, +) +from mcp.shared.auth import OAuthMetadata, OAuthToken, ProtectedResourceMetadata + +from deerflow.community.url_safety import resolve_host_addresses, resolve_public_addresses +from deerflow.config.extensions_config import ExtensionsConfig, McpServerConfig +from deerflow.mcp import oauth_store +from deerflow.mcp.headers import illegal_header_value_reason +from deerflow.mcp.personal_network import DestinationPinnedTransport + +_CONNECT = "Connect or reconnect this MCP server in Capability Center." +_UNAVAILABLE = "The MCP authorization service is unavailable. Please try again later." +_MAX_RESPONSE = 256 * 1024 + + +class BrowserOAuthError(Exception): + """All outward errors are fixed messages; remote bodies / credentials stay private.""" + + +class _InvalidGrant(BrowserOAuthError): + pass + + +def _https(value) -> httpx.URL: + url = httpx.URL(str(value)) + if url.scheme != "https" or not url.host or url.userinfo or url.fragment: + raise BrowserOAuthError("MCP authorization requires trusted HTTPS endpoints.") + return url + + +def _origin(url: httpx.URL) -> tuple[str, str, int | None]: + return url.scheme, url.host, url.port + + +def _trusted_endpoint(value, configured) -> httpx.URL: + url = _https(value) + if _origin(url) != _origin(_https(configured)): + raise BrowserOAuthError("The discovered endpoint is outside the configured origin.") + return url + + +def _transport(server: McpServerConfig, *, resource_only: bool) -> DestinationPinnedTransport: + resource = _https(server.url) + trusted = {_origin(resource), _origin(_https(server.user_oauth.issuer))} + + def resolve(value: httpx.URL) -> list[str]: + url = _https(value) + if (resource_only and url != resource) or _origin(url) not in trusted: + raise BrowserOAuthError("The destination does not match the configured MCP connection.") + addresses = resolve_host_addresses(url.host) if server.user_oauth.allow_private_addresses else resolve_public_addresses(url.host, action="connect to") + if not addresses: + raise BrowserOAuthError(_UNAVAILABLE) + return list(map(str, addresses)) + + # Respect the operator's CA trust for this opt-in mode, never proxy credentials through env proxies. + return DestinationPinnedTransport(resolve=resolve, tls_context=ssl.create_default_context) + + +def mcp_client_factory(server: McpServerConfig): + def factory(headers=None, timeout=None, auth=None): + return httpx.AsyncClient(headers=headers, timeout=timeout or 10.0, auth=auth, follow_redirects=False, trust_env=False, transport=_transport(server, resource_only=True)) + + return factory + + +def browser_grant_fingerprint(server: McpServerConfig) -> str: + oauth = server.user_oauth + binding = [server.type, server.url, oauth.issuer, oauth.client_id, oauth.redirect_uri, oauth.scope, oauth.grant_revision, oauth.allow_private_addresses] + return hashlib.sha256(json.dumps(binding, separators=(",", ":"), default=str).encode()).hexdigest() + + +def configured_servers() -> dict[str, McpServerConfig]: + # The same deployment JSON snapshot feeds tool assembly. Never substitute a + # last-known-good cache, a YAML-only entry, or an untrusted run override. + config = ExtensionsConfig.from_file() + return {name: s for name, s in config.get_enabled_mcp_servers().items() if s.uses_browser_oauth} + + +def get_browser_oauth_server(name: str) -> McpServerConfig | None: + return configured_servers().get(name) + + +def _store(): + store = oauth_store.get_mcp_oauth_token_store() + if store is None: + raise BrowserOAuthError(_UNAVAILABLE) + return store + + +async def _json(client, method: str, url, **kwargs) -> tuple[int, dict]: + async with client.stream(method, url, **kwargs) as response: + data = bytearray() + async for chunk in response.aiter_bytes(chunk_size=16384): + data.extend(chunk) + if len(data) > _MAX_RESPONSE: + raise BrowserOAuthError("The authorization response is too large.") + try: + body = json.loads(data) if data else {} + except ValueError: + body = {} + return response.status_code, body if isinstance(body, dict) else {} + + +async def _metadata(client, urls, model, expected_origin): + for url in dict.fromkeys(urls): + status, data = await _json(client, "GET", _trusted_endpoint(url, expected_origin), headers={"Accept": "application/json"}) + if status == 404: + continue + if status == 200: + return model.model_validate(data) + break + raise BrowserOAuthError("Could not discover OAuth metadata for the configured MCP server.") + + +async def begin_connection(name, server, owner, browser_binding, state): + oauth = server.user_oauth + async with asyncio.timeout(20), httpx.AsyncClient(transport=_transport(server, resource_only=False), follow_redirects=False, trust_env=False, timeout=5) as client: + # No credential on the probe. Real Streamable HTTP servers may reply with an SSE stream; + # consume only the challenge headers, never that stream. + async with client.stream( + "POST", + _https(server.url), + headers={"Accept": "application/json, text/event-stream"}, + json={"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-11-25", "capabilities": {}, "clientInfo": {"name": "DeerFlow", "version": "1"}}}, + ) as response: + if response.is_redirect or response.status_code >= 500: + raise BrowserOAuthError("Could not contact the configured MCP server.") + challenge = extract_resource_metadata_from_www_auth(response) + required_scope = extract_scope_from_www_auth(response) + protected = await _metadata(client, build_protected_resource_metadata_discovery_urls(challenge, str(server.url)), ProtectedResourceMetadata, server.url) + if not issuers_match(str(protected.resource), str(server.url)) or not any(issuers_match(str(i), str(oauth.issuer)) for i in protected.authorization_servers or ()): + raise BrowserOAuthError("The MCP resource or authorization issuer does not match its configuration.") + issuer = str(oauth.issuer) + md = await _metadata(client, build_oauth_authorization_server_metadata_discovery_urls(issuer, str(server.url)), OAuthMetadata, issuer) + validate_metadata_issuer(md, issuer) + if "S256" not in (md.code_challenge_methods_supported or ()) or "code" not in md.response_types_supported: + raise BrowserOAuthError("The MCP authorization server must support authorization code with PKCE S256.") + auth_method = "client_secret_basic" if oauth.client_secret else "none" + if md.token_endpoint_auth_methods_supported is not None and auth_method not in md.token_endpoint_auth_methods_supported: + raise BrowserOAuthError("The configured client authentication method is not supported.") + token_url = _trusted_endpoint(md.token_endpoint, issuer) + authorize = _trusted_endpoint(md.authorization_endpoint, issuer) + if not oauth.allow_private_addresses: + await asyncio.to_thread(resolve_public_addresses, authorize.host, action="connect to") + pkce = PKCEParameters.generate() + # The configured scope bounds what a challenge may request. + if oauth.scope and required_scope and not set(required_scope.split()) <= set(oauth.scope.split()): + raise BrowserOAuthError("The challenged scopes exceed the operator-approved scope.") + scope = required_scope or oauth.scope or " ".join(protected.scopes_supported or ()) or None + context = oauth_store.DelegatedOAuthContext(issuer=issuer, resource=str(server.url), token_url=str(token_url), scope=scope) + params = {"response_type": "code", "client_id": oauth.client_id, "redirect_uri": str(oauth.redirect_uri), "resource": context.resource, "code_challenge": pkce.code_challenge, "code_challenge_method": "S256", "state": state} + if scope: + params["scope"] = scope + key = oauth_store.McpOAuthTokenKey.for_delegated(name, owner) + await asyncio.to_thread(_store().begin_delegated, key, fingerprint=browser_grant_fingerprint(server), state=state, browser_binding=browser_binding, code_verifier=pkce.code_verifier, context=context) + return str(authorize.copy_merge_params(params)) + + +async def _exchange(server, context, form): + oauth = server.user_oauth + data = {**form, "resource": context.resource} + auth = None + if oauth.client_secret: + auth = httpx.BasicAuth(quote_plus(oauth.client_id), quote_plus(oauth.client_secret)) + else: + data["client_id"] = oauth.client_id + async with asyncio.timeout(10), httpx.AsyncClient(transport=_transport(server, resource_only=False), trust_env=False, follow_redirects=False, timeout=5.0) as client: + status, body = await _json(client, "POST", _trusted_endpoint(context.token_url, oauth.issuer), data=data, auth=auth, headers={"Accept": "application/json"}) + if status in (400, 401) and body.get("error") == "invalid_grant": + raise _InvalidGrant(_CONNECT) + if status != 200 or not isinstance(body.get("token_type"), str): + raise BrowserOAuthError(_UNAVAILABLE) + token = OAuthToken.model_validate(body) + if not token.access_token or illegal_header_value_reason(token.access_token) or not re.fullmatch(r"[A-Za-z0-9._~+/=-]+", token.access_token): + raise BrowserOAuthError("The provider did not return a usable bearer token.") + # RFC 6749 permits the provider to omit expires_in. Use a bounded local lifetime + # instead of considering an unqualified browser credential permanent. + expires = datetime.now(UTC) + timedelta(seconds=min(365 * 86400, max(0, token.expires_in if token.expires_in is not None else 3600))) + return token, expires + + +async def finish_connection(attempt, server, code: str) -> bool: + if browser_grant_fingerprint(server) != attempt.fingerprint: + return False + token, expires = await _exchange(server, attempt.context, {"grant_type": "authorization_code", "code": code, "code_verifier": attempt.code_verifier, "redirect_uri": str(server.user_oauth.redirect_uri)}) + current = (await asyncio.to_thread(configured_servers)).get(attempt.key.server_key) + if not current or browser_grant_fingerprint(current) != attempt.fingerprint: + return False + return await asyncio.to_thread(_store().complete_delegated, attempt, access_token=token.access_token, expires_at=expires, refresh_token=token.refresh_token) + + +def connection_state(name, server, owner): + store = oauth_store.get_mcp_oauth_token_store() + if store is None: + return "unavailable" + key = oauth_store.McpOAuthTokenKey.for_delegated(name, owner) + fingerprint = browser_grant_fingerprint(server) + grant = store.get_delegated(key, fingerprint=fingerprint) + if grant is None: + return "reconnect_required" if store.delegated_needs_reconnect(key, fingerprint=fingerprint) else "disconnected" + if not grant.token.refresh_token and grant.token.expires_at and grant.token.expires_at <= datetime.now(UTC): + return "reconnect_required" + return "connected" + + +async def get_call_token(name, server, owner, *, expected_epoch=None, rejected_token=None): + """Get current authority at dispatch; the caller must not replay a tool side effect.""" + try: + return await _call_token(name, server, owner, expected_epoch, rejected_token) + except ToolException: + raise + except Exception: + raise ToolException(_UNAVAILABLE) from None + + +async def _call_token(name, server, owner, expected_epoch, rejected_token): + store = _store() + key = oauth_store.McpOAuthTokenKey.for_delegated(name, owner) + fp = browser_grant_fingerprint(server) + deadline = time.monotonic() + oauth_store.REFRESH_LEASE_SECONDS + 12 + while time.monotonic() < deadline: + grant = await asyncio.to_thread(store.get_delegated, key, fingerprint=fp) + if grant is None or expected_epoch is not None and grant.grant_epoch != expected_epoch: + raise ToolException(_CONNECT) + current = grant.token + rejected = rejected_token is not None and secrets.compare_digest(current.access_token or "", rejected_token) + if current.access_token and not rejected and (current.expires_at is None or current.expires_at > datetime.now(UTC)): + return current.access_token, grant.grant_epoch + if not current.refresh_token: + if await asyncio.to_thread(store.mark_delegated_reconnect, key, expected_epoch=grant.grant_epoch, expected_version=grant.version): + raise ToolException(_CONNECT) + continue + lease = await asyncio.to_thread(store.claim, key, fingerprint=fp, expected_version=grant.version, grant_epoch=grant.grant_epoch) + if not lease: + await asyncio.sleep(oauth_store.REFRESH_POLL_SECONDS) + continue + try: + # Hard timeout < the existing refresh lease; no second worker can refresh a live request. + token, expires = await _exchange(server, grant.context, {"grant_type": "refresh_token", "refresh_token": current.refresh_token}) + saved = await asyncio.to_thread( + store.save, + key, + lease_owner=lease, + fingerprint=fp, + request_fingerprint=fp, + grant_epoch=grant.grant_epoch, + access_token=token.access_token, + token_type=token.token_type, + expires_at=expires, + refresh_token=token.refresh_token or current.refresh_token, + rotated=bool(token.refresh_token and token.refresh_token != current.refresh_token), + ) + if saved: + return token.access_token, grant.grant_epoch + raise ToolException(_CONNECT) + except _InvalidGrant: + await asyncio.to_thread(store.disconnect_delegated, key, expected_epoch=grant.grant_epoch, lease_owner=lease) + raise ToolException(_CONNECT) from None + finally: + await asyncio.to_thread(store.release, key, lease) + raise ToolException(_UNAVAILABLE) diff --git a/backend/packages/harness/deerflow/mcp/cache.py b/backend/packages/harness/deerflow/mcp/cache.py index 97c3276be7..08a7d86b54 100644 --- a/backend/packages/harness/deerflow/mcp/cache.py +++ b/backend/packages/harness/deerflow/mcp/cache.py @@ -1041,7 +1041,7 @@ async def initialize_mcp_tools() -> list[BaseTool]: # a claim can observe an interceptor edit after reconciliation, # and a failed claim already advanced that baseline on retry. if loaded_revision is not None: - for name in loaded_config.get_enabled_mcp_servers(): + for name in loaded_config.get_discoverable_mcp_servers(): entry = _server_tool_cache.get(name) if ( entry is not None @@ -1054,7 +1054,7 @@ async def initialize_mcp_tools() -> list[BaseTool]: if retired_before_claim is not None: retired_before_claim.close_all_sync() - enabled_names = list(loaded_config.get_enabled_mcp_servers()) + enabled_names = list(loaded_config.get_discoverable_mcp_servers()) missing_names = [name for name in enabled_names if name not in reusable_entries] discovered_groups: dict[str, ServerDiscoveryResult] = {} try: diff --git a/backend/packages/harness/deerflow/mcp/client.py b/backend/packages/harness/deerflow/mcp/client.py index f02bb32dc7..522d74d50f 100644 --- a/backend/packages/harness/deerflow/mcp/client.py +++ b/backend/packages/harness/deerflow/mcp/client.py @@ -69,7 +69,7 @@ def build_servers_config(extensions_config: ExtensionsConfig) -> dict[str, dict[ Returns: Dictionary mapping server names to their parameters. """ - enabled_servers = extensions_config.get_enabled_mcp_servers() + enabled_servers = extensions_config.get_discoverable_mcp_servers() if not enabled_servers: logger.info("No enabled MCP servers found") diff --git a/backend/packages/harness/deerflow/mcp/oauth_store.py b/backend/packages/harness/deerflow/mcp/oauth_store.py index 2bc8f4df34..110ea32f97 100644 --- a/backend/packages/harness/deerflow/mcp/oauth_store.py +++ b/backend/packages/harness/deerflow/mcp/oauth_store.py @@ -10,6 +10,9 @@ connection's latest tokens in ``mcp_oauth_tokens`` (see credentials key (``DEER_FLOW_CREDENTIALS_KEY``), and arbitrates refreshes between processes with a short lease. +Browser OAuth grants use the same cipher, database and refresh lease with a +separate scope and grant epoch. Only that scope can store access-only grants. + The host installs one store per process (:func:`set_mcp_oauth_token_store`); without one, tokens stay in process memory as before. Every method blocks (SQL, possibly the first key-file read): call it through ``asyncio.to_thread``. @@ -24,7 +27,7 @@ import logging import time import uuid from collections.abc import Callable, Collection -from dataclasses import dataclass +from dataclasses import asdict, dataclass, field from datetime import UTC, datetime from typing import Literal, NamedTuple @@ -56,7 +59,7 @@ class McpOAuthTokenKeyUnavailable(McpOAuthTokenStoreUnavailable): class McpOAuthTokenKey: """Row key: personal connections never share a row with a same-named deployment one.""" - scope: Literal["deployment", "personal"] + scope: Literal["deployment", "personal", "delegated"] owner_user_id: str server_key: str @@ -66,6 +69,10 @@ class McpOAuthTokenKey: return cls(scope="deployment", owner_user_id="", server_key=server_name) return cls(scope="personal", owner_user_id=owner_user_id, server_key=server_name) + @classmethod + def for_delegated(cls, server_name: str, owner_user_id: str) -> McpOAuthTokenKey: + return cls(scope="delegated", owner_user_id=owner_user_id, server_key=server_name) + @dataclass(frozen=True) class PersistedOAuthToken: @@ -86,6 +93,42 @@ class StoredTokenLookup(NamedTuple): undecryptable: bool = False +@dataclass(frozen=True) +class DelegatedOAuthContext: + issuer: str + resource: str + token_url: str + scope: str | None = None + + +@dataclass(frozen=True) +class DelegatedOAuthAttempt: + key: McpOAuthTokenKey + fingerprint: str + grant_epoch: int + context: DelegatedOAuthContext + code_verifier: str = field(repr=False) + + +@dataclass(frozen=True) +class DelegatedOAuthToken: + access_token: str = field(repr=False) + expires_at: datetime | None + refresh_token: str | None = field(repr=False) + + +@dataclass(frozen=True) +class DelegatedOAuthGrant: + grant_epoch: int + version: int + context: DelegatedOAuthContext + token: DelegatedOAuthToken + + +def _digest(value: str) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest() + + def _server_subject(key: McpOAuthTokenKey) -> str: return f"MCP server '{key.server_key}'" @@ -174,7 +217,120 @@ class McpOAuthTokenStore: expires_at = datetime.fromtimestamp(row.access_expires_at, UTC) if row.access_expires_at is not None else None return StoredTokenLookup(row.version, PersistedOAuthToken(access_token=access_token, token_type=row.token_type, expires_at=expires_at, refresh_token=refresh_token)) - def claim(self, key: McpOAuthTokenKey, *, fingerprint: str, expected_version: int | None) -> str | None: + def begin_delegated( + self, + key: McpOAuthTokenKey, + *, + fingerprint: str, + state: str, + browser_binding: str, + code_verifier: str, + context: DelegatedOAuthContext, + ttl_seconds: int = 300, + ) -> int: + """Begin the latest authorization attempt and invalidate the old grant.""" + verifier_enc = self._cipher().encrypt_text(code_verifier) + return self._call( + _server_subject(key), + "begin OAuth authorization for", + lambda: self._repo.begin_delegated( + key.owner_user_id, + key.server_key, + fingerprint=fingerprint, + state_digest=_digest(state), + browser_digest=_digest(browser_binding), + verifier_enc=verifier_enc, + context=json.dumps(asdict(context)), + ttl_seconds=ttl_seconds, + ), + ) + + def consume_delegated(self, state: str, *, owner_user_id: str, browser_binding: str) -> DelegatedOAuthAttempt | None: + """Claim this browser's state, releasing database resources before token exchange.""" + attempt = self._call( + "MCP browser authorization", + "claim", + lambda: self._repo.consume_delegated(_digest(state), owner_user_id=owner_user_id, browser_digest=_digest(browser_binding)), + ) + if attempt is None: + return None + try: + return DelegatedOAuthAttempt( + McpOAuthTokenKey.for_delegated(attempt.server_key, attempt.owner_user_id), + attempt.config_fingerprint, + attempt.grant_epoch, + DelegatedOAuthContext(**json.loads(attempt.grant_context)), + self._cipher().decrypt_text(attempt.verifier_enc), + ) + except CredentialsDecryptError: + raise McpOAuthTokenKeyUnavailable("The MCP browser authorization cannot be decrypted") from None + + def complete_delegated( + self, + attempt: DelegatedOAuthAttempt, + *, + access_token: str, + expires_at: datetime | None, + refresh_token: str | None = None, + ) -> bool: + """Publish tokens if this attempt still owns the grant epoch.""" + key = attempt.key + cipher = self._cipher() + return self._call( + _server_subject(key), + "complete OAuth authorization for", + lambda: self._repo.complete_delegated( + key.owner_user_id, + key.server_key, + grant_epoch=attempt.grant_epoch, + fingerprint=attempt.fingerprint, + context=json.dumps(asdict(attempt.context)), + access_token_enc=cipher.encrypt_text(access_token), + access_expires_at=expires_at.timestamp() if expires_at is not None else None, + refresh_token_enc=cipher.encrypt_text(refresh_token) if refresh_token else None, + ), + ) + + def get_delegated(self, key: McpOAuthTokenKey, *, fingerprint: str) -> DelegatedOAuthGrant | None: + """Read the current grant from shared storage before using any delegated token.""" + row = self._call(_server_subject(key), "read", lambda: self._repo.get("delegated", key.owner_user_id, key.server_key)) + if row is None or row.config_fingerprint != fingerprint or row.token_request_fingerprint != fingerprint or row.access_token_enc is None or row.grant_context is None or row.grant_epoch is None: + return None + cipher = self._cipher() + try: + token = DelegatedOAuthToken( + access_token=cipher.decrypt_text(row.access_token_enc), + expires_at=datetime.fromtimestamp(row.access_expires_at, UTC) if row.access_expires_at is not None else None, + refresh_token=cipher.decrypt_text(row.refresh_token_enc) if row.refresh_token_enc else None, + ) + except CredentialsDecryptError: + raise McpOAuthTokenKeyUnavailable("The MCP browser grant cannot be decrypted") from None + return DelegatedOAuthGrant(row.grant_epoch, row.version, DelegatedOAuthContext(**json.loads(row.grant_context)), token) + + def list_delegated_servers(self, owner_user_id: str) -> list[str]: + return self._call("MCP browser connections", "list", lambda: self._repo.list_delegated_servers(owner_user_id)) + + def delegated_needs_reconnect(self, key: McpOAuthTokenKey, *, fingerprint: str) -> bool: + row = self._call(_server_subject(key), "read", lambda: self._repo.get("delegated", key.owner_user_id, key.server_key)) + return bool(row and row.config_fingerprint == fingerprint and row.grant_context is not None and row.access_token_enc is None) + + def disconnect_delegated(self, key: McpOAuthTokenKey, *, expected_epoch: int | None = None, lease_owner: str | None = None) -> bool: + """Disconnect, or mark reconnect-required if the refresh lease holder failed.""" + return self._call( + _server_subject(key), + "disconnect", + lambda: self._repo.disconnect_delegated(key.owner_user_id, key.server_key, expected_epoch=expected_epoch, lease_owner=lease_owner), + ) + + def mark_delegated_reconnect(self, key: McpOAuthTokenKey, *, expected_epoch: int, expected_version: int) -> bool: + """Retire a rejected access-only token if it still belongs to this grant.""" + return self._call( + _server_subject(key), + "mark reconnect-required", + lambda: self._repo.disconnect_delegated(key.owner_user_id, key.server_key, expected_epoch=expected_epoch, access_only_version=expected_version), + ) + + def claim(self, key: McpOAuthTokenKey, *, fingerprint: str, expected_version: int | None, grant_epoch: int | None = None) -> str | None: """Claim the next refresh; returns the lease token, or ``None`` while a peer holds it or wrote since the read.""" lease_owner = str(uuid.uuid4()) claimed = self._call( @@ -189,6 +345,7 @@ class McpOAuthTokenStore: lease_owner=lease_owner, lease_seconds=REFRESH_LEASE_SECONDS, now=time.time(), + grant_epoch=grant_epoch, ), ) return lease_owner if claimed else None @@ -202,9 +359,10 @@ class McpOAuthTokenStore: request_fingerprint: str, access_token: str, token_type: str, - expires_at: datetime, + expires_at: datetime | None, refresh_token: str, rotated: bool, + grant_epoch: int | None = None, ) -> bool: """Store a refreshed token under the claim; ``False`` when the lease was lost meanwhile.""" cipher = self._cipher() @@ -222,10 +380,11 @@ class McpOAuthTokenStore: access_token_enc=access_token_enc, token_request_fingerprint=request_fingerprint, token_type=token_type, - access_expires_at=expires_at.timestamp(), + access_expires_at=expires_at.timestamp() if expires_at is not None else None, refresh_token_enc=refresh_token_enc, rotated=rotated, now=time.time(), + grant_epoch=grant_epoch, ), ) diff --git a/backend/packages/harness/deerflow/mcp/personal_network.py b/backend/packages/harness/deerflow/mcp/personal_network.py index 43b10959e7..976e8179e4 100644 --- a/backend/packages/harness/deerflow/mcp/personal_network.py +++ b/backend/packages/harness/deerflow/mcp/personal_network.py @@ -1,8 +1,9 @@ -"""Public-network policy for non-operator personal HTTP MCP connections.""" +"""Destination-pinned HTTP transport; personal MCP connections require public network addresses.""" import asyncio import ipaddress import ssl +from collections.abc import Callable import httpx @@ -23,20 +24,22 @@ def _public_addresses(url: httpx.URL) -> list[str]: return list(dict.fromkeys(addresses)) if addresses else [str(ipaddress.ip_address(url.host))] -class _PersonalTransport(httpx.AsyncBaseTransport): - def __init__(self): +class DestinationPinnedTransport(httpx.AsyncBaseTransport): + def __init__(self, *, resolve: Callable[[httpx.URL], list[str]] = _public_addresses, tls_context: Callable[[], ssl.SSLContext] | None = None): + self._resolve = resolve + self._tls_context = tls_context self._ssl_context: ssl.SSLContext | None = None self._ssl_context_lock = asyncio.Lock() self._transports: dict[tuple[bytes, bytes, int | None], httpx.AsyncHTTPTransport] = {} async def handle_async_request(self, request: httpx.Request) -> httpx.Response: - addresses = await asyncio.to_thread(_public_addresses, request.url) + addresses = await asyncio.to_thread(self._resolve, request.url) # The synchronous client factory can run on the event loop. Load TLS # trust lazily off-loop, sharing one context across concurrent requests. if self._ssl_context is None: async with self._ssl_context_lock: if self._ssl_context is None: - self._ssl_context = await asyncio.to_thread(httpx.create_ssl_context, trust_env=False) + self._ssl_context = await asyncio.to_thread(self._tls_context) if self._tls_context else await asyncio.to_thread(httpx.create_ssl_context, trust_env=False) origin = (request.url.raw_scheme, request.url.raw_host, request.url.port) # Pin TCP to the vetted IP, but isolate pools by original origin so two # names sharing an IP cannot reuse a connection authenticated for one. @@ -64,7 +67,7 @@ class _PersonalTransport(httpx.AsyncBaseTransport): def personal_httpx_client_factory(headers=None, timeout=None, auth=None): - kwargs = {"headers": headers, "auth": auth, "follow_redirects": False, "trust_env": False, "transport": _PersonalTransport()} + kwargs = {"headers": headers, "auth": auth, "follow_redirects": False, "trust_env": False, "transport": DestinationPinnedTransport()} if timeout is not None: kwargs["timeout"] = timeout return httpx.AsyncClient(**kwargs) diff --git a/backend/packages/harness/deerflow/mcp/tools.py b/backend/packages/harness/deerflow/mcp/tools.py index b373af372f..6999b8cb64 100644 --- a/backend/packages/harness/deerflow/mcp/tools.py +++ b/backend/packages/harness/deerflow/mcp/tools.py @@ -1387,7 +1387,7 @@ def _prepare_server_discovery( session_pool: MCPSessionPool | None, ) -> _PreparedServerDiscovery | None: """Build selected connections and capture bindings before discovery.""" - all_enabled = extensions_config.get_enabled_mcp_servers() + all_enabled = extensions_config.get_discoverable_mcp_servers() requested = set(all_enabled) if server_names is None else set(server_names) & set(all_enabled) selected_names = [name for name in all_enabled if name in requested] if not selected_names: @@ -1507,6 +1507,100 @@ async def _discover_and_wrap_prepared( return groups +async def get_browser_mcp_tools(config: ExtensionsConfig, owner: str, selected: set[str] | None = None) -> list[BaseTool]: + """Discover as the signed-in lead agent, without publishing to the shared cache.""" + import httpx + from langchain_core.tools import ToolException + + from deerflow.approvals.policy import digest + from deerflow.mcp.browser_oauth import browser_grant_fingerprint, get_browser_oauth_server, get_call_token, mcp_client_factory + from deerflow.mcp.client import build_server_params + from deerflow.runtime.context_keys import MCP_BROWSER_USER_CONTEXT_KEY + + adapter = _load_mcp_adapter_symbols() + if adapter is None: + return [] + client_cls, load_tools = adapter + redirect_hint = "Connect or reconnect this MCP server in Capability Center." + + async def discover(name: str, server: McpServerConfig) -> tuple[BaseTool, ...]: + fingerprint = browser_grant_fingerprint(server) + + async def check_current(): + try: + current = await asyncio.to_thread(get_browser_oauth_server, name) + except Exception: + raise ToolException("MCP credential policy is unavailable") from None + if current is None or browser_grant_fingerprint(current) != fingerprint: + raise ToolException(redirect_hint) + return current + + try: + await check_current() + _, epoch = await get_call_token(name, server, owner) + except ToolException: + return () + + class CurrentGrant(httpx.Auth): + async def async_auth_flow(self, request): + current = await check_current() + token, _ = await get_call_token(name, current, owner, expected_epoch=epoch) + await check_current() + request.headers["Authorization"] = f"Bearer {token}" + response = yield request + if response.status_code == 401: + # Do not replay remote calls. A later request can use the rotated token. + await get_call_token(name, current, owner, expected_epoch=epoch, rejected_token=token) + + async def require_current_grant(request, handler): + runtime = getattr(request, "runtime", None) + context = getattr(runtime, "context", None) + if not isinstance(context, Mapping) or context.get(MCP_BROWSER_USER_CONTEXT_KEY) != owner: + raise ToolException(redirect_hint) + current = await check_current() + await get_call_token(name, current, owner, expected_epoch=epoch) + return await handler(request) + + connection = build_server_params(name, server) + connection.update(auth=CurrentGrant(), httpx_client_factory=mcp_client_factory(server)) + view = config.model_copy(update={"mcp_servers": {name: server}}) + interceptors = [ + require_current_grant, + *build_mcp_tool_interceptors(view, connection_scope="personal"), + ] + client = client_cls({name: connection}, tool_interceptors=interceptors, tool_name_prefix=True) + prepared = _PreparedServerClient(name, connection, client, interceptors, server.tool_name_prefix, _resolve_session_init_timeout(server)) + _, raw = await _discover_server_tools(prepared, load_mcp_tools_fn=load_tools) + if raw is None: + return () + tools = _wrap_discovered_server_tools( + config, + name, + connection, + raw, + tool_name_prefix=server.tool_name_prefix, + session_init_timeout=prepared.session_init_timeout, + pool=None, + binding=None, + ownership_domain="deployment", + connection_scope="deployment", + ).tools + for tool in tools: + metadata = tool.metadata or {} + tool.metadata = {**metadata, "deerflow_approval_binding": digest([metadata.get("deerflow_approval_binding"), owner, epoch])} + return tools + + async def discover_safely(name, server): + try: + return await discover(name, server) + except Exception as exc: + logger.warning("Skipping browser MCP discovery for '%s' (%s)", name, type(exc).__name__) + return () + + groups = await asyncio.gather(*(discover_safely(name, server) for name, server in config.get_enabled_mcp_servers().items() if server.uses_browser_oauth and (selected is None or name in selected))) + return [tool for group in groups for tool in group] + + async def get_mcp_tools_by_server( extensions_config: ExtensionsConfig | None = None, *, diff --git a/backend/packages/harness/deerflow/mcp/user_config.py b/backend/packages/harness/deerflow/mcp/user_config.py index c9d4b2edcc..6b4a41dcab 100644 --- a/backend/packages/harness/deerflow/mcp/user_config.py +++ b/backend/packages/harness/deerflow/mcp/user_config.py @@ -61,8 +61,8 @@ def load_user_mcp_config(user_id: str) -> ExtensionsConfig: runtime_name = personal_server_name(user_id, name, definition) servers[runtime_name] = {**definition, "tool_name_prefix": True} config = ExtensionsConfig.model_validate({"mcpServers": servers}) - if any(server.agent_auth for server in config.mcp_servers.values()): - raise ValueError("agent_auth is available only for deployment MCP servers") + if any(server.agent_auth or server.uses_browser_oauth for server in config.mcp_servers.values()): + raise ValueError("agent_auth and user_oauth are available only for deployment MCP servers") return config diff --git a/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/__init__.py b/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/__init__.py index 536c4995d0..674550edb8 100644 --- a/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/__init__.py +++ b/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/__init__.py @@ -1,9 +1,10 @@ """MCP OAuth tokens shared by every Gateway instance (``mcp_oauth_tokens``).""" -from deerflow.persistence.mcp_oauth_tokens.model import McpOAuthTokenRow, StoredMcpOAuthToken +from deerflow.persistence.mcp_oauth_tokens.model import McpOAuthAttemptRow, McpOAuthTokenRow, StoredMcpOAuthToken from deerflow.persistence.mcp_oauth_tokens.sql import SqlMcpOAuthTokenRepository __all__ = [ + "McpOAuthAttemptRow", "McpOAuthTokenRow", "SqlMcpOAuthTokenRepository", "StoredMcpOAuthToken", diff --git a/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/model.py b/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/model.py index 2f2f6a7778..c7e17dc61f 100644 --- a/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/model.py +++ b/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/model.py @@ -1,6 +1,6 @@ """ORM model for MCP OAuth tokens shared by every Gateway instance (``mcp_oauth_tokens``). -One row per OAuth connection that uses the ``refresh_token`` grant, keyed by +One row per OAuth connection with persisted credentials, keyed by ``(scope, owner_user_id, server_key)``: - ``scope='deployment'``: ``owner_user_id`` is ``''`` and ``server_key`` the @@ -10,6 +10,8 @@ One row per OAuth connection that uses the ``refresh_token`` grant, keyed by - ``scope='personal'``: ``owner_user_id`` is the owner and ``server_key`` the ``personal_`` runtime name (``deerflow.mcp.user_config``), so a personal connection never shares a row with a same-named deployment one. +- ``scope='delegated'``: one browser grant per user and deployment server. + Its grant epoch changes on connect/disconnect and fences late writes. The row holds only what the token endpoint returned -- the access token, its expiry and the latest (possibly rotated) refresh token -- as @@ -32,12 +34,12 @@ from __future__ import annotations from dataclasses import dataclass -from sqlalchemy import BigInteger, Double, PrimaryKeyConstraint, String, Text +from sqlalchemy import BigInteger, Double, Index, PrimaryKeyConstraint, String, Text from sqlalchemy.orm import Mapped, mapped_column from deerflow.persistence.base import Base -#: ``'deployment'`` or ``'personal'``; plain text so a new scope needs no migration. +#: ``'deployment'``, ``'personal'`` or ``'delegated'``. MCP_OAUTH_TOKEN_SCOPE_LENGTH = 16 MCP_OAUTH_TOKEN_OWNER_LENGTH = 64 #: Deployment server names are operator-chosen; personal runtime names are 41 characters. @@ -63,6 +65,8 @@ class McpOAuthTokenRow(Base): refresh_lease_until: Mapped[float | None] = mapped_column(Double, nullable=True) rotated_at: Mapped[float | None] = mapped_column(Double, nullable=True) updated_at: Mapped[float] = mapped_column(Double, nullable=False) + grant_epoch: Mapped[int | None] = mapped_column(BigInteger, nullable=True) + grant_context: Mapped[str | None] = mapped_column(Text, nullable=True) __table_args__ = (PrimaryKeyConstraint("scope", "owner_user_id", "server_key", name="pk_mcp_oauth_tokens"),) @@ -78,3 +82,33 @@ class StoredMcpOAuthToken: access_expires_at: float | None refresh_token_enc: str | None version: int + grant_epoch: int | None + grant_context: str | None + + +class McpOAuthAttemptRow(Base): + """Short-lived browser authorization, stored until one callback claims it.""" + + __tablename__ = "mcp_oauth_attempts" + + owner_user_id: Mapped[str] = mapped_column(String(MCP_OAUTH_TOKEN_OWNER_LENGTH), primary_key=True) + server_key: Mapped[str] = mapped_column(String(MCP_OAUTH_TOKEN_SERVER_KEY_LENGTH), primary_key=True) + state_digest: Mapped[str] = mapped_column(String(64), unique=True) + browser_digest: Mapped[str] = mapped_column(String(64)) + config_fingerprint: Mapped[str] = mapped_column(String(MCP_OAUTH_TOKEN_FINGERPRINT_LENGTH)) + grant_epoch: Mapped[int] = mapped_column(BigInteger) + grant_context: Mapped[str] = mapped_column(Text) + verifier_enc: Mapped[str] = mapped_column(Text) + expires_at: Mapped[float] = mapped_column(Double) + + __table_args__ = (Index("ix_mcp_oauth_attempts_expires_at", "expires_at"),) + + +@dataclass(frozen=True) +class StoredMcpOAuthAttempt: + owner_user_id: str + server_key: str + config_fingerprint: str + grant_epoch: int + grant_context: str + verifier_enc: str diff --git a/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/sql.py b/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/sql.py index beb4f3fc39..1fb3afb296 100644 --- a/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/sql.py +++ b/backend/packages/harness/deerflow/persistence/mcp_oauth_tokens/sql.py @@ -36,13 +36,13 @@ from __future__ import annotations from collections.abc import Collection -from sqlalchemy import delete, or_, update +from sqlalchemy import delete, or_, select, update from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.dialects.sqlite import insert as sqlite_insert from sqlalchemy.orm import Session, sessionmaker from deerflow.persistence.channel_leases.sql import db_now -from deerflow.persistence.mcp_oauth_tokens.model import McpOAuthTokenRow, StoredMcpOAuthToken +from deerflow.persistence.mcp_oauth_tokens.model import McpOAuthAttemptRow, McpOAuthTokenRow, StoredMcpOAuthAttempt, StoredMcpOAuthToken def _dialect(session: Session) -> str: @@ -56,6 +56,22 @@ def _key(scope: str, owner_user_id: str, server_key: str): return (McpOAuthTokenRow.scope == scope, McpOAuthTokenRow.owner_user_id == owner_user_id, McpOAuthTokenRow.server_key == server_key) +def _attempt_key(owner_user_id: str, server_key: str): + return (McpOAuthAttemptRow.owner_user_id == owner_user_id, McpOAuthAttemptRow.server_key == server_key) + + +_CLEARED_TOKENS = { + "access_token_enc": None, + "token_request_fingerprint": None, + "token_type": None, + "access_expires_at": None, + "refresh_token_enc": None, + "refresh_lease_owner": None, + "refresh_lease_until": None, + "rotated_at": None, +} + + class SqlMcpOAuthTokenRepository: """Persistence facade for ``mcp_oauth_tokens``; every call blocks, so run it off the event loop.""" @@ -75,8 +91,179 @@ class SqlMcpOAuthTokenRepository: access_expires_at=row.access_expires_at, refresh_token_enc=row.refresh_token_enc, version=int(row.version), + grant_epoch=row.grant_epoch, + grant_context=row.grant_context, ) + def list_delegated_servers(self, owner_user_id: str) -> list[str]: + """List the owner's grants, including those awaiting reconnect, without reading tokens.""" + row = McpOAuthTokenRow + stmt = select(row.server_key).where(row.scope == "delegated", row.owner_user_id == owner_user_id, row.grant_context.is_not(None)).order_by(row.server_key) + with self._sf() as session: + return list(session.scalars(stmt)) + + def begin_delegated( + self, + owner_user_id: str, + server_key: str, + *, + fingerprint: str, + state_digest: str, + browser_digest: str, + verifier_enc: str, + context: str, + ttl_seconds: int, + ) -> int: + """Reserve a new epoch and replace any pending attempt in one commit.""" + # Expiry cleanup acquires no grant row locks. Commit it separately so + # it cannot deadlock with a peer replacing or disconnecting a grant. + with self._sf() as session: + session.execute(delete(McpOAuthAttemptRow).where(McpOAuthAttemptRow.expires_at <= db_now(_dialect(session)))) + session.commit() + with self._sf() as session: + dialect = _dialect(session) + insert = pg_insert if dialect == "postgresql" else sqlite_insert + clock = db_now(dialect) + epoch = session.execute( + insert(McpOAuthTokenRow) + .values( + scope="delegated", + owner_user_id=owner_user_id, + server_key=server_key, + config_fingerprint=fingerprint, + grant_epoch=1, + updated_at=clock, + version=0, + ) + .on_conflict_do_update( + index_elements=[McpOAuthTokenRow.scope, McpOAuthTokenRow.owner_user_id, McpOAuthTokenRow.server_key], + set_={ + **_CLEARED_TOKENS, + "grant_epoch": McpOAuthTokenRow.grant_epoch + 1, + "config_fingerprint": fingerprint, + "grant_context": None, + "updated_at": clock, + "version": McpOAuthTokenRow.version + 1, + }, + ) + .returning(McpOAuthTokenRow.grant_epoch) + ).scalar_one() + attempt = { + "state_digest": state_digest, + "browser_digest": browser_digest, + "config_fingerprint": fingerprint, + "grant_epoch": epoch, + "grant_context": context, + "verifier_enc": verifier_enc, + "expires_at": clock + ttl_seconds, + } + session.execute( + insert(McpOAuthAttemptRow).values(owner_user_id=owner_user_id, server_key=server_key, **attempt).on_conflict_do_update(index_elements=[McpOAuthAttemptRow.owner_user_id, McpOAuthAttemptRow.server_key], set_=attempt) + ) + session.commit() + return epoch + + def consume_delegated(self, state_digest: str, *, owner_user_id: str, browser_digest: str) -> StoredMcpOAuthAttempt | None: + """Consume the current attempt for this browser, if it has not expired. + + Beginning a new attempt or disconnecting replaces or removes this row + in the same commit as the epoch change. Completion still checks the + epoch because it runs after the remote token exchange. + """ + with self._sf() as session: + row = session.execute( + delete(McpOAuthAttemptRow) + .where( + McpOAuthAttemptRow.state_digest == state_digest, + McpOAuthAttemptRow.browser_digest == browser_digest, + McpOAuthAttemptRow.owner_user_id == owner_user_id, + McpOAuthAttemptRow.expires_at > db_now(_dialect(session)), + ) + .returning( + McpOAuthAttemptRow.server_key, + McpOAuthAttemptRow.config_fingerprint, + McpOAuthAttemptRow.grant_epoch, + McpOAuthAttemptRow.grant_context, + McpOAuthAttemptRow.verifier_enc, + ) + ).one_or_none() + session.commit() + return StoredMcpOAuthAttempt(owner_user_id, *row) if row is not None else None + + def complete_delegated( + self, + owner_user_id: str, + server_key: str, + *, + grant_epoch: int, + fingerprint: str, + context: str, + access_token_enc: str, + access_expires_at: float | None, + refresh_token_enc: str | None, + ) -> bool: + with self._sf() as session: + stmt = ( + update(McpOAuthTokenRow) + .where( + *_key("delegated", owner_user_id, server_key), + McpOAuthTokenRow.config_fingerprint == fingerprint, + McpOAuthTokenRow.grant_epoch == grant_epoch, + McpOAuthTokenRow.grant_context.is_(None), + ) + .values( + grant_context=context, + access_token_enc=access_token_enc, + access_expires_at=access_expires_at, + refresh_token_enc=refresh_token_enc, + token_request_fingerprint=fingerprint, + token_type="Bearer", + version=McpOAuthTokenRow.version + 1, + updated_at=db_now(_dialect(session)), + ) + ) + committed = session.execute(stmt).rowcount == 1 + session.commit() + return committed + + def disconnect_delegated( + self, + owner_user_id: str, + server_key: str, + *, + expected_epoch: int | None, + lease_owner: str | None = None, + access_only_version: int | None = None, + ) -> bool: + """Revoke the grant while retaining its epoch.""" + with self._sf() as session: + conditions = list(_key("delegated", owner_user_id, server_key)) + values = dict(_CLEARED_TOKENS) + if expected_epoch is not None: + conditions.append(McpOAuthTokenRow.grant_epoch == expected_epoch) + if lease_owner is not None: + conditions.append(McpOAuthTokenRow.refresh_lease_owner == lease_owner) + if access_only_version is not None: + conditions.extend((McpOAuthTokenRow.version == access_only_version, McpOAuthTokenRow.refresh_token_enc.is_(None))) + if lease_owner is None and access_only_version is None: + # An explicit disconnect clears status as well as credentials. + values["grant_context"] = None + stmt = ( + update(McpOAuthTokenRow) + .where(*conditions) + .values( + **values, + grant_epoch=McpOAuthTokenRow.grant_epoch + 1, + version=McpOAuthTokenRow.version + 1, + updated_at=db_now(_dialect(session)), + ) + ) + disconnected = session.execute(stmt).rowcount == 1 + if disconnected: + session.execute(delete(McpOAuthAttemptRow).where(*_attempt_key(owner_user_id, server_key))) + session.commit() + return disconnected + def claim( self, scope: str, @@ -88,11 +275,14 @@ class SqlMcpOAuthTokenRepository: lease_owner: str, lease_seconds: float, now: float, + grant_epoch: int | None = None, ) -> bool: """Take the refresh lease if the row is still at ``expected_version`` (``None``: no row yet).""" with self._sf() as session: clock = db_now(_dialect(session)) if expected_version is None: + if scope == "delegated": + return False # Browser grants can only be created by completing authorization. insert = pg_insert if _dialect(session) == "postgresql" else sqlite_insert stmt = ( insert(McpOAuthTokenRow) @@ -111,15 +301,16 @@ class SqlMcpOAuthTokenRepository: ) claimed = len(session.execute(stmt).all()) == 1 else: - stmt = ( - update(McpOAuthTokenRow) - .where( - *_key(scope, owner_user_id, server_key), - McpOAuthTokenRow.version == expected_version, - or_(McpOAuthTokenRow.refresh_lease_owner.is_(None), McpOAuthTokenRow.refresh_lease_until < clock), - ) - .values(refresh_lease_owner=lease_owner, refresh_lease_until=clock + lease_seconds) - ) + conditions = [ + *_key(scope, owner_user_id, server_key), + McpOAuthTokenRow.version == expected_version, + or_(McpOAuthTokenRow.refresh_lease_owner.is_(None), McpOAuthTokenRow.refresh_lease_until < clock), + ] + if scope == "delegated": + if grant_epoch is None: + return False + conditions.extend((McpOAuthTokenRow.grant_epoch == grant_epoch, McpOAuthTokenRow.config_fingerprint == config_fingerprint, McpOAuthTokenRow.refresh_token_enc.is_not(None))) + stmt = update(McpOAuthTokenRow).where(*conditions).values(refresh_lease_owner=lease_owner, refresh_lease_until=clock + lease_seconds) claimed = session.execute(stmt).rowcount == 1 session.commit() return claimed @@ -135,10 +326,11 @@ class SqlMcpOAuthTokenRepository: access_token_enc: str, token_request_fingerprint: str, token_type: str, - access_expires_at: float, + access_expires_at: float | None, refresh_token_enc: str, rotated: bool, now: float, + grant_epoch: int | None = None, ) -> bool: """Store a refreshed token and release the lease; ``False`` when the lease is no longer this claim's.""" values = { @@ -156,7 +348,12 @@ class SqlMcpOAuthTokenRepository: if rotated: values["rotated_at"] = now with self._sf() as session: - stmt = update(McpOAuthTokenRow).where(*_key(scope, owner_user_id, server_key), McpOAuthTokenRow.refresh_lease_owner == lease_owner).values(**values) + conditions = [*_key(scope, owner_user_id, server_key), McpOAuthTokenRow.refresh_lease_owner == lease_owner] + if scope == "delegated": + if grant_epoch is None: + return False + conditions.extend((McpOAuthTokenRow.grant_epoch == grant_epoch, McpOAuthTokenRow.config_fingerprint == config_fingerprint)) + stmt = update(McpOAuthTokenRow).where(*conditions).values(**values) written = session.execute(stmt).rowcount == 1 session.commit() return written diff --git a/backend/packages/harness/deerflow/persistence/migrations/versions/0058_mcp_browser_oauth.py b/backend/packages/harness/deerflow/persistence/migrations/versions/0058_mcp_browser_oauth.py new file mode 100644 index 0000000000..e76eea74c6 --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/migrations/versions/0058_mcp_browser_oauth.py @@ -0,0 +1,45 @@ +"""Persist single-use MCP browser authorizations and fence grant changes.""" + +import sqlalchemy as sa +from alembic import op + +from deerflow.persistence.migrations._helpers import safe_add_column, safe_drop_column + +revision = "0058_mcp_browser_oauth" +down_revision = "0057_coordination_workers" +branch_labels = None +depends_on = None + +_TOKENS = "mcp_oauth_tokens" +_ATTEMPTS = "mcp_oauth_attempts" +_EXPIRY_INDEX = "ix_mcp_oauth_attempts_expires_at" + + +def upgrade() -> None: + safe_add_column(_TOKENS, sa.Column("grant_epoch", sa.BigInteger, nullable=True)) + safe_add_column(_TOKENS, sa.Column("grant_context", sa.Text, nullable=True)) + if not sa.inspect(op.get_bind()).has_table(_ATTEMPTS): + op.create_table( + _ATTEMPTS, + sa.Column("owner_user_id", sa.String(64), primary_key=True), + sa.Column("server_key", sa.String(255), primary_key=True), + sa.Column("state_digest", sa.String(64), nullable=False, unique=True), + sa.Column("browser_digest", sa.String(64), nullable=False), + sa.Column("config_fingerprint", sa.String(64), nullable=False), + sa.Column("grant_epoch", sa.BigInteger(), nullable=False), + sa.Column("grant_context", sa.Text(), nullable=False), + sa.Column("verifier_enc", sa.Text(), nullable=False), + sa.Column("expires_at", sa.Double(), nullable=False), + ) + if _EXPIRY_INDEX not in {idx["name"] for idx in sa.inspect(op.get_bind()).get_indexes(_ATTEMPTS)}: + op.create_index(_EXPIRY_INDEX, _ATTEMPTS, ["expires_at"]) + + +def downgrade() -> None: + if sa.inspect(op.get_bind()).has_table(_ATTEMPTS): + op.drop_table(_ATTEMPTS) + if sa.inspect(op.get_bind()).has_table(_TOKENS): + # A re-upgrade must not revive grants whose epoch was dropped. + op.execute(sa.table(_TOKENS, sa.column("scope")).delete().where(sa.column("scope") == "delegated")) + safe_drop_column(_TOKENS, "grant_context") + safe_drop_column(_TOKENS, "grant_epoch") diff --git a/backend/packages/harness/deerflow/runtime/context_keys.py b/backend/packages/harness/deerflow/runtime/context_keys.py index f7fb781b4a..332ab34548 100644 --- a/backend/packages/harness/deerflow/runtime/context_keys.py +++ b/backend/packages/harness/deerflow/runtime/context_keys.py @@ -3,6 +3,8 @@ from collections.abc import Mapping from typing import Final +MCP_BROWSER_USER_CONTEXT_KEY: Final[str] = "__deerflow_mcp_browser_user" + CURRENT_RUN_PRE_EXISTING_MESSAGE_IDS_KEY: Final[str] = "__deerflow_pre_run_message_ids" # Server-authored checkpoint metadata that binds materialized state to the diff --git a/backend/packages/harness/deerflow/runtime/runs/worker.py b/backend/packages/harness/deerflow/runtime/runs/worker.py index 26d0de0fe6..63227f2537 100644 --- a/backend/packages/harness/deerflow/runtime/runs/worker.py +++ b/backend/packages/harness/deerflow/runtime/runs/worker.py @@ -66,6 +66,7 @@ from deerflow.runtime.context_keys import ( CHECKPOINT_AGENT_NAME_METADATA_KEY, CURRENT_RUN_PRE_EXISTING_MESSAGE_IDS_KEY, DEFAULT_AGENT_NAME_METADATA_VALUE, + MCP_BROWSER_USER_CONTEXT_KEY, PROJECT_CONTEXT_KEY, checkpoint_agent_binding_metadata, ) @@ -630,6 +631,7 @@ _SERVER_OWNED_RUNTIME_CONTEXT_KEYS: Final[frozenset[str]] = ( SCHEDULER_CAPABILITY_CONTEXT_KEY, AGENT_RUNS_CONTEXT_KEY, AGENT_AUTH_CONTEXT_KEY, + MCP_BROWSER_USER_CONTEXT_KEY, "__run_input_control", "__tool_approval_runtime", "_hitl_disabled_resume_escape", @@ -664,6 +666,7 @@ def _build_runtime_context( thread_incarnation: str | None | object = _THREAD_INCARNATION_UNSET, scheduler_capability: SchedulerRunCapability | None = None, agent_mcp_authority: Any | None = None, + mcp_browser_user: str | None = None, ) -> dict[str, Any]: """Build the dict that becomes ``ToolRuntime.context`` for the run. @@ -695,6 +698,8 @@ def _build_runtime_context( runtime_ctx[SCHEDULER_CAPABILITY_CONTEXT_KEY] = scheduler_capability if agent_mcp_authority is not None: runtime_ctx[AGENT_AUTH_CONTEXT_KEY] = agent_mcp_authority + if mcp_browser_user is not None: + runtime_ctx[MCP_BROWSER_USER_CONTEXT_KEY] = mcp_browser_user if task_store is not None: from deerflow_extension_api import EXTENSION_TASK_STORE_KEY @@ -761,6 +766,7 @@ class RunContext: agent_runs: Any | None = field(default=None) scheduler_capability: SchedulerRunCapability | None = field(default=None) agent_mcp_authority: Any | None = field(default=None) + mcp_browser_user: str | None = None # Server-selected occurrence identity. Metadata alone never activates a goal. scheduled_task_runtime: Mapping[str, Any] | None = field(default=None) # Host-only preflight under durable run ownership; failures reject execution. @@ -776,6 +782,7 @@ def _install_runtime_context(config: dict, runtime_context: dict[str, Any]) -> N configurable.pop(SCHEDULER_CAPABILITY_CONTEXT_KEY, None) configurable.pop(AGENT_RUNS_CONTEXT_KEY, None) configurable.pop(AGENT_AUTH_CONTEXT_KEY, None) + configurable.pop(MCP_BROWSER_USER_CONTEXT_KEY, None) existing_context = config.get("context") if isinstance(existing_context, dict): existing_context.setdefault("thread_id", runtime_context["thread_id"]) @@ -1391,6 +1398,7 @@ async def run_agent( thread_incarnation=thread_incarnation, scheduler_capability=ctx.scheduler_capability, agent_mcp_authority=ctx.agent_mcp_authority, + mcp_browser_user=ctx.mcp_browser_user, ) # A disabled all-reject escape still needs the HITL hook to consume the # pending interrupt. The assembly marker makes that hook deny rather @@ -1481,6 +1489,10 @@ async def run_agent( configurable["checkpoint_ns"] = "" configurable.pop("checkpoint_id", None) configurable.pop("checkpoint_map", None) + if runtime_ctx.pop(MCP_BROWSER_USER_CONTEXT_KEY, None) is not None: + # The worker can continue a Goal after the interactive turn. + # Keep the same runtime state but retire browser-only authority. + continuation_config["context"].pop(MCP_BROWSER_USER_CONTEXT_KEY, None) continuation_config["configurable"] = configurable continuation = RunnableConfig(**continuation_config) runnable_configs.append(continuation) diff --git a/backend/packages/harness/deerflow/tools/builtins/invoke_acp_agent_tool.py b/backend/packages/harness/deerflow/tools/builtins/invoke_acp_agent_tool.py index 5d09f32959..9cb09930cf 100644 --- a/backend/packages/harness/deerflow/tools/builtins/invoke_acp_agent_tool.py +++ b/backend/packages/harness/deerflow/tools/builtins/invoke_acp_agent_tool.py @@ -75,7 +75,7 @@ def _build_acp_mcp_servers() -> list[dict[str, Any]]: from deerflow.config.extensions_config import ExtensionsConfig extensions_config = ExtensionsConfig.from_file() - enabled_servers = extensions_config.get_enabled_mcp_servers() + enabled_servers = extensions_config.get_discoverable_mcp_servers() mcp_servers: list[dict[str, Any]] = [] for name, server_config in enabled_servers.items(): diff --git a/backend/packages/harness/deerflow/tools/tools.py b/backend/packages/harness/deerflow/tools/tools.py index ca2dc27358..2878861360 100644 --- a/backend/packages/harness/deerflow/tools/tools.py +++ b/backend/packages/harness/deerflow/tools/tools.py @@ -173,6 +173,7 @@ def get_available_tools( app_config: AppConfig | None = None, extensions=None, chat_model: BaseChatModel | None = None, + mcp_browser_user: str | None = None, ) -> list[BaseTool]: """Get all available tools from config. @@ -287,7 +288,7 @@ def get_available_tools( # ValidationError message can embed secrets. Log the type only. logger.error("Failed to load MCP extensions config (%s)", type(exc).__name__) else: - if extensions_config.get_enabled_mcp_servers(): + if extensions_config.get_discoverable_mcp_servers(): mcp_tools = get_cached_mcp_tools() if mcp_tools: logger.info(f"Using {len(mcp_tools)} cached MCP tool(s)") @@ -324,6 +325,12 @@ def get_available_tools( available_servers = {name: server for name, server in personal_config.mcp_servers.items() if name not in colliding_names} personal_config = personal_config.model_copy(update={"mcp_servers": available_servers}) mcp_tools = [*mcp_tools, *personal_tools] + if mcp_browser_user and any(server.uses_browser_oauth for server in extensions_config.get_enabled_mcp_servers().values()): + from deerflow.capabilities.runtime import selected_mcp_server_names + from deerflow.mcp.tools import get_browser_mcp_tools + + selected = None if mcp_plugins is None else selected_mcp_server_names(mcp_plugins, extensions_config) + mcp_tools.extend(make_sync_tool_wrapper(get_browser_mcp_tools, "browser MCP discovery")(extensions_config, mcp_browser_user, selected)) extensions_config = extensions_config.model_copy(update={"mcp_servers": {**extensions_config.mcp_servers, **personal_config.mcp_servers}}) if mcp_plugins is not None: from deerflow.capabilities.runtime import filter_mcp_plugins diff --git a/backend/tests/test_invoke_acp_agent_tool.py b/backend/tests/test_invoke_acp_agent_tool.py index 02abd999c7..6754ff3808 100644 --- a/backend/tests/test_invoke_acp_agent_tool.py +++ b/backend/tests/test_invoke_acp_agent_tool.py @@ -43,6 +43,13 @@ def test_build_mcp_servers_filters_disabled_and_maps_transports(): mcp_servers={ "stdio": McpServerConfig(enabled=True, type="stdio", command="npx", args=["srv"]), "http": McpServerConfig(enabled=True, type="http", url="https://example.com/mcp"), + "browser": McpServerConfig.model_validate( + { + "type": "http", + "url": "https://browser.example.com/mcp", + "user_oauth": {"issuer": "https://id.example.com", "client_id": "deerflow", "redirect_uri": "https://app.example.com/api/mcp/user-oauth/callback"}, + } + ), "disabled": McpServerConfig(enabled=False, type="stdio", command="echo"), }, skills={}, @@ -69,6 +76,13 @@ def test_build_acp_mcp_servers_formats_list_payload(): mcp_servers={ "stdio": McpServerConfig(enabled=True, type="stdio", command="npx", args=["srv"], env={"FOO": "bar"}), "http": McpServerConfig(enabled=True, type="http", url="https://example.com/mcp", headers={"Authorization": "Bearer token"}), + "browser": McpServerConfig.model_validate( + { + "type": "http", + "url": "https://browser.example.com/mcp", + "user_oauth": {"issuer": "https://id.example.com", "client_id": "deerflow", "redirect_uri": "https://app.example.com/api/mcp/user-oauth/callback"}, + } + ), "disabled": McpServerConfig(enabled=False, type="stdio", command="echo"), }, skills={}, diff --git a/backend/tests/test_mcp_browser_oauth_protocol.py b/backend/tests/test_mcp_browser_oauth_protocol.py new file mode 100644 index 0000000000..6cebb59d03 --- /dev/null +++ b/backend/tests/test_mcp_browser_oauth_protocol.py @@ -0,0 +1,137 @@ +"""Exercise the split protocol over HTTPX's transport boundary, without live credentials.""" + +import hashlib +from urllib.parse import parse_qs, urlsplit + +import httpx +import pytest + +from deerflow.config.extensions_config import McpServerConfig +from deerflow.mcp import browser_oauth as oauth + + +@pytest.fixture +def server(): + return McpServerConfig.model_validate( + { + "type": "http", + "url": "https://observability.example/mcp", + "user_oauth": {"client_id": "monitor", "issuer": "https://login.example", "redirect_uri": "https://gateway.example/api/mcp/user-oauth/callback", "scope": "logs:read"}, + } + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("pkce", [True, False]) +async def test_metadata_challenge_and_preregistered_client(monkeypatch, server, pkce): + from base64 import urlsafe_b64encode + from unittest.mock import Mock + + seen = [] + issuer = server.user_oauth.issuer + resource = server.url + + def responder(request): + seen.append(request.url.path) + if request.url.path == "/mcp": + return httpx.Response(401, headers={"www-authenticate": 'Bearer resource_metadata="https://observability.example/mcp-metadata", scope="logs:read"'}) + if request.url.path == "/mcp-metadata": + return httpx.Response(200, json={"resource": resource, "authorization_servers": [issuer]}) + assert request.url.path == "/.well-known/oauth-authorization-server" + return httpx.Response(200, json={"issuer": issuer, "authorization_endpoint": issuer + "/authorize", "token_endpoint": issuer + "/token", "code_challenge_methods_supported": ["S256"] if pkce else []}) + + store = Mock() + monkeypatch.setattr(oauth, "_transport", lambda *_a, **_kw: httpx.MockTransport(responder)) + monkeypatch.setattr(oauth, "resolve_public_addresses", lambda *a, **k: ["192.0.2.1"]) + monkeypatch.setattr(oauth, "_store", lambda: store) + if pkce: + url = await oauth.begin_connection("logs", server, "alice", "browser-binding", "transaction-state") + query = parse_qs(urlsplit(url).query) + _, data = store.begin_delegated.call_args + challenge = urlsafe_b64encode(hashlib.sha256(data["code_verifier"].encode()).digest()).decode().rstrip("=") + assert query["resource"] == [resource] and query["client_id"] == ["monitor"] and query["scope"] == ["logs:read"] + assert query["state"] == ["transaction-state"] and query["code_challenge"] == [challenge] and query["code_challenge_method"] == ["S256"] + else: + with pytest.raises(oauth.BrowserOAuthError, match="S256"): + await oauth.begin_connection("logs", server, "alice", "browser-binding", "transaction-state") + store.begin_delegated.assert_not_called() + assert seen == ["/mcp", "/mcp-metadata", "/.well-known/oauth-authorization-server"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("status", "body", "expected"), [(400, {"error": "invalid_grant"}, oauth._InvalidGrant), (503, {}, oauth.BrowserOAuthError), (302, {}, oauth.BrowserOAuthError)]) +async def test_token_errors_and_redirects_have_distinct_local_outcomes(monkeypatch, server, status, body, expected): + from deerflow.mcp.oauth_store import DelegatedOAuthContext + + ctx = DelegatedOAuthContext(server.user_oauth.issuer, server.url, "https://login.example/token") + called = [] + + def responder(request): + called.append(request.url.path) + assert parse_qs(request.content.decode())["resource"] == [server.url] + return httpx.Response(status, json=body, headers={"Location": "https://login.example/other"}) + + monkeypatch.setattr(oauth, "_transport", lambda *_a, **_kw: httpx.MockTransport(responder)) + with pytest.raises(oauth.BrowserOAuthError) as exc: + await oauth._exchange(server, ctx, {"grant_type": "refresh_token", "refresh_token": "example-token"}) + assert type(exc.value) is expected + assert called == ["/token"] + + +@pytest.mark.asyncio +async def test_transport_does_not_connect_to_unregistered_destination(server): + async with oauth.mcp_client_factory(server)() as client: + with pytest.raises(oauth.BrowserOAuthError, match="configured MCP connection"): + await client.get("https://other.example/mcp") + + +@pytest.mark.asyncio +async def test_access_only_grant_survives_until_expired_or_rejected(server, tmp_path, monkeypatch): + from datetime import UTC, datetime, timedelta + + from cryptography.fernet import Fernet + from langchain_core.tools import ToolException + from sqlalchemy import create_engine + from sqlalchemy.orm import sessionmaker + + from deerflow.config.credentials_key import CredentialsCipher + from deerflow.mcp import oauth_store + from deerflow.persistence.base import Base + from deerflow.persistence.mcp_oauth_tokens import McpOAuthAttemptRow, McpOAuthTokenRow, SqlMcpOAuthTokenRepository + + engine = create_engine("sqlite:///" + str(tmp_path / "grants.db")) + try: + Base.metadata.create_all(engine, tables=[McpOAuthTokenRow.__table__, McpOAuthAttemptRow.__table__]) + store = oauth_store.McpOAuthTokenStore(SqlMcpOAuthTokenRepository(sessionmaker(engine)), cipher=CredentialsCipher.from_keys([Fernet.generate_key()])) + monkeypatch.setattr(oauth_store, "get_mcp_oauth_token_store", lambda: store) + context = oauth_store.DelegatedOAuthContext(server.user_oauth.issuer, server.url, "https://login.example/token") + for user, duration, reject in [("alice", 120, True), ("bob", -1, False)]: + key = oauth_store.McpOAuthTokenKey.for_delegated("logs", user) + epoch = store.begin_delegated(key, fingerprint=oauth.browser_grant_fingerprint(server), state=user, browser_binding=user, code_verifier="opaque", context=context) + attempt = store.consume_delegated(user, owner_user_id=user, browser_binding=user) + assert store.complete_delegated(attempt, access_token=user, expires_at=datetime.now(UTC) + timedelta(seconds=duration)) + if reject: + assert await oauth.get_call_token("logs", server, user) == (user, epoch) + with pytest.raises(ToolException, match="Capability Center"): + await oauth.get_call_token("logs", server, user, rejected_token=user if reject else None) + assert oauth.connection_state("logs", server, user) == "reconnect_required" + finally: + engine.dispose() + + +def test_registered_callback_only_allows_exact_route_and_https_or_loopback(server): + from pydantic import ValidationError + + from deerflow.config.extensions_config import MCP_USER_OAUTH_CALLBACK_PATH, McpUserOAuthConfig + + entry = server.user_oauth.model_dump() + for origin in ("http://localhost:8001", "http://127.0.0.1:8001", "http://[::1]:8001", "https://gateway.example"): + assert McpUserOAuthConfig(**{**entry, "redirect_uri": origin + MCP_USER_OAUTH_CALLBACK_PATH}).redirect_uri == origin + MCP_USER_OAUTH_CALLBACK_PATH + for bad in ( + "http://other.example" + MCP_USER_OAUTH_CALLBACK_PATH, + "https://gateway.example/elsewhere", + "https://user@gateway.example" + MCP_USER_OAUTH_CALLBACK_PATH, + "https://gateway.example" + MCP_USER_OAUTH_CALLBACK_PATH + "?code=old", + ): + with pytest.raises(ValidationError): + McpUserOAuthConfig(**{**entry, "redirect_uri": bad}) diff --git a/backend/tests/test_mcp_cache_discovery.py b/backend/tests/test_mcp_cache_discovery.py index b945cea5c6..284694ccf9 100644 --- a/backend/tests/test_mcp_cache_discovery.py +++ b/backend/tests/test_mcp_cache_discovery.py @@ -382,6 +382,36 @@ async def test_unchanged_server_is_reused_by_identity(discovery_cache, monkeypat assert pool._bindings[("deployment", "B")] is binding_b +@pytest.mark.asyncio +async def test_browser_oauth_server_is_excluded_from_global_discovery_after_toggle(discovery_cache, monkeypatch): + standard = {"type": "http", "url": "https://tools.example.com/mcp"} + delegated = { + **standard, + "user_oauth": { + "issuer": "https://auth.example.com", + "client_id": "deerflow", + "redirect_uri": "https://app.example.com/api/mcp/user-oauth/callback", + }, + } + _write_config(discovery_cache, {"A": standard, "B": _stdio("B"), "C": delegated}) + discovery = _install(monkeypatch, _Discovery()) + original = await cache_module.initialize_mcp_tools() + assert _names(original) == ["A", "B"] + assert discovery.calls == [("A", "B")] + + _write_config(discovery_cache, {"A": delegated, "B": _stdio("B"), "C": delegated}) + assert cache_module.refresh_mcp_cache_if_active() + assert _names(await cache_module.initialize_mcp_tools()) == ["B"] + assert set(cache_module._server_tool_cache) == {"B"} + assert discovery.calls == [("A", "B")] + + _write_config(discovery_cache, {"A": delegated, "C": delegated}) + assert cache_module.refresh_mcp_cache_if_active() + assert await cache_module.initialize_mcp_tools() == [] + assert not cache_module._server_tool_cache + assert discovery.calls == [("A", "B")] + + @pytest.mark.asyncio async def test_metadata_only_change_rebuilds_only_that_server(discovery_cache, monkeypatch): """A presentation-only change rebuilds A but reuses B's entry.""" diff --git a/backend/tests/test_mcp_config_error_details.py b/backend/tests/test_mcp_config_error_details.py index 13f0ecd700..1a2f901e9f 100644 --- a/backend/tests/test_mcp_config_error_details.py +++ b/backend/tests/test_mcp_config_error_details.py @@ -18,9 +18,10 @@ import logging from pathlib import Path import pytest -from fastapi import HTTPException +from fastapi import HTTPException, Request from app.gateway.routers import mcp as mcp_router +from app.gateway.routers import mcp_user_oauth from app.gateway.routers.mcp import ( McpConfigUpdateRequest, McpServerConfigResponse, @@ -122,3 +123,26 @@ async def test_update_mcp_server_state_hides_the_host_path(written_config, faili _assert_fixed_detail(excinfo.value, "Failed to update MCP server state") assert HOST_PATH in caplog.text + + +async def test_user_oauth_callback_logs_only_the_failure_type(monkeypatch, caplog) -> None: + def failing_store(): + raise ConnectionError("private storage details") + + monkeypatch.setattr(mcp_user_oauth, "_store", failing_store) + state = "s" * 43 + request = Request( + { + "type": "http", + "path": "/api/mcp/user-oauth/callback", + "query_string": f"state={state}&code=private-code".encode(), + "headers": [(b"cookie", f"df_mcp_{state}=browser-nonce".encode())], + } + ) + + response = await mcp_user_oauth.callback(request, owner="alice") + + assert response.status_code == 303 + assert "mcp_oauth=failed" in response.headers["location"] + assert "ConnectionError" in caplog.text + assert all(value not in caplog.text for value in ("private storage details", "private-code", state, "browser-nonce")) diff --git a/backend/tests/test_mcp_oauth_token_store.py b/backend/tests/test_mcp_oauth_token_store.py index a4b8f2c827..7b1e5d85cb 100644 --- a/backend/tests/test_mcp_oauth_token_store.py +++ b/backend/tests/test_mcp_oauth_token_store.py @@ -31,6 +31,8 @@ from deerflow.config.extensions_config import ExtensionsConfig from deerflow.mcp import oauth_store from deerflow.mcp.oauth import McpOAuthReauthorizationRequired, OAuthTokenManager from deerflow.mcp.oauth_store import ( + DelegatedOAuthContext, + McpOAuthTokenKey, McpOAuthTokenStore, McpOAuthTokenStoreUnavailable, StoredTokenLookup, @@ -39,7 +41,7 @@ from deerflow.mcp.oauth_store import ( set_mcp_oauth_token_store, ) from deerflow.persistence.base import Base -from deerflow.persistence.mcp_oauth_tokens import McpOAuthTokenRow, SqlMcpOAuthTokenRepository +from deerflow.persistence.mcp_oauth_tokens import McpOAuthAttemptRow, McpOAuthTokenRow, SqlMcpOAuthTokenRepository from deerflow.persistence.postgres_schema import dsn_with_search_path SERVER = "reports" @@ -119,7 +121,7 @@ def session_factory(request, tmp_path) -> sessionmaker[Session]: conn.execute(sa.text(f'CREATE SCHEMA "{schema}"')) admin.dispose() engine = sa.create_engine(make_url(dsn_with_search_path(uri, schema)).set(drivername="postgresql+psycopg")) - Base.metadata.create_all(engine, tables=[McpOAuthTokenRow.__table__]) + Base.metadata.create_all(engine, tables=[McpOAuthTokenRow.__table__, McpOAuthAttemptRow.__table__]) yield sessionmaker(engine, expire_on_commit=False) if schema is not None: with engine.begin() as conn: @@ -156,6 +158,103 @@ def _expire_access_tokens() -> None: _Clock.current = _Clock.current + timedelta(seconds=300) +def _delegated_attempt(store, key, state, *, ttl_seconds=300): + return store.begin_delegated( + key, + fingerprint=REQUEST, + state=state, + browser_binding="browser", + code_verifier="verifier", + context=DelegatedOAuthContext("https://issuer.example", "https://reports.example/mcp", "https://issuer.example/token", "reports:read"), + ttl_seconds=ttl_seconds, + ) + + +def test_browser_state_is_single_use_across_replicas_and_bound_to_owner_and_browser(session_factory, cipher): + a = McpOAuthTokenStore(SqlMcpOAuthTokenRepository(session_factory), cipher=cipher) + b = McpOAuthTokenStore(SqlMcpOAuthTokenRepository(session_factory), cipher=cipher) + key = McpOAuthTokenKey.for_delegated(SERVER, "alice") + _delegated_attempt(a, key, "expired", ttl_seconds=0) + assert b.consume_delegated("expired", owner_user_id="alice", browser_binding="browser") is None + begin_epoch = _delegated_attempt(a, key, "latest") + assert b.consume_delegated("latest", owner_user_id="bob", browser_binding="browser") is None + assert b.consume_delegated("latest", owner_user_id="alice", browser_binding="another-browser") is None + with session_factory() as session: + row = session.get(McpOAuthAttemptRow, ("alice", SERVER)) + assert row.state_digest != "latest" + assert row.browser_digest != "browser" + assert row.verifier_enc != "verifier" + barrier = threading.Barrier(2) + + def finish(store): + barrier.wait(timeout=5) + return store.consume_delegated("latest", owner_user_id="alice", browser_binding="browser") + + with ThreadPoolExecutor(max_workers=2) as pool: + (attempt,) = [item for item in pool.map(finish, (a, b)) if item is not None] + assert attempt.key == key + assert attempt.grant_epoch == begin_epoch + assert attempt.code_verifier == "verifier" + assert b.complete_delegated(attempt, access_token="alice-access-only", expires_at=_Clock.current) + grant = a.get_delegated(key, fingerprint=REQUEST) + assert grant.token.access_token == "alice-access-only" + assert grant.token.expires_at == _Clock.current + assert grant.token.refresh_token is None + assert a.get_delegated(key, fingerprint="replacement") is None + assert a.claim(key, fingerprint=REQUEST, expected_version=grant.version, grant_epoch=grant.grant_epoch) is None + assert not a.mark_delegated_reconnect(key, expected_epoch=grant.grant_epoch, expected_version=grant.version - 1) + assert a.mark_delegated_reconnect(key, expected_epoch=grant.grant_epoch, expected_version=grant.version) + assert b.delegated_needs_reconnect(key, fingerprint=REQUEST) + assert b.get_delegated(key, fingerprint=REQUEST) is None + + +def test_disconnect_fences_late_callback_and_refresh_and_preserves_the_other_user(session_factory, cipher): + a = McpOAuthTokenStore(SqlMcpOAuthTokenRepository(session_factory), cipher=cipher) + b = McpOAuthTokenStore(SqlMcpOAuthTokenRepository(session_factory), cipher=cipher) + alice = McpOAuthTokenKey.for_delegated(SERVER, "alice") + bob = McpOAuthTokenKey.for_delegated(SERVER, "bob") + + for key in (alice, bob): + _delegated_attempt(a, key, key.owner_user_id) + callback = b.consume_delegated(key.owner_user_id, owner_user_id=key.owner_user_id, browser_binding="browser") + assert a.complete_delegated(callback, access_token=key.owner_user_id, expires_at=None, refresh_token="seed") + bob_grant = b.get_delegated(bob, fingerprint=REQUEST) + old_alice = b.get_delegated(alice, fingerprint=REQUEST) + old_lease = b.claim(alice, fingerprint=REQUEST, expected_version=old_alice.version, grant_epoch=old_alice.grant_epoch) + assert old_lease + assert a.disconnect_delegated(alice) + assert a.get_delegated(alice, fingerprint=REQUEST) is None + assert b.get_delegated(bob, fingerprint=REQUEST) == bob_grant + + _delegated_attempt(a, alice, "stale") + stale = b.consume_delegated("stale", owner_user_id="alice", browser_binding="browser") + _delegated_attempt(a, alice, "current") + assert not b.complete_delegated(stale, access_token="stale", expires_at=None) + current = b.consume_delegated("current", owner_user_id="alice", browser_binding="browser") + assert b.complete_delegated(current, access_token="new", expires_at=None, refresh_token="new-refresh") + assert not b.disconnect_delegated(alice, expected_epoch=old_alice.grant_epoch, lease_owner=old_lease) + assert not b.save( + alice, + lease_owner=old_lease, + grant_epoch=old_alice.grant_epoch, + fingerprint=REQUEST, + request_fingerprint=REQUEST, + access_token="late", + expires_at=None, + refresh_token="late-refresh", + token_type="Bearer", + rotated=True, + ) + current_grant = a.get_delegated(alice, fingerprint=REQUEST) + assert current_grant.token.access_token == "new" + lease = b.claim(alice, fingerprint=REQUEST, expected_version=current_grant.version, grant_epoch=current_grant.grant_epoch) + assert lease + assert b.disconnect_delegated(alice, expected_epoch=current_grant.grant_epoch, lease_owner=lease) + assert a.delegated_needs_reconnect(alice, fingerprint=REQUEST) + assert a.get_delegated(alice, fingerprint=REQUEST) is None + assert a.get_delegated(bob, fingerprint=REQUEST) == bob_grant + + @pytest.mark.asyncio async def test_peer_uses_the_rotated_refresh_token_without_calling_the_token_endpoint(session_factory, cipher, endpoint): a = _replica(session_factory, cipher) @@ -673,3 +772,41 @@ def test_request_fingerprint_follows_token_request_parameters_not_the_chain(): assert oauth_token_request_fingerprint(changed) != fingerprint, update assert oauth_config_fingerprint(changed) == oauth_config_fingerprint(base), "the refresh-token chain is unaffected" assert oauth_token_request_fingerprint(base.model_copy(update={"extra_token_params": {"resource": "https://api"}})) == fingerprint + + +@pytest.mark.asyncio +async def test_removed_server_grants_can_be_listed_and_disconnected_by_their_owner(session_factory, cipher, tmp_path, monkeypatch): + from fastapi import Response + + from app.gateway.routers import mcp_user_oauth as router + + path = tmp_path / "extensions_config.json" + path.write_text('{"mcpServers": {}}', encoding="utf-8") + monkeypatch.setenv("DEER_FLOW_EXTENSIONS_CONFIG_PATH", str(path)) + store = McpOAuthTokenStore(SqlMcpOAuthTokenRepository(session_factory), cipher=cipher) + set_mcp_oauth_token_store(store) + alice = McpOAuthTokenKey.for_delegated(SERVER, "alice") + bob = McpOAuthTokenKey.for_delegated(SERVER, "bob") + bob_only = McpOAuthTokenKey.for_delegated("bob-only", "bob") + for key in (alice, bob, bob_only): + state = f"{key.owner_user_id}:{key.server_key}" + _delegated_attempt(store, key, state) + attempt = store.consume_delegated(state, owner_user_id=key.owner_user_id, browser_binding="browser") + assert store.complete_delegated(attempt, access_token="access", refresh_token="refresh", expires_at=None) + + rows = (await router.list_connections(Response(), owner="alice")).connections + assert [(row.server_key, row.status) for row in rows] == [(SERVER, "removed")] + assert (await router.disconnect(SERVER, owner="alice")).status_code == 204 + assert (await router.list_connections(Response(), owner="alice")).connections == [] + with session_factory() as session: + row = session.get(McpOAuthTokenRow, ("delegated", "alice", SERVER)) + assert row.access_token_enc is None and row.refresh_token_enc is None + assert store.get_delegated(bob, fingerprint=REQUEST) is not None + + # Revocation also fences a callback already exchanging its code. + _delegated_attempt(store, alice, "in-flight") + in_flight = store.consume_delegated("in-flight", owner_user_id="alice", browser_binding="browser") + assert (await router.disconnect(SERVER, owner="alice")).status_code == 204 + assert not store.complete_delegated(in_flight, access_token="late", expires_at=None) + assert (await router.disconnect("unknown", owner="alice")).status_code == 204 + assert all(row.server_key != "unknown" for row in _rows(session_factory)) diff --git a/backend/tests/test_mcp_session_pool.py b/backend/tests/test_mcp_session_pool.py index 87d03abdad..dd51e4bae3 100644 --- a/backend/tests/test_mcp_session_pool.py +++ b/backend/tests/test_mcp_session_pool.py @@ -1782,6 +1782,7 @@ async def test_http_transport_tools_not_pooled(): from langchain_core.tools import StructuredTool from pydantic import BaseModel, Field + from deerflow.config.extensions_config import ExtensionsConfig, McpServerConfig from deerflow.mcp.tools import get_mcp_tools class Args(BaseModel): @@ -1808,21 +1809,17 @@ async def test_http_transport_tools_not_pooled(): mock_cm.__aenter__ = AsyncMock(return_value=mock_session) mock_cm.__aexit__ = AsyncMock(return_value=False) - extensions_config = MagicMock() - extensions_config.get_enabled_mcp_servers.return_value = { - "myserver": MagicMock(type="http", url="http://localhost:8000/mcp", headers=None, command=None, args=[], env=None), - "playwright": MagicMock(type="stdio", command="npx", args=["-y", "@anthropic/mcp-server-playwright"], env=None, url=None, headers=None), - } - extensions_config.model_extra = {} + extensions_config = ExtensionsConfig( + mcpServers={ + "myserver": McpServerConfig(type="http", url="http://localhost:8000/mcp"), + "playwright": McpServerConfig(type="stdio", command="npx", args=["-y", "@anthropic/mcp-server-playwright"]), + } + ) servers_config = { "myserver": {"transport": "http", "url": "http://localhost:8000/mcp"}, "playwright": {"transport": "stdio", "command": "npx", "args": ["-y", "@anthropic/mcp-server-playwright"]}, } - for name, server in extensions_config.get_enabled_mcp_servers.return_value.items(): - server.model_dump.return_value = servers_config[name] - extensions_config.mcp_servers = extensions_config.get_enabled_mcp_servers.return_value - with ( patch("deerflow.mcp.tools.ExtensionsConfig.from_file", return_value=extensions_config), patch("deerflow.mcp.tools.build_servers_config", return_value=servers_config), @@ -1865,7 +1862,7 @@ async def test_non_stdio_tool_call_timeout_warns_that_it_is_ignored(caplog): from langchain_core.tools import StructuredTool from pydantic import BaseModel, Field - from deerflow.config.extensions_config import McpServerConfig + from deerflow.config.extensions_config import ExtensionsConfig, McpServerConfig from deerflow.mcp.tools import get_mcp_tools class Args(BaseModel): @@ -1884,10 +1881,7 @@ async def test_non_stdio_tool_call_timeout_warns_that_it_is_ignored(caplog): url="https://example.com/mcp", tool_call_timeout=30.0, ) - extensions_config = MagicMock() - extensions_config.get_enabled_mcp_servers.return_value = {"remote": server_cfg} - extensions_config.mcp_servers = {"remote": server_cfg} - extensions_config.model_extra = {} + extensions_config = ExtensionsConfig(mcpServers={"remote": server_cfg}) servers_config = { "remote": {"transport": "http", "url": "https://example.com/mcp"}, @@ -1927,7 +1921,7 @@ async def test_stdio_tool_call_timeout_does_not_raise_typeerror(): from langchain_core.tools import StructuredTool from pydantic import BaseModel, Field - from deerflow.config.extensions_config import McpServerConfig + from deerflow.config.extensions_config import ExtensionsConfig, McpServerConfig from deerflow.mcp.tools import get_mcp_tools class Args(BaseModel): @@ -1955,10 +1949,7 @@ async def test_stdio_tool_call_timeout_does_not_raise_typeerror(): tool_call_timeout=60.0, ) - extensions_config = MagicMock() - extensions_config.get_enabled_mcp_servers.return_value = {"biomcp": server_cfg} - extensions_config.mcp_servers = {"biomcp": server_cfg} - extensions_config.model_extra = {} + extensions_config = ExtensionsConfig(mcpServers={"biomcp": server_cfg}) # Connection dict must NOT contain tool_call_timeout — this is the key assertion. servers_config = { diff --git a/backend/tests/test_migration_0047_mcp_oauth_tokens.py b/backend/tests/test_migration_0047_mcp_oauth_tokens.py index 5ac1634564..5f914f833e 100644 --- a/backend/tests/test_migration_0047_mcp_oauth_tokens.py +++ b/backend/tests/test_migration_0047_mcp_oauth_tokens.py @@ -21,6 +21,7 @@ from deerflow.persistence.mcp_oauth_tokens import McpOAuthTokenRow from deerflow.persistence.postgres_schema import build_asyncpg_connect_args REVISION = "0047_mcp_oauth_tokens" +HEAD = "0058_mcp_browser_oauth" PREVIOUS = "0046_skill_mutations" TABLE = "mcp_oauth_tokens" COLUMNS = { @@ -44,9 +45,10 @@ pytestmark = pytest.mark.asyncio async def test_0047_remains_in_the_single_migration_chain(): - assert bootstrap._get_head_revision() == "0057_coordination_workers" + assert bootstrap._get_head_revision() == HEAD script = ScriptDirectory(str(bootstrap._MIGRATIONS_DIR)) - assert script.get_heads() == ["0057_coordination_workers"] + assert script.get_heads() == [HEAD] + assert script.get_revision(HEAD).down_revision == "0057_coordination_workers" assert script.get_revision("0057_coordination_workers").down_revision == "0056_coordination_task_state" assert script.get_revision("0056_coordination_task_state").down_revision == "0055_thread_shares" assert script.get_revision("0055_thread_shares").down_revision == "0054_project_memory" @@ -96,8 +98,8 @@ async def _orm_diff(engine) -> list: def only_oauth_tokens(obj, name, type_, reflected, compare_to): if type_ == "table": - return name == TABLE - return getattr(getattr(obj, "table", None), "name", TABLE) == TABLE + return name in {TABLE, "mcp_oauth_attempts"} + return getattr(getattr(obj, "table", None), "name", TABLE) in {TABLE, "mcp_oauth_attempts"} async with engine.connect() as conn: @@ -138,16 +140,14 @@ async def test_0047_creates_the_table_matching_the_orm_and_downgrades_cleanly(tm assert shape["pk"]["name"] in ("pk_mcp_oauth_tokens", None) # SQLite does not report constraint names # Token columns are empty while the first refresh is claimed; the key never is. assert {name for name, column in shape["columns"].items() if column["nullable"]} == NULLABLE - # ``make migrate-rev`` would propose nothing: the revision matches the ORM model. - assert await _orm_diff(engine) == [] - async with engine.begin() as conn: - await conn.execute(sa.insert(McpOAuthTokenRow).values(**_row())) + table = await conn.run_sync(lambda sync: sa.Table(TABLE, sa.MetaData(), autoload_with=sync)) + await conn.execute(sa.insert(table).values(**_row())) # A personal connection may reuse a deployment server's name. - await conn.execute(sa.insert(McpOAuthTokenRow).values(**_row(scope="personal", owner_user_id="user-1"))) + await conn.execute(sa.insert(table).values(**_row(scope="personal", owner_user_id="user-1"))) with pytest.raises(sa.exc.IntegrityError): async with engine.begin() as conn: - await conn.execute(sa.insert(McpOAuthTokenRow).values(**_row(version=3))) + await conn.execute(sa.insert(table).values(**_row(version=3))) await asyncio.to_thread(command.downgrade, cfg, PREVIOUS) assert TABLE not in (await _shape(engine))["tables"] @@ -190,8 +190,38 @@ async def test_bootstrap_provisions_the_table_on_an_empty_database(tmp_path): try: await bootstrap.bootstrap_schema(engine, backend="sqlite") await bootstrap.bootstrap_schema(engine, backend="sqlite") - assert set((await _shape(engine))["columns"]) == COLUMNS + assert set((await _shape(engine))["columns"]) == COLUMNS | {"grant_epoch", "grant_context"} + assert "mcp_oauth_attempts" in (await _shape(engine))["tables"] async with engine.connect() as conn: assert (await conn.execute(sa.text("SELECT version_num FROM alembic_version"))).scalar_one() == bootstrap._get_head_revision() finally: await engine.dispose() + + +@pytest.mark.parametrize("backend", ["sqlite", "postgres"]) +async def test_browser_oauth_migration_preserves_legacy_tokens_and_drops_delegated_grants_on_downgrade(tmp_path, backend): + engine, schema = _engine(tmp_path, backend) + cfg = bootstrap._get_alembic_config(engine, postgres_schema=schema or "") + try: + if schema: + async with engine.begin() as conn: + await conn.execute(sa.text(f'CREATE SCHEMA "{schema}"')) + await asyncio.to_thread(command.upgrade, cfg, "0057_coordination_workers") + async with engine.begin() as conn: + table = await conn.run_sync(lambda sync: sa.Table(TABLE, sa.MetaData(), autoload_with=sync)) + await conn.execute(sa.insert(table).values(**_row(refresh_token_enc="legacy ciphertext"))) + await asyncio.to_thread(command.upgrade, cfg, HEAD) + assert await _orm_diff(engine) == [] + async with engine.begin() as conn: + assert (await conn.execute(sa.select(McpOAuthTokenRow.grant_epoch))).scalar_one() is None + await conn.execute(sa.insert(McpOAuthTokenRow).values(**_row(scope="delegated", owner_user_id="alice", grant_epoch=1))) + await asyncio.to_thread(command.downgrade, cfg, "0057_coordination_workers") + shape = await _shape(engine) + assert set(shape["columns"]) == COLUMNS + assert "mcp_oauth_attempts" not in shape["tables"] + async with engine.begin() as conn: + table = await conn.run_sync(lambda sync: sa.Table(TABLE, sa.MetaData(), autoload_with=sync)) + assert (await conn.execute(sa.select(table.c.scope, table.c.refresh_token_enc))).one() == ("deployment", "legacy ciphertext") + finally: + await _drop_schema(engine, schema) + await engine.dispose() diff --git a/backend/tests/test_plugin_tools.py b/backend/tests/test_plugin_tools.py index 81a4bb0e1b..e6fc2263af 100644 --- a/backend/tests/test_plugin_tools.py +++ b/backend/tests/test_plugin_tools.py @@ -129,7 +129,8 @@ def test_assembly_keeps_ordinary_and_unaffected_plugin_tools_on_collision(instal monkeypatch.setattr(assembly, "is_mcp_task_runtime_available", lambda: False) monkeypatch.setattr(assembly, "is_host_bash_allowed", lambda config: False) monkeypatch.setattr(assembly, "resolve_variable", lambda *args: ordinary) - monkeypatch.setattr(ExtensionsConfig, "from_file", lambda: SimpleNamespace(get_enabled_mcp_servers=lambda: {"test": {}})) + mcp_config = ExtensionsConfig.model_validate({"mcpServers": {"test": {"type": "http", "url": "https://example.com/mcp"}}}) + monkeypatch.setattr(ExtensionsConfig, "from_file", lambda: mcp_config) monkeypatch.setattr("deerflow.mcp.cache.get_cached_mcp_tools", lambda: [ordinary]) monkeypatch.setattr("deerflow.tools.builtins.invoke_acp_agent_tool.build_invoke_acp_agent_tool", lambda agents: ordinary) diff --git a/config.example.yaml b/config.example.yaml index cb95430129..65b92b73fa 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -3011,6 +3011,9 @@ scheduler: recursion_limit: 1000 # ============================================================================ +# Per-user browser OAuth for a deployment MCP service is configured in the +# matching extensions_config.json server via user_oauth. See backend/docs/MCP_SERVER.md. + # Per-agent MCP credentials (opt-in, deployment-managed HTTP servers only). # Bindings stay operator-owned here; set agent_auth: true on the matching # extensions_config.json server. See backend/docs/MCP_SERVER.md for the digest diff --git a/docs/guide/mcp.md b/docs/guide/mcp.md index 1340b574a6..8e2bfc8e9c 100644 --- a/docs/guide/mcp.md +++ b/docs/guide/mcp.md @@ -21,8 +21,8 @@ Tool-produced paths and URLs can be retained as short artifact handles across co DeerFlow supports configurable MCP servers and skills to extend its capabilities. Inline MCP audio results are not supported. Stdio tools report an explicit error, matching HTTP/SSE tools, rather than treating base64 audio as a successful text result. When durable MCP background tasks are enabled, agents can use `list_background_tasks(status="failed")` or `status="input_required"` to find failed tasks or tasks awaiting input in the current chat. Other supported statuses are `submitted`, `working`, `completed`, and `cancelled`; omitting the status preserves existing behavior. The database applies the filter before limiting results to the 20 most recent matching tasks. When combined with `active_only=true`, both filters apply: active statuses are `submitted`, `working`, and `input_required`, so terminal statuses return an empty list. `GET /api/threads/{thread_id}/mcp-tasks` supports the same `status` and `active_only` filters before its `limit` (default 50, range 1–100); for example, `?status=failed&limit=20`. Unknown statuses return 422, and omitting the filters preserves the existing response. -For HTTP/SSE MCP servers, OAuth token flows are supported (`client_credentials`, `refresh_token`). -Missing, malformed, or out-of-range token response `expires_in` values use a one-hour default lifetime. This includes lifetimes that cannot be added to the current time without overflowing the expiry timestamp. +For HTTP/SSE MCP servers, administrators can configure the `client_credentials` or `refresh_token` OAuth grant. Missing, malformed, or out-of-range token response `expires_in` values use a one-hour default lifetime. This includes lifetimes that cannot be added to the current time without overflowing the expiry timestamp. +For operator-configured Streamable HTTP servers that opt in to [browser authorization](../../backend/docs/MCP_SERVER.md#browser-authorization-for-deployment-mcp), sign in and go to **Capability Center → Tools & integrations → My MCP connections** to connect your account. Durable HTTP/SSE task status and cancellation calls select configured `user_auth` credentials using the persisted task owner, including after restart; per-request secrets are not retained for background calls. If a request-scoped credential overrides submit authentication, both credentials must authorize access to the same remote task. For stdio MCP servers, per-tool call timeouts can be configured with `tool_call_timeout`; durable background-task calls honor the same setting for HTTP/SSE servers as well. Durable background-task status and cancellation calls renew their claims while they run, so a slow response can still be saved after the original lease duration. If ownership is lost or renewal cannot be confirmed, the worker stops its local call and leaves recovery to the durable state. See [control-call leases](../../backend/docs/mcp-control-leases.md) for recovery and shutdown behavior. diff --git a/frontend/src/components/workspace/capabilities/mcp-user-connections.tsx b/frontend/src/components/workspace/capabilities/mcp-user-connections.tsx new file mode 100644 index 0000000000..7fdd6fff00 --- /dev/null +++ b/frontend/src/components/workspace/capabilities/mcp-user-connections.tsx @@ -0,0 +1,122 @@ +"use client"; + +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; + +import { Button } from "@/components/ui/button"; +import { useI18n } from "@/core/i18n/hooks"; +import { + changeMCPUserConnection, + loadMCPUserConnections, +} from "@/core/mcp/user-oauth"; + +export function MCPUserConnections({ + userId, + query, + callbackFailed, +}: { + userId: string; + query: string; + callbackFailed: boolean; +}) { + const { t } = useI18n(); + const copy = t.capabilities.mcpConnections; + const client = useQueryClient(); + // Configuration changes already invalidate the MCP query family. + const queryKey = ["mcpConfig", "user-oauth", userId]; + const connections = useQuery({ + queryKey, + queryFn: ({ signal }) => loadMCPUserConnections(signal), + retry: false, + }); + const change = useMutation({ + mutationFn: ({ + serverKey, + action, + }: { + serverKey: string; + action: "connect" | "disconnect"; + }) => changeMCPUserConnection(serverKey, action), + retry: false, + onSuccess: async (authorizationUrl) => { + if (!authorizationUrl) await client.invalidateQueries({ queryKey }); + }, + }); + const visible = (connections.data ?? []).filter((item) => + item.display_name.toLowerCase().includes(query.trim().toLowerCase()), + ); + if (!visible.length && !connections.isError && !callbackFailed) return null; + + return ( +
+

+ {copy.title} +

+ {(change.isError || callbackFailed) && ( +

+ {copy.actionFailed} +

+ )} + {connections.isError ? ( +

+ {copy.loadFailed} +

+ ) : ( +
    + {visible.map((item) => { + const canDisconnect = + item.status === "connected" || item.status === "removed"; + const actionLabel = canDisconnect + ? copy.disconnect + : item.status === "reconnect_required" + ? copy.reconnect + : t.capabilities.connect; + return ( +
  • +
    +

    + {item.display_name} +

    +

    + {copy.status[item.status]} +

    +
    + {item.status !== "unavailable" && ( + + )} +
  • + ); + })} +
+ )} +
+ ); +} diff --git a/frontend/src/components/workspace/capabilities/plugin-gallery.tsx b/frontend/src/components/workspace/capabilities/plugin-gallery.tsx index f2cbb9baf1..4a9007ad45 100644 --- a/frontend/src/components/workspace/capabilities/plugin-gallery.tsx +++ b/frontend/src/components/workspace/capabilities/plugin-gallery.tsx @@ -27,6 +27,7 @@ import { isStaticWebsiteOnly } from "@/core/static-mode"; import { cn } from "@/lib/utils"; import { MCPPluginManager } from "./mcp-plugin-manager"; +import { MCPUserConnections } from "./mcp-user-connections"; import { pluginSettingsAdapters } from "./plugin-adapters"; import { catalogText, @@ -269,6 +270,14 @@ export function PluginGallery({ query }: { query: string }) {

{labels.platformHint}

+ {user && canManage && ( + + )} {canManagePlatform ? ( `${action} ${name}`, + disconnect: "Disconnect", + reconnect: "Reconnect", + actionFailed: "Could not change the connection. Try again.", + loadFailed: "Could not load your MCP connections.", + status: { + disconnected: "Not connected", + connected: "Connected", + reconnect_required: "Reconnect to use this server.", + removed: "User authorization is no longer enabled for this server.", + unavailable: "Connection unavailable. Contact your administrator.", + }, + }, icon: { title: "Plugin icon", upload: "Upload plugin icon", diff --git a/frontend/src/core/i18n/locales/types.ts b/frontend/src/core/i18n/locales/types.ts index 049e57e405..0462f16404 100644 --- a/frontend/src/core/i18n/locales/types.ts +++ b/frontend/src/core/i18n/locales/types.ts @@ -175,6 +175,21 @@ export interface Translations { capabilities: { toolsAndIntegrations: string; + mcpConnections: { + title: string; + action: (action: string, name: string) => string; + disconnect: string; + reconnect: string; + actionFailed: string; + loadFailed: string; + status: { + disconnected: string; + connected: string; + reconnect_required: string; + removed: string; + unavailable: string; + }; + }; icon: { title: string; upload: string; diff --git a/frontend/src/core/i18n/locales/zh-CN.ts b/frontend/src/core/i18n/locales/zh-CN.ts index 13a4f97aca..a0ec141433 100644 --- a/frontend/src/core/i18n/locales/zh-CN.ts +++ b/frontend/src/core/i18n/locales/zh-CN.ts @@ -207,6 +207,21 @@ export const zhCN: Translations = { capabilities: { toolsAndIntegrations: "工具与集成", + mcpConnections: { + title: "我的 MCP 连接", + action: (action, name) => `${action} ${name}`, + disconnect: "断开", + reconnect: "重新连接", + actionFailed: "无法更改连接,请重试。", + loadFailed: "无法加载你的 MCP 连接。", + status: { + disconnected: "未连接", + connected: "已连接", + reconnect_required: "重新连接后即可使用此服务器。", + removed: "此服务器已停用用户授权。", + unavailable: "连接不可用,请联系管理员。", + }, + }, icon: { title: "插件图标", upload: "上传插件图标", diff --git a/frontend/src/core/mcp/user-oauth.ts b/frontend/src/core/mcp/user-oauth.ts new file mode 100644 index 0000000000..50176f1dd7 --- /dev/null +++ b/frontend/src/core/mcp/user-oauth.ts @@ -0,0 +1,56 @@ +import { z } from "zod"; + +import { fetch } from "@/core/api/fetcher"; +import { getBackendBaseURL } from "@/core/config"; + +const path = "/api/mcp/user-oauth"; + +const connectionsResponse = z.object({ + connections: z.array( + z.object({ + server_key: z.string(), + display_name: z.string(), + status: z.enum([ + "disconnected", + "connected", + "reconnect_required", + "unavailable", + "removed", + ]), + }), + ), +}); + +export async function loadMCPUserConnections(signal: AbortSignal) { + const response = await fetch(`${getBackendBaseURL()}${path}`, { signal }); + // Auth-disabled deployments cannot establish user grants. An older Gateway + // might also lack this optional surface. + if (response.status === 403 || response.status === 404) return []; + if (!response.ok) throw new Error("Could not load MCP connections"); + return connectionsResponse.parse(await response.json()).connections; +} + +export async function changeMCPUserConnection( + serverKey: string, + action: "connect" | "disconnect", +) { + const connect = action === "connect"; + const connectionURL = `${getBackendBaseURL()}${path}/${encodeURIComponent(serverKey)}`; + const response = await fetch( + connect ? `${connectionURL}/connect` : connectionURL, + { + method: connect ? "POST" : "DELETE", + }, + ); + if (!response.ok) throw new Error("Could not change MCP connection"); + if (!connect) return; + const result = (await response.json()) as { authorization_url?: unknown }; + if (typeof result.authorization_url !== "string") { + throw new Error("Missing MCP authorization URL"); + } + const url = new URL(result.authorization_url); + if (url.protocol !== "https:" || url.username || url.password) { + throw new Error("Invalid MCP authorization URL"); + } + return url.href; +} diff --git a/frontend/tests/e2e/platform-mcp-controls.spec.ts b/frontend/tests/e2e/platform-mcp-controls.spec.ts index 409870b05c..05b82ec682 100644 --- a/frontend/tests/e2e/platform-mcp-controls.spec.ts +++ b/frontend/tests/e2e/platform-mcp-controls.spec.ts @@ -16,6 +16,9 @@ async function mockConnections(page: Page) { }, }), ); + await page.route("**/api/mcp/user-oauth", (route) => + route.fulfill({ json: { connections: [] } }), + ); await page.route("**/api/capabilities/installations/mcp?scope=all", (route) => route.fulfill({ json: { @@ -134,6 +137,80 @@ test("administrators toggle shared MCP globally without changing a same-named pe expect(writes).toHaveLength(3); }); +test("a member connects and disconnects their own MCP account from Capability Center", async ({ + page, +}) => { + const { state } = await mockConnections(page); + state.role = "user"; + let status = "reconnect_required"; + let retired = [ + { server_key: "retired", display_name: "Retired tools", status: "removed" }, + ]; + const calls: string[] = []; + await page.route("**/api/mcp/user-oauth", (route) => + route.fulfill({ + json: { + connections: [ + ...retired, + { server_key: "logs", display_name: "Log tools", status }, + { + server_key: "unavailable", + display_name: "Unavailable tools", + status: "unavailable", + }, + ], + }, + }), + ); + await page.route("**/api/mcp/user-oauth/logs/connect", (route) => { + calls.push(route.request().method()); + return route.fulfill({ + json: { authorization_url: "https://provider.example.test/authorize" }, + }); + }); + await page.route("https://provider.example.test/authorize", (route) => { + status = "connected"; + return route.fulfill({ + status: 303, + headers: { + location: new URL( + "/workspace/capabilities?tab=plugins&mcp_oauth=connected#my-mcp-connections", + page.url(), + ).href, + }, + }); + }); + await page.route("**/api/mcp/user-oauth/retired", (route) => { + expect(route.request().method()).toBe("DELETE"); + retired = []; + return route.fulfill({ status: 204 }); + }); + await page.route("**/api/mcp/user-oauth/logs", (route) => { + calls.push(route.request().method()); + status = "disconnected"; + return route.fulfill({ status: 204 }); + }); + + await page.goto("/workspace/capabilities"); + const mine = page.getByRole("region", { name: "My MCP connections" }); + await expect( + mine.getByText("Connection unavailable. Contact your administrator."), + ).toBeVisible(); + await expect( + mine.getByRole("button", { name: /Unavailable tools/ }), + ).toHaveCount(0); + await mine.getByRole("button", { name: "Reconnect Log tools" }).click(); + const disconnect = mine.getByRole("button", { name: "Disconnect Log tools" }); + await expect(disconnect).toBeVisible(); + await disconnect.click(); + await expect( + mine.getByRole("button", { name: "Connect Log tools" }), + ).toBeVisible(); + expect(calls).toEqual(["POST", "DELETE"]); + await mine.getByRole("button", { name: "Disconnect Retired tools" }).click(); + await expect(mine.getByText("Retired tools")).toHaveCount(0); +}); + test("a rejected platform toggle keeps the stored state and reports the error", async ({ page, }) => {