python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

fix(oauth): narrow context.lock scope in async_auth_flow (rebase of #2660 by @peisuke, closes #2847)

Open Bartok9 opened this issue 5 months ago • 0 comments

Summary

This is a conflict-free rebase of #2660 by @peisuke onto current main, opened as a fresh, mergeable PR so it can land without waiting on the original draft to be un-conflicted. All credit for the fix goes to @peisuke — the four commits below preserve their original authorship; I only resolved the rebase against main.

Closes #2847. Addresses the same RuntimeError: The current task is not holding this lock reported in #2644 and #2847.

Why a new PR

#2660 has been a CONFLICTING draft since May 22 with no maintainer review. Issue #2847 (June 12) is a second, independent production repro of the exact bug, and the reporter explicitly asks for #2660 to be reviewed/merged. The conflict against main is small and isolated to the Phase-1 refresh block. Rather than let the fix keep sitting, this PR provides a ready-to-merge version.

If maintainers prefer to merge #2660 directly, or if @peisuke wants to push the rebase to their own branch, this PR can be closed — the goal is just to unblock the fix. @peisuke, happy to defer entirely to you.

The bug

OAuthContext.lock is an anyio.Lock, which records task identity at acquire() and enforces same-task release(). async_auth_flow holds this lock across yield points. When httpx drives the generator from a different task during concurrent OAuth connections (e.g. Notion's frequent token refresh behind a gateway), release() raises RuntimeError: The current task is not holding this lock.

The fix (@peisuke's approach)

Narrow the lock scope so no HTTP yield (including the long-poll GET SSE and the token-refresh round trips) runs while holding context.lock, plus a single-flight refresh_lock with a re-check under the lock. This keeps trio portability (unlike swapping to asyncio.Lock).

Commits (authored by @peisuke)

  • fix(oauth): narrow async_auth_flow lock scope to avoid blocking long-poll requests
  • test: add regression coverage for OAuthClientProvider concurrent requests
  • test: cover refresh failure paths and double-check refresh skip
  • fix(oauth): cover Python 3.10/3.11 partial-branch coverage gap

Verification

Rebased onto current main (cf110e3). 0 behind, 4 ahead, touches only src/mcp/client/auth/oauth2.py and tests/client/test_auth.py.

$ uv run pytest tests/client/test_auth.py -q
108 passed, 1 xfailed (0.26s)

$ uv run ruff check src/mcp/client/auth/oauth2.py tests/client/test_auth.py
All checks passed!

cc @peisuke @EnGassa

Bartok9 avatar Jun 13 '26 14:06 Bartok9