Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions openhands-agent-server/openhands/agent_server/mcp_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,10 +572,10 @@ def _bind(self, mcp_url: str) -> None:
if self._static_client_info is not None:
self._static_client_info.redirect_uris = redirect_uris

async def _initialize(self) -> None:
await super()._initialize()
# A client registered for an earlier redirect URI (e.g. a loopback
# port) would be rejected for this one; register a new client.
async def redirect_handler(self, authorization_url: str) -> None:
"""Capture the URL instead of opening a browser from the backend."""
# Keep the original client for refresh; only fresh authorization needs
# a registration for this redirect. FastMCP retries stale clients once.
redirect_url = self._redirect_url
client_info = self.context.client_info
if (
Expand All @@ -585,10 +585,8 @@ async def _initialize(self) -> None:
and redirect_url
not in {str(uri) for uri in client_info.redirect_uris or []}
):
self.context.client_info = None
raise ClientNotFoundError("OAuth client has a different redirect URI")

async def redirect_handler(self, authorization_url: str) -> None:
"""Capture the URL instead of opening a browser from the backend."""
async with self.httpx_client_factory() as client:
response = await client.get(authorization_url, follow_redirects=False)
if response.status_code == 400:
Expand Down
39 changes: 39 additions & 0 deletions tests/agent_server/test_mcp_oauth_redirect.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import httpx
import pytest
from fastapi.testclient import TestClient
from fastmcp.server.auth.providers.in_memory import InMemoryOAuthProvider
from pydantic import SecretStr

from openhands.agent_server.api import create_app
Expand Down Expand Up @@ -216,6 +217,44 @@ def test_a_client_registered_for_the_loopback_callback_is_registered_again(
assert second["oauth_state"]["client_info"]["redirect_uris"] == [PUBLIC_REDIRECT]


def test_changed_callback_refreshes_stored_tokens_without_authorization(
protected_oauth_mcp_server: str, # noqa: F811
oauth_provider: InMemoryOAuthProvider, # noqa: F811
jobs: None,
):
client = _client()
job_id, authorization_url = _start(
client, {"server": _oauth_server(protected_oauth_mcp_server)}
)
httpx.get(_sign_in(authorization_url), timeout=10.0)
first = _wait_for_result(client, job_id)
state = first["oauth_state"]
state["token_expires_at"] = time.time() - 60
registered_clients = set(oauth_provider.clients)
refresh_tokens = set(oauth_provider.refresh_tokens)

response = client.post(
"/api/mcp/oauth/start",
json={
"timeout": 10.0,
"server": _oauth_server(protected_oauth_mcp_server, state),
"callback_base_url": "https://canvas.example.test",
},
)

assert response.status_code == 200, response.text
started = response.json()
assert started["ok"] is True, started
assert "authorization_url" not in started, started
second = _wait_for_result(client, started["job_id"])
assert second["status"] == "succeeded", second
assert second["tools"] == ["read_subject"]
assert second["oauth_state"]["client_info"] == state["client_info"]
assert second["oauth_state"]["token_expires_at"] > time.time()
assert set(oauth_provider.clients) == registered_clients
assert not refresh_tokens.intersection(oauth_provider.refresh_tokens)


def _job() -> _MCPOAuthProbeJob:
return _MCPOAuthProbeJob(
request=MCPTestRequest.model_validate(
Expand Down