The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): OAuth login keeps discovered server metadata; token errors carry a redacted body excerpt
teknium1f44e73dab6f7
diff --git a/hermes_cli/mcp_config.py b/hermes_cli/mcp_config.pyindex d5955cb708a..ba9d2ca2ff6 100644--- a/hermes_cli/mcp_config.py+++ b/hermes_cli/mcp_config.py@@ -835,7 +835,13 @@ def _reauth_oauth_server(name: str, server_config: dict, *, flow: str | None = Ntry:from tools.mcp_oauth_manager import get_managerif selected_flow == "browser":- get_manager().remove(name)+ # Tokens, client registration and the CIMD refusal go; the cached authorization-server+ # metadata stays. A fresh discovery still overwrites it, but when the metadata document+ # cannot be re-fetched (WAF-fronted split-host servers) it is the only thing that keeps+ # the announced authorize URL off the SDK's `{mcp-origin}/authorize` guess (#115329).+ from tools.mcp_oauth import HermesTokenStorage+ get_manager().evict(name)+ HermesTokenStorage(name).remove(keep_metadata=True)except Exception as exc:_warning(f"Could not clear existing OAuth state: {exc}")diff --git a/tests/hermes_cli/test_mcp_config.py b/tests/hermes_cli/test_mcp_config.pyindex 2f868e50789..f509f0e23b1 100644--- a/tests/hermes_cli/test_mcp_config.py+++ b/tests/hermes_cli/test_mcp_config.py@@ -846,6 +846,38 @@ class TestMcpLogin:# OAuth round-trip — far longer than the 30s probe default.assert seen["connect_timeout"] >= 180+ def test_login_clears_tokens_but_keeps_discovered_server_metadata(self, tmp_path, capsys, monkeypatch):+ """Re-login wipes the stale grant and client registration but spares ``.meta.json``: when the+ authorization server's metadata document cannot be re-fetched (a WAF-fronted split-host+ server), the cached ``authorization_endpoint`` is what keeps the announced authorize URL off+ the SDK's ``{mcp-origin}/authorize`` guess (#115329)."""+ _seed_config(tmp_path, {+ "tv": {"url": "https://mcp.example.com/mcp", "auth": "oauth"},+ })+ token_dir = tmp_path / "mcp-tokens"+ token_dir.mkdir()+ (token_dir / "tv.json").write_text('{"access_token": "stale"}', encoding="utf-8")+ (token_dir / "tv.client.json").write_text('{"client_id": "old"}', encoding="utf-8")+ (token_dir / "tv.meta.json").write_text(+ '{"issuer": "https://www.example.com", "authorization_endpoint": "https://www.example.com/oauth/authorize",'+ ' "token_endpoint": "https://www.example.com/oauth/token"}', encoding="utf-8")+ state_at_probe = {}++ def mock_probe(name, cfg, connect_timeout=30):+ state_at_probe.update({p.name: p.exists() for p in token_dir.glob("tv*")})+ state_at_probe["meta"] = (token_dir / "tv.meta.json").exists()+ (token_dir / "tv.json").write_text('{"access_token": "fresh"}', encoding="utf-8")+ return [("a", "d")]++ monkeypatch.setattr("hermes_cli.mcp_config._probe_single_server", mock_probe)+ from hermes_cli.mcp_config import cmd_mcp_login++ cmd_mcp_login(_make_args(name="tv"))++ assert state_at_probe["meta"] is True+ assert state_at_probe.get("tv.json") is None and state_at_probe.get("tv.client.json") is None+ assert "Authenticated — 1 tool(s) available" in capsys.readouterr().out+# ---------------------------------------------------------------------------# Tests: cmd_mcp_reauth (GH#36767)diff --git a/tests/tools/test_mcp_oauth.py b/tests/tools/test_mcp_oauth.pyindex 0cde66ccf58..9c0abbaddcb 100644--- a/tests/tools/test_mcp_oauth.py+++ b/tests/tools/test_mcp_oauth.py@@ -314,6 +314,28 @@ class TestBuildOAuthAuth:assert "access-secret" not in str(exc_info.value)+ @pytest.mark.asyncio+ async def test_failed_token_exchange_carries_a_bounded_redacted_excerpt(self, tmp_path, monkeypatch):+ """A non-2xx body names the cause (WAF "Request blocked" vs ``invalid_grant``) without HTML,+ beyond 200 characters or credential-shaped spans (#115329)."""+ import httpx+ from mcp.client.auth.oauth2 import OAuthTokenError++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ _set_interactive_stdin(monkeypatch)+ provider = build_oauth_auth("supabase", "https://mcp.supabase.com/mcp")+ waf = ("<HTML><HEAD><TITLE>ERROR</TITLE></HEAD><BODY><H1>403 ERROR</H1>\n Request blocked.\n"+ "Bearer leaked-bearer-token <PRE>" + "x" * 400 + "</PRE></BODY></HTML>")++ with pytest.raises(OAuthTokenError) as exc_info:+ await provider._handle_token_response(httpx.Response(403, content=waf.encode()))++ message = str(exc_info.value)+ assert message.startswith("Token exchange failed (403): ERROR 403 ERROR Request blocked. Bearer [REDACTED]")+ assert "<" not in message and "leaked-bearer-token" not in message+ assert len(message) <= len("Token exchange failed (403): ") + 200+ assert provider.context.current_tokens is None+@pytest.mark.asyncioasync def test_token_read_error_does_not_expose_body(self, tmp_path, monkeypatch):import httpxdiff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.pyindex 5700b3624ba..4a4d578020d 100644--- a/tools/mcp_oauth.py+++ b/tools/mcp_oauth.py@@ -584,11 +584,14 @@ class HermesTokenStorage:"""True when this server has refused our metadata document before."""return self._cimd_rejected_path().exists()- def remove(self) -> None:- """Delete all stored OAuth state for this server."""+ def remove(self, *, keep_metadata: bool = False) -> None:+ """Delete all stored OAuth state for this server; ``keep_metadata`` spares ``.meta.json`` so a+ re-login can still announce the discovered ``authorization_endpoint`` when the authorization+ server's metadata document cannot be re-fetched (#115329)."""# The ``.refresh.lock`` sidecar is deliberately kept: flock is inode-bound, so unlinking it# while a peer holds the fence would let the next acquirer lock a fresh inode (two holders).- for p in (*self._state_paths(), self._cimd_rejected_path()):+ for p in (self._tokens_path(), self._client_info_path(), self._cimd_rejected_path(),+ *(() if keep_metadata else (self._meta_path(),))):p.unlink(missing_ok=True)def snapshot(self) -> dict[str, bytes]:diff --git a/tools/mcp_oauth_provider.py b/tools/mcp_oauth_provider.pyindex d3d528e05c2..a6035b36216 100644--- a/tools/mcp_oauth_provider.py+++ b/tools/mcp_oauth_provider.py@@ -9,6 +9,7 @@ modules keep their own subclass (logger name, disk-watch hooks) on top of it.from __future__ import annotationsimport logging+import refrom typing import TYPE_CHECKING, Anyif TYPE_CHECKING:@@ -376,10 +377,16 @@ class HermesProviderMixin:await self.context.storage.set_tokens(token_response)async def _handle_token_response(self, response):- """Accept any 2xx token response; never echo the body into errors."""+ """Accept any 2xx token response; a 2xx body (it carries the tokens) never reaches an error.++ A non-2xx body carries no tokens and is the only clue to WHY the exchange failed — a WAF's+ HTML "Request blocked" page vs the issuer's ``invalid_grant`` JSON (#115329) — so a short,+ tag-stripped, redacted excerpt rides along with the status."""from mcp.client.auth.oauth2 import OAuthTokenErrorif not (200 <= response.status_code < 300):- raise OAuthTokenError(f"Token exchange failed ({response.status_code})")+ from tools.mcp_tool_common import _sanitize_error+ excerpt = " ".join(re.sub(r"<[^>]+>", " ", response.text).split())[:200]+ raise OAuthTokenError(f"Token exchange failed ({response.status_code}): {_sanitize_error(excerpt)}".rstrip(": "))from httpx import HTTPErrorfrom mcp.client.auth.utils import handle_token_response_scopestry: