mcp_oauth_manager.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. """Central manager for per-server MCP OAuth state (one instance per process): per-server providers, cross-process
  2. token reload (mtime-based disk watch so tokens refreshed by cron/another CLI are picked up without a restart), 401
  3. deduplication (N concurrent 401s with the same access_token trigger one recovery) and reconnect signalling
  4. (``MCPServerTask`` drives the reconnect; the manager decides when). The ONLY place that instantiates the SDK's
  5. ``OAuthClientProvider`` for runtime use; refresh stays lazy in the SDK — one ``stat()`` per tool call is cheaper
  6. than an await + refresh round-trip."""
  7. from __future__ import annotations
  8. import asyncio
  9. import logging
  10. import re
  11. import threading
  12. import time
  13. from dataclasses import dataclass, field
  14. from pathlib import Path
  15. from typing import Any, Optional
  16. from tools.mcp_oauth_provider import HermesProviderMixin
  17. logger = logging.getLogger(__name__)
  18. try:
  19. from mcp.client.auth.oauth2 import OAuthClientProvider as _SDKOAuthClientProvider
  20. _SDK_BASES: tuple = (_SDKOAuthClientProvider,)
  21. except ImportError: # pragma: no cover — SDK required in CI; module must still import
  22. _SDK_BASES = ()
  23. @dataclass
  24. class _ProviderEntry:
  25. """Per-server OAuth state. ``last_mtime_ns``: last-seen tokens-file mtime (0 = never read),
  26. ``last_version`` its ``file_cache_version``, for external-refresh detection; ``lock`` binds to the first asyncio loop awaiting it (the MCP
  27. loop); ``pending_401`` dedupes thundering-herd 401s by failed access_token."""
  28. server_url: str
  29. oauth_config: Optional[dict]
  30. provider: Optional[Any] = None
  31. last_mtime_ns: int = 0
  32. last_version: tuple = ()
  33. lock: asyncio.Lock = field(default_factory=asyncio.Lock)
  34. pending_401: dict[str, asyncio.Future[bool]] = field(default_factory=dict)
  35. class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
  36. """OAuthClientProvider with pre-flow disk-mtime reload (external refreshes become visible to
  37. a running session), expiry seeding on cold load, pre-flight metadata discovery, dead-client
  38. registration detection and the bidirectional ``async_auth_flow`` bridge. Token-endpoint
  39. fixes come from ``HermesProviderMixin``. Only usable when the SDK's OAuth module imported.
  40. Reference: Claude Code's ``invalidateOAuthCacheIfDiskChanged`` (``src/utils/auth.ts:1320``, CC-1096 /
  41. GH#24317).
  42. """
  43. _hermes_logger = logger
  44. def __init__(self, *args: Any, server_name: str = "", preregistered: bool = False, **kwargs: Any):
  45. super().__init__(*args, **kwargs)
  46. # mcp 2.0 uses a task-owned anyio.Lock held across the yielded resource request (a session-long GET blocks
  47. # every POST; HTTPX may close the generator from another task). A binary semaphore drops task ownership.
  48. import anyio
  49. self.context.lock = anyio.Semaphore(1, max_value=1)
  50. self._hermes_server_name = server_name
  51. self._hermes_home = ""
  52. # A config-supplied client_id rejected as invalid_client means the *config* is wrong — only DCR clients auto-heal.
  53. self._hermes_preregistered = preregistered
  54. def _hermes_storage(self):
  55. """The context storage when it is a ``HermesTokenStorage``, else None."""
  56. from tools.mcp_oauth import HermesTokenStorage
  57. return self.context.storage if isinstance(self.context.storage, HermesTokenStorage) else None
  58. def _log_nonfatal(self, what: str, exc: BaseException) -> None:
  59. logger.debug("MCP OAuth '%s': %s failed (non-fatal): %s", self._hermes_server_name, what, exc)
  60. async def _initialize(self) -> None:
  61. """Load stored state, seed ``token_expiry_time``, restore/prefetch metadata. The SDK's
  62. ``_initialize`` never calls ``update_token_expiry``, so a restarted process would ship stale
  63. Bearer tokens as "valid"; seeding the expiry (``HermesTokenStorage`` persists absolute
  64. ``expires_at``) makes the SDK refresh first. Metadata is restored from disk, else discovered
  65. pre-flight when we hold tokens but no metadata: otherwise ``_refresh_token`` guesses
  66. ``{server_url}/token`` (wrong for split-origin providers), 404s, and we fall to browser reauth."""
  67. await super()._initialize() # HermesProviderMixin: restores metadata from disk, enforces issuer binding
  68. tokens = self.context.current_tokens
  69. if tokens is not None and tokens.expires_in is not None:
  70. # The SDK maps a zero TTL to ``time.time()`` and accepts equality
  71. # in ``is_token_valid()``. On a cold load that same-tick boundary
  72. # can send an already-expired access token instead of refreshing it.
  73. if tokens.expires_in <= 0:
  74. self.context.token_expiry_time = time.time() - 1
  75. else:
  76. self.context.update_token_expiry(tokens)
  77. if tokens is not None and self.context.oauth_metadata is None:
  78. try:
  79. await self._prefetch_oauth_metadata()
  80. except Exception as exc: # pragma: no cover — the SDK's 401-branch discovery runs next request
  81. self._log_nonfatal("pre-flight metadata discovery", exc)
  82. else:
  83. from tools.mcp_oauth_provider import enforce_refresh_token_issuer
  84. enforce_refresh_token_issuer(self.context) # metadata (issuer) only just became known
  85. async def _prefetch_oauth_metadata(self) -> None:
  86. """Fetch PRM + ASM from the well-known endpoints before the first request, via the SDK's own URL
  87. builders/response handlers so we track whatever the pinned SDK expects."""
  88. # The SDK's httpx flavour, not Hermes': `create_oauth_metadata_request` returns *its* (httpx2) Request objects.
  89. from tools.mcp_tool import sdk_httpx
  90. httpx = sdk_httpx()
  91. if httpx is None: # pragma: no cover — SDK import would have failed
  92. return
  93. from mcp.client.auth.utils import (
  94. build_oauth_authorization_server_metadata_discovery_urls,
  95. build_protected_resource_metadata_discovery_urls, create_oauth_metadata_request,
  96. handle_auth_metadata_response, handle_protected_resource_response)
  97. from tools.mcp_oauth_provider import stamp_default_user_agent
  98. server_url = self.context.server_url
  99. async def _send(client, url: str, label: str):
  100. try:
  101. return await client.send(stamp_default_user_agent(create_oauth_metadata_request(url)))
  102. except httpx.HTTPError as exc:
  103. logger.debug("MCP OAuth '%s': %s discovery to %s failed: %s", self._hermes_server_name, label, url, exc)
  104. return None
  105. async with httpx.AsyncClient(timeout=10.0) as client:
  106. # PRM discovery to learn the authorization_server URL.
  107. for url in build_protected_resource_metadata_discovery_urls(None, server_url):
  108. resp = await _send(client, url, "PRM")
  109. prm = await handle_protected_resource_response(resp) if resp is not None else None
  110. if prm:
  111. self.context.protected_resource_metadata = prm
  112. if prm.authorization_servers:
  113. self.context.auth_server_url = str(prm.authorization_servers[0])
  114. break
  115. # ASM discovery against auth_server_url (server_url fallback for legacy providers).
  116. for url in build_oauth_authorization_server_metadata_discovery_urls(self.context.auth_server_url, server_url):
  117. resp = await _send(client, url, "ASM")
  118. if resp is None:
  119. continue
  120. ok, asm = await handle_auth_metadata_response(resp)
  121. if not ok:
  122. break
  123. if asm:
  124. self.context.oauth_metadata = asm
  125. storage = self._hermes_storage() # persist now so a later cold-load skips discovery
  126. if storage is not None:
  127. storage.save_oauth_metadata(asm)
  128. logger.debug("MCP OAuth '%s': pre-flight ASM discovered token_endpoint=%s",
  129. self._hermes_server_name, asm.token_endpoint)
  130. break
  131. def _persist_oauth_metadata_if_changed(self) -> None:
  132. """Save metadata the SDK discovered lazily (401 branch); no-op when absent/unchanged."""
  133. meta = self.context.oauth_metadata
  134. storage = self._hermes_storage()
  135. if meta is None or storage is None:
  136. return
  137. existing = storage.load_oauth_metadata()
  138. if existing is None or str(existing.token_endpoint) != str(meta.token_endpoint):
  139. storage.save_oauth_metadata(meta)
  140. async def _is_invalid_client_at_token_endpoint(self, response: Any) -> bool:
  141. """True when *response* is the token endpoint (same scheme/host/path, query ignored)
  142. rejecting our client_id with ``invalid_client`` — whole word, so RFC 7591's
  143. ``invalid_client_metadata`` does not trip it. The body is read only after the endpoint matches."""
  144. from urllib.parse import urlsplit
  145. token_endpoint = getattr(getattr(self.context, "oauth_metadata", None), "token_endpoint", None)
  146. req = getattr(response, "request", None)
  147. if not token_endpoint or req is None:
  148. return False
  149. try:
  150. pa, pb = urlsplit(str(req.url)), urlsplit(str(token_endpoint))
  151. except ValueError: # pragma: no cover — malformed URL
  152. return False
  153. if (pa.scheme, pa.netloc.lower(), pa.path.rstrip("/")) != (pb.scheme, pb.netloc.lower(), pb.path.rstrip("/")):
  154. return False
  155. return re.search(rb"\binvalid_client\b", (await response.aread()).lower()) is not None
  156. async def _maybe_flag_poisoned_client(self, response: Any) -> None:
  157. """An ``invalid_client`` rejection of our ``client_id`` at the token endpoint proves the cached registration
  158. is dead server-side: delete ``client.json`` (+ stale metadata) so the SDK re-runs DCR next flow.
  159. Conservative: acts ONLY on 400/401 at the discovered ``token_endpoint`` (the only request carrying our
  160. ``client_id``) with ``invalid_client`` in the body; pre-registered clients are never poisoned; any failure
  161. is swallowed. The browser-side "Redirect URI Mismatch" case has no HTTP signal (``hermes mcp reauth``).
  162. See #36767.
  163. """
  164. try:
  165. if (self._hermes_preregistered or getattr(response, "status_code", None) not in (400, 401)
  166. or not await self._is_invalid_client_at_token_endpoint(response)):
  167. return
  168. storage = self._hermes_storage()
  169. # A rejected CIMD URL would loop if re-presented (the server already fetched and refused
  170. # it): drop it so the retry takes DCR, and mark it on disk so the next process doesn't walk
  171. # back into the same refusal (`hermes mcp login` clears the marker).
  172. cimd_url = getattr(self.context, "client_metadata_url", None)
  173. if cimd_url and getattr(self.context.client_info, "client_id", None) == cimd_url:
  174. logger.warning("MCP OAuth '%s': authorization server rejected our Client ID Metadata Document (%s) "
  175. "with invalid_client — falling back to dynamic client registration.",
  176. self._hermes_server_name, cimd_url)
  177. self.context.client_metadata_url = None
  178. if storage is not None:
  179. storage.mark_cimd_rejected()
  180. if storage is not None:
  181. storage.poison_client_registration()
  182. # Drop the in-memory client so the SDK re-registers next flow.
  183. self.context.client_info = None
  184. self._initialized = False
  185. except Exception as exc: # pragma: no cover — must not throw
  186. self._log_nonfatal("invalid_client detection", exc)
  187. async def _maybe_reject_fabricated_registration(self, outgoing: Any) -> None:
  188. """Refuse to send the SDK's *fabricated* dynamic client registration (#78190).
  189. When the discovered authorization-server metadata (RFC 8414) has no ``registration_endpoint``,
  190. ``create_client_registration_request`` (mcp/client/auth/utils.py) guesses ``POST {origin}/register``.
  191. Providers without RFC 7591 DCR — Google's hosted Gmail/Drive MCP servers among them — answer with an
  192. opaque 404 and the gateway burns its reconnect ladder on an unrecoverable failure. Their supported
  193. path is a pre-registered client (``oauth.client_id`` / ``client_secret``), so raise that guidance
  194. instead of sending the request.
  195. Fires only when the metadata WAS discovered and lacks the endpoint, and the request is a POST to the
  196. exact guessed URL. Undiscovered metadata (a WAF-blocked fetch) keeps the SDK's guess, so a real
  197. ``/register`` still works and the discovery-context error (#113771) still explains a failure.
  198. """
  199. meta = getattr(self.context, "oauth_metadata", None)
  200. if meta is None or getattr(meta, "registration_endpoint", None) or getattr(outgoing, "method", None) != "POST":
  201. return
  202. from urllib.parse import urljoin
  203. url = outgoing.url
  204. # Same URL type as the request (httpx or httpx2), so default-port handling matches on both sides.
  205. expected = type(url)(urljoin(self.context.get_authorization_base_url(self.context.server_url), "/register"))
  206. if (url.scheme, url.host, url.port, url.path) != (expected.scheme, expected.host, expected.port, expected.path):
  207. return
  208. from mcp.client.auth.oauth2 import OAuthRegistrationError
  209. name = self._hermes_server_name
  210. raise OAuthRegistrationError(
  211. f"MCP OAuth '{name}': this provider does not support automatic client registration (its authorization "
  212. f"server advertises no registration_endpoint), so the SDK's fallback would POST {expected} and fail "
  213. "(Google's hosted Gmail/Drive MCP servers and similar providers return 404 for it). Create an OAuth "
  214. "client for this provider and add it under config.yaml mcp_servers.<name>.oauth (client_id, "
  215. f"client_secret), then run `hermes mcp login {name}`.")
  216. async def async_auth_flow(self, request): # type: ignore[override]
  217. try: # pre-flow hook: reload from disk if it changed (non-fatal on error)
  218. await get_manager().invalidate_if_disk_changed(self._hermes_server_name, hermes_home=self._hermes_home)
  219. except Exception as exc: # pragma: no cover — defensive
  220. self._log_nonfatal("pre-flow disk-watch", exc)
  221. # Bridge the bidirectional generator by hand: a naive ``async for item in inner: yield
  222. # item`` DISCARDS the responses httpx sends back via ``asend``, and the SDK crashes on None.
  223. # Manually bridge the bidirectional generator protocol. httpx's auth_flow driver
  224. # (httpx._client._send_handling_auth) calls ``auth_flow.asend(response)`` to feed HTTP responses
  225. # back into the generator. A naive wrapper using ``async for item in inner: yield item`` DISCARDS
  226. # those .asend(response) values and resumes the inner generator with None, so the SDK's ``response =
  227. # yield request`` branch in mcp/client/auth/oauth2.py sees response=None and crashes at ``if
  228. # response.status_code == 401`` with AttributeError. The bridge below forwards each .asend() value
  229. # into the inner generator via inner.asend(incoming), preserving the bidirectional contract.
  230. # Regression from PR #11383 caught by tests/tools/test_mcp_oauth_bidirectional.py.
  231. inner = super().async_auth_flow(request)
  232. resource_lock_released = retry_after_concurrent_auth = False
  233. sent_access_token = None
  234. try:
  235. outgoing = await inner.__anext__()
  236. while True:
  237. # The SDK holds context.lock for its whole generator, even while HTTPX waits on
  238. # the MCP request. Release it for that request only; OAuth transitions stay serialized.
  239. if outgoing is request:
  240. tokens = self.context.current_tokens
  241. sent_access_token = tokens.access_token if tokens is not None else None
  242. self.context.lock.release()
  243. resource_lock_released = True
  244. else:
  245. try: # refuse the SDK's guessed DCR POST before it hits the network
  246. await self._maybe_reject_fabricated_registration(outgoing)
  247. except Exception:
  248. await inner.aclose() # release the SDK's context.lock now, not at GC
  249. raise
  250. incoming = yield outgoing
  251. if resource_lock_released:
  252. await self.context.lock.acquire()
  253. resource_lock_released = False
  254. # Another request may have refreshed/authorized while this one was in flight:
  255. # retry with that token instead of a duplicate OAuth transition from a stale 401/403.
  256. tokens = self.context.current_tokens
  257. if (getattr(incoming, "status_code", None) in (401, 403) and self.context.is_token_valid()
  258. and tokens is not None and tokens.access_token != sent_access_token):
  259. self._add_auth_header(request)
  260. await inner.aclose()
  261. retry_after_concurrent_auth = True
  262. break
  263. # Sniff the response for a dead-client-registration signal before handing it back to the SDK
  264. # (best-effort, GH#36767).
  265. await self._maybe_flag_poisoned_client(incoming)
  266. outgoing = await inner.asend(incoming)
  267. except StopAsyncIteration:
  268. self._persist_oauth_metadata_if_changed() # metadata discovered lazily in the 401 branch
  269. finally:
  270. if resource_lock_released:
  271. # Balance the SDK's surrounding ``async with`` even when HTTPX cancels/closes the
  272. # flow mid-request; shield only this local bookkeeping.
  273. import anyio
  274. with anyio.CancelScope(shield=True):
  275. await self.context.lock.acquire()
  276. if retry_after_concurrent_auth:
  277. yield request
  278. self._persist_oauth_metadata_if_changed()
  279. # Cached at import time; None when the SDK's OAuth module is unavailable.
  280. _HERMES_PROVIDER_CLS: Optional[type] = HermesMCPOAuthProvider if _SDK_BASES else None
  281. class MCPOAuthManager:
  282. """Single source of truth for per-server MCP OAuth state. ``_entries`` is guarded by
  283. ``_entries_lock`` (get-or-create); per-entry state by the entry's ``asyncio.Lock``."""
  284. def __init__(self) -> None:
  285. self._entries: dict[tuple[str, str], _ProviderEntry] = {}
  286. self._entries_lock = threading.Lock()
  287. # Strong refs to in-flight 401 tasks so the loop's weak bookkeeping cannot GC them mid-run.
  288. self._inflight_tasks: set[asyncio.Task] = set()
  289. def get_or_build_provider(self, server_name: str, server_url: str, oauth_config: Optional[dict]) -> Optional[Any]:
  290. """Cached OAuth provider for ``server_name``, built on first use (rebuilt when ``server_url`` changes);
  291. None if the MCP SDK's OAuth support is unavailable."""
  292. key = self._key(server_name)
  293. with self._entries_lock:
  294. entry = self._entries.get(key)
  295. if entry is not None and entry.server_url != server_url:
  296. logger.info("MCP OAuth '%s': URL changed from %s to %s, discarding cache", server_name, entry.server_url, server_url)
  297. entry = None
  298. if entry is None:
  299. entry = self._entries[key] = _ProviderEntry(server_url=server_url, oauth_config=oauth_config)
  300. if entry.provider is None:
  301. entry.provider = self._build_provider(server_name, entry)
  302. if entry.provider is not None:
  303. entry.provider._hermes_home = key[0]
  304. return entry.provider
  305. @staticmethod
  306. def _key(server_name: str, hermes_home: str | Path | None = None) -> tuple[str, str]:
  307. from hermes_constants import get_hermes_home
  308. home = Path(hermes_home) if hermes_home is not None else get_hermes_home()
  309. return (str(home.expanduser().resolve(strict=False)), server_name)
  310. def _build_provider(self, server_name: str, entry: _ProviderEntry) -> Optional[Any]:
  311. """Build a ``HermesMCPOAuthProvider``; None if the SDK's OAuth support is unavailable."""
  312. if _HERMES_PROVIDER_CLS is None:
  313. logger.warning("MCP OAuth '%s': SDK auth module unavailable", server_name)
  314. return None
  315. from tools.mcp_dashboard_oauth import get_dashboard_oauth_flow # lazy: circular at import time
  316. from tools.mcp_oauth import _OAUTH_AVAILABLE, OAuthNonInteractiveError, _is_interactive
  317. from tools.mcp_oauth_provider import build_provider_kwargs, prepare_oauth_config
  318. if not _OAUTH_AVAILABLE:
  319. return None
  320. cfg, storage = prepare_oauth_config(server_name, entry.server_url, entry.oauth_config)
  321. if get_dashboard_oauth_flow() is None and not _is_interactive() and not storage.has_cached_tokens():
  322. raise OAuthNonInteractiveError(
  323. f"MCP OAuth for '{server_name}': non-interactive environment and no cached tokens found. "
  324. f"Run `hermes mcp login {server_name}` interactively first to complete initial authorization.")
  325. return _HERMES_PROVIDER_CLS(
  326. server_name=server_name, preregistered=bool(cfg.get("client_id")), server_url=entry.server_url,
  327. **build_provider_kwargs(cfg, storage, ssh_proxy_hint=False))
  328. def remove(self, server_name: str, *, hermes_home: str | Path | None = None) -> _ProviderEntry | None:
  329. """Evict the provider from cache AND delete tokens from disk (``hermes mcp remove`` / forced re-auth)."""
  330. entry = self.evict(server_name, hermes_home=hermes_home)
  331. from tools.mcp_oauth import remove_oauth_tokens
  332. remove_oauth_tokens(server_name, hermes_home=hermes_home)
  333. logger.info("MCP OAuth '%s': evicted from cache and removed from disk", server_name)
  334. return entry
  335. def restore_entry(self, server_name: str, entry: _ProviderEntry | None, *, hermes_home: str | Path | None = None) -> None:
  336. """Restore a provider entry removed for a failed reauthorization."""
  337. if entry is None:
  338. return
  339. with self._entries_lock:
  340. self._entries.setdefault(self._key(server_name, hermes_home), entry)
  341. def evict(self, server_name: str, *, hermes_home: str | Path | None = None) -> _ProviderEntry | None:
  342. """Drop only the in-process provider, preserving persisted OAuth state."""
  343. with self._entries_lock:
  344. return self._entries.pop(self._key(server_name, hermes_home), None)
  345. async def invalidate_if_disk_changed(self, server_name: str, *, hermes_home: str | Path | None = None) -> bool:
  346. """Force the SDK provider to reload when the tokens file mtime changed (e.g. a cron refresh); True if so."""
  347. from tools.mcp_oauth import _get_token_dir, _safe_filename
  348. from utils import file_cache_version
  349. entry = self._entries.get(self._key(server_name, hermes_home))
  350. if entry is None or entry.provider is None:
  351. return False
  352. async with entry.lock:
  353. try:
  354. # Hashed every time: a refresh atomically replaced in the same tick keeps the mtime,
  355. # and a racy digest going empty later would read as a change and tear the session down.
  356. version = file_cache_version(_get_token_dir(hermes_home) / f"{_safe_filename(server_name)}.json",
  357. always_digest=True)
  358. except OSError:
  359. return False
  360. if version == entry.last_version:
  361. return False
  362. mtime_ns, entry.last_version = version[0], version
  363. old, entry.last_mtime_ns = entry.last_mtime_ns, mtime_ns
  364. if old == 0 and getattr(getattr(entry.provider, "context", None), "current_tokens", None) is not None:
  365. # First observation with tokens already in memory only seeds the
  366. # baseline: the file was written by this process's own first
  367. # sign-in, and reloading on the next request would tear down the
  368. # live HTTP MCP session. With no tokens in memory (started before
  369. # an external `hermes mcp login`), fall through and reload.
  370. return False
  371. # `_initialized` is private SDK API but stable across the pinned versions (>=1.26.0).
  372. if hasattr(entry.provider, "_initialized"):
  373. entry.provider._initialized = False
  374. logger.info("MCP OAuth '%s': tokens file changed (mtime %d -> %d), forcing reload", server_name, old, mtime_ns)
  375. return True
  376. async def _recover_401(self, server_name: str, entry: _ProviderEntry, key: str, pending: asyncio.Future) -> None:
  377. """Single recovery attempt behind *pending*; always clears the dedup slot."""
  378. try:
  379. # Disk changed (external refresh)? Else: if the SDK can refresh in place, let the caller retry.
  380. can_refresh = await self.invalidate_if_disk_changed(server_name)
  381. if not can_refresh:
  382. try:
  383. can_refresh = bool(entry.provider.context.can_refresh_token())
  384. except Exception: # no context / not callable / probe failed
  385. can_refresh = False
  386. except Exception as exc: # pragma: no cover — defensive
  387. logger.warning("MCP OAuth '%s': 401 handler failed: %s", server_name, exc)
  388. can_refresh = False
  389. finally:
  390. entry.pending_401.pop(key, None)
  391. if not pending.done():
  392. pending.set_result(can_refresh)
  393. async def handle_401(self, server_name: str, failed_access_token: Optional[str] = None) -> bool:
  394. """Handle a 401 from a tool call. True: a (possibly new) token is available — reconnect and retry. False: no
  395. recovery path — surface ``needs_reauth`` so the model stops hallucinating manual refreshes. Concurrent 401s
  396. with the same ``failed_access_token`` fire one recovery attempt; the rest await its future."""
  397. entry = self._entries.get(self._key(server_name))
  398. if entry is None or entry.provider is None:
  399. return False
  400. key = failed_access_token or "<unknown>"
  401. async with entry.lock:
  402. pending = entry.pending_401.get(key)
  403. if pending is None:
  404. pending = entry.pending_401[key] = asyncio.get_running_loop().create_future()
  405. task = asyncio.create_task(self._recover_401(server_name, entry, key, pending))
  406. self._inflight_tasks.add(task)
  407. task.add_done_callback(self._inflight_tasks.discard)
  408. try:
  409. return await pending
  410. except Exception as exc: # pragma: no cover — defensive
  411. logger.warning("MCP OAuth '%s': awaiting 401 handler failed: %s", server_name, exc)
  412. return False
  413. _MANAGER: Optional[MCPOAuthManager] = None
  414. _MANAGER_LOCK = threading.Lock()
  415. def get_manager() -> MCPOAuthManager:
  416. """Return the process-wide :class:`MCPOAuthManager` singleton."""
  417. global _MANAGER
  418. with _MANAGER_LOCK:
  419. if _MANAGER is None:
  420. _MANAGER = MCPOAuthManager()
  421. return _MANAGER
  422. def reset_manager_for_tests() -> None:
  423. """Test-only helper: drop the singleton so fixtures start clean."""
  424. global _MANAGER
  425. with _MANAGER_LOCK:
  426. _MANAGER = None