Skip to content

The agent that grows with you

feat(mcp): bind stored OAuth refresh tokens to their issuer

Tekniumd9e88e19e2ae
diff --git a/tests/tools/test_mcp_oauth_issuer_binding.py b/tests/tools/test_mcp_oauth_issuer_binding.py
new file mode 100644
index 00000000000..fa51e2d84c7
--- /dev/null
+++ b/tests/tools/test_mcp_oauth_issuer_binding.py
@@ -0,0 +1,81 @@
+"""Refresh tokens are bound to the authorization-server issuer that granted them.
+
+The discovered authorization server for an MCP server can change (server migration, protected-resource
+metadata edit, DNS takeover). A stored refresh token must never be sent to a different issuer.
+"""
+
+import asyncio
+import json
+from types import SimpleNamespace
+
+import pytest
+
+pytest.importorskip("mcp")
+
+from mcp.shared.auth import OAuthToken # noqa: E402
+
+from tools.mcp_oauth import HermesTokenStorage # noqa: E402
+from tools.mcp_oauth_provider import bind_issuer_from_context, enforce_refresh_token_issuer # noqa: E402
+
+
+def _token_file(tmp_path):
+ return tmp_path / "mcp-tokens" / "srv.json"
+
+
+def _stored(tmp_path, issuer):
+ payload = {"access_token": "a", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "r"}
+ if issuer is not None:
+ payload["hermes_issuer"] = issuer
+ _token_file(tmp_path).parent.mkdir(parents=True, exist_ok=True)
+ _token_file(tmp_path).write_text(json.dumps(payload))
+ storage = HermesTokenStorage("srv", hermes_home=tmp_path)
+ tokens = asyncio.run(storage.get_tokens())
+ assert tokens is not None
+ return storage, tokens
+
+
+def _context(storage, issuer, tokens=None):
+ meta = SimpleNamespace(issuer=issuer) if issuer is not None else None
+ return SimpleNamespace(storage=storage, oauth_metadata=meta, current_tokens=tokens)
+
+
+def test_issuer_mismatch_strips_refresh_token_in_memory_and_on_disk(tmp_path):
+ storage, tokens = _stored(tmp_path, "https://old.example.com")
+ ctx = _context(storage, "https://evil.example.com", tokens)
+ enforce_refresh_token_issuer(ctx)
+ assert ctx.current_tokens.refresh_token is None
+ assert ctx.current_tokens.access_token == "a" # unexpired access token stays usable
+ on_disk = json.loads(_token_file(tmp_path).read_text())
+ assert "refresh_token" not in on_disk and on_disk["access_token"] == "a"
+
+
+def test_matching_issuer_keeps_refresh_token_even_with_trailing_slash(tmp_path):
+ storage, tokens = _stored(tmp_path, "https://as.example.com/")
+ ctx = _context(storage, "https://as.example.com", tokens)
+ enforce_refresh_token_issuer(ctx)
+ assert ctx.current_tokens.refresh_token == "r"
+ assert json.loads(_token_file(tmp_path).read_text())["refresh_token"] == "r"
+
+
+def test_legacy_file_without_issuer_adopts_current_issuer_once(tmp_path):
+ storage, tokens = _stored(tmp_path, None)
+ enforce_refresh_token_issuer(_context(storage, "https://as.example.com", tokens))
+ assert tokens.refresh_token == "r"
+ assert json.loads(_token_file(tmp_path).read_text())["hermes_issuer"] == "https://as.example.com"
+ # Now bound: a later issuer change is rejected.
+ storage2 = HermesTokenStorage("srv", hermes_home=tmp_path)
+ tokens2 = asyncio.run(storage2.get_tokens())
+ assert tokens2 is not None
+ enforce_refresh_token_issuer(_context(storage2, "https://evil.example.com", tokens2))
+ assert tokens2.refresh_token is None
+
+
+def test_set_tokens_stamps_bound_issuer_and_get_tokens_keeps_it_out_of_the_sdk_model(tmp_path):
+ storage = HermesTokenStorage("srv", hermes_home=tmp_path)
+ bind_issuer_from_context(_context(storage, "https://as.example.com"))
+ asyncio.run(storage.set_tokens(OAuthToken(access_token="a", token_type="Bearer", expires_in=3600, refresh_token="r")))
+ assert json.loads(_token_file(tmp_path).read_text())["hermes_issuer"] == "https://as.example.com"
+ fresh = HermesTokenStorage("srv", hermes_home=tmp_path)
+ tokens = asyncio.run(fresh.get_tokens())
+ assert fresh.loaded_issuer == "https://as.example.com"
+ assert not hasattr(tokens, "hermes_issuer") # never leaks into the wire model
diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.py
index 6f0b5ed34c5..cfe5cda6f4d 100644
--- a/tools/mcp_oauth.py
+++ b/tools/mcp_oauth.py
@@ -275,6 +275,11 @@ class HermesTokenStorage:
def __init__(self, server_name: str, *, hermes_home: str | Path | None = None):
self._server_name = _safe_filename(server_name)
self._hermes_home = Path(hermes_home) if hermes_home is not None else None
+ # Issuer binding: ``loaded_issuer`` is what the token file on disk recorded (the authorization
+ # server that granted the stored refresh token); ``_bound_issuer`` is stamped onto the next
+ # ``set_tokens`` write. See ``tools.mcp_oauth_provider.enforce_refresh_token_issuer``.
+ self.loaded_issuer: str | None = None
+ self._bound_issuer: str | None = None
def _path(self, suffix: str) -> Path:
return _get_token_dir(self._hermes_home) / f"{self._server_name}{suffix}"
@@ -326,8 +331,14 @@ class HermesTokenStorage:
implied_expiry = self._tokens_path().stat().st_mtime + int(data["expires_in"])
data["expires_in"] = int(max(implied_expiry - time.time(), 0))
+ def _fixup_loaded_tokens(self, data: dict) -> None:
+ # ``hermes_issuer`` is Hermes bookkeeping, not an SDK OAuthToken field: pop before validation.
+ self.loaded_issuer = data.pop("hermes_issuer", None)
+ self._rebase_expires_in(data)
+
async def get_tokens(self) -> "OAuthToken | None":
- return self._load_model(self._tokens_path(), "OAuthToken", "tokens", self._rebase_expires_in)
+ self.loaded_issuer = None
+ return self._load_model(self._tokens_path(), "OAuthToken", "tokens", self._fixup_loaded_tokens)
async def set_tokens(self, tokens: "OAuthToken") -> None:
payload = _model_json(tokens)
@@ -335,9 +346,48 @@ class HermesTokenStorage:
if payload.get("expires_in") is not None:
with contextlib.suppress(TypeError, ValueError): # mock tokens / odd shapes: skip, don't fail persistence
payload["expires_at"] = time.time() + int(payload["expires_in"])
+ if self._bound_issuer: # which authorization server granted these tokens (never sent on the wire)
+ payload["hermes_issuer"] = self._bound_issuer
+ self.loaded_issuer = self._bound_issuer
_write_json(self._tokens_path(), payload)
logger.debug("OAuth tokens saved for %s", self._server_name)
+ def bind_issuer(self, issuer: str | None) -> None:
+ """Set the authorization-server issuer stamped on future token writes."""
+ self._bound_issuer = str(issuer) if issuer else None
+
+ def stamp_issuer(self, issuer: str) -> None:
+ """Backfill ``hermes_issuer`` onto a pre-binding token file: adopt the currently discovered
+ issuer once instead of forcing a re-login, so the *next* read is protected."""
+ data = _read_json(self._tokens_path())
+ if data is None or data.get("hermes_issuer"):
+ return
+ data["hermes_issuer"] = str(issuer)
+ try:
+ _write_json(self._tokens_path(), data)
+ except OSError as exc: # non-fatal — worst case we stamp next time
+ logger.debug("Could not stamp issuer on tokens for %s: %s", self._server_name, exc)
+ return
+ self.loaded_issuer = str(issuer)
+
+ def strip_refresh_token(self) -> None:
+ """Drop the refresh token (and its issuer record) from disk, keeping the access token: the
+ unexpired access token may still be used, but a refresh token must never go to a different
+ issuer than the one that granted it."""
+ data = _read_json(self._tokens_path())
+ if data is None or not data.get("refresh_token"):
+ return
+ data.pop("refresh_token", None)
+ data.pop("hermes_issuer", None)
+ self.loaded_issuer = None
+ try:
+ _write_json(self._tokens_path(), data)
+ except OSError as exc:
+ logger.warning("Could not strip refresh token for %s: %s", self._server_name, exc)
+ return
+ logger.info("Removed issuer-mismatched refresh token for %s (re-authorization will be required "
+ "when the access token expires)", self._server_name)
+
@staticmethod
def _coerce_secret_auth_method(data: dict) -> bool:
"""Set ``client_secret_post`` when a secret is present but no method is: some DCR providers
diff --git a/tools/mcp_oauth_manager.py b/tools/mcp_oauth_manager.py
index e443d3b1938..f88ab41a5e6 100644
--- a/tools/mcp_oauth_manager.py
+++ b/tools/mcp_oauth_manager.py
@@ -78,22 +78,18 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
``expires_at``) makes the SDK refresh first. Metadata is restored from disk, else discovered
pre-flight when we hold tokens but no metadata: otherwise ``_refresh_token`` guesses
``{server_url}/token`` (wrong for split-origin providers), 404s, and we fall to browser reauth."""
- await super()._initialize()
+ await super()._initialize() # HermesProviderMixin: restores metadata from disk, enforces issuer binding
tokens = self.context.current_tokens
if tokens is not None and tokens.expires_in is not None:
self.context.update_token_expiry(tokens)
- storage = self._hermes_storage()
- if storage is not None and self.context.oauth_metadata is None:
- meta = storage.load_oauth_metadata()
- if meta is not None:
- self.context.oauth_metadata = meta
- logger.debug("MCP OAuth '%s': restored metadata from disk (token_endpoint=%s)",
- self._hermes_server_name, meta.token_endpoint)
if tokens is not None and self.context.oauth_metadata is None:
try:
await self._prefetch_oauth_metadata()
except Exception as exc: # pragma: no cover — the SDK's 401-branch discovery runs next request
self._log_nonfatal("pre-flight metadata discovery", exc)
+ else:
+ from tools.mcp_oauth_provider import enforce_refresh_token_issuer
+ enforce_refresh_token_issuer(self.context) # metadata (issuer) only just became known
async def _prefetch_oauth_metadata(self) -> None:
"""Fetch PRM + ASM from the well-known endpoints before the first request, via the SDK's own URL
diff --git a/tools/mcp_oauth_provider.py b/tools/mcp_oauth_provider.py
index 7df4f980ec9..c51a9cb4846 100644
--- a/tools/mcp_oauth_provider.py
+++ b/tools/mcp_oauth_provider.py
@@ -74,9 +74,23 @@ class HermesProviderMixin:
self._coerce_client_secret_post()
return self._prepare_token_request(await super()._refresh_token())
+ async def _initialize(self) -> None:
+ """Load stored state, restore persisted server metadata when the SDK has none (so the issuer
+ check and any refresh see the discovered ``issuer``/``token_endpoint`` instead of SDK guesses),
+ then enforce refresh-token issuer binding."""
+ await super()._initialize()
+ storage = self.context.storage
+ from tools.mcp_oauth import HermesTokenStorage
+ if isinstance(storage, HermesTokenStorage) and self.context.oauth_metadata is None:
+ meta = storage.load_oauth_metadata()
+ if meta is not None:
+ self.context.oauth_metadata = meta
+ enforce_refresh_token_issuer(self.context)
+
async def _store_tokens(self, token_response) -> None:
self.context.current_tokens = token_response
self.context.update_token_expiry(token_response)
+ bind_issuer_from_context(self.context)
await self.context.storage.set_tokens(token_response)
async def _handle_token_response(self, response):
@@ -121,6 +135,51 @@ class HermesProviderMixin:
return True
+def _metadata_issuer(context: Any) -> str | None:
+ """Discovered authorization-server issuer from the SDK auth context, without trailing slash."""
+ meta = getattr(context, "oauth_metadata", None)
+ issuer = getattr(meta, "issuer", None) if meta is not None else None
+ return (str(issuer).rstrip("/") or None) if issuer else None
+
+
+def bind_issuer_from_context(context: Any) -> None:
+ """Record the discovered issuer so the next ``storage.set_tokens`` (exchange or refresh) carries
+ it. No-op when metadata is not discovered yet or storage is not Hermes'."""
+ from tools.mcp_oauth import HermesTokenStorage
+ storage = getattr(context, "storage", None)
+ issuer = _metadata_issuer(context)
+ if isinstance(storage, HermesTokenStorage) and issuer:
+ storage.bind_issuer(issuer)
+
+
+def enforce_refresh_token_issuer(context: Any) -> None:
+ """Refuse to reuse a refresh token minted by a different issuer.
+
+ The authorization server discovered for an MCP server can change (DNS takeover, protected-resource
+ metadata edit, server migration); sending the stored refresh token to the new issuer hands it a
+ long-lived credential. On mismatch the refresh token is stripped (memory + disk) while an unexpired
+ access token stays usable; full re-authorization happens at expiry. Token files predating the field
+ adopt the current issuer once rather than forcing a re-login. Runs after ``_initialize`` restored
+ tokens + metadata, before the SDK's ``can_refresh_token()`` decision."""
+ from tools.mcp_oauth import HermesTokenStorage
+ storage = getattr(context, "storage", None)
+ tokens = getattr(context, "current_tokens", None)
+ if not isinstance(storage, HermesTokenStorage) or tokens is None or not getattr(tokens, "refresh_token", None):
+ return
+ current = _metadata_issuer(context)
+ if current is None: # not discovered yet; the SDK's 401-branch discovery + _store_tokens stamp it later
+ return
+ stored = (storage.loaded_issuer or "").rstrip("/") or None
+ if stored is None:
+ storage.stamp_issuer(current)
+ return
+ if stored != current:
+ logger.warning("MCP OAuth: authorization server issuer changed (%s -> %s); dropping the stored "
+ "refresh token rather than sending it to a different issuer", stored, current)
+ storage.strip_refresh_token()
+ tokens.refresh_token = None
+
+
def prepare_oauth_config(server_name: str, server_url: str, oauth_config: dict | None) -> tuple[dict, "HermesTokenStorage"]:
"""Copy the ``oauth:`` block, apply provider defaults, open its token storage. The copy
matters: later steps record ``_resolved_port`` / ``_cimd_url`` in the dict, which must
diff --git a/website/docs/user-guide/features/mcp.md b/website/docs/user-guide/features/mcp.md
index e33d42b98bf..6dd9abc6a70 100644
--- a/website/docs/user-guide/features/mcp.md
+++ b/website/docs/user-guide/features/mcp.md
@@ -271,6 +271,8 @@ mcp_servers:
On first connect, Hermes prints an authorize URL, opens your browser when possible, and waits for the OAuth callback on a local loopback port. Tokens are cached at `~/.hermes/mcp-tokens/<server>.json` with 0o600 perms; subsequent runs reuse them silently until refresh fails.
+Refresh tokens are bound to the authorization server that granted them: Hermes records the discovered issuer alongside the cached tokens and, if a server's advertised authorization server ever changes (server migration, metadata edit, or hijack), the stored refresh token is dropped instead of being sent to the new issuer. The current access token keeps working until it expires, then a normal re-authorization runs against the new issuer.
+
**Remote / headless hosts.** When Hermes runs on a different machine than your browser, the loopback callback can't reach your laptop. Ways to complete the flow:
- **Hermes Desktop (automatic):** when you run the OAuth sign-in from the Desktop app's MCP setup UI against a remote backend, Desktop hosts the callback listener on *your* machine and relays the authorization back to the gateway automatically — no tunnel, paste, or proxy needed. Requires both the Desktop app and the backend to be up to date.