From d63a6815c4437eea5e82301319d4b1a16c0d1441 Mon Sep 17 00:00:00 2001
From: 2301_80183707 <2100820071@qq.com>
Date: Sun, 25 Oct 2026 22:16:56 +0800
Subject: [PATCH 1/5] fix(agent-server): support public MCP OAuth callbacks
---
.pr/design.html | 72 +++++++++++
.../openhands/agent_server/api.py | 6 +-
.../openhands/agent_server/config.py | 3 +-
.../openhands/agent_server/mcp_router.py | 115 +++++++++++++++++-
tests/agent_server/test_mcp_router.py | 104 ++++++++++++++++
5 files changed, 295 insertions(+), 5 deletions(-)
create mode 100644 .pr/design.html
diff --git a/.pr/design.html b/.pr/design.html
new file mode 100644
index 00000000000..659cb48346e
--- /dev/null
+++ b/.pr/design.html
@@ -0,0 +1,72 @@
+
+
+
+
+ Public OAuth callbacks for hosted Agent Server
+
+ OAuth MCP installation currently registers a FastMCP loopback redirect such as
+ http://localhost:<port>/callback. That only works when the browser can
+ reach the agent process. A hosted agent needs its configured public origin instead.
+
+
+ Interface
+
+ When OH_WEB_URL is unset, the existing local callback and authenticated
+ POST /api/mcp/oauth/callback/{job_id} flow are unchanged. When it is set,
+ OAuth client registration uses:
+
+ GET {OH_WEB_URL}/api/mcp/oauth/callback/{job_id}?code=...&state=...
+
+ The route is intentionally public: an authorization server redirect cannot carry the
+ agent session API key. Access is constrained by an unguessable probe job ID and the
+ state generated for that specific authorization request. This is an additive endpoint;
+ no existing request or response schema changes.
+
+
+ Flow
+
+
Start OAuth probe
→
+
Register public redirect URI
→
+
Browser authorizes and redirects
+
+
+
Public route validates job + state
→
+
Waiting FastMCP client receives code
→
+
Existing token exchange and status flow
+
+
+ Failure handling
+
+ - Unknown or expired job:
404.
+ - Callback before the client is waiting:
409.
+ - Missing or mismatched OAuth state:
400, without waking the job.
+ - Provider error redirects wake the job with a generic failure; provider text is not reflected into HTML.
+
+
+ Compatibility and verification
+
+ The implementation changes FastMCP client metadata after its normal initialization rather
+ than copying its private binding implementation. Both dynamically registered and
+ pre-registered clients use the public callback URI. Tests cover the configured path prefix,
+ local-flow preservation, session-key-free public delivery, ready-state checks, state
+ isolation, and expiration.
+
+
+
+
diff --git a/openhands-agent-server/openhands/agent_server/api.py b/openhands-agent-server/openhands/agent_server/api.py
index 650cce4cff7..ab7d29ab8ab 100644
--- a/openhands-agent-server/openhands/agent_server/api.py
+++ b/openhands-agent-server/openhands/agent_server/api.py
@@ -71,7 +71,10 @@
)
from openhands.agent_server.llm_router import llm_router
from openhands.agent_server.local_secret_resolver import local_secret_resolution
-from openhands.agent_server.mcp_router import mcp_router
+from openhands.agent_server.mcp_router import (
+ mcp_router,
+ public_mcp_oauth_callback_router,
+)
from openhands.agent_server.meta_profiles_router import meta_profiles_router
from openhands.agent_server.middleware import CORSDispatcher
from openhands.agent_server.openai.router import (
@@ -568,6 +571,7 @@ def _add_api_routes(app: FastAPI) -> None:
init_api_router = APIRouter(prefix="/api")
init_api_router.include_router(init_router)
app.include_router(init_api_router)
+ app.include_router(public_mcp_oauth_callback_router)
# Header-only auth: applied to every /api/* route EXCEPT the workspace
# static-file routes (handled separately below). Cookies are NOT honored
diff --git a/openhands-agent-server/openhands/agent_server/config.py b/openhands-agent-server/openhands/agent_server/config.py
index f461e9fc3d1..842cc69fb01 100644
--- a/openhands-agent-server/openhands/agent_server/config.py
+++ b/openhands-agent-server/openhands/agent_server/config.py
@@ -381,7 +381,8 @@ class Config(BaseModel):
web_url: str | None = Field(
default_factory=_default_web_url,
description=(
- "The URL where this agent server instance is available externally"
+ "The externally reachable agent-server URL, including any path prefix. "
+ "It is used for root-path routing and OAuth MCP callback redirects."
),
)
app_backend_public_url: str | None = Field(
diff --git a/openhands-agent-server/openhands/agent_server/mcp_router.py b/openhands-agent-server/openhands/agent_server/mcp_router.py
index 0061f683b23..29ad30f1e59 100644
--- a/openhands-agent-server/openhands/agent_server/mcp_router.py
+++ b/openhands-agent-server/openhands/agent_server/mcp_router.py
@@ -20,17 +20,19 @@
from __future__ import annotations
import asyncio
+import secrets
import threading
import time
import uuid
from typing import Annotated, Any, Literal
-from urllib.parse import urlparse
+from urllib.parse import parse_qs, urlparse
import httpx
import mcp.types
from fastapi import APIRouter, HTTPException, Request
+from fastapi.responses import HTMLResponse
from fastmcp.client.auth.oauth import ClientNotFoundError, OAuth
-from pydantic import BaseModel, Field, model_validator
+from pydantic import AnyHttpUrl, BaseModel, Field, model_validator
from openhands.agent_server._secrets_exposure import get_cipher
from openhands.agent_server.mcp_oauth_store import (
@@ -54,6 +56,7 @@
logger = get_logger(__name__)
mcp_router = APIRouter(prefix="/mcp", tags=["MCP"])
+public_mcp_oauth_callback_router = APIRouter(prefix="/api/mcp/oauth", tags=["MCP"])
# ---------------------------------------------------------------------------
@@ -313,19 +316,31 @@ class MCPOAuthCallbackRequest(BaseModel):
class _MCPOAuthProbeJob:
- def __init__(self, *, request: MCPTestRequest, cipher: Cipher | None):
+ def __init__(
+ self,
+ *,
+ request: MCPTestRequest,
+ cipher: Cipher | None,
+ public_callback_url: str | None = None,
+ ):
self.id = uuid.uuid4().hex
self.request = request
self.cipher = cipher
+ self.public_callback_url = public_callback_url
self.created_at = time.monotonic()
self.authorization_url: str | None = None
self.callback_url: str | None = None
+ self.expected_state: str | None = None
+ self.callback_code: str | None = None
+ self.callback_state: str | None = None
+ self.callback_error: str | None = None
self.result: MCPTestResponse | None = None
self.status: Literal["pending", "authorizing", "succeeded", "failed"] = (
"pending"
)
self.authorization_ready = threading.Event()
self.callback_ready = threading.Event()
+ self.callback_received = threading.Event()
self.done = threading.Event()
self.lock = threading.Lock()
@@ -340,6 +355,25 @@ def set_callback_ready(self, callback_url: str) -> None:
self.callback_url = callback_url
self.callback_ready.set()
+ def set_expected_state(self, state: str) -> None:
+ with self.lock:
+ self.expected_state = state
+
+ def set_public_callback(
+ self,
+ *,
+ code: str | None = None,
+ state: str | None = None,
+ error: str | None = None,
+ ) -> None:
+ with self.lock:
+ if self.callback_received.is_set():
+ return
+ self.callback_code = code
+ self.callback_state = state
+ self.callback_error = error
+ self.callback_received.set()
+
def set_result(self, result: MCPTestResponse) -> None:
with self.lock:
self.result = result
@@ -450,6 +484,11 @@ class _BrowserCoordinatedOAuth(MCPOAuth):
def __init__(self, *, job: _MCPOAuthProbeJob, **kwargs: Any):
super().__init__(**kwargs)
self._job = job
+ if job.public_callback_url is not None:
+ redirect_uris = [AnyHttpUrl(job.public_callback_url)]
+ self.context.client_metadata.redirect_uris = redirect_uris
+ if self._static_client_info is not None:
+ self._static_client_info.redirect_uris = redirect_uris
async def redirect_handler(self, authorization_url: str) -> None:
"""Capture the URL instead of opening a browser from the backend."""
@@ -465,6 +504,11 @@ async def redirect_handler(self, authorization_url: str) -> None:
)
logger.info("MCP OAuth authorization URL captured for job %s", self._job.id)
+ if self._job.public_callback_url is not None:
+ state = parse_qs(urlparse(authorization_url).query).get("state", [None])[0]
+ if state is None:
+ raise RuntimeError("OAuth authorization URL did not include state")
+ self._job.set_expected_state(state)
self._job.set_authorization_url(authorization_url)
async def callback_handler(self):
@@ -474,6 +518,27 @@ async def callback_handler(self):
rejects -- it wants an ``AuthorizationCodeResult``. Only
``redirect_port`` is read: ``_callback_host`` is absent in fastmcp 3.2.0.
"""
+ callback_url = self._job.public_callback_url
+ if callback_url is not None:
+ self._job.set_callback_ready(callback_url)
+ logger.info(
+ "MCP OAuth public callback ready for job %s at %s",
+ self._job.id,
+ callback_url,
+ )
+ received = await asyncio.to_thread(self._job.callback_received.wait, 300.0)
+ if not received:
+ raise TimeoutError("OAuth callback timed out after 300.0 seconds")
+ with self._job.lock:
+ code = self._job.callback_code
+ state = self._job.callback_state
+ error = self._job.callback_error
+ if error is not None:
+ raise RuntimeError(error)
+ if code is None or state is None:
+ raise RuntimeError("OAuth callback did not include code and state")
+ return code, state
+
callback_url = f"http://localhost:{self.redirect_port}/callback"
self._job.set_callback_ready(callback_url)
logger.info(
@@ -672,6 +737,12 @@ def _get_oauth_job(job_id: str) -> _MCPOAuthProbeJob:
return job
+def _public_callback_url(web_url: str | None, job_id: str) -> str | None:
+ if web_url is None:
+ return None
+ return f"{web_url.rstrip('/')}/api/mcp/oauth/callback/{job_id}"
+
+
@mcp_router.post(
"/oauth/start",
response_model=MCPOAuthStartResponse,
@@ -689,6 +760,9 @@ async def start_mcp_oauth(
)
job = _MCPOAuthProbeJob(request=request, cipher=get_cipher(http_request))
+ job.public_callback_url = _public_callback_url(
+ http_request.app.state.config.web_url, job.id
+ )
_register_oauth_job(job)
thread = threading.Thread(
target=_run_oauth_probe_job,
@@ -743,6 +817,41 @@ async def get_mcp_oauth_status(job_id: str) -> MCPOAuthStatusResponse:
return _get_oauth_job(job_id).to_status_response()
+@public_mcp_oauth_callback_router.get(
+ "/callback/{job_id}",
+ include_in_schema=False,
+)
+async def receive_mcp_oauth_callback(job_id: str, request: Request) -> HTMLResponse:
+ """Receive an OAuth redirect at the agent server's public URL."""
+ job = _get_oauth_job(job_id)
+ code = request.query_params.get("code")
+ state = request.query_params.get("state")
+ error = request.query_params.get("error")
+
+ with job.lock:
+ expected_state = job.expected_state
+
+ if not job.callback_ready.is_set() or expected_state is None:
+ raise HTTPException(status_code=409, detail="OAuth callback is not ready")
+ if state is None or not secrets.compare_digest(state, expected_state):
+ raise HTTPException(
+ status_code=400, detail="OAuth callback state did not match"
+ )
+ if error is not None:
+ job.set_public_callback(error="OAuth authorization failed")
+ return HTMLResponse(
+ "You can close this tab.
",
+ status_code=400,
+ )
+ if code is None:
+ raise HTTPException(
+ status_code=400, detail="OAuth callback did not include code"
+ )
+
+ job.set_public_callback(code=code, state=state)
+ return HTMLResponse("You can close this tab.
")
+
+
def _validate_callback_url(callback_url: str, job: _MCPOAuthProbeJob) -> None:
try:
parsed = urlparse(callback_url)
diff --git a/tests/agent_server/test_mcp_router.py b/tests/agent_server/test_mcp_router.py
index e6659c8a3fa..b012548fcff 100644
--- a/tests/agent_server/test_mcp_router.py
+++ b/tests/agent_server/test_mcp_router.py
@@ -22,6 +22,7 @@
_MCPOAuthProbeJob,
_oauth_probe_jobs,
_oauth_probe_jobs_lock,
+ _public_callback_url,
_register_oauth_job,
)
from openhands.agent_server.persistence import reset_stores
@@ -857,6 +858,109 @@ async def fake_base_callback_handler(self):
assert job.callback_url == "http://localhost:64801/callback"
+def test_browser_coordinated_oauth_uses_public_callback_url():
+ job = _MCPOAuthProbeJob(
+ request=MCPTestRequest.model_validate(
+ {"server": {"transport": "http", "url": "https://mcp.example.com/mcp"}}
+ ),
+ cipher=None,
+ )
+ public_callback_url = (
+ f"https://agent.example.com/openhands/api/mcp/oauth/callback/{job.id}"
+ )
+ job.public_callback_url = public_callback_url
+ job.set_public_callback(code="authorization-code", state="oauth-state")
+ oauth = _BrowserCoordinatedOAuth(
+ job=job,
+ mcp_url="https://mcp.example.com/mcp",
+ client_id="client-id",
+ )
+
+ assert str(oauth.context.client_metadata.redirect_uris[0]) == public_callback_url
+ asyncio.run(oauth._initialize())
+ assert oauth.context.client_info is not None
+ assert str(oauth.context.client_info.redirect_uris[0]) == public_callback_url
+ assert asyncio.run(oauth.callback_handler()) == (
+ "authorization-code",
+ "oauth-state",
+ )
+ assert job.callback_url == public_callback_url
+
+
+def test_public_callback_url_preserves_configured_path_prefix():
+ assert _public_callback_url("https://agent.example.com/openhands/", "job-123") == (
+ "https://agent.example.com/openhands/api/mcp/oauth/callback/job-123"
+ )
+ assert _public_callback_url(None, "job-123") is None
+
+
+def test_public_mcp_oauth_callback_requires_ready_matching_state_without_api_key():
+ reset_stores()
+ config = Config(
+ session_api_keys=[SecretStr("session-key")],
+ web_url="https://agent.example.com/openhands",
+ )
+ job = _MCPOAuthProbeJob(
+ request=MCPTestRequest.model_validate(
+ {"server": {"transport": "http", "url": "https://mcp.example.com/mcp"}}
+ ),
+ cipher=None,
+ )
+ job.public_callback_url = (
+ f"https://agent.example.com/openhands/api/mcp/oauth/callback/{job.id}"
+ )
+ job.set_expected_state("expected-state")
+ _register_oauth_job(job)
+
+ try:
+ with TestClient(
+ create_app(config), raise_server_exceptions=False
+ ) as test_client:
+ callback_path = f"/api/mcp/oauth/callback/{job.id}"
+ before_ready = test_client.get(
+ f"{callback_path}?code=authorization-code&state=expected-state"
+ )
+ assert before_ready.status_code == 409
+
+ job.set_callback_ready(job.public_callback_url or "")
+ wrong_state = test_client.get(
+ f"{callback_path}?code=authorization-code&state=wrong-state"
+ )
+ assert wrong_state.status_code == 400
+ assert not job.callback_received.is_set()
+
+ success = test_client.get(
+ f"{callback_path}?code=authorization-code&state=expected-state"
+ )
+ assert success.status_code == 200
+ assert "Authorization received" in success.text
+ assert job.callback_received.is_set()
+ finally:
+ with _oauth_probe_jobs_lock:
+ _oauth_probe_jobs.clear()
+ reset_stores()
+
+
+def test_public_mcp_oauth_callback_rejects_expired_job(client: TestClient):
+ job = _MCPOAuthProbeJob(
+ request=MCPTestRequest.model_validate(
+ {"server": {"transport": "http", "url": "https://mcp.example.com/mcp"}}
+ ),
+ cipher=None,
+ )
+ job.public_callback_url = (
+ f"https://agent.example.com/api/mcp/oauth/callback/{job.id}"
+ )
+ job.created_at -= _OAUTH_PROBE_JOB_TTL_SECONDS + 1
+ _register_oauth_job(job)
+
+ response = client.get(
+ f"/api/mcp/oauth/callback/{job.id}?code=authorization-code&state=expected"
+ )
+
+ assert response.status_code == 404
+
+
def test_mcp_oauth_callback_rejects_unknown_job(client: TestClient):
response = client.post(
"/api/mcp/oauth/callback/not-a-job",
From 2caf545de79d50cdef68bcb1de2785fbdba60ed2 Mon Sep 17 00:00:00 2001
From: openhands