The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): re-mint an ended dashboard OAuth flow instead of parking the server
finn7630a37960b2e4c
diff --git a/hermes_cli/web_routers/mcp.py b/hermes_cli/web_routers/mcp.pyindex 6b52e68efb5..a34babb6f71 100644--- a/hermes_cli/web_routers/mcp.py+++ b/hermes_cli/web_routers/mcp.py@@ -282,7 +282,7 @@ async def cancel_mcp_oauth_flow(flow_id: str, request: Request):flow = _mcp_oauth_flows.get(flow_id)if flow is None: # expired/GC'd is the goal state of a cancel — not an errorreturn {"ok": True, "status": "expired"}- flow.mark_error("Cancelled by user")+ flow.mark_error("Cancelled by user", cancelled=True)return {"ok": True, "status": flow.snapshot()["status"]}diff --git a/tests/hermes_cli/test_mcp_dashboard_oauth.py b/tests/hermes_cli/test_mcp_dashboard_oauth.pyindex c4df8eeeaba..d24c2ae0044 100644--- a/tests/hermes_cli/test_mcp_dashboard_oauth.py+++ b/tests/hermes_cli/test_mcp_dashboard_oauth.py@@ -1,5 +1,6 @@"""Dashboard HTTP contract for hosted MCP OAuth."""+import asynciofrom unittest.mock import patchimport pytest@@ -141,3 +142,24 @@ def test_flow_status_does_not_expose_authorization_code():assert body["status"] == "approved"assert "secret-code" not in response.textassert "secret-state" not in response.text+++def test_cancel_marks_the_flow_terminal_for_a_retrying_worker():+ """DELETE /flows/{id} is a user cancellation: the worker's next attempt must not re-mint the+ flow behind the dashboard's back (it would reopen a URL the user just dismissed)."""+ from tools.mcp_dashboard_oauth import DashboardOAuthFlow++ flow = DashboardOAuthFlow(+ flow_id="flow-cancel-retry",+ server_name="reports",+ profile=None,+ hermes_home="/tmp/hermes-test",+ redirect_uri="https://agent.example/api/mcp/oauth/callback/reports",+ )+ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=first"))+ _web_server_mcp._mcp_oauth_flows[flow.flow_id] = flow++ assert _client().delete("/api/mcp/oauth/flows/flow-cancel-retry").json()["ok"] is True+ with pytest.raises(RuntimeError, match="cancelled"):+ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=second"))+ assert flow.snapshot()["status"] == "error"diff --git a/tests/tools/test_mcp_dashboard_oauth.py b/tests/tools/test_mcp_dashboard_oauth.pyindex 28e1baebfef..0b052f9fa8a 100644--- a/tests/tools/test_mcp_dashboard_oauth.py+++ b/tests/tools/test_mcp_dashboard_oauth.py@@ -1,11 +1,24 @@"""Hosted-dashboard bridge for MCP OAuth browser callbacks."""import asyncio+import loggingimport threadingimport pytest+def _flow(flow_id: str = "flow-retry", server_name: str = "asana"):+ from tools.mcp_dashboard_oauth import DashboardOAuthFlow++ return DashboardOAuthFlow(+ flow_id=flow_id,+ server_name=server_name,+ profile=None,+ hermes_home="/tmp/hermes-test",+ redirect_uri=f"https://agent.example/mcp/oauth/callback/{flow_id}",+ )++def test_dashboard_flow_exposes_authorization_url_and_accepts_callback():from tools.mcp_dashboard_oauth import DashboardOAuthFlow@@ -121,14 +134,6 @@ def test_mcp_oauth_helpers_use_dashboard_flow_without_loopback_port():assert flow.authorization_url == "https://idp.example/authorize?state=state-4"-def _flow(flow_id: str):- from tools.mcp_dashboard_oauth import DashboardOAuthFlow-- return DashboardOAuthFlow(- flow_id=flow_id, server_name="asana", profile=None, hermes_home="/tmp/hermes-test",- redirect_uri=f"https://agent.example/mcp/oauth/callback/{flow_id}")--def test_first_mark_error_reason_reaches_callback_waiter_and_is_never_clobbered():"""A failure marked before any browser redirect (worker crash, authorization-URL timeout,user cancel) must reach the SDK's callback waiter — not the generic no-code line — and the@@ -219,3 +224,201 @@ def test_preregistered_pinned_redirect_port_keeps_loopback_listener_under_dashboresult = asyncio.run(_authorize())assert (result.code, result.state) == ("code-5", "state-5")+++def test_ended_flow_is_reopened_for_the_retry_instead_of_raising():+ """An ended handle must be re-minted for the next authorization attempt, not raise.++ The MCP server task inherits this flow for its whole life (``_park`` re-establishes nothing:+ the ContextVar stays set), so a stale handle raised ``RuntimeError: OAuth flow already+ ended`` out of the SDK's auth flow on every retry and parked the server for good.+ """+ flow = _flow()+ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=stale"))+ flow.deliver_callback(code="spent-code", state="stale", error=None)+ assert asyncio.run(flow.wait_for_callback()) == ("spent-code", "stale", None)+ flow.mark_approved()++ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=fresh"))++ snapshot = flow.snapshot()+ assert snapshot["status"] == "authorization_required"+ assert snapshot["authorization_url"] == "https://idp.example/authorize?state=fresh"+ assert flow.expected_state == "fresh"+ # the ended attempt's spent authorization code must never be replayed to the new attempt+ with pytest.raises(TimeoutError):+ asyncio.run(flow.wait_for_callback(timeout=0.05))+ flow.deliver_callback(code="fresh-code", state="fresh", error=None)+ assert asyncio.run(flow.wait_for_callback()) == ("fresh-code", "fresh", None)+++def test_failed_attempt_reopens_the_same_handle():+ """An attempt that failed (not cancelled) is recoverable too — the desktop keeps polling the+ same flow id, so re-minting in place is what lets it show a working URL again."""+ flow = _flow("flow-failed")+ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=one"))+ flow.mark_error("connection dropped mid-consent")++ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=two"))++ assert flow.snapshot() == {+ "flow_id": "flow-failed",+ "server_name": "asana",+ "status": "authorization_required",+ "authorization_url": "https://idp.example/authorize?state=two",+ "error": None,+ }+++def test_first_publish_is_unchanged_and_a_repeat_does_not_reopen():+ """Protection: the ordinary first flow behaves exactly as before, and a repeat of the same URL+ (the SDK re-invoking the handler) neither reopens the flow nor pushes a second URL."""+ flow = _flow("flow-first")+ url = "https://idp.example/authorize?state=s1"+ expected = {+ "flow_id": "flow-first",+ "server_name": "asana",+ "status": "authorization_required",+ "authorization_url": url,+ "error": None,+ }++ asyncio.run(flow.publish_authorization_url(url))+ assert flow.snapshot() == expected++ asyncio.run(flow.publish_authorization_url(url))+ assert flow.snapshot() == expected+ assert flow.expected_state == "s1"+ # nothing was re-minted, so no callback slot was opened/wiped behind the waiting worker+ assert not flow._callback_ready.is_set()+ # and the flow is still the one the browser callback completes+ flow.deliver_callback(code="code-first", state="s1", error=None)+ assert asyncio.run(flow.wait_for_callback()) == ("code-first", "s1", None)+++def test_concurrent_reopens_leave_one_live_url_and_state_pair():+ """Re-minting is serialized on the flow lock: concurrent publishes leave ONE live (url, state)+ pair — never two active flows — and the callback slot still belongs to that pair."""+ flow = _flow("flow-race-reopen")+ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=ended"))+ flow.mark_error("attempt 1 failed")++ start = threading.Barrier(3)+ errors: list = []++ def publish(state: str) -> None:+ start.wait()+ try:+ asyncio.run(+ flow.publish_authorization_url(f"https://idp.example/authorize?state={state}")+ )+ except Exception as exc: # noqa: BLE001 — reported, not swallowed+ errors.append(exc)++ workers = [threading.Thread(target=publish, args=(state,)) for state in ("a", "b")]+ for worker in workers:+ worker.start()+ start.wait()+ for worker in workers:+ worker.join()++ assert errors == []+ assert flow.expected_state in {"a", "b"}+ assert flow.snapshot()["status"] == "authorization_required"+ assert flow.snapshot()["authorization_url"] == (+ f"https://idp.example/authorize?state={flow.expected_state}"+ )+ flow.deliver_callback(code="code-race", state=flow.expected_state, error=None)+ assert asyncio.run(flow.wait_for_callback())[0] == "code-race"+++def test_cancelled_flow_stays_terminal():+ """A user cancellation is not "ended by accident": the retrying worker must not reopen it+ (the per-server slot has to free promptly, and the user said no)."""+ flow = _flow("flow-cancelled")+ flow.mark_error("Cancelled by user", cancelled=True)++ with pytest.raises(RuntimeError, match="cancelled"):+ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=late"))++ assert flow.snapshot()["status"] == "error"+ assert flow.expected_state is None++[email protected]_isolate[email protected]("ended_by", ["approved", "error"])+def test_server_task_does_not_park_on_an_ended_dashboard_flow(+ ended_by, monkeypatch, tmp_path, caplog+):+ """End-to-end shape of the report: an MCP server task whose inherited dashboard flow already+ ended used to raise out of the redirect handler on every attempt of the initial-connect ladder+ and park ("failed initial connection after 3 attempts").++ With the flow re-minted, the ladder fails (if at all) only for the ordinary reason — nobody+ completed the consent screen — and the handle is live and completable again.+ """+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ from tools import mcp_tool+ from tools.mcp_dashboard_oauth import dashboard_oauth_flow+ from tools.mcp_oauth import _make_redirect_handler+ from tools.mcp_tool import MCPServerTask++ monkeypatch.setattr(mcp_tool, "_PARKED_RETRY_INTERVAL", 0.05)+ _real_sleep = asyncio.sleep++ async def _fast_sleep(_delay, *a, **kw):+ await _real_sleep(0)++ monkeypatch.setattr(mcp_tool.asyncio, "sleep", _fast_sleep)++ flow = _flow("flow-stale", "asana")+ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=spent"))+ if ended_by == "approved":+ flow.mark_approved()+ else:+ flow.mark_error("worker gave up on the earlier attempt")+ flow.mark_worker_done()++ handler = _make_redirect_handler(0)++ class _Task(MCPServerTask):+ def _is_http(self) -> bool:+ return False++ def _deregister_tools(self) -> None:+ self._registered_tool_names = []++ async def _run_stdio(self, config):+ # The SDK's auth flow sits inside the transport and calls the redirect handler.+ with dashboard_oauth_flow(flow):+ await handler("https://idp.example/authorize?state=fresh")+ raise TimeoutError("OAuth callback timed out — the consent screen was never completed")++ async def _scenario():+ task = _Task("asana")+ failure = None+ try:+ await task.start({"command": "x"})+ except Exception as exc: # noqa: BLE001 — the connect failure under test+ failure = exc+ parked = task._was_parked+ await task.shutdown()+ return failure, parked, task._task++ with caplog.at_level(logging.WARNING, logger="tools.mcp_tool"):+ failure, parked, run_task = asyncio.run(_scenario())++ assert failure is not None, "the transport never failed, so the ladder was not exercised"+ assert not (isinstance(failure, RuntimeError) and "already ended" in str(failure)), (+ "an ended dashboard flow handle reached the connect ladder"+ )+ assert parked, "the ladder should end in a park, not a silent exit"+ assert run_task.done(), "run task must be reaped by shutdown()"+ assert any("parking" in record.getMessage() for record in caplog.records)++ # The retry re-minted the handle: the browser can still complete the new attempt.+ assert flow.snapshot()["status"] == "authorization_required"+ assert flow.expected_state == "fresh"+ flow.deliver_callback(code="late-code", state="fresh", error=None)+ assert asyncio.run(flow.wait_for_callback())[0] == "late-code"diff --git a/tests/tui_gateway/test_mcp_oauth_cancel.py b/tests/tui_gateway/test_mcp_oauth_cancel.pyindex 0fd7918f0e3..3ffa61a7829 100644--- a/tests/tui_gateway/test_mcp_oauth_cancel.py+++ b/tests/tui_gateway/test_mcp_oauth_cancel.py@@ -141,3 +141,30 @@ def test_cancel_does_not_revoke_an_approved_flow(tmp_path, monkeypatch):"status": "approved",}assert sessions.cancel_flow("missing", "reports", home)["ok"] is False+++def test_cancelled_session_is_not_reopened_by_a_retrying_worker(tmp_path, monkeypatch):+ """A cancel is terminal-for-good: the worker's next authorization attempt must fail instead of+ silently re-minting the flow the user abandoned (and holding the per-server slot again)."""+ home = str(tmp_path)+ flow = DashboardOAuthFlow(+ "cancel-then-retry", "reports", None, home, "http://127.0.0.1:49152/callback"+ )+ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=first"))+ monkeypatch.setattr(+ sessions,+ "_sessions",+ {+ "cancel-then-retry": {+ "flow": flow,+ "server_name": "reports",+ "hermes_home": home,+ "httpd": None,+ }+ },+ )++ assert sessions.cancel_flow("cancel-then-retry", "reports", home)["ok"] is True+ with pytest.raises(RuntimeError, match="cancelled"):+ asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=second"))+ assert flow.snapshot()["status"] == "error"diff --git a/tools/mcp_dashboard_oauth.py b/tools/mcp_dashboard_oauth.pyindex 66d3a0c4cf1..d56f27fe5d9 100644--- a/tools/mcp_dashboard_oauth.py+++ b/tools/mcp_dashboard_oauth.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport asyncioimport contextvars+import loggingimport secretsimport threadingimport time@@ -14,6 +15,8 @@ from dataclasses import dataclass, fieldfrom typing import Iteratorfrom urllib.parse import parse_qs, urlparse+logger = logging.getLogger(__name__)+@contextmanagerdef contextvar_set(var: contextvars.ContextVar, value) -> Iterator[None]:@@ -48,6 +51,8 @@ class DashboardOAuthFlow:authorization_url: str | None = Noneerror: str | None = Nonetools: list[dict] = field(default_factory=list)+ # The user abandoned this flow: terminal for good, never re-minted (see publish_authorization_url).+ cancelled: bool = field(default=False, init=False)expected_state: str | None = field(default=None, init=False)_callback: tuple[str, str | None, str | None] | None = field(default=None, init=False, repr=False)_callback_error: str | None = field(default=None, init=False, repr=False)@@ -57,18 +62,41 @@ class DashboardOAuthFlow:_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)async def publish_authorization_url(self, url: str) -> None:- """Record the SDK's authorization URL (with its ``state``) for the dashboard to show."""+ """Record the SDK's authorization URL (with its ``state``) for the dashboard to show.++ A flow whose EARLIER attempt already ended is re-minted here instead of raising: the MCP server+ task inherits this handle for the whole life of the task, so ``RuntimeError: OAuth flow already+ ended`` escaped the SDK's auth flow on every retry and parked the server ("failed initial+ connection after 3 attempts") with no way back short of restarting Hermes (#114739). A flow the+ user CANCELLED stays terminal — the retrying worker must not reopen what they abandoned.+ """state = parse_qs(urlparse(url).query).get("state", [None])[0]if not state:raise ValueError("OAuth authorization URL did not include state")with self._lock:+ if self.cancelled:+ raise RuntimeError("OAuth flow already ended: cancelled by user")if self.status in {"approved", "error"}:- raise RuntimeError("OAuth flow already ended")+ self._reopen_ended_attempt()self.expected_state = stateself.authorization_url = urlself.status = "authorization_required"self._authorization_ready.set()+ def _reopen_ended_attempt(self) -> None:+ """Reset an ended attempt so the next authorization URL mints a fresh state (caller holds+ ``self._lock``). The ended attempt's URL, state and spent authorization code are dropped —+ replaying them would hand the SDK a code the provider already burned."""+ logger.info("MCP OAuth: dashboard flow %s for '%s' ended (%s); re-minting for the next attempt",+ self.flow_id, self.server_name, self.status)+ self.authorization_url = None+ self.expected_state = None+ self._callback = None+ self._callback_error = None+ self._callback_ready.clear()+ self.error = None+ self.status = "starting"+async def wait_for_authorization_url(self, timeout: float = 30.0) -> str:if not await asyncio.to_thread(self._authorization_ready.wait, timeout):raise TimeoutError("Timed out waiting for MCP authorization URL")@@ -114,10 +142,16 @@ class DashboardOAuthFlow:self.status = "approved"self.error = None- def mark_error(self, error: str) -> None:+ def mark_error(self, error: str, *, cancelled: bool = False) -> None:"""Fail the flow with *error*; the first reason wins. Waking the callback waiter makes the- worker fail too, and its follow-on ``mark_error`` must not clobber the cause the user needs."""+ worker fail too, and its follow-on ``mark_error`` must not clobber the cause the user needs.++ ``cancelled`` marks a user cancellation, which ``publish_authorization_url`` refuses to re-mint+ (unlike an ordinary failure, which a retry may reopen). It is recorded even when the flow has+ already ended: the user's "no" outranks the recorded cause and keeps the handle terminal.+ """with self._lock:+ self.cancelled = self.cancelled or cancelledif self.status in {"approved", "error"}:returnself.status = "error"diff --git a/tui_gateway/mcp_oauth_sessions.py b/tui_gateway/mcp_oauth_sessions.pyindex de2bec209aa..5adfe6e1dd8 100644--- a/tui_gateway/mcp_oauth_sessions.py+++ b/tui_gateway/mcp_oauth_sessions.py@@ -249,7 +249,7 @@ def cancel_flow(session_id: str, server_name: str, hermes_home: str) -> Dict[strif rec is None:return {"ok": False, "error_message": err}flow = rec["flow"]- flow.mark_error("OAuth cancelled by user")+ flow.mark_error("OAuth cancelled by user", cancelled=True)_shutdown_listener(rec)return {"ok": True, "status": flow.snapshot()["status"]}