Skip to content

The agent that grows with you

fix(mcp): send a User-Agent on SDK-built OAuth discovery/registration requests

Ivyleaguelawyer7eed615690ec
diff --git a/tests/tools/test_mcp_oauth_discovery_user_agent.py b/tests/tools/test_mcp_oauth_discovery_user_agent.py
new file mode 100644
index 00000000000..8c6bec55bbd
--- /dev/null
+++ b/tests/tools/test_mcp_oauth_discovery_user_agent.py
@@ -0,0 +1,105 @@
+"""SDK-built OAuth discovery/registration requests must carry a User-Agent.
+
+The MCP SDK constructs ``/.well-known/...`` discovery and dynamic client
+registration requests as bare ``httpx.Request`` objects inside
+``async_auth_flow``. The client's default headers never apply to them, so
+they leave with NO ``User-Agent`` at all. Some WAFs reject header-less
+requests outright: coda.io answers 403 on every discovery and registration
+call, which Hermes then misreports as "only allows pre-approved OAuth
+clients". (``oauth.user_agent`` does not help — it is stamped only on
+token-endpoint requests.)
+
+``HermesMCPOAuthProvider`` now gives such requests a default User-Agent.
+These tests drive the bridge through the 401 branch so the SDK yields a
+real discovery request, then assert on its headers.
+"""
+from __future__ import annotations
+
+import pytest
+
+
+pytest.importorskip("mcp.client.auth.oauth2", reason="MCP SDK 1.26.0+ required")
+
+
+async def _noop_redirect(url: str) -> None:
+ pass
+
+
+async def _noop_callback():
+ return ("code", None)
+
+
+async def _make_flow(tmp_path, monkeypatch):
+ from tools.mcp_tool import sdk_httpx
+ httpx = sdk_httpx()
+ from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
+ from pydantic import AnyUrl
+
+ from tools.mcp_oauth import HermesTokenStorage
+ from tools.mcp_oauth_manager import _HERMES_PROVIDER_CLS, reset_manager_for_tests
+
+ assert _HERMES_PROVIDER_CLS is not None
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ reset_manager_for_tests()
+
+ storage = HermesTokenStorage("srv")
+ await storage.set_tokens(
+ OAuthToken(access_token="old_access", token_type="Bearer", expires_in=3600, refresh_token="old_refresh")
+ )
+ await storage.set_client_info(
+ OAuthClientInformationFull(
+ client_id="test-client",
+ redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],
+ grant_types=["authorization_code", "refresh_token"],
+ response_types=["code"],
+ token_endpoint_auth_method="none",
+ )
+ )
+ provider = _HERMES_PROVIDER_CLS(
+ server_name="srv",
+ server_url="https://example.com/mcp",
+ client_metadata=OAuthClientMetadata(
+ redirect_uris=[AnyUrl("http://127.0.0.1:12345/callback")],
+ client_name="Hermes Agent",
+ ),
+ storage=storage,
+ redirect_handler=_noop_redirect,
+ callback_handler=_noop_callback,
+ )
+ req = httpx.Request("POST", "https://example.com/mcp")
+ return httpx, req, provider.async_auth_flow(req)
+
+
+async def test_discovery_request_gets_default_user_agent(tmp_path, monkeypatch):
+ from tools.mcp_oauth_manager import DEFAULT_AUTH_REQUEST_USER_AGENT
+
+ httpx, req, flow = await _make_flow(tmp_path, monkeypatch)
+ outbound = await flow.__anext__()
+
+ fake_401 = httpx.Response(
+ 401,
+ request=outbound,
+ headers={"www-authenticate": 'Bearer resource_metadata="https://example.com/.well-known/oauth-protected-resource"'},
+ )
+ discovery = await flow.asend(fake_401)
+
+ assert discovery is not req, "SDK must have yielded its own discovery request"
+ assert ".well-known" in str(discovery.url)
+ assert discovery.headers.get("user-agent") == DEFAULT_AUTH_REQUEST_USER_AGENT
+
+ await flow.aclose()
+
+
+async def test_callers_mcp_request_is_left_untouched(tmp_path, monkeypatch):
+ """The bridge must not decorate the caller's own MCP request — those
+ headers belong to the transport client, not the OAuth layer."""
+ _httpx, req, flow = await _make_flow(tmp_path, monkeypatch)
+ outbound = await flow.__anext__()
+
+ assert outbound is req
+ assert "user-agent" not in outbound.headers
+
+ await flow.aclose()
diff --git a/tools/mcp_oauth_manager.py b/tools/mcp_oauth_manager.py
index 721756a805b..4c66483360b 100644
--- a/tools/mcp_oauth_manager.py
+++ b/tools/mcp_oauth_manager.py
@@ -41,6 +41,22 @@ class _ProviderEntry:
pending_401: dict[str, "asyncio.Future[bool]"] = field(default_factory=dict)
+def _default_auth_request_user_agent() -> str:
+ """``Hermes-Agent/<version>`` for SDK-built OAuth discovery/registration
+ requests that would otherwise carry no User-Agent at all (see
+ ``_ensure_auth_request_user_agent``). Versioned so server operators
+ debugging a WAF block can tell which client they are looking at — same
+ shape as ``tools.xai_http.hermes_xai_user_agent``."""
+ try:
+ from hermes_cli import __version__
+ except Exception: # pragma: no cover — defensive
+ __version__ = "unknown"
+ return f"Hermes-Agent/{__version__}"
+
+
+DEFAULT_AUTH_REQUEST_USER_AGENT = _default_auth_request_user_agent()
+
+
class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
"""OAuthClientProvider with pre-flow disk-mtime reload (external refreshes become visible to
a running session), expiry seeding on cold load, pre-flight metadata discovery, dead-client
@@ -72,6 +88,24 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
def _log_nonfatal(self, what: str, exc: BaseException) -> None:
logger.debug("MCP OAuth '%s': %s failed (non-fatal): %s", self._hermes_server_name, what, exc)
+ def _ensure_auth_request_user_agent(self, outgoing, original) -> None:
+ """Give SDK-built auth requests a User-Agent if they have none.
+
+ The SDK constructs discovery (``/.well-known/...``) and dynamic
+ client registration requests as bare ``httpx.Request`` objects, so
+ the client's default headers never apply and they leave with NO
+ User-Agent at all. Some WAFs reject header-less requests outright
+ (coda.io returns 403 on every one, which Hermes then misreports as
+ "only allows pre-approved OAuth clients").
+
+ Only requests the SDK built itself are touched — never the caller's
+ MCP request — and only when the header is absent, so an
+ ``oauth.user_agent`` stamped on token requests still wins.
+ """
+ if outgoing is original or "user-agent" in outgoing.headers:
+ return
+ outgoing.headers["User-Agent"] = DEFAULT_AUTH_REQUEST_USER_AGENT
+
async def _initialize(self) -> None:
"""Load stored state, seed ``token_expiry_time``, restore/prefetch metadata. The SDK's
``_initialize`` never calls ``update_token_expiry``, so a restarted process would ship stale
@@ -226,6 +260,7 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
try:
outgoing = await inner.__anext__()
while True:
+ self._ensure_auth_request_user_agent(outgoing, request)
# The SDK holds context.lock for its whole generator, even while HTTPX waits on
# the MCP request. Release it for that request only; OAuth transitions stay serialized.
if outgoing is request: