The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): token-endpoint requests always carry a User-Agent
finn763af1ac349eb3a
diff --git a/tests/tools/test_mcp_oauth_user_agent.py b/tests/tools/test_mcp_oauth_user_agent.pyindex 39759a45a60..ac42000a839 100644--- a/tests/tools/test_mcp_oauth_user_agent.py+++ b/tests/tools/test_mcp_oauth_user_agent.py@@ -3,14 +3,23 @@Some authorization servers and WAFs reject httpx's default User-Agent on thetoken endpoint (#75576). The header is opt-in, per-server, and applied ONLY tothe two token-endpoint requests (authorization-code exchange and refresh) —-never to MCP traffic or discovery.+never to MCP traffic or discovery. With no ``oauth.user_agent`` configured the+shared ``Hermes-Agent/<version>`` default is stamped instead: those requests+are hand-built and sent with ``client.send()``, which never merges the client's+default headers, so an unset UA used to mean NO ``User-Agent`` on the wire at+all and a WAF-fronted authorization server answered 403 (#115329).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.+constructor call. The device-flow test additionally observes the headers on a+real socket, because that path (``tools.mcp_oauth_device``) sends its own token+request instead of yielding it into the SDK's auth flow."""import asyncio+import json+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom types import SimpleNamespacefrom unittest.mock import MagicMock@@ -25,6 +34,7 @@ from tools.mcp_oauth import ( # noqa: E402 — after the SDK availability gatebuild_oauth_auth,token_request_user_agent,)+from tools.mcp_oauth_provider import DEFAULT_AUTH_REQUEST_USER_AGENT # noqa: E402def _set_interactive_stdin(monkeypatch, *, is_tty: bool = True) -> None:@@ -132,12 +142,15 @@ def test_token_requests_carry_the_configured_user_agent(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(+def test_unconfigured_user_agent_falls_back_to_the_hermes_default(builder, tmp_path, monkeypatch):- """No config → httpx's own default, exactly as before the feature."""- import httpx+ """No config → the shared ``Hermes-Agent/<version>`` default, never a header-less request.+ A bare ``httpx.Request`` carries no User-Agent and ``client.send()`` never merges the+ client's default headers, so an unset ``oauth.user_agent`` used to put these POSTs on+ the wire with nothing but host/content-type/content-length (#115329).+ """provider = _build_provider_via(builder, monkeypatch, tmp_path, {})_ready_for_token_requests(provider)@@ -146,9 +159,8 @@ def test_unconfigured_user_agent_leaves_the_default_header()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+ assert exchange.headers.get("User-Agent") == DEFAULT_AUTH_REQUEST_USER_AGENT+ assert refresh.headers.get("User-Agent") == DEFAULT_AUTH_REQUEST_USER_AGENTdef test_user_agent_does_not_disturb_token_auth_preparation(tmp_path, monkeypatch):@@ -175,3 +187,101 @@ def test_user_agent_does_not_disturb_token_auth_preparation(tmp_path, monkeypatcassert exchange.headers["User-Agent"] == "UA/1"assert exchange.headers.get("Authorization", "").startswith("Basic ")+++# ---------------------------------------------------------------------------+# Device flow: the token poll is sent by Hermes itself, so watch the socket+# ---------------------------------------------------------------------------+++def device_authorization_server():+ """A local RFC 8628 authorization server that records the headers it receives."""+ seen: list[tuple[str, dict]] = []++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def _reply(self, status, payload):+ body = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_POST(self): # noqa: N802+ self.rfile.read(int(self.headers.get("Content-Length") or 0))+ seen.append((self.path, {k.lower(): v for k, v in self.headers.items()}))+ base = f"http://127.0.0.1:{self.server.server_port}"+ if self.path == "/device":+ return self._reply(200, {"device_code": "fixture-device-code", "user_code": "TEST-CODE",+ "verification_uri": f"{base}/verify", "interval": 0.01,+ "expires_in": 30})+ if self.path == "/token":+ if sum(path == "/token" for path, _ in seen) == 1:+ return self._reply(400, {"error": "authorization_pending"})+ return self._reply(200, {"access_token": "at", "refresh_token": "rt",+ "token_type": "Bearer", "expires_in": 3600})+ self._reply(404, {})++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ worker = threading.Thread(target=server.serve_forever, daemon=True)+ worker.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}", seen+ finally:+ server.shutdown()+ server.server_close()+ worker.join()+++def test_device_flow_token_poll_carries_a_user_agent_on_the_wire(+ device_authorization_server, tmp_path, monkeypatch+):+ """Every request of an unconfigured device login reaches the server with a User-Agent.++ ``tools.mcp_oauth_device._authorize`` builds its token poll by hand and sends it with+ ``client.send()`` — the one token request that never passes through the SDK auth flow's+ default-UA stamp, so it left the socket header-less (#115329).+ """+ from mcp.shared.auth import OAuthClientInformationFull++ from tools.mcp_oauth import _build_client_metadata+ from tools.mcp_oauth_device import _authorize+ from tools.mcp_oauth_manager import HermesMCPOAuthProvider+ from tools.mcp_oauth_provider import prepare_oauth_config+ from tools.mcp_tool import sdk_httpx++ base, seen = device_authorization_server+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ # Exactly how `login_device` builds it for an unconfigured (`oauth.user_agent` absent) server.+ cfg, storage = prepare_oauth_config("srv", f"{base}/mcp", {})+ cfg["_resolved_port"] = cfg.get("redirect_port", 8420)+ provider = HermesMCPOAuthProvider(+ server_url=f"{base}/mcp", server_name="srv", storage=storage,+ client_metadata=_build_client_metadata(cfg),+ token_user_agent=cfg.get("user_agent"),+ )+ provider.context.oauth_metadata = SimpleNamespace(+ issuer=base, token_endpoint=f"{base}/token", device_authorization_endpoint=f"{base}/device")+ provider.context.client_info = OAuthClientInformationFull.model_validate({+ "client_id": "fixture-client",+ "token_endpoint_auth_method": "none",+ "redirect_uris": [f"http://127.0.0.1:33333/callback"],+ })++ httpx = sdk_httpx()++ async def run():+ async with httpx.AsyncClient(timeout=5.0) as client:+ return await _authorize(client, provider, {"timeout": 5})++ assert asyncio.run(run()).access_token == "at"++ assert [path for path, _ in seen] == ["/device", "/token", "/token"]+ agents = [headers.get("user-agent") for _, headers in seen]+ assert all(agents), seen # nothing leaves Hermes header-less+ polls = [headers.get("user-agent") for path, headers in seen if path == "/token"]+ assert polls == [DEFAULT_AUTH_REQUEST_USER_AGENT] * len(polls)diff --git a/tools/mcp_oauth_provider.py b/tools/mcp_oauth_provider.pyindex 6b9c4de6d3d..d3d528e05c2 100644--- a/tools/mcp_oauth_provider.py+++ b/tools/mcp_oauth_provider.py@@ -78,7 +78,9 @@ class HermesProviderMixin:``token_endpoint_auth_method``; the SDK then treats the client as public and the tokenendpoint rejects the exchange (looping the browser page) — coerce ``client_secret_post``.- ``token_user_agent`` (``oauth.user_agent``) is stamped onto token-endpoint requests only- (some authorization servers/WAFs reject httpx's default).+ (some authorization servers/WAFs reject httpx's default); unset falls back to the shared+ ``Hermes-Agent/<version>`` default, since a header-less token POST is 403'd by WAF-fronted+ authorization servers (#115329).- Any 2xx token/refresh response is accepted; token bodies never leak into errors/logs."""_hermes_logger: logging.Logger = logger@@ -148,11 +150,16 @@ class HermesProviderMixin:return type(response)(204, request=response.request)def _prepare_token_request(self, request):- """Stamp the configured User-Agent onto a token/refresh request."""+ """Stamp a token/refresh request's User-Agent: the configured ``oauth.user_agent`` when set,+ else the shared ``Hermes-Agent/<version>`` default. These requests are built by hand — the+ SDK's ``_exchange_token_authorization_code``/``_refresh_token`` and ``tools.mcp_oauth_device``+ — and travel through ``client.send()``, which never merges the client's default headers, so+ without a stamp the POST leaves with NO ``User-Agent`` at all and a WAF-fronted authorization+ server answers 403 (#115329)."""ua = getattr(self, "_hermes_token_user_agent", None) # tests build via __new__if ua:request.headers["User-Agent"] = ua- return request+ return stamp_default_user_agent(request)def _coerce_client_secret_post(self) -> None:"""Same rule as ``HermesTokenStorage._coerce_secret_auth_method``, applied to the