The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
MCP CIMD auth
rob-maron0b588cb3a42a
diff --git a/scripts/ci/classify_changes.py b/scripts/ci/classify_changes.pyindex 95a9bb13da3..3a3e2684235 100644--- a/scripts/ci/classify_changes.py+++ b/scripts/ci/classify_changes.py@@ -42,6 +42,9 @@ must never skip one a change could break:only the flake reads them, so they skip the Python lanes and run ``nix``alone. ``pyproject.toml`` and ``uv.lock`` are flake inputs too, but thepackaging tests read them, so they keep every Python lane.+* ``website/static/oauth/`` is python-relevant too: it publishes the OAuth+ Client ID Metadata Document that ``tests/tools/test_mcp_cimd.py`` checks+ against the pinned callback ports in ``tools/mcp_oauth.py``."""from __future__ import annotations@@ -58,6 +61,12 @@ _NIX_FILES = {"flake.nix", "flake.lock"} # base nix files_SITE = ("website/", "skills/", "optional-skills/") # docs site + skill pages# Prose/frontend trees that can't touch Python. skills/ is excluded on purpose._PY_SKIP = ("docs/", "website/") + _FRONTEND+# Published artifacts that live under website/ but that Python asserts about.+# The OAuth Client ID Metadata Document is cross-checked against the pinned+# callback ports in tools/mcp_oauth.py, so editing it alone must still run the+# Python lane — otherwise dropping a redirect URI goes green here and breaks+# every CIMD login on main.+_PY_RELEVANT_SITE = ("website/static/oauth/",)# CI-sensitive files: eslint config, workflow files, composite actions.# Changes here can influence what code the autofix job executes and pushes to@@ -96,6 +105,8 @@ def _is_nix(p: str) -> bool:def _py_irrelevant(p: str) -> bool:+ if p.startswith(_PY_RELEVANT_SITE):+ return Falsereturn (_is_docs(p)or p in _ROOT_NPMdiff --git a/tests/ci/test_classify_changes.py b/tests/ci/test_classify_changes.pyindex 7c4bd0415e9..3a33f576f7e 100644--- a/tests/ci/test_classify_changes.py+++ b/tests/ci/test_classify_changes.py@@ -82,6 +82,12 @@ CASES = {# otherwise shows up as a blocking "uv.lock out of sync" red X."docs → no uv_lock": (["website/docs/user-guide/profiles.md"], _lanes(site=True)),"frontend → no uv_lock": (["apps/desktop/src/store/profile.ts"], _lanes(frontend=True)),+ # The published CIMD document is asserted about by the Python suite, so a+ # lone edit there must not skip the lane that would catch a bad edit.+ "cimd document → python + site": (+ ["website/static/oauth/client-metadata.json"],+ _lanes(python=True, site=True),+ ),# SKILL.md reads like docs, but the skill-doc tests read skills/, so a# skill edit must still run Python."skill md → python + site": (["skills/github/SKILL.md"], _lanes(python=True, site=True)),diff --git a/tests/tools/test_mcp_cimd.py b/tests/tools/test_mcp_cimd.pynew file mode 100644index 00000000000..5964894d2b7--- /dev/null+++ b/tests/tools/test_mcp_cimd.py@@ -0,0 +1,646 @@+"""Tests for CIMD (Client ID Metadata Document) support in MCP OAuth.++Under CIMD the ``client_id`` is the HTTPS URL of a document Hermes publishes,+which the authorization server fetches to learn our redirect URIs. The spec+requires an exact string match between the redirect URI in the authorization+request and one listed in that document+(draft-ietf-oauth-client-id-metadata-document section 4.2), so most of what+follows guards the two halves staying consistent: the published document, and+the conditions under which Hermes is allowed to present it.++Port mechanics run against a private range rather than the real one. The+production range is bound for real by ``_pick_cimd_port``, and test files run+as concurrent subprocesses, so sharing it across files would make whichever+test lost the race fail on a port another file legitimately held.+"""++import asyncio+import json+import socket+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++pytest.importorskip(+ "mcp.client.auth.oauth2",+ reason="MCP SDK 1.26.0+ required for OAuth support",+)++from tools.mcp_oauth import ( # noqa: E402 — after the SDK availability gate+ HermesTokenStorage,+ _CIMD_CLIENT_METADATA_URL,+ _CIMD_PORTS,+ _CIMD_REDIRECT_HOSTS,+ _build_client_metadata,+ _configure_callback_port,+ _is_valid_cimd_url,+ _maybe_use_cimd,+)++_DOCUMENT_PATH = (+ Path(__file__).resolve().parents[2]+ / "website" / "static" / "oauth" / "client-metadata.json"+)+++def _document() -> dict:+ return json.loads(_DOCUMENT_PATH.read_text())+++def _set_interactive_stdin(monkeypatch, *, is_tty: bool = True) -> None:+ mock_stdin = MagicMock()+ mock_stdin.isatty.return_value = is_tty+ monkeypatch.setattr("tools.mcp_oauth.sys.stdin", mock_stdin)++[email protected](autouse=True)+def clean_port_state():+ """Give each test the port state of a freshly started process.++ Pinned-port assignments accumulate for the life of the process, and both+ ``_pick_cimd_port`` and ``_reserve_callback_port`` hold their socket until+ ``_wait_for_callback`` adopts it — which these tests stop short of.+ """+ import tools.mcp_oauth as mod++ mod._assigned_cimd_ports.clear()+ yield+ mod._assigned_cimd_ports.clear()+ for port in list(mod._reserved_sockets):+ sock = mod._reserved_sockets.pop(port, None)+ if sock is not None:+ sock.close()+++def private_ports(monkeypatch):+ """Swap the pinned range for ports no other test file competes for."""+ import tools.mcp_oauth as mod++ ports = (28890, 28891, 28892)+ monkeypatch.setattr(mod, "_CIMD_PORTS", ports)+ return ports+++# ---------------------------------------------------------------------------+# The published document and the code must agree+# ---------------------------------------------------------------------------+++def test_document_client_id_is_the_url_hermes_sends():+ """A CIMD document is only valid when its client_id is its own URL."""+ assert _document()["client_id"] == _CIMD_CLIENT_METADATA_URL+++def test_document_declares_every_callback_hermes_can_build(tmp_path, monkeypatch):+ """Every loopback URI a CIMD flow could produce must be registered.++ Exact string matching means one missing entry is a hard auth failure on+ whichever port the OS happens to hand out that day. Built through the real+ ``_build_client_metadata`` so pydantic's URL serialization — not an+ f-string that merely resembles it — is what gets compared.+ """+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ declared = set(_document()["redirect_uris"])++ for host in _CIMD_REDIRECT_HOSTS:+ for port in _CIMD_PORTS:+ cfg = {"redirect_host": host, "_resolved_port": port}+ uri = str(_build_client_metadata(cfg).redirect_uris[0])+ assert uri in declared, f"{uri} is not registered in the document"+++def test_document_url_passes_the_sdk_validator():+ """The SDK's constructor rejects a URL that fails this check."""+ from mcp.client.auth.utils import is_valid_client_metadata_url++ assert is_valid_client_metadata_url(_CIMD_CLIENT_METADATA_URL)+++def test_document_advertises_a_public_native_client():+ """Loopback redirects need application_type=native (SEP-837), and CIMD+ carries no secret, so the client must be public."""+ doc = _document()+ assert doc["application_type"] == "native"+ assert doc["token_endpoint_auth_method"] == "none"+ assert "authorization_code" in doc["grant_types"]+ assert "refresh_token" in doc["grant_types"]+++def test_document_carries_no_shared_secret():+ """Draft section 4.1 forbids secret material in the document."""+ doc = _document()+ assert "client_secret" not in doc+ assert "client_secret_expires_at" not in doc+++def test_default_document_url_is_a_valid_client_identifier():+ """Section 3 constrains the URL beyond the SDK's https + path check."""+ assert _is_valid_cimd_url(_CIMD_CLIENT_METADATA_URL)++[email protected]("url", [+ pytest.param("http://example.com/cimd.json", id="not-https"),+ pytest.param("https://example.com/", id="root-path"),+ pytest.param("https://example.com/cimd.json#frag", id="fragment"),+ pytest.param("https://user:[email protected]/cimd.json", id="userinfo"),+ pytest.param("https://example.com/./cimd.json", id="dot-segment"),+ pytest.param("https://example.com/../cimd.json", id="double-dot-segment"),+])+def test_client_identifier_url_requirements_are_enforced(url):+ """Rejecting locally beats an opaque invalid-client page mid-flow."""+ assert not _is_valid_cimd_url(url)+++def test_generated_redirect_uri_is_registered_in_the_document(tmp_path, monkeypatch):+ """End to end on the real range: the URI the SDK will actually send is+ one the authorization server accepts.++ The only test that runs the whole chain on production constants, so it+ binds a real pinned port. Another test file mid-flight can legitimately+ be holding all of them; the invariant itself is covered port-by-port,+ without binding, by the document tests above.+ """+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ cfg: dict = {}++ _configure_callback_port(cfg, HermesTokenStorage("srv"))+ if "_cimd_url" not in cfg:+ pytest.skip("every pinned CIMD port is held by another process")+ metadata = _build_client_metadata(cfg)++ assert cfg["_cimd_url"] == _CIMD_CLIENT_METADATA_URL+ assert cfg["_resolved_port"] in _CIMD_PORTS+ assert str(metadata.redirect_uris[0]) in set(_document()["redirect_uris"])+++# ---------------------------------------------------------------------------+# Eligibility+# ---------------------------------------------------------------------------+++def test_eligible_flow_gets_a_pinned_port(tmp_path, monkeypatch, private_ports):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ result = _maybe_use_cimd({}, HermesTokenStorage("srv"))++ assert result is not None+ url, port = result+ assert url == _CIMD_CLIENT_METADATA_URL+ assert port in private_ports+++def test_pinned_port_is_held_until_the_callback_adopts_it(+ tmp_path, monkeypatch, private_ports+):+ """A fixed port is as stealable as an ephemeral one in the minutes+ between selection and the browser redirect (#22161), so the socket stays+ bound rather than being probed and released."""+ import tools.mcp_oauth as mod++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ result = _maybe_use_cimd({}, HermesTokenStorage("srv"))+ assert result is not None+ port = result[1]++ assert port in mod._reserved_sockets+ thief = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ with pytest.raises(OSError):+ thief.bind(("127.0.0.1", port))+ thief.close()+++def test_concurrent_servers_get_different_pinned_ports(+ tmp_path, monkeypatch, private_ports+):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ ports = {+ _maybe_use_cimd({}, HermesTokenStorage(f"srv-{i}"))[1]+ for i in range(len(private_ports))+ }++ assert ports == set(private_ports)+++def test_occupied_port_moves_to_the_next_in_the_range(+ tmp_path, monkeypatch, private_ports+):+ """Another profile mid-login holds a port; we take a different one."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ squatter = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ squatter.bind(("127.0.0.1", private_ports[0]))+ except OSError:+ squatter.close()+ pytest.skip(f"could not occupy port {private_ports[0]}")++ try:+ result = _maybe_use_cimd({}, HermesTokenStorage("srv"))+ finally:+ squatter.close()++ assert result is not None+ assert result[1] in private_ports[1:]+++def test_self_hosted_document_url_overrides_the_default(+ tmp_path, monkeypatch, private_ports+):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ cfg = {"client_metadata_url": "https://example.com/my-cimd.json"}++ result = _maybe_use_cimd(cfg, HermesTokenStorage("srv"))++ assert result is not None+ assert result[0] == "https://example.com/my-cimd.json"++[email protected]("cfg", [+ pytest.param({"cimd": False}, id="explicitly-disabled"),+ pytest.param({"client_id": "preregistered"}, id="preregistered-client-id"),+ pytest.param({"client_secret": "shh"}, id="confidential-client"),+ pytest.param({"client_name": "Claude Code"}, id="pinned-client-name"),+ pytest.param(+ {"token_endpoint_auth_method": "client_secret_post"}, id="secret-auth-method"+ ),+ pytest.param({"redirect_port": 49399}, id="pinned-redirect-port"),+ pytest.param(+ {"redirect_uri": "https://proxy.example/callback"}, id="proxied-redirect-uri"+ ),+ pytest.param({"redirect_host": "example.test"}, id="non-loopback-redirect-host"),+ pytest.param(+ {"client_metadata_url": "http://insecure.example/cimd.json"}, id="http-document"+ ),+ pytest.param(+ {"client_metadata_url": "https://example.com/"}, id="root-path-document"+ ),+])+def test_config_that_conflicts_with_the_document_falls_back_to_dcr(+ cfg, tmp_path, monkeypatch, private_ports+):+ """Each of these asks for an identity or a callback the document can't+ present."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ assert _maybe_use_cimd(dict(cfg), HermesTokenStorage("srv")) is None+++def test_dashboard_flow_falls_back_to_dcr(tmp_path, monkeypatch, private_ports):+ """The dashboard redirects to its own public URL, which no static+ document can declare — it is per-deployment."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ from tools.mcp_dashboard_oauth import DashboardOAuthFlow, dashboard_oauth_flow++ flow = DashboardOAuthFlow(+ flow_id="flow-1",+ server_name="srv",+ profile=None,+ hermes_home=str(tmp_path),+ redirect_uri="https://agent.example/api/mcp/oauth/callback/srv",+ )++ cfg: dict = {}+ with dashboard_oauth_flow(flow):+ _configure_callback_port(cfg, HermesTokenStorage("srv"))++ assert "_cimd_url" not in cfg+ assert cfg["redirect_uri"] == flow.redirect_uri+++def test_existing_registration_falls_back_to_dcr(tmp_path, monkeypatch, private_ports):+ """A stored client_id is bound to the redirect URI it registered with;+ switching to CIMD now would invalidate it."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ storage = HermesTokenStorage("srv")+ storage._client_info_path().parent.mkdir(parents=True, exist_ok=True)+ storage._client_info_path().write_text('{"client_id": "dcr-issued"}')++ assert _maybe_use_cimd({}, storage) is None+++def test_exhausted_port_range_falls_back_to_dcr(tmp_path, monkeypatch, private_ports):+ """With every pinned port held elsewhere, the flow reverts to an+ ephemeral port and no CIMD client_id."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ squatters = []+ try:+ for port in private_ports:+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ sock.bind(("127.0.0.1", port))+ squatters.append(sock)+ except OSError:+ for sock in squatters:+ sock.close()+ pytest.skip("could not occupy the full pinned CIMD port range")++ try:+ cfg: dict = {}+ port = _configure_callback_port(cfg, HermesTokenStorage("srv"))+ finally:+ for sock in squatters:+ sock.close()++ assert "_cimd_url" not in cfg+ assert port not in private_ports+ assert cfg["_resolved_port"] == port+++def test_more_servers_than_pinned_ports_all_get_cimd(+ tmp_path, monkeypatch, private_ports+):+ """Providers are built per configured server, well before any browser+ flow runs, so the size of the port range must not cap how many servers+ can use CIMD."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ results = [+ _maybe_use_cimd({}, HermesTokenStorage(f"srv-{i}"))+ for i in range(len(private_ports) + 3)+ ]++ assert all(r is not None for r in results)+ assert {r[0] for r in results} == {_CIMD_CLIENT_METADATA_URL}+++# ---------------------------------------------------------------------------+# Only pin a port for servers that might actually want a document+# ---------------------------------------------------------------------------+++def _cache_server_metadata(storage, *, supports_cimd):+ from mcp.shared.auth import OAuthMetadata++ storage.save_oauth_metadata(OAuthMetadata.model_validate({+ "issuer": "https://idp.example.com",+ "authorization_endpoint": "https://idp.example.com/authorize",+ "token_endpoint": "https://idp.example.com/token",+ "response_types_supported": ["code"],+ "client_id_metadata_document_supported": supports_cimd,+ }))++[email protected]("supports_cimd, expect_pinned", [+ pytest.param(True, True, id="server-advertises-cimd"),+ pytest.param(False, False, id="server-does-not"),+])+def test_cached_metadata_decides_whether_to_pin(+ supports_cimd, expect_pinned, tmp_path, monkeypatch, private_ports+):+ """The SDK only learns whether a server does CIMD during its 401 branch,+ long after Hermes fixes the redirect URI. Metadata cached by an earlier+ connection closes that gap, so a known DCR-only server keeps the reserved+ ephemeral port it has always used instead of a guessable fixed one."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ storage = HermesTokenStorage("srv")+ _cache_server_metadata(storage, supports_cimd=supports_cimd)++ cfg: dict = {}+ port = _configure_callback_port(cfg, storage)++ assert (cfg.get("_cimd_url") is not None) is expect_pinned+ assert (port in private_ports) is expect_pinned+++def test_unknown_server_still_gets_a_document(tmp_path, monkeypatch, private_ports):+ """No cached metadata means a first-ever connect, where guessing CIMD is+ the only way to ever use it."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ cfg: dict = {}+ _configure_callback_port(cfg, HermesTokenStorage("srv"))++ assert cfg["_cimd_url"] == _CIMD_CLIENT_METADATA_URL+++def test_cached_pinned_port_is_not_handed_to_a_sibling_server(+ tmp_path, monkeypatch, private_ports+):+ """An earlier CIMD login leaves its pinned port in the registration on+ disk. Restoring it must also claim it, or the next server picks the same+ one and the two flows fight over one listener."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ settled = HermesTokenStorage("settled")+ settled._client_info_path().parent.mkdir(parents=True, exist_ok=True)+ settled._client_info_path().write_text(json.dumps({+ "client_id": _CIMD_CLIENT_METADATA_URL,+ "redirect_uris": [f"http://127.0.0.1:{private_ports[0]}/callback"],+ }))++ restored = _configure_callback_port({}, settled)+ fresh = _maybe_use_cimd({}, HermesTokenStorage("fresh"))++ assert restored == private_ports[0]+ assert fresh is not None+ assert fresh[1] != private_ports[0]+++# ---------------------------------------------------------------------------+# Provider wiring+# ---------------------------------------------------------------------------+++def test_build_oauth_auth_forwards_the_document_url(+ tmp_path, monkeypatch, private_ports+):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ _set_interactive_stdin(monkeypatch)+ from tools.mcp_oauth import build_oauth_auth++ provider = build_oauth_auth("srv", "https://mcp.example.com/mcp", {})++ assert provider.context.client_metadata_url == _CIMD_CLIENT_METADATA_URL+++def test_build_oauth_auth_omits_the_url_when_disabled(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ _set_interactive_stdin(monkeypatch)+ from tools.mcp_oauth import build_oauth_auth++ provider = build_oauth_auth("srv", "https://mcp.example.com/mcp", {"cimd": False})++ assert provider.context.client_metadata_url is None+++def test_dcr_flow_passes_no_cimd_keyword_at_all():+ """An SDK predating CIMD rejects the keyword outright, so a DCR flow must+ not carry it — otherwise one unsupported argument breaks every login."""+ from tools.mcp_oauth import cimd_provider_kwargs++ assert cimd_provider_kwargs({}) == {}+ assert cimd_provider_kwargs({"_cimd_url": "https://x.example/c.json"}) == {+ "client_metadata_url": "https://x.example/c.json"+ }++[email protected]("advertised, expect_cimd", [+ pytest.param(True, True, id="server-supports-cimd"),+ pytest.param(False, False, id="server-does-not"),+ pytest.param(None, False, id="server-silent"),+])+def test_sdk_chooses_cimd_only_when_the_server_advertises_it(+ advertised, expect_cimd, tmp_path, monkeypatch, private_ports+):+ """Closes the loop on the handoff: feed what Hermes configured into the+ SDK's own branch condition rather than asserting on our side of it."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ _set_interactive_stdin(monkeypatch)+ from mcp.client.auth.utils import should_use_client_metadata_url+ from tools.mcp_oauth import build_oauth_auth++ provider = build_oauth_auth("srv", "https://mcp.example.com/mcp", {})+ server_metadata = SimpleNamespace(client_id_metadata_document_supported=advertised)++ chosen = should_use_client_metadata_url(+ server_metadata, provider.context.client_metadata_url+ )++ assert chosen is expect_cimd+++def test_manager_forwards_the_document_url(tmp_path, monkeypatch, private_ports):+ """The manager is the path live MCP connections actually take."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ _set_interactive_stdin(monkeypatch)+ from tools.mcp_oauth_manager import MCPOAuthManager, reset_manager_for_tests++ reset_manager_for_tests()+ provider = MCPOAuthManager().get_or_build_provider(+ "srv", "https://mcp.example.com/mcp", {}+ )++ assert provider.context.client_metadata_url == _CIMD_CLIENT_METADATA_URL+++# ---------------------------------------------------------------------------+# Rejection fallback+# ---------------------------------------------------------------------------+++def _fake_response(status, url, body):+ """A minimal stand-in for the httpx.Response the SDK feeds our bridge."""+ resp = MagicMock()+ resp.status_code = status+ resp.request = SimpleNamespace(url=url)++ async def _aread():+ return body++ resp.aread = _aread+ return resp+++def _provider_rejected_at_token_endpoint(tmp_path, monkeypatch, client_id):+ from tools.mcp_oauth_manager import MCPOAuthManager, reset_manager_for_tests++ reset_manager_for_tests()+ _set_interactive_stdin(monkeypatch)+ token_endpoint = "https://idp.example.com/oauth/token"++ provider = MCPOAuthManager().get_or_build_provider(+ "srv", "https://mcp.example.com", {}+ )+ provider.context.oauth_metadata = SimpleNamespace(token_endpoint=token_endpoint)+ provider.context.client_info = SimpleNamespace(client_id=client_id)+ provider._initialized = True++ asyncio.run(provider._maybe_flag_poisoned_client(+ _fake_response(400, token_endpoint, b'{"error":"invalid_client"}')+ ))+ return provider+++def test_rejected_document_stops_being_presented(tmp_path, monkeypatch, private_ports):+ """A server that fetched our document and refused it would loop if we+ kept sending the same client_id, so the retry drops to DCR."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ provider = _provider_rejected_at_token_endpoint(+ tmp_path, monkeypatch, _CIMD_CLIENT_METADATA_URL+ )++ assert provider.context.client_metadata_url is None+ assert provider.context.client_info is None+ assert provider._initialized is False+++def test_rejected_document_stays_rejected_after_a_restart(+ tmp_path, monkeypatch, private_ports+):+ """The in-memory drop dies with the process; a fresh one would walk back+ into the same refusal without a marker on disk."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ _provider_rejected_at_token_endpoint(+ tmp_path, monkeypatch, _CIMD_CLIENT_METADATA_URL+ )+ storage = HermesTokenStorage("srv")++ assert storage.cimd_rejected()+ assert _maybe_use_cimd({}, storage) is None+++def test_reauthorizing_clears_the_rejection(tmp_path, monkeypatch, private_ports):+ """`hermes mcp login` wipes stored state, so a fixed document is retried."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ storage = HermesTokenStorage("srv")+ storage.mark_cimd_rejected()++ storage.remove()++ assert not storage.cimd_rejected()+ assert _maybe_use_cimd({}, storage) is not None+++def test_rejected_dcr_client_leaves_cimd_available(+ tmp_path, monkeypatch, private_ports+):+ """A dead DCR registration says nothing about our document."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ provider = _provider_rejected_at_token_endpoint(+ tmp_path, monkeypatch, "dcr-issued-id"+ )++ assert provider.context.client_metadata_url == _CIMD_CLIENT_METADATA_URL+ assert not HermesTokenStorage("srv").cimd_rejected()+++# ---------------------------------------------------------------------------+# Diagnosing a refusal the protocol gives us no signal for+# ---------------------------------------------------------------------------+++def _timed_out_waiter_message(monkeypatch, cimd_url):+ """Run a callback waiter to its timeout and return the error text."""+ import tools.mcp_oauth as mod++ # No paste thread and no fail-fast: this exercises the timeout itself.+ monkeypatch.setattr(mod, "_is_interactive", lambda: False)+ monkeypatch.setattr(mod, "_raise_if_non_interactive", lambda lead: None)++ async def instant_sleep(_seconds):+ pass++ waiter = mod._make_callback_waiter(mod._reserve_callback_port(), cimd_url)+ monkeypatch.setattr(mod.asyncio, "sleep", instant_sleep)+ with pytest.raises(mod.OAuthNonInteractiveError) as excinfo:+ asyncio.run(waiter())+ return str(excinfo.value)+++def test_timeout_on_a_cimd_flow_names_the_document_and_the_escape_hatch(monkeypatch):+ """A server that can't validate the document aborts at the authorization+ endpoint (draft section 5.1), so no redirect ever arrives and the only+ symptom Hermes sees is the callback timing out."""+ message = _timed_out_waiter_message(monkeypatch, _CIMD_CLIENT_METADATA_URL)++ assert _CIMD_CLIENT_METADATA_URL in message+ assert "cimd: false" in message+++def test_timeout_without_cimd_stays_quiet_about_it(monkeypatch):+ assert "cimd" not in _timed_out_waiter_message(monkeypatch, None).lower()diff --git a/tests/tools/test_mcp_oauth.py b/tests/tools/test_mcp_oauth.pyindex dae8c51917b..8052a791357 100644--- a/tests/tools/test_mcp_oauth.py+++ b/tests/tools/test_mcp_oauth.py@@ -493,7 +493,10 @@ class TestCallbackPortReservation:import threadingimport tools.mcp_oauth as mod- cfg: dict = {}+ # cimd: false keeps this on the ephemeral branch. A CIMD-eligible+ # config would take a pinned port instead, and this test would pass+ # while never exercising _reserve_callback_port at all.+ cfg: dict = {"cimd": False}port = mod._configure_callback_port(cfg)monkeypatch.setattr(mod, "_is_interactive", lambda: False)# Bypass the non-interactive guard — this test drives the flow directly.@@ -531,11 +534,14 @@ class TestCallbackPortReservation:monkeypatch.setattr(mod, "_is_interactive", lambda: False)monkeypatch.setattr(mod, "_raise_if_non_interactive", lambda lead: None)- cfg_a: dict = {}+ # cimd: false keeps both flows on ephemeral ports, which is where the+ # #34260 clobbering happens; the pinned range has its own coverage in+ # tests/tools/test_mcp_cimd.py.+ cfg_a: dict = {"cimd": False}port_a = mod._configure_callback_port(cfg_a)waiter_a = mod._make_callback_waiter(port_a)# Flow B configures afterwards — overwrites mod._oauth_port.- cfg_b: dict = {}+ cfg_b: dict = {"cimd": False}port_b = mod._configure_callback_port(cfg_b)assert mod._oauth_port == port_b != port_a@@ -860,7 +866,7 @@ _PROXY_REDIRECT = "https://oauth.example.ts.net/callback"@pytest.mark.parametrize("cfg, expected_auth", [- ({}, "none"), # public client+ ({"cimd": False}, "none"), # public client({"client_secret": "shh"}, "client_secret_post"), # confidential client])def test_build_client_metadata_token_endpoint_auth(cfg, expected_auth):diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.pyindex c2f6aff0ad8..2ff3b9f5769 100644--- a/tools/mcp_oauth.py+++ b/tools/mcp_oauth.py@@ -7,9 +7,15 @@ for MCP servers that require OAuth authentication instead of static bearertokens.Uses the MCP Python SDK's ``OAuthClientProvider`` (an ``httpx.Auth`` subclass)-which handles discovery, dynamic client registration, PKCE, token exchange,+which handles discovery, client identification, PKCE, token exchange,refresh, and step-up authorization automatically.+Client identification follows the MCP 2026-07-28 spec: when the authorization+server advertises ``client_id_metadata_document_supported``, the SDK uses the+URL of Hermes' published Client ID Metadata Document (CIMD) as the+``client_id``; otherwise it falls back to RFC 7591 dynamic client registration,+which that spec revision deprecated.+This module provides the glue:- ``HermesTokenStorage``: persists tokens/client-info to disk so theysurvive across process restarts.@@ -32,6 +38,8 @@ Configuration in config.yaml::redirect_uri: "https://proxy/callback" # default: loopback callbackredirect_host: "localhost" # loopback hostname (WAF-safe)client_name: "My Custom Client" # default: "Hermes Agent"+ client_metadata_url: "https://me/cimd.json" # self-hosted CIMD+ cimd: false # force DCR for this server"""import asyncio@@ -215,6 +223,19 @@ _reserved_sockets: "dict[int, socket.socket]" = {}_MAX_RESERVED_SOCKETS = 8+def _park_reserved_socket(port: int, sock: socket.socket) -> None:+ """Hold *sock* bound to *port* until ``_wait_for_callback`` adopts it."""+ # Evict oldest reservations past the cap (dict preserves insertion order).+ while len(_reserved_sockets) >= _MAX_RESERVED_SOCKETS:+ stale_port, stale = next(iter(_reserved_sockets.items()))+ _reserved_sockets.pop(stale_port, None)+ try:+ stale.close()+ except OSError:+ pass+ _reserved_sockets[port] = sock++def _reserve_callback_port() -> int:"""Pick an ephemeral callback port and keep its socket bound.@@ -230,15 +251,7 @@ def _reserve_callback_port() -> int:s.close()raiseport = s.getsockname()[1]- # Evict oldest reservations past the cap (dict preserves insertion order).- while len(_reserved_sockets) >= _MAX_RESERVED_SOCKETS:- _, stale = next(iter(_reserved_sockets.items()))- _reserved_sockets.pop(next(iter(_reserved_sockets)), None)- try:- stale.close()- except OSError:- pass- _reserved_sockets[port] = s+ _park_reserved_socket(port, s)return port@@ -434,6 +447,7 @@ class HermesTokenStorage:HERMES_HOME/mcp-tokens/<server_name>.json -- tokensHERMES_HOME/mcp-tokens/<server_name>.client.json -- client infoHERMES_HOME/mcp-tokens/<server_name>.meta.json -- oauth server metadata+ HERMES_HOME/mcp-tokens/<server_name>.cimd-off -- CIMD refused here"""def __init__(self, server_name: str, *, hermes_home: str | Path | None = None):@@ -449,6 +463,9 @@ class HermesTokenStorage:def _meta_path(self) -> Path:return _get_token_dir(self._hermes_home) / f"{self._server_name}.meta.json"+ def _cimd_rejected_path(self) -> Path:+ return _get_token_dir(self._hermes_home) / f"{self._server_name}.cimd-off"+# -- tokens ------------------------------------------------------------async def get_tokens(self) -> "OAuthToken | None":@@ -573,11 +590,38 @@ class HermesTokenStorage:logger.warning("Corrupt OAuth metadata at %s -- ignoring: %s", self._meta_path(), exc)return None+ # -- CIMD refusal ------------------------------------------------------++ def mark_cimd_rejected(self) -> None:+ """Record that this server refused our Client ID Metadata Document.++ Without a durable marker the in-memory fallback in+ ``mcp_oauth_manager`` only holds for the current process, so every+ restart re-presents a client_id the server has already fetched and+ refused. Cleared by ``remove()``, i.e. by ``hermes mcp login`` /+ ``hermes mcp remove``, so a fixed document gets another chance.+ """+ path = self._cimd_rejected_path()+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.touch()+ except OSError as exc: # non-fatal — worst case we retry CIMD later+ logger.debug("Could not record CIMD rejection at %s: %s", path, exc)++ def cimd_rejected(self) -> bool:+ """True when this server has refused our metadata document before."""+ return self._cimd_rejected_path().exists()+# -- cleanup -----------------------------------------------------------def remove(self) -> None:"""Delete all stored OAuth state for this server."""- for p in (self._tokens_path(), self._client_info_path(), self._meta_path()):+ for p in (+ self._tokens_path(),+ self._client_info_path(),+ self._meta_path(),+ self._cimd_rejected_path(),+ ):p.unlink(missing_ok=True)def snapshot(self) -> dict[str, bytes]:@@ -856,7 +900,9 @@ async def _wait_for_callback() -> tuple[str, str | None]:return await _make_callback_waiter(_oauth_port)()-def _make_callback_waiter(port: int, timeout: float = 300.0):+def _make_callback_waiter(+ port: int, cimd_url: str | None = None, timeout: float = 300.0+):"""Return a callback waiter bound to a single OAuth flow's port.``timeout`` bounds how long the waiter polls for the redirect. It used to@@ -870,6 +916,12 @@ def _make_callback_waiter(port: int, timeout: float = 300.0):overwrites the legacy global afterwards (#34260, the callback-sidesibling of the #44588 redirect-handler fix).+ ``cimd_url`` is the Client ID Metadata Document this flow presents, when+ it presents one. It only tailors the timeout message: a server that+ fetches the document and refuses it aborts at the *authorization*+ endpoint (draft section 5.1), so no redirect ever reaches us and a bare+ "timed out" hides the real cause.+The waiter polls for the redirect without blocking the event loop. On aninteractive TTY it races the HTTP listener against a stdin paste fallbackso users without an SSH tunnel can paste the redirect URL (or just the@@ -981,9 +1033,19 @@ def _make_callback_waiter(port: int, timeout: float = 300.0):if result["error"]:raise RuntimeError(f"OAuth authorization failed: {result['error']}")if result["auth_code"] is None:+ hint = ""+ if cimd_url:+ hint = (+ " If the browser showed an invalid-client error instead of "+ "an approval prompt, the authorization server rejected "+ f"Hermes' Client ID Metadata Document ({cimd_url}); set "+ "``cimd: false`` under that server's ``oauth:`` block in "+ "config.yaml to authorize via dynamic client registration "+ "instead."+ )raise OAuthNonInteractiveError("OAuth callback timed out — no authorization code received. "- "Ensure you completed the browser authorization flow."+ "Ensure you completed the browser authorization flow." + hint)return _authorization_code_result(@@ -1197,6 +1259,232 @@ def remove_oauth_tokens(# ---------------------------------------------------------------------------+# ---------------------------------------------------------------------------+# CIMD -- OAuth Client ID Metadata Documents+#+# Under CIMD the client_id IS an HTTPS URL that the authorization server+# fetches to learn our app name, logo and permitted redirect URIs, replacing+# the per-install RFC 7591 registration that the MCP spec deprecated in+# 2026-07-28. The SDK does the protocol work; Hermes only decides whether a+# given flow is eligible and hands the URL to ``OAuthClientProvider``.+# ---------------------------------------------------------------------------++# Published from ``website/static/oauth/client-metadata.json`` by the docs+# deploy. The github.io origin is deliberate: an authorization server MUST NOT+# follow HTTP redirects when fetching the document+# (draft-ietf-oauth-client-id-metadata-document section 5), and+# hermes-agent.nousresearch.com/docs/* 301s here.+_CIMD_CLIENT_METADATA_URL = (+ "https://nousresearch.github.io/hermes-agent/docs/oauth/client-metadata.json"+)++# Loopback callback ports declared in that document. The redirect URI in the+# authorization request must be an exact string match against a listed one+# (section 4.2), so a CIMD flow cannot use the ephemeral port Hermes picks+# otherwise. These sit below Linux's 32768 ephemeral floor, so the kernel never+# hands one to an unrelated process. Keep in sync with the document — the+# cross-artifact test in tests/tools/test_mcp_cimd.py enforces that.+_CIMD_PORTS = (27890, 27891, 27892, 27893, 27894)++# Loopback hostnames the document lists alongside each port, so the+# ``oauth.redirect_host: localhost`` WAF workaround still works under CIMD.+_CIMD_REDIRECT_HOSTS = frozenset({"127.0.0.1", "localhost"})+++def _is_valid_cimd_url(url: str) -> bool:+ """True when *url* is usable as a CIMD client_id on the installed SDK.++ Delegates to the SDK's own validator so we never hand+ ``OAuthClientProvider`` a URL its constructor would reject outright. An+ ImportError means the SDK predates CIMD, leaving DCR as the only option.++ The SDK checks only the https-scheme and non-root-path halves of+ draft-ietf-oauth-client-id-metadata-document section 3. The rest is+ enforced here because a URL that violates it fails at the authorization+ server, mid-browser-flow, where the user sees an opaque invalid-client+ page instead of a config error.+ """+ try:+ from mcp.client.auth.utils import is_valid_client_metadata_url+ except ImportError:+ return False+ if not is_valid_client_metadata_url(url):+ return False+ try:+ parsed = urlparse(url)+ # Accessing username/password parses the netloc, which can raise.+ has_userinfo = bool(parsed.username or parsed.password)+ except ValueError:+ return False+ if has_userinfo or parsed.fragment:+ return False+ return not any(seg in {".", ".."} for seg in parsed.path.split("/"))+++# Pinned ports this process has committed to, in the order they were taken.+# A provider is built once per configured OAuth server and keeps its port for+# the process lifetime, so assignments are never released. Includes a port+# restored from a cached client registration, so a sibling server is never+# handed a port another one is already registered on (#34260).+_assigned_cimd_ports: "list[int]" = []+++def _note_assigned_cimd_port(port: int) -> None:+ """Claim *port* for this process when it belongs to the pinned range."""+ if port in _CIMD_PORTS and port not in _assigned_cimd_ports:+ _assigned_cimd_ports.append(port)+++def _reserve_cimd_port(port: int) -> bool:+ """Bind *port* and park the socket, or return False if it's taken."""+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ sock.bind(("127.0.0.1", port))+ except OSError:+ sock.close()+ return False+ _park_reserved_socket(port, sock)+ return True+++def _pick_cimd_port() -> int | None:+ """Reserve a pinned CIMD callback port, or None when none is usable.++ Holding the bound socket until ``_wait_for_callback`` adopts it does the+ same job here as ``_reserve_callback_port`` does for ephemeral ports+ (#22161): a fixed port is just as stealable in the minutes between+ selection and the browser redirect arriving. It also makes contention+ cooperative — a second profile mid-login, or a sibling server in this+ process, finds the bind refused and moves down the range instead of+ racing us to the same listener.++ Once every pinned port belongs to this process the range wraps rather+ than falling back to DCR: a reused port only bites if both of its+ servers authorize at the same moment, and ``_wait_for_callback`` reports+ that collision clearly, whereas the DCR fallback would silently use a+ mechanism the server may not support at all.+ """+ for port in _CIMD_PORTS:+ if port in _assigned_cimd_ports:+ continue+ if _reserve_cimd_port(port):+ _assigned_cimd_ports.append(port)+ return port+ return _assigned_cimd_ports[0] if _assigned_cimd_ports else None+++def _has_cached_client_info(storage: "HermesTokenStorage | None") -> bool:+ """True when a client registration is already on disk for this server."""+ if storage is None:+ return False+ try:+ return _read_json(storage._client_info_path()) is not None+ except (AttributeError, TypeError, ValueError):+ return False+++def _server_declined_cimd(storage: "HermesTokenStorage | None") -> bool:+ """True when cached metadata shows this server doesn't advertise CIMD.++ Pinning a callback port is only needed for a flow that actually ends up+ using CIMD, but the SDK decides that during its 401 branch — long after+ Hermes has to fix the redirect URI. Cached authorization-server metadata+ from an earlier connection closes the gap for every server the user has+ already reached: one that never advertised+ ``client_id_metadata_document_supported`` keeps the reserved ephemeral+ port it has always used, and only a genuinely unknown server pays the+ optimistic pin.+ """+ if storage is None:+ return False+ try:+ metadata = storage.load_oauth_metadata()+ except (AttributeError, TypeError, ValueError):+ return False+ if metadata is None:+ return False+ return getattr(metadata, "client_id_metadata_document_supported", None) is not True+++def _maybe_use_cimd(+ cfg: dict,+ storage: "HermesTokenStorage | None" = None,+) -> "tuple[str, int] | None":+ """Return ``(client_id URL, pinned callback port)``, or None to use DCR.++ Every early return below is a case where the redirect URI Hermes would+ send is not one the published document declares, where the client+ identity is already settled, or where the server is known not to want a+ document — DCR remains correct in all of them. Passing a metadata URL+ anyway would make the SDK present a client_id whose registered redirect+ URIs don't match the request, and the authorization server would reject+ the flow.+ """+ if cfg.get("cimd") is False:+ return None++ url = cfg.get("client_metadata_url") or _CIMD_CLIENT_METADATA_URL+ if not _is_valid_cimd_url(url):+ return None++ # A client pinned in config.yaml is the user's explicit choice, and a+ # secret means they want a confidential client — the document forbids+ # shared secrets (draft section 4.1).+ if cfg.get("client_id") or cfg.get("client_secret"):+ return None++ # The document, not the config, supplies the name and auth method the+ # server sees, so a caller that set either is asking for an identity CIMD+ # cannot present. Figma's DCR name allowlist (applied by+ # apply_oauth_provider_defaults) is the in-tree example.+ if cfg.get("client_name"):+ return None+ if (cfg.get("token_endpoint_auth_method") or "none") != "none":+ return None++ # Dashboard/desktop flows redirect to the server's own externally+ # reachable URL (``/api/mcp/oauth/callback/<name>``), which is+ # deployment-specific and can never appear in a static document.+ from tools.mcp_dashboard_oauth import get_dashboard_oauth_flow++ if get_dashboard_oauth_flow() is not None:+ return None++ if cfg.get("redirect_uri") or cfg.get("redirect_port"):+ return None++ if (cfg.get("redirect_host") or "127.0.0.1") not in _CIMD_REDIRECT_HOSTS:+ return None++ # An existing registration is bound to the redirect URI it registered+ # with; swapping in a CIMD client_id now would invalidate stored tokens.+ if _has_cached_client_info(storage):+ return None++ if storage is not None and storage.cimd_rejected():+ return None++ if _server_declined_cimd(storage):+ return None++ port = _pick_cimd_port()+ if port is None:+ return None+ return url, port+++def cimd_provider_kwargs(cfg: dict) -> dict[str, Any]:+ """``client_metadata_url=`` for ``OAuthClientProvider``, when CIMD applies.++ Returned as kwargs rather than a plain value so the argument is omitted+ entirely on a DCR flow. An SDK old enough to lack CIMD support — the case+ ``_is_valid_cimd_url`` already refuses to produce a URL for — rejects the+ keyword outright, and that must not take every other OAuth flow with it.+ """+ url = cfg.get("_cimd_url")+ return {"client_metadata_url": url} if url else {}++def _configure_callback_port(cfg: dict,storage: "HermesTokenStorage | None" = None,@@ -1210,7 +1498,11 @@ def _configure_callback_port(Port choice precedence:1. explicit ``oauth.redirect_port`` config2. cached client registration redirect URI port- 3. newly allocated free port+ 3. a pinned CIMD port, when the flow is CIMD-eligible+ 4. newly allocated free port++ A CIMD-eligible flow also records the client_id URL in+ ``cfg['_cimd_url']`` for the provider constructors to forward.NOTE: also sets the legacy module-level ``_oauth_port`` so existingcalls to ``_wait_for_callback`` keep working. The legacy global is@@ -1231,6 +1523,12 @@ def _configure_callback_port(cfg["redirect_uri"] = cached_redirect_uricfg["_resolved_port"] = 0return 0+ cimd = _maybe_use_cimd(cfg, storage)+ if cimd is not None:+ cfg["_cimd_url"], port = cimd+ cfg["_resolved_port"] = port+ _oauth_port = port+ return portrequested = int(cfg.get("redirect_port", 0))# Precedence: explicit config port → cached client-registration port →# fresh ephemeral port. The cached port keeps re-auth consistent with the@@ -1241,6 +1539,10 @@ def _configure_callback_port(# (#22161). Explicit and cached ports are fixed, known values and bind# via the reuse_address path instead.port = requested or _cached_redirect_port(storage) or _reserve_callback_port()+ # A cached port can be one of the pinned CIMD ports, left behind by an+ # earlier CIMD login for this server. Claim it so a sibling server's+ # _pick_cimd_port doesn't hand the same port out a second time.+ _note_assigned_cimd_port(port)cfg["_resolved_port"] = port_oauth_port = port # legacy consumer: _wait_for_callback reads thisreturn port@@ -1580,7 +1882,7 @@ def build_oauth_auth(resolved_port, redirect_uri=cfg.get("redirect_uri") or None)callback_handler = _make_callback_waiter(- resolved_port, timeout=float(cfg.get("timeout", 300))+ resolved_port, cfg.get("_cimd_url"), timeout=float(cfg.get("timeout", 300)))provider_class = _get_hermes_oauth_provider_class()@@ -1600,4 +1902,5 @@ def build_oauth_auth(# `oauth.timeout` is applied inside the callback waiter above, which is# where the browser round-trip is actually awaited.callback_handler=callback_handler,+ **cimd_provider_kwargs(cfg),)diff --git a/tools/mcp_oauth_manager.py b/tools/mcp_oauth_manager.pyindex 636c2a84127..dc5442962fc 100644--- a/tools/mcp_oauth_manager.py+++ b/tools/mcp_oauth_manager.py@@ -457,6 +457,27 @@ def _make_hermes_provider_class() -> Optional[type]:storage = self.context.storagefrom tools.mcp_oauth import HermesTokenStorage++ # When the rejected client_id was our Client ID Metadata+ # Document URL, re-presenting it next flow would loop: the+ # server has already fetched that document and refused it.+ # Dropping the URL sends the retry down the DCR branch+ # instead, and the marker on disk keeps the next process from+ # walking back into the same refusal. `hermes mcp login`+ # clears the marker, so a fixed document gets another chance.+ cimd_url = getattr(self.context, "client_metadata_url", None)+ rejected_id = getattr(self.context.client_info, "client_id", None)+ if cimd_url and rejected_id == cimd_url:+ logger.warning(+ "MCP OAuth '%s': authorization server rejected our "+ "Client ID Metadata Document (%s) with invalid_client "+ "— falling back to dynamic client registration.",+ self._hermes_server_name, cimd_url,+ )+ self.context.client_metadata_url = None+ if isinstance(storage, HermesTokenStorage):+ storage.mark_cimd_rejected()+if isinstance(storage, HermesTokenStorage):storage.poison_client_registration()# Drop the in-memory client so the SDK re-registers next flow.@@ -621,6 +642,7 @@ class MCPOAuthManager:_maybe_preregister_client,_make_callback_waiter,_make_redirect_handler,+ cimd_provider_kwargs,)if not _OAUTH_AVAILABLE:@@ -659,7 +681,7 @@ class MCPOAuthManager:# configured `oauth.timeout` now bounds the callback waiter's own poll# loop instead — that is where the browser round-trip is awaited.callback_handler = _make_callback_waiter(- resolved_port, timeout=float(cfg.get("timeout", 300))+ resolved_port, cfg.get("_cimd_url"), timeout=float(cfg.get("timeout", 300)))return _HERMES_PROVIDER_CLS(@@ -670,6 +692,7 @@ class MCPOAuthManager:storage=storage,redirect_handler=redirect_handler,callback_handler=callback_handler,+ **cimd_provider_kwargs(cfg),)def remove(diff --git a/website/docs/reference/mcp-config-reference.md b/website/docs/reference/mcp-config-reference.mdindex 494a66b397b..2a3214acbe0 100644--- a/website/docs/reference/mcp-config-reference.md+++ b/website/docs/reference/mcp-config-reference.md@@ -331,12 +331,51 @@ mcp_servers:```Behavior:-- Hermes uses the MCP SDK's OAuth 2.1 PKCE flow (metadata discovery, dynamic client registration, token exchange, and refresh)+- Hermes uses the MCP SDK's OAuth 2.1 PKCE flow (metadata discovery, client identification, token exchange, and refresh)- On first connect, a browser window opens for authorization- Tokens are persisted to `~/.hermes/mcp-tokens/<server>.json` and reused across sessions- Token refresh is automatic; re-authorization only happens when refresh fails- Only applies to HTTP/StreamableHTTP transport (`url`-based servers)+### Client identification: CIMD and DCR++Hermes identifies itself to authorization servers with a **Client ID Metadata Document** (CIMD), the mechanism the MCP `2026-07-28` spec adopted in place of Dynamic Client Registration. The document is published at+`https://nousresearch.github.io/hermes-agent/docs/oauth/client-metadata.json`, and that URL *is* the `client_id` — the authorization server fetches it to learn Hermes' name, logo, and permitted redirect URIs. Nothing is registered per install, and nothing is user-specific.++The final choice belongs to the authorization server: the SDK sends the document URL as the `client_id` only when the server advertises `client_id_metadata_document_supported: true` in its metadata, and otherwise registers via DCR exactly as before. DCR is deprecated in the MCP spec but still what almost every deployed server uses today.++#### Callback ports++The document declares a fixed set of loopback redirect URIs, and the spec requires the redirect URI in an authorization request to be an *exact string match* against one of them — so a CIMD flow cannot use the random high port Hermes normally picks. Hermes therefore pins the callback to one of ports `27890`–`27894`.++That pin has to be chosen before the server's capabilities are known, because the redirect URI is fixed at the start of the flow while the server's metadata only arrives partway through. So Hermes pins the port for any flow that *could* end up using CIMD, and reverts to a random port for the rest:++- A server Hermes has connected to before, whose cached metadata does not advertise CIMD, keeps the random port it has always used.+- A server Hermes has never reached gets a pinned port on that first login, since guessing is the only way CIMD can ever be used.+- Anything that would move the callback elsewhere reverts too: a pre-registered `oauth.client_id`, an `oauth.client_secret`, a custom `oauth.client_name` or `oauth.token_endpoint_auth_method`, an `oauth.redirect_uri` or `oauth.redirect_port` override, a dashboard- or desktop-driven login, an existing client registration on disk, or all five ports being held by other processes.++Each pinned port is bound as soon as it is chosen and held until the browser redirect arrives, so two concurrent logins — a second profile, or another server in the same process — cannot land on the same listener.++#### When a server rejects the document++If a server fetches the document and refuses it at the *token* endpoint (`invalid_client`), Hermes logs the rejection, records it under `~/.hermes/mcp-tokens/<server>.cimd-off`, and uses DCR for that server from then on.++A server that cannot fetch or validate the document at all aborts at the *authorization* endpoint instead, before any redirect happens. There is no signal Hermes can observe there, so the browser shows an invalid-client error and the login times out after five minutes. The timeout message names the document and points at `cimd: false`. Running `hermes mcp login <server>` clears the recorded rejection, so a corrected document gets another chance.++#### Optional per-server keys++```yaml+mcp_servers:+ protected_api:+ url: "https://mcp.example.com/mcp"+ auth: oauth+ oauth:+ client_metadata_url: "https://example.com/my-cimd.json" # self-hosted document+ cimd: false # force DCR+```++`client_metadata_url` must be an HTTPS URL with a path (no bare origin, no fragment, no userinfo, no `.`/`..` segments) that returns `200` and `Content-Type: application/json` with **no redirect** — authorization servers are forbidden from following redirects when fetching it. Hermes still pins its callback to the same `27890`–`27894` range, so a self-hosted document must declare all ten loopback URIs (`http://127.0.0.1:<port>/callback` and `http://localhost:<port>/callback` for each port), and its `client_id` must be its own URL.+## Add to Hermes linkMCP vendors and docs can offer a one-click **"Add to Hermes"** button that opens the Hermes desktop app with a pre-filled server config, mirroring Cursor's `cursor://anysphere.cursor-deeplink/mcp/install` scheme:diff --git a/website/docs/user-guide/features/mcp.md b/website/docs/user-guide/features/mcp.mdindex 41dce482390..755941407aa 100644--- a/website/docs/user-guide/features/mcp.md+++ b/website/docs/user-guide/features/mcp.md@@ -238,7 +238,9 @@ Use HTTP servers when:### OAuth-authenticated HTTP servers-Most hosted MCP servers (Linear, Sentry, Atlassian, Asana, Figma, Stripe, …) require OAuth 2.1 instead of a static bearer token. Set `auth: oauth` and Hermes handles discovery, dynamic client registration, PKCE, token exchange, refresh, and step-up auth via the MCP Python SDK.+Most hosted MCP servers (Linear, Sentry, Atlassian, Asana, Figma, Stripe, …) require OAuth 2.1 instead of a static bearer token. Set `auth: oauth` and Hermes handles discovery, client identification, PKCE, token exchange, refresh, and step-up auth via the MCP Python SDK.++Hermes identifies itself with a [Client ID Metadata Document](../../reference/mcp-config-reference.md#client-identification-cimd-and-dcr) on servers that support one, and falls back to Dynamic Client Registration on those that don't. Both are automatic; there is nothing to configure.:::tip Figma remote MCPFigma's hosted endpoint (`https://mcp.figma.com/mcp`) allowlists Dynamic Client Registration by **exact `client_name`** — bare `"Hermes Agent"` 403s, while `"Claude Code"` and `"Codex"` succeed. Hermes auto-sets `oauth.client_name: "Claude Code"` for `mcp.figma.com` so install/login works without a special trick:diff --git a/website/static/oauth/client-metadata.json b/website/static/oauth/client-metadata.jsonnew file mode 100644index 00000000000..b82f9e10b0d--- /dev/null+++ b/website/static/oauth/client-metadata.json@@ -0,0 +1,22 @@+{+ "client_id": "https://nousresearch.github.io/hermes-agent/docs/oauth/client-metadata.json",+ "client_name": "Hermes Agent",+ "client_uri": "https://hermes-agent.nousresearch.com",+ "logo_uri": "https://nousresearch.github.io/hermes-agent/docs/img/logo.png",+ "application_type": "native",+ "grant_types": ["authorization_code", "refresh_token"],+ "response_types": ["code"],+ "token_endpoint_auth_method": "none",+ "redirect_uris": [+ "http://127.0.0.1:27890/callback",+ "http://localhost:27890/callback",+ "http://127.0.0.1:27891/callback",+ "http://localhost:27891/callback",+ "http://127.0.0.1:27892/callback",+ "http://localhost:27892/callback",+ "http://127.0.0.1:27893/callback",+ "http://localhost:27893/callback",+ "http://127.0.0.1:27894/callback",+ "http://localhost:27894/callback"+ ]+}