The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): a parked OAuth server no longer replays its dead refresh token on every new session
Tekniumf7b26efc2ffa
diff --git a/tests/tools/test_mcp_auth_park_discovery_nudge.py b/tests/tools/test_mcp_auth_park_discovery_nudge.pynew file mode 100644index 00000000000..fbe5da93c7c--- /dev/null+++ b/tests/tools/test_mcp_auth_park_discovery_nudge.py@@ -0,0 +1,57 @@+"""An OAuth server parked on an auth failure must not be revived by discovery passes until a+re-authorization rewrites its credentials: every nudge replayed the same rejected refresh token,+once per agent build, until the authorization server rate-limited the user's IP."""++import asyncio+import json++import pytest++[email protected]_isolate+def test_auth_parked_oauth_server_ignores_discovery_until_credentials_change(monkeypatch, tmp_path):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ from tools import mcp_tool+ from tools.mcp_oauth import HermesTokenStorage, OAuthNonInteractiveError+ from tools.mcp_tool import MCPServerTask+ from tools.mcp_tool_discovery import _select_new_servers++ cfg = {"url": "https://mcp.example.test/mcp", "auth": "oauth"}+ token_file = HermesTokenStorage("cloud")._tokens_path()+ token_file.parent.mkdir(parents=True)+ token_file.write_text(json.dumps({"access_token": "a", "token_type": "Bearer", "refresh_token": "dead"}))+ attempts = []++ class _Task(MCPServerTask):+ def _deregister_tools(self):+ self._registered_tool_names = []++ async def _run_http(self, config):+ attempts.append(config["url"])+ raise OAuthNonInteractiveError("refresh token rejected; browser authorization required")++ async def _settle():+ for _ in range(50):+ await asyncio.sleep(0)++ async def scenario():+ task = _Task("cloud")+ monkeypatch.setitem(mcp_tool._servers, "cloud", task)+ run = asyncio.ensure_future(task.run(cfg))+ await _settle()+ assert attempts and task._was_parked and not run.done()++ for _ in range(5): # five agent builds re-running discovery+ _select_new_servers({"cloud": cfg})+ await _settle()+ assert len(attempts) == 1++ token_file.write_text(json.dumps({"access_token": "b", "token_type": "Bearer", "refresh_token": "new"}))+ _select_new_servers({"cloud": cfg}) # `hermes mcp login` landed: the next pass revives it+ await _settle()+ assert len(attempts) == 2++ task._shutdown_event.set()+ await asyncio.wait_for(run, 5)++ asyncio.run(scenario())diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.pyindex 00ef6a7f9f8..9f63bfaddca 100644--- a/tools/mcp_oauth.py+++ b/tools/mcp_oauth.py@@ -648,6 +648,18 @@ class HermesTokenStorage:"""True if we have tokens on disk (may be expired)."""return self._tokens_path().exists()+ def credential_stamp(self) -> tuple:+ """``stat()`` of the token and client files: what any re-authorization rewrites. No bytes read."""+ stamp = []+ for path in (self._tokens_path(), self._client_info_path()):+ try:+ st = path.stat()+ except OSError:+ stamp.append(None)+ else:+ stamp.append((st.st_mtime_ns, st.st_size, st.st_ino))+ return tuple(stamp)+# Callback capture: the HTTP listener and the stdin paste reader share one result dict.def _authorization_code_result(code: str, state: str | None, iss: str | None = None):diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex 556b2f9dbbf..b2707acd953 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -310,6 +310,7 @@ class MCPServerTask(MCPServerRunMixin, MCPServerTransportMixin, MCPServerHealthMkeepalive/liveness live in the three mixins."""__slots__ = (+ "_auth_park","_auth_type","_config","_elicitation",@@ -391,6 +392,8 @@ class MCPServerTask(MCPServerRunMixin, MCPServerTransportMixin, MCPServerHealthM# (revoked credentials, dead endpoint) that must not run the job tool-less forever.self._park_reason: Optional[str] = Noneself._last_park_line: Optional[str] = None # last park WARNING text; identical re-parks log at DEBUG+ # (token storage, credential stamp) while parked on an OAuth failure; see _arm_auth_park.+ self._auth_park: Optional[tuple] = None# Digest of the resolved inputs the transport last connected with; a cross-profile adopter# must resolve the same digest in its own scope. None until the transport publishes it.self._resolved_identity: Optional[str] = Nonediff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.pyindex e4bb702e07f..5aa51f17063 100644--- a/tools/mcp_tool_discovery.py+++ b/tools/mcp_tool_discovery.py@@ -391,7 +391,10 @@ def _select_new_servers(servers: dict[str, dict]) -> dict[str, dict]:else:_core._parallel_safe_servers.discard(own_key)for srv in stale_cached:- _loop._signal_reconnect(srv)+ auth_park = getattr(srv, "_auth_park", None)+ # Parked on an OAuth failure and not re-authorized since: leave it to its timed self-probe.+ if auth_park is None or auth_park[0].credential_stamp() != auth_park[1]:+ _loop._signal_reconnect(srv)return new_serversdiff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.pyindex 7fff1ccf41b..10141145c39 100644--- a/tools/mcp_tool_server_run.py+++ b/tools/mcp_tool_server_run.py@@ -352,6 +352,7 @@ class MCPServerRunMixin:from agent.secret_scope import reset_secret_scopereset_secret_scope(scope_token)rebuild = True+ self._auth_park = Nonerun_transport = self._run_http if self._is_http() else self._run_stdioself._resolved_identity = None # the transport publishes the inputs it connects withif not await self._on_clean_return(await run_transport(config), budget):@@ -486,6 +487,7 @@ class MCPServerRunMixin:else "connection with a permanent error, parking without retries")self._log_park("MCP server '%s' failed initial %s (state: connecting → parked): %s: %s",self.name, detail, type(root).__name__, root)+ self._arm_auth_park(root)return await self._park_initial_failure(exc, "after permanent initial failure", budget)budget.initial_retries += 1if budget.initial_retries > _core._MAX_INITIAL_CONNECT_RETRIES:@@ -520,8 +522,20 @@ class MCPServerRunMixin:self._log_park("MCP server '%s' hit a permanent error, parking without retries; will self-probe every %ds ""(state: connected → parked): %s: %s", self.name, _core._PARKED_RETRY_INTERVAL, type(root).__name__, root)+ self._arm_auth_park(root)return await self._park_and_rearm("from parked state (permanent error)", budget)+ def _arm_auth_park(self, root: BaseException) -> None:+ """Record the OAuth credentials an auth-failure park failed with. Until a re-authorization+ rewrites them, a discovery pass has nothing new to try: every nudge replayed the same rejected+ refresh token, so a backend building agents (each one re-runs discovery while no server is+ connected) hit the authorization server once per session, enough for a rate-limit ban."""+ if self._auth_type == "oauth" and _errors._is_auth_error(root):+ from hermes_constants import get_hermes_home+ from tools.mcp_oauth import HermesTokenStorage+ storage = HermesTokenStorage(self.name, hermes_home=get_hermes_home())+ self._auth_park = (storage, storage.credential_stamp())+async def start(self, config: dict):"""Create the background Task and wait until ready (or failed)."""self._task = asyncio.ensure_future(self.run(config))diff --git a/website/docs/user-guide/features/mcp.md b/website/docs/user-guide/features/mcp.mdindex 8ca23c4d815..c42d98a39e6 100644--- a/website/docs/user-guide/features/mcp.md+++ b/website/docs/user-guide/features/mcp.md@@ -786,7 +786,7 @@ This reloads MCP servers from config and refreshes the available tool list. It iA running messaging gateway (`hermes gateway run`) also watches `config.yaml` on its own: within about a minute of you removing an `mcp_servers` entry or setting `enabled: false`, that server's connection is torn down; a newly added entry is connected. A server whose first connect failed (an unreachable host, or an OAuth server on a headless box that had no token yet) is retried automatically on its connect cooldown schedule (30 s, doubling up to 10 min) once you fix the cause. No restart or `/reload-mcp` needed for the edit to take effect.-**Expired OAuth tokens in the background.** The gateway, `/reload-mcp`, and the periodic self-probe of a parked server never open a browser — nobody is there to complete the flow. When a refresh token dies, the server parks with a warning in `gateway.log` and you re-authorize once with `hermes mcp login <server>` (or the Desktop/dashboard *Authorize* button); the parked server picks the new token up on its next probe.+**Expired OAuth tokens in the background.** The gateway, `/reload-mcp`, and the periodic self-probe of a parked server never open a browser — nobody is there to complete the flow. When a refresh token dies, the server parks with a warning in `gateway.log` and you re-authorize once with `hermes mcp login <server>` (or the Desktop/dashboard *Authorize* button); the parked server picks the new token up on its next probe. Until the token files change, starting new sessions does not retry the rejected token: only the timed self-probe does, so a dead grant cannot hammer the provider's token endpoint.### Toolsets