The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(mcp): per-server oauth.user_agent for token-endpoint requests (#75576)
Tekniuma6bada232c48
diff --git a/tests/tools/test_mcp_oauth_user_agent.py b/tests/tools/test_mcp_oauth_user_agent.pynew file mode 100644index 00000000000..39759a45a60--- /dev/null+++ b/tests/tools/test_mcp_oauth_user_agent.py@@ -0,0 +1,177 @@+"""Tests for the per-server ``oauth.user_agent`` on MCP OAuth token requests.++Some authorization servers and WAFs reject httpx's default User-Agent on the+token endpoint (#75576). The header is opt-in, per-server, and applied ONLY to+the two token-endpoint requests (authorization-code exchange and refresh) —+never to MCP traffic or discovery.++The tests drive the REAL provider classes' request builders end to end: the+``httpx.Request`` the SDK would send is what gets inspected, not a mocked+constructor call.+"""++import asyncio+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++pytest.importorskip(+ "mcp.client.auth.oauth2",+ reason="MCP SDK required for OAuth support",+)++from tools.mcp_oauth import ( # noqa: E402 — after the SDK availability gate+ build_oauth_auth,+ token_request_user_agent,+)+++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():+ 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()+++# ---------------------------------------------------------------------------+# Config parsing+# ---------------------------------------------------------------------------+++def test_configured_user_agent_is_returned():+ assert token_request_user_agent({"user_agent": "My-MCP-Client/1.0"}) == "My-MCP-Client/1.0"++[email protected]("cfg", [+ pytest.param({}, id="absent"),+ pytest.param({"user_agent": None}, id="null"),+ pytest.param({"user_agent": ""}, id="empty"),+ pytest.param({"user_agent": " "}, id="whitespace-only"),+ pytest.param({"user_agent": 7}, id="non-string"),+])+def test_unset_user_agent_values_are_treated_as_absent(cfg):+ assert token_request_user_agent(cfg) is None+++def test_user_agent_is_stripped():+ assert token_request_user_agent({"user_agent": " UA/2 "}) == "UA/2"+++# ---------------------------------------------------------------------------+# The requests the SDK actually sends+# ---------------------------------------------------------------------------+++def _ready_for_token_requests(provider):+ """Give the provider the minimum context both builders require."""+ from mcp.shared.auth import OAuthClientInformationFull, OAuthToken++ provider.context.oauth_metadata = SimpleNamespace(+ token_endpoint="https://idp.example.com/oauth/token"+ )+ provider.context.client_info = OAuthClientInformationFull.model_validate({+ "client_id": "client-1",+ "redirect_uris": ["http://127.0.0.1:33333/callback"],+ })+ provider.context.current_tokens = OAuthToken.model_validate({+ "access_token": "at",+ "token_type": "Bearer",+ "refresh_token": "rt",+ })+++def _build_provider_via(builder, monkeypatch, tmp_path, cfg):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ _set_interactive_stdin(monkeypatch)+ return builder("srv", "https://mcp.example.com/mcp", cfg)+++def _manager_builder(server_name, server_url, cfg):+ from tools.mcp_oauth_manager import MCPOAuthManager, reset_manager_for_tests++ reset_manager_for_tests()+ return MCPOAuthManager().get_or_build_provider(server_name, server_url, cfg)++[email protected]("builder", [+ pytest.param(build_oauth_auth, id="build_oauth_auth"),+ pytest.param(_manager_builder, id="oauth_manager"),+])+def test_token_requests_carry_the_configured_user_agent(+ builder, tmp_path, monkeypatch+):+ """Both token-endpoint requests, on both provider construction paths."""+ provider = _build_provider_via(+ builder, monkeypatch, tmp_path, {"user_agent": "My-MCP-Client/1.0"}+ )+ _ready_for_token_requests(provider)++ exchange = asyncio.run(+ provider._exchange_token_authorization_code("code", "verifier")+ )+ refresh = asyncio.run(provider._refresh_token())++ assert exchange.headers["User-Agent"] == "My-MCP-Client/1.0"+ assert refresh.headers["User-Agent"] == "My-MCP-Client/1.0"++[email protected]("builder", [+ pytest.param(build_oauth_auth, id="build_oauth_auth"),+ pytest.param(_manager_builder, id="oauth_manager"),+])+def test_unconfigured_user_agent_leaves_the_default_header(+ builder, tmp_path, monkeypatch+):+ """No config → httpx's own default, exactly as before the feature."""+ import httpx++ provider = _build_provider_via(builder, monkeypatch, tmp_path, {})+ _ready_for_token_requests(provider)++ exchange = asyncio.run(+ provider._exchange_token_authorization_code("code", "verifier")+ )+ refresh = asyncio.run(provider._refresh_token())++ default_ua = httpx.Request("POST", "https://x.example/").headers.get("User-Agent")+ assert exchange.headers.get("User-Agent") == default_ua+ assert refresh.headers.get("User-Agent") == default_ua+++def test_user_agent_does_not_disturb_token_auth_preparation(tmp_path, monkeypatch):+ """The stamp runs after prepare_token_auth — a confidential client's+ Authorization header must survive alongside the custom User-Agent."""+ provider = _build_provider_via(+ build_oauth_auth, monkeypatch, tmp_path,+ {"user_agent": "UA/1", "client_id": "pre", "client_secret": "shh",+ "token_endpoint_auth_method": "client_secret_basic"},+ )+ _ready_for_token_requests(provider)+ from mcp.shared.auth import OAuthClientInformationFull++ provider.context.client_info = OAuthClientInformationFull.model_validate({+ "client_id": "pre",+ "client_secret": "shh",+ "token_endpoint_auth_method": "client_secret_basic",+ "redirect_uris": ["http://127.0.0.1:33333/callback"],+ })++ exchange = asyncio.run(+ provider._exchange_token_authorization_code("code", "verifier")+ )++ assert exchange.headers["User-Agent"] == "UA/1"+ assert exchange.headers.get("Authorization", "").startswith("Basic ")diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.pyindex a4c3d91a079..1eb6f57051e 100644--- a/tools/mcp_oauth.py+++ b/tools/mcp_oauth.py@@ -1179,8 +1179,22 @@ def _get_hermes_oauth_provider_class() -> type | None:request, causing Supabase to reject the exchange and the browser to showthe authorization page again. Coerce the in-memory client info right beforetoken/refresh requests as well as persisting the fixed shape in storage.++ ``token_user_agent`` (from ``oauth.user_agent``) is stamped onto the+ token-endpoint requests the SDK builds — some authorization servers+ and WAFs reject httpx's default User-Agent there (#75576)."""+ def __init__(self, *args: Any, token_user_agent: "str | None" = None, **kwargs: Any):+ super().__init__(*args, **kwargs)+ self._hermes_token_user_agent = token_user_agent++ def _stamp_token_user_agent(self, request):+ ua = getattr(self, "_hermes_token_user_agent", None)+ if ua:+ request.headers["User-Agent"] = ua+ return request+def _coerce_client_secret_post(self) -> None:info = getattr(self.context, "client_info", None)if not info or not getattr(info, "client_secret", None):@@ -1194,11 +1208,13 @@ def _get_hermes_oauth_provider_class() -> type | None:async def _exchange_token_authorization_code(self, *args: Any, **kwargs: Any):self._coerce_client_secret_post()- return await super()._exchange_token_authorization_code(*args, **kwargs)+ request = await super()._exchange_token_authorization_code(*args, **kwargs)+ return self._stamp_token_user_agent(request)async def _refresh_token(self):self._coerce_client_secret_post()- return await super()._refresh_token()+ request = await super()._refresh_token()+ return self._stamp_token_user_agent(request)async def _handle_token_response(self, response):"""Accept any 2xx token response and avoid leaking token bodies in errors."""@@ -1499,6 +1515,25 @@ def cimd_provider_kwargs(cfg: dict) -> dict[str, Any]:return {"client_metadata_url": url} if url else {}+def token_request_user_agent(cfg: dict) -> str | None:+ """The configured ``oauth.user_agent`` for token-endpoint requests, or None.++ Some authorization servers and network protection layers (WAFs) reject+ the default python-httpx User-Agent on the token endpoint. The value is+ opt-in and per-server; anything that is not a non-empty string is+ treated as unset so a null/empty YAML value never sends a blank header.+ Applied ONLY to authorization-code exchange and refresh-token requests —+ never to MCP traffic or discovery, and no other headers are configurable+ (arbitrary token headers risk secrets landing in config.yaml).+ """+ ua = cfg.get("user_agent")+ if isinstance(ua, str):+ ua = ua.strip()+ if ua:+ return ua+ return None++def _configure_callback_port(cfg: dict,storage: "HermesTokenStorage | None" = None,@@ -1916,5 +1951,6 @@ 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,+ token_user_agent=token_request_user_agent(cfg),**cimd_provider_kwargs(cfg),)diff --git a/tools/mcp_oauth_manager.py b/tools/mcp_oauth_manager.pyindex dc5442962fc..d0bca49967b 100644--- a/tools/mcp_oauth_manager.py+++ b/tools/mcp_oauth_manager.py@@ -134,6 +134,7 @@ def _make_hermes_provider_class() -> Optional[type]:*args: Any,server_name: str = "",preregistered: bool = False,+ token_user_agent: "str | None" = None,**kwargs: Any,):super().__init__(*args, **kwargs)@@ -145,6 +146,15 @@ def _make_hermes_provider_class() -> Optional[type]:# registration can't help. Only auto-heal dynamically-registered# clients. See _maybe_flag_poisoned_client.self._hermes_preregistered = preregistered+ # oauth.user_agent — stamped onto token-endpoint requests only;+ # some authorization servers/WAFs reject httpx's default (#75576).+ self._hermes_token_user_agent = token_user_agent++ def _stamp_token_user_agent(self, request):+ ua = getattr(self, "_hermes_token_user_agent", None)+ if ua:+ request.headers["User-Agent"] = ua+ return requestdef _coerce_client_secret_post(self) -> None:"""Use client_secret_post when dynamic registration returned a secret.@@ -171,11 +181,13 @@ def _make_hermes_provider_class() -> Optional[type]:async def _exchange_token_authorization_code(self, *args: Any, **kwargs: Any):self._coerce_client_secret_post()- return await super()._exchange_token_authorization_code(*args, **kwargs)+ request = await super()._exchange_token_authorization_code(*args, **kwargs)+ return self._stamp_token_user_agent(request)async def _refresh_token(self):self._coerce_client_secret_post()- return await super()._refresh_token()+ request = await super()._refresh_token()+ return self._stamp_token_user_agent(request)async def _handle_token_response(self, response):"""Accept any 2xx token response and avoid leaking token bodies in errors."""@@ -643,6 +655,7 @@ class MCPOAuthManager:_make_callback_waiter,_make_redirect_handler,cimd_provider_kwargs,+ token_request_user_agent,)if not _OAUTH_AVAILABLE:@@ -692,6 +705,7 @@ class MCPOAuthManager:storage=storage,redirect_handler=redirect_handler,callback_handler=callback_handler,+ token_user_agent=token_request_user_agent(cfg),**cimd_provider_kwargs(cfg),)diff --git a/website/docs/reference/mcp-config-reference.md b/website/docs/reference/mcp-config-reference.mdindex 2a3214acbe0..35bb31e64dc 100644--- a/website/docs/reference/mcp-config-reference.md+++ b/website/docs/reference/mcp-config-reference.md@@ -372,10 +372,13 @@ mcp_servers:oauth:client_metadata_url: "https://example.com/my-cimd.json" # self-hosted documentcimd: false # force DCR+ user_agent: "My-MCP-Client/1.0" # token-request User-Agent````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.+`user_agent` replaces the HTTP library's default `User-Agent` on **token-endpoint requests only** (authorization-code exchange and refresh) — some authorization servers and WAFs reject the default `python-httpx/...` value there. It never applies to MCP traffic or OAuth discovery, and no other token-request headers are configurable. Empty or null values are ignored.+## 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: