The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(mcp-oauth): split the refresh fence into acquire/release functions, drop the lock sidecar on remove
kshitijk4poor60262f71bdf8
diff --git a/tests/tools/test_mcp_oauth.py b/tests/tools/test_mcp_oauth.pyindex bb854eb72ae..272e55452c9 100644--- a/tests/tools/test_mcp_oauth.py+++ b/tests/tools/test_mcp_oauth.py@@ -5,7 +5,6 @@ import statimport sysimport timefrom io import BytesIO-from pathlib import Pathfrom unittest.mock import patch, MagicMockfrom urllib.parse import quotediff --git a/tests/tools/test_mcp_oauth_manager.py b/tests/tools/test_mcp_oauth_manager.pyindex 5d9599cb21a..c0f3a7b6ae3 100644--- a/tests/tools/test_mcp_oauth_manager.py+++ b/tests/tools/test_mcp_oauth_manager.py@@ -835,14 +835,17 @@ async def test_refresh_fails_closed_while_a_peer_holds_the_fence(tmp_path, monkeprovider = _fenced_provider(tmp_path, monkeypatch, endpoint)await provider.context.storage.set_tokens(_token("A1", "R1"))monkeypatch.setattr(- mcp_oauth, "_refresh_fence", functools.partial(mcp_oauth._refresh_fence, timeout=0.2)+ mcp_oauth, "acquire_refresh_fence", functools.partial(mcp_oauth.acquire_refresh_fence, timeout=0.2))sent = []- async with mcp_oauth._refresh_fence(provider.context.storage._tokens_path()):+ peer_fd = await mcp_oauth.acquire_refresh_fence(provider.context.storage._tokens_path())+ try:with pytest.raises(mcp_oauth.RefreshFenceTimeout):await _drive_flow(provider, sent.append)+ finally:+ mcp_oauth.release_refresh_fence(peer_fd)assert sent == []assert provider.context.current_tokens.refresh_token == "R1"@@ -922,6 +925,5 @@ async def test_refresh_fence_surfaces_non_contention_lock_errors_immediately(tmpmonkeypatch.setattr(mcp_oauth.fcntl, "flock", broken_flock)started = time.monotonic()with pytest.raises(mcp_oauth.RefreshFenceTimeout, match="unavailable on this filesystem"):- async with mcp_oauth._refresh_fence(tmp_path / "srv.json", timeout=5.0):- pass+ await mcp_oauth.acquire_refresh_fence(tmp_path / "srv.json", timeout=5.0)assert time.monotonic() - started < 1.0, "must fail fast, not wait out the deadline"diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.pyindex c08888e8f7c..c824478e641 100644--- a/tools/mcp_oauth.py+++ b/tools/mcp_oauth.py@@ -73,9 +73,12 @@ class RefreshFenceTimeout(RuntimeError):_FENCE_CONTENTION_ERRNOS = frozenset({errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES, errno.EDEADLK})-async def _refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUT_SECONDS):- """Own one refresh generation across read -> POST -> persist.+def _refresh_lock_path(path: "Path") -> "Path":+ return path.with_suffix(path.suffix + ".refresh.lock")+++async def acquire_refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUT_SECONDS) -> int:+ """Take the fence that owns one refresh generation across read -> POST -> persist.Token files are written atomically (``_write_json``), so a reader neversees a torn file; the only cross-process hazard is the read-modify-write@@ -98,13 +101,16 @@ async def _refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUalready excludes sibling tasks and threads of the same process.Acquisition failure RAISES. Degrading to "proceed unlocked" would- reintroduce the exact race.+ reintroduce the exact race. Returns the locked descriptor; the caller+ hands it back to ``release_refresh_fence`` from its own exit path (the+ SDK drives the refresh as a generator, so no single ``with`` block can+ span the critical section)."""- lock_path = path.with_suffix(path.suffix + ".refresh.lock")+ lock_path = _refresh_lock_path(path)try:lock_path.parent.mkdir(parents=True, exist_ok=True)secure_parent_dir(lock_path)- lock_fd = open(lock_path, "a+", encoding="utf-8")+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)except OSError as exc:# No lock file means no ownership proof. Fail closed: see the# class docstring for why proceeding is worse than aborting.@@ -112,24 +118,19 @@ async def _refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUf"refresh fence unavailable ({lock_path.name}): {exc}") from exc- acquired = False+ deadline = time.monotonic() + timeouttry:- lock_fd.seek(0)- deadline = time.monotonic() + timeoutwhile True:try:if fcntl is not None:- fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)elif msvcrt is not None:- getattr(msvcrt, "locking")(- lock_fd.fileno(), getattr(msvcrt, "LK_NBLCK"), 1- )+ getattr(msvcrt, "locking")(fd, getattr(msvcrt, "LK_NBLCK"), 1)else: # pragma: no cover - no advisory locking primitiveraise RefreshFenceTimeout("refresh fence unsupported: no flock/msvcrt on this platform")- acquired = True- break+ return fdexcept OSError as exc:if exc.errno not in _FENCE_CONTENTION_ERRNOS:# Not "a peer holds it" but "this filesystem cannot lock"@@ -143,21 +144,23 @@ async def _refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUf"refresh fence held by a peer for {timeout:.0f}s ({lock_path.name})") from Noneawait asyncio.sleep(0.05)+ except BaseException:+ os.close(fd)+ raise- yield++def release_refresh_fence(fd: int) -> None:+ """Unlock and close a descriptor returned by ``acquire_refresh_fence``. Never raises."""+ try:+ if fcntl is not None:+ fcntl.flock(fd, fcntl.LOCK_UN)+ elif msvcrt is not None:+ getattr(msvcrt, "locking")(fd, getattr(msvcrt, "LK_UNLCK"), 1)+ except OSError:+ passfinally:- try:- if acquired:- if fcntl is not None:- fcntl.flock(lock_fd, fcntl.LOCK_UN)- elif msvcrt is not None:- getattr(msvcrt, "locking")(- lock_fd.fileno(), getattr(msvcrt, "LK_UNLCK"), 1- )- except (OSError, IOError):- pass- finally:- lock_fd.close()+ with contextlib.suppress(OSError):+ os.close(fd)# ---------------------------------------------------------------------------@@ -563,7 +566,7 @@ class HermesTokenStorage:def remove(self) -> None:"""Delete all stored OAuth state for this server."""- for p in (*self._state_paths(), self._cimd_rejected_path()):+ for p in (*self._state_paths(), self._cimd_rejected_path(), _refresh_lock_path(self._tokens_path())):p.unlink(missing_ok=True)def snapshot(self) -> dict[str, bytes]:diff --git a/tools/mcp_oauth_provider.py b/tools/mcp_oauth_provider.pyindex 3b1c196e635..1ae586154bd 100644--- a/tools/mcp_oauth_provider.py+++ b/tools/mcp_oauth_provider.py@@ -74,9 +74,9 @@ class HermesProviderMixin:self._coerce_client_secret_post()return self._prepare_token_request(await super()._exchange_token_authorization_code(*args, **kwargs))- # Set while this provider owns the refresh fence; cleared by+ # Locked descriptor while this provider owns the refresh fence; cleared by# _hermes_release_refresh_fence. Never shared across instances.- _hermes_fence: Any = None+ _hermes_fence: int | None = Noneasync def async_auth_flow(self, request):"""Guarantee fence release even if the auth generator is abandoned.@@ -130,7 +130,7 @@ class HermesProviderMixin:The fence is acquired BEFORE the final read of the refresh token and isreleased only after _handle_refresh_response has persisted thereplacement, so one refresh generation is consumed by exactly one- process. See tools.mcp_oauth._refresh_fence for the interleaving this+ process. See tools.mcp_oauth.acquire_refresh_fence for the interleaving thiscloses.Holding a lock across ``yield`` in the SDK's generator-based auth flow@@ -176,26 +176,22 @@ class HermesProviderMixin:be POSTed. A stale fence from an aborted attempt is replaced ratherthan stacked, so a crashed generator cannot leak ownership."""- from tools.mcp_oauth import _refresh_fence+ from tools.mcp_oauth import acquire_refresh_fenceawait self._hermes_release_refresh_fence()storage = self.context.storagetokens_path = getattr(storage, "_tokens_path", None)if tokens_path is None: # pragma: no cover - non-Hermes storagereturn- fence = _refresh_fence(tokens_path())- await fence.__aenter__()- self._hermes_fence = fence+ self._hermes_fence = await acquire_refresh_fence(tokens_path())async def _hermes_release_refresh_fence(self) -> None:"""Release the fence if held. Idempotent and never raises."""- fence, self._hermes_fence = self._hermes_fence, None- if fence is None:- return- try:- await fence.__aexit__(None, None, None)- except Exception: # pragma: no cover - release must never mask the outcome- self._hermes_logger.debug("Refresh fence release failed", exc_info=True)+ from tools.mcp_oauth import release_refresh_fence++ fd, self._hermes_fence = self._hermes_fence, None+ if fd is not None:+ release_refresh_fence(fd)async def _hermes_rotated_candidate(self):"""The on-disk pair, if a peer rotated it past the one we hold.