Skip to content

The agent that grows with you

fix(mcp): OAuth discovery/registration carry a User-Agent; cancelled login frees its callback port

teknium1668e505ac7b7
diff --git a/tests/tools/test_mcp_oauth.py b/tests/tools/test_mcp_oauth.py
index 6a3e2c29464..0cde66ccf58 100644
--- a/tests/tools/test_mcp_oauth.py
+++ b/tests/tools/test_mcp_oauth.py
@@ -1249,6 +1249,32 @@ def test_wait_for_callback_port_in_use_reports_clear_error(monkeypatch):
assert "timed out" not in msg
+def test_cancelled_waiter_releases_pinned_port_for_retry(monkeypatch):
+ """A flow cancelled mid-wait (handshake timeout) must leave its pinned/cached port bindable: the
+ retry reuses the same port and previously died with EADDRINUSE because the listener thread parked
+ in select() kept the closed socket alive (#113771)."""
+ import socket
+ import tools.mcp_oauth as mo
+
+ monkeypatch.setattr(mo, "_is_interactive", lambda: False)
+ monkeypatch.setattr(mo, "_raise_if_non_interactive", lambda lead: None)
+ with socket.socket() as probe:
+ probe.bind(("127.0.0.1", 0))
+ port = probe.getsockname()[1]
+ waiter = mo._make_callback_waiter(port, timeout=30)
+
+ async def drive():
+ task = asyncio.create_task(waiter())
+ await asyncio.sleep(0.3) # listener bound and parked in its poll
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ with socket.socket() as again: # what the retry's _start_callback_server does
+ again.bind(("127.0.0.1", port))
+
+ asyncio.run(drive())
+
+
# ---------------------------------------------------------------------------
# Figma remote MCP DCR allowlist workarounds
# ---------------------------------------------------------------------------
diff --git a/tests/tools/test_mcp_oauth_discovery_user_agent.py b/tests/tools/test_mcp_oauth_discovery_requests.py
similarity index 58%
rename from tests/tools/test_mcp_oauth_discovery_user_agent.py
rename to tests/tools/test_mcp_oauth_discovery_requests.py
index 8c6bec55bbd..8d312dc4677 100644
--- a/tests/tools/test_mcp_oauth_discovery_user_agent.py
+++ b/tests/tools/test_mcp_oauth_discovery_requests.py
@@ -1,4 +1,4 @@
-"""SDK-built OAuth discovery/registration requests must carry a User-Agent.
+"""SDK-built OAuth discovery/registration requests: default User-Agent, and discovery context on failure.
The MCP SDK constructs ``/.well-known/...`` discovery and dynamic client
registration requests as bare ``httpx.Request`` objects inside
@@ -29,7 +29,7 @@ async def _noop_callback():
return ("code", None)
-async def _make_flow(tmp_path, monkeypatch):
+async def _make_flow(tmp_path, monkeypatch, *, registered=True):
from tools.mcp_tool import sdk_httpx
httpx = sdk_httpx()
from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
@@ -47,15 +47,16 @@ async def _make_flow(tmp_path, monkeypatch):
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",
+ if registered:
+ 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",
@@ -73,7 +74,7 @@ async def _make_flow(tmp_path, monkeypatch):
@pytest.mark.asyncio
async def test_discovery_request_gets_default_user_agent(tmp_path, monkeypatch):
- from tools.mcp_oauth_manager import DEFAULT_AUTH_REQUEST_USER_AGENT
+ from tools.mcp_oauth_provider import DEFAULT_AUTH_REQUEST_USER_AGENT
httpx, req, flow = await _make_flow(tmp_path, monkeypatch)
outbound = await flow.__anext__()
@@ -103,3 +104,30 @@ async def test_callers_mcp_request_is_left_untouched(tmp_path, monkeypatch):
assert "user-agent" not in outbound.headers
await flow.aclose()
+
+
+async def test_registration_failure_after_failed_discovery_leads_with_discovery(tmp_path, monkeypatch):
+ """When every authorization-server metadata fetch fails, the SDK guesses ``/register`` on the MCP
+ host; the surfaced error must name the metadata refusal first, not only the fallback 404 (#113771),
+ and must not be mistaken for a DCR allowlist refusal by the humanizer."""
+ from mcp.client.auth.oauth2 import OAuthRegistrationError
+ from tools.mcp_oauth import humanize_oauth_registration_error
+
+ httpx, req, flow = await _make_flow(tmp_path, monkeypatch, registered=False)
+ outbound = await flow.__anext__()
+ response = httpx.Response(401, request=outbound, headers={"www-authenticate": "Bearer"})
+ with pytest.raises(OAuthRegistrationError) as excinfo:
+ for _ in range(10):
+ outbound = await flow.asend(response)
+ url = str(outbound.url)
+ if "oauth-authorization-server" in url or "openid-configuration" in url:
+ response = httpx.Response(403, request=outbound, text="Forbidden")
+ elif outbound.method == "POST": # the guessed /register on the MCP host
+ response = httpx.Response(404, request=outbound, text='{"detail":"Not Found"}')
+ else:
+ response = httpx.Response(404, request=outbound)
+ msg = str(excinfo.value)
+ assert msg.startswith("Could not read authorization-server metadata (403 from https://example.com/.well-known/oauth-authorization-server")
+ assert "Registration failed: 404" in msg
+ assert humanize_oauth_registration_error("srv", excinfo.value, server_url="https://example.com/mcp") is None
diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.py
index a65acf8c6c0..0c699aad2b7 100644
--- a/tools/mcp_oauth.py
+++ b/tools/mcp_oauth.py
@@ -868,7 +868,11 @@ def _make_callback_waiter(port: int, cimd_url: str | None = None, timeout: float
"context); skipping browser authorization without binding a callback listener.")
handler_cls, result = _make_callback_handler()
server = _start_callback_server(port, handler_cls)
- threading.Thread(target=server.handle_request, daemon=True).start()
+ # serve_forever/shutdown, not a bare handle_request thread: a thread parked in handle_request's
+ # select() keeps the listening socket alive past server_close() (the kernel holds the file for
+ # the duration of the poll), so a cancelled flow — e.g. the handshake timeout firing mid-login —
+ # left the port bound and the retry on the same pinned/cached port died with EADDRINUSE (#113771).
+ threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.25}, daemon=True).start()
# Paste fallback races the HTTP listener; whichever fills result first wins (no stdin reader
# under a dashboard flow — the gateway's stdin is not the user's).
if _is_interactive() and dashboard_flow is None:
@@ -883,6 +887,7 @@ def _make_callback_waiter(port: int, cimd_url: str | None = None, timeout: float
await asyncio.sleep(0.5)
elapsed += 0.5
finally:
+ server.shutdown() # returns once the serve loop exits (≤ poll_interval) — the port is free after close
server.server_close()
return _callback_outcome(result, cimd_url)
@@ -1164,6 +1169,9 @@ def humanize_oauth_registration_error(
when the user overrode it or an older Hermes is running."""
msg = str(exc)
lowered = msg.lower()
+ from tools.mcp_oauth_provider import _DISCOVERY_CONTEXT_LEAD
+ if msg.startswith(_DISCOVERY_CONTEXT_LEAD): # the 403 there is the metadata fetch, not a DCR refusal
+ return None
looks_like_registration = ("403" in msg or "forbidden" in lowered) and (
any(k in lowered for k in ("regist", "dcr", "dynamic client"))
or lowered.strip() in {"forbidden", "403 forbidden", "http 403: forbidden"}
diff --git a/tools/mcp_oauth_manager.py b/tools/mcp_oauth_manager.py
index 4c66483360b..bf9507f4602 100644
--- a/tools/mcp_oauth_manager.py
+++ b/tools/mcp_oauth_manager.py
@@ -41,22 +41,6 @@ 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
@@ -88,24 +72,6 @@ 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
@@ -144,11 +110,12 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
build_oauth_authorization_server_metadata_discovery_urls,
build_protected_resource_metadata_discovery_urls, create_oauth_metadata_request,
handle_auth_metadata_response, handle_protected_resource_response)
+ from tools.mcp_oauth_provider import stamp_default_user_agent
server_url = self.context.server_url
async def _send(client, url: str, label: str):
try:
- return await client.send(create_oauth_metadata_request(url))
+ return await client.send(stamp_default_user_agent(create_oauth_metadata_request(url)))
except httpx.HTTPError as exc:
logger.debug("MCP OAuth '%s': %s discovery to %s failed: %s", self._hermes_server_name, label, url, exc)
return None
@@ -260,7 +227,6 @@ 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:
diff --git a/tools/mcp_oauth_provider.py b/tools/mcp_oauth_provider.py
index 94e216e0a1c..cc145827e9d 100644
--- a/tools/mcp_oauth_provider.py
+++ b/tools/mcp_oauth_provider.py
@@ -19,6 +19,55 @@ logger = logging.getLogger(__name__)
# omit ``iss`` from the redirect (#111135). Exact issuer match, nothing else is relaxed.
_ISS_OMITTING_ISSUERS = frozenset({"https://api.figma.com"})
+# Authorization-server metadata documents the SDK tries in its 401 branch (RFC 8414 / OIDC discovery).
+_ASM_DISCOVERY_PATHS = ("/.well-known/oauth-authorization-server", "/.well-known/openid-configuration")
+_DISCOVERY_CONTEXT_LEAD = "Could not read authorization-server metadata"
+
+
+def _default_auth_request_user_agent() -> str:
+ """``Hermes-Agent/<version>`` for SDK-built OAuth requests that would otherwise carry no User-Agent at
+ all; versioned so an operator debugging a WAF block can tell which client they are looking at."""
+ 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()
+
+
+def stamp_default_user_agent(request):
+ """Give an SDK-built OAuth request (discovery, registration, token) a User-Agent if it has none.
+
+ The SDK builds those as bare ``httpx.Request`` objects and sends them through ``client.send()``,
+ which never merges the client's default headers, so they leave with NO ``User-Agent`` at all.
+ WAF-fronted authorization servers (www.tradingview.com, coda.io) answer 403 to header-less
+ requests while curl and a plain ``client.get()`` get 200 — the metadata document is then "not
+ found", the SDK falls back to guessing ``/register`` and ``/authorize`` on the MCP host, and the
+ user sees ``Registration failed: 404`` (#113771). Only an absent header is filled, so a
+ configured ``oauth.user_agent`` (token requests) still wins."""
+ if "user-agent" not in request.headers:
+ request.headers["User-Agent"] = DEFAULT_AUTH_REQUEST_USER_AGENT
+ return request
+
+
+def _asm_discovery_failure(response) -> str | None:
+ """``"<status> from <url>"`` when *response* is a failed authorization-server metadata fetch."""
+ req = getattr(response, "request", None)
+ status = getattr(response, "status_code", None)
+ if req is None or status is None or 200 <= status < 300:
+ return None
+ url = str(req.url)
+ return f"{status} from {url}" if any(p in url for p in _ASM_DISCOVERY_PATHS) else None
+
+
+def _with_discovery_context(exc: Exception, failures: list[str]):
+ """Re-shape a registration error raised after every metadata fetch failed: lead with the discovery
+ failure, since the 404 on the guessed ``/register`` URL is only its consequence (#113771)."""
+ return type(exc)(f"{_DISCOVERY_CONTEXT_LEAD} ({'; '.join(failures)}); dynamic client registration "
+ f"then fell back to a guessed endpoint on the MCP host and failed: {exc}")
+
class _RefreshCompletedByPeer(Exception):
@@ -122,6 +171,7 @@ class HermesProviderMixin:
"""
while True:
inner = super().async_auth_flow(request)
+ discovery_failures: list[str] = []
try:
sent, thrown = None, None
while True:
@@ -135,6 +185,14 @@ class HermesProviderMixin:
return
except _RefreshCompletedByPeer:
break
+ except Exception as exc:
+ from mcp.client.auth.oauth2 import OAuthRegistrationError
+ if (isinstance(exc, OAuthRegistrationError) and discovery_failures
+ and self.context.oauth_metadata is None):
+ raise _with_discovery_context(exc, discovery_failures) from exc
+ raise
+ if out is not request:
+ stamp_default_user_agent(out)
# Full bidirectional delegation: the SDK drives this flow with
# asend(response), so `async for` would swallow the response and
# feed the inner generator None. Async generators have no
@@ -146,6 +204,10 @@ class HermesProviderMixin:
raise
except BaseException as exc:
sent, thrown = None, exc
+ else:
+ failure = _asm_discovery_failure(sent)
+ if failure:
+ discovery_failures.append(failure)
finally:
await self._hermes_release_refresh_fence()
diff --git a/website/docs/reference/mcp-config-reference.md b/website/docs/reference/mcp-config-reference.md
index ad3339e3d24..fdd6efd0c18 100644
--- a/website/docs/reference/mcp-config-reference.md
+++ b/website/docs/reference/mcp-config-reference.md
@@ -415,7 +415,9 @@ mcp_servers:
`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.
+`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, and no other token-request headers are configurable. Empty or null values are ignored.
+
+OAuth discovery and dynamic-client-registration requests (the `/.well-known/...` metadata documents and the `registration_endpoint` POST) always carry `User-Agent: Hermes-Agent/<version>`. The MCP SDK builds those requests without any client default headers, and WAF-fronted authorization servers answer a header-less request with `403` — the metadata document then looks unreadable, registration falls back to a guessed `/register` on the MCP host, and the login fails with `Registration failed: 404`. When every metadata fetch does fail, the error now leads with those statuses (`Could not read authorization-server metadata (403 from https://…/.well-known/oauth-authorization-server; …)`) before the registration fallback's own error.
## Add to Hermes link