The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): dashboard OAuth failures keep their first cause on every surface
teknium1a764a5442dea
diff --git a/hermes_cli/web_routers/mcp.py b/hermes_cli/web_routers/mcp.pyindex f15c27ffc69..6b52e68efb5 100644--- a/hermes_cli/web_routers/mcp.py+++ b/hermes_cli/web_routers/mcp.py@@ -212,7 +212,7 @@ async def auth_mcp_server(name: str, request: Request, profile: Optional[str] ="""Start MCP OAuth and hand the authorization URL to the dashboard browser."""from hermes_cli.mcp_config import _get_mcp_serversfrom hermes_constants import get_hermes_home- from tools.mcp_dashboard_oauth import DashboardOAuthFlow+ from tools.mcp_dashboard_oauth import DashboardOAuthFlow, exception_message_require_token(request)_gc_mcp_oauth_flows()@@ -256,7 +256,7 @@ async def auth_mcp_server(name: str, request: Request, profile: Optional[str] =try:await flow.wait_for_authorization_url(timeout=30)except Exception as exc:- flow.mark_error(str(exc))+ flow.mark_error(exception_message(exc))return flow.snapshot()diff --git a/hermes_cli/web_server_mcp.py b/hermes_cli/web_server_mcp.pyindex 3172dd6054c..02a5bf43d9f 100644--- a/hermes_cli/web_server_mcp.py+++ b/hermes_cli/web_server_mcp.py@@ -158,7 +158,9 @@ def _run_dashboard_mcp_oauth(flow, cfg: dict) -> None:reset_secret_scope(secret_token)reset_hermes_home_override(home_token)except Exception as exc:- msg = str(exc)+ from tools.mcp_dashboard_oauth import exception_message++ msg = exception_message(exc)# Providers gating RFC 7591 registration to pre-approved clients 403 the# register call before any auth URL exists; say so, not "403 Forbidden".try:diff --git a/tests/tools/test_mcp_dashboard_oauth.py b/tests/tools/test_mcp_dashboard_oauth.pyindex 8d9abba5e65..fce5edec17f 100644--- a/tests/tools/test_mcp_dashboard_oauth.py+++ b/tests/tools/test_mcp_dashboard_oauth.py@@ -118,61 +118,48 @@ def test_mcp_oauth_helpers_use_dashboard_flow_without_loopback_port():assert flow.authorization_url == "https://idp.example/authorize?state=state-4"-def test_mark_error_surfaces_real_cause_to_callback_waiter():- """A failure marked before any browser redirect (worker crash,- authorization-URL timeout, user cancel) must reach the SDK's callback- waiter, not the generic "did not include an authorization code" line."""+def _flow(flow_id: str):from tools.mcp_dashboard_oauth import DashboardOAuthFlow- flow = DashboardOAuthFlow(- flow_id="flow-err",- server_name="asana",- profile=None,- hermes_home="/tmp/hermes-test",- redirect_uri="https://agent.example/mcp/oauth/callback/flow-err",- )- flow.mark_error("403 Forbidden from the OAuth registration endpoint")+ 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}")+- assert flow.snapshot()["error"] == "403 Forbidden from the OAuth registration endpoint"- with pytest.raises(RuntimeError, match="403 Forbidden from the OAuth registration endpoint"):+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+ worker's follow-on ``mark_error`` (the waiter's own exception) must not overwrite the cause+ the dashboard/Desktop polls. A delivered callback likewise survives a late ``mark_error``."""+ flow = _flow("flow-err")+ flow.mark_error("OAuth cancelled by user")+ with pytest.raises(RuntimeError, match="OAuth cancelled by user"):asyncio.run(flow.wait_for_callback())+ flow.mark_error("OAuth authorization failed: OAuth cancelled by user")+ assert flow.snapshot()["error"] == "OAuth cancelled by user"+ delivered = _flow("flow-late")+ asyncio.run(delivered.publish_authorization_url("https://idp.example/authorize?state=s9"))+ delivered.deliver_callback(code="code-9", state="s9", error=None)+ delivered.mark_error("worker crashed after the browser redirected")+ assert asyncio.run(delivered.wait_for_callback())[:2] == ("code-9", "s9")-def test_mark_error_with_empty_message_stays_diagnosable():- """str() of a bare TimeoutError() is ""; the waiter must still report a- flow failure instead of falling through to the no-code message."""- from tools.mcp_dashboard_oauth import DashboardOAuthFlow- flow = DashboardOAuthFlow(- flow_id="flow-empty",- server_name="asana",- profile=None,- hermes_home="/tmp/hermes-test",- redirect_uri="https://agent.example/mcp/oauth/callback/flow-empty",- )- flow.mark_error("")+def test_empty_exception_text_stays_diagnosable():+ """``str()`` of a bare ``TimeoutError()``/``RuntimeError()`` is ""; the workers record the type+ name and the flow never exposes a blank cause to the waiter or the poller."""+ from tools.mcp_dashboard_oauth import exception_message++ assert exception_message(RuntimeError()) == "RuntimeError"+ assert exception_message(RuntimeError("boom")) == "boom"+ flow = _flow("flow-empty")+ flow.mark_error("")+ assert flow.snapshot()["error"]with pytest.raises(RuntimeError, match="empty error message"):asyncio.run(flow.wait_for_callback())-def test_late_mark_error_cannot_override_delivered_callback():- from tools.mcp_dashboard_oauth import DashboardOAuthFlow-- flow = DashboardOAuthFlow(- flow_id="flow-late",- server_name="reports",- profile=None,- hermes_home="/tmp/hermes-test",- redirect_uri="https://agent.example/mcp/oauth/callback/flow-late",- )- asyncio.run(flow.publish_authorization_url("https://idp.example/authorize?state=s9"))- flow.deliver_callback(code="code-9", state="s9", error=None)-- flow.mark_error("worker crashed after the browser redirected")- assert asyncio.run(flow.wait_for_callback())[:2] == ("code-9", "s9")--def test_failed_reauth_rollback_preserves_newer_oauth_state(tmp_path, monkeypatch):from tools.mcp_oauth import HermesTokenStoragediff --git a/tools/mcp_dashboard_oauth.py b/tools/mcp_dashboard_oauth.pyindex 5caea620292..66d3a0c4cf1 100644--- a/tools/mcp_dashboard_oauth.py+++ b/tools/mcp_dashboard_oauth.py@@ -29,6 +29,12 @@ def _event_field():return field(default_factory=threading.Event, init=False, repr=False)+def exception_message(exc: BaseException) -> str:+ """``str(exc)``, or the type name when it is empty (bare ``TimeoutError()``/``RuntimeError()``)+ so ``mark_error`` never records a blank cause."""+ return str(exc) or type(exc).__name__++@dataclassclass DashboardOAuthFlow:flow_id: str@@ -96,7 +102,9 @@ class DashboardOAuthFlow:if self._callback_error:raise RuntimeError(f"OAuth authorization failed: {self._callback_error}")if self._callback is None:- raise RuntimeError("OAuth callback did not include an authorization code")+ raise RuntimeError(+ f"MCP OAuth flow for '{self.server_name}' ended without an authorization code "+ f"(status={self.status}, error={self.error!r})")return self._callbackdef mark_approved(self) -> None:@@ -107,21 +115,22 @@ class DashboardOAuthFlow:self.error = Nonedef mark_error(self, error: str) -> 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."""with self._lock:- if self.status == "approved":+ if self.status in {"approved", "error"}:returnself.status = "error"- self.error = error+ self.error = error or "MCP OAuth flow failed before the callback was received (empty error message)"# The SDK's callback waiter reads _callback_error, not error — without# this copy, a failure marked before any browser redirect (worker# crash, authorization-URL timeout, user cancel) wakes the waiter# with no callback and no error, surfacing as the generic# "did not include an authorization code" RuntimeError while the- # real cause stays unread. An empty message (str() of a bare- # TimeoutError) must not fall through either. Guarded so a late- # mark_error cannot override an already delivered callback.+ # real cause stays unread. Guarded so a late mark_error cannot+ # override an already delivered callback.if self._callback is None and self._callback_error is None:- self._callback_error = error or "MCP OAuth flow failed before the callback was received (empty error message)"+ self._callback_error = self.errorself._authorization_ready.set()self._callback_ready.set()diff --git a/tui_gateway/mcp_oauth_sessions.py b/tui_gateway/mcp_oauth_sessions.pyindex f2b66c557ef..9b4ebdaf3b0 100644--- a/tui_gateway/mcp_oauth_sessions.py+++ b/tui_gateway/mcp_oauth_sessions.py@@ -133,7 +133,8 @@ def _worker(reset_secret_scope(secret_token)reset_hermes_home_override(home_token)except Exception as exc:- msg = str(exc)+ from tools.mcp_dashboard_oauth import exception_message+ msg = exception_message(exc)with suppress(Exception):from tools.mcp_oauth import humanize_oauth_registration_errormsg = humanize_oauth_registration_error(@@ -199,8 +200,9 @@ def start_flow(time.sleep(0.1)if not auth_url:raise TimeoutError("Timed out waiting for MCP authorization URL")- except Exception:- flow.mark_error("Timed out waiting for MCP authorization URL")+ except Exception as exc:+ from tools.mcp_dashboard_oauth import exception_message+ flow.mark_error(exception_message(exc)) # no-op when the worker already recorded the cause_shutdown_listener(rec)raise# ``flow`` mirrors the provider-OAuth discriminator: open a URL then poll (no user_code).