fix(oauth): narrow context.lock scope in async_auth_flow
Narrows the lock scope inside OAuthClientProvider.async_auth_flow so the actual HTTP request yield runs outside any lock. Concurrent requests through the same provider — in particular, a POST issued while a GET SSE long-poll is in flight — no longer serialize on context.lock. A new refresh_lock preserves single-flight semantics for token refresh so the change does not introduce a refresh race.
Motivation and Context
OAuthClientProvider.async_auth_flow previously held self.context.lock for the entire flow body, including the response = yield request that hands the request off to httpx. For requests that complete quickly this is fine, but a Streamable HTTP transport opens a long-lived GET SSE stream for server-initiated messages alongside the POST stream for client-initiated RPCs. Both go through the same OAuthClientProvider instance, so the GET SSE long-poll's yield request holds context.lock for the entire SSE lifetime. Any concurrent tools/call POST then blocks on the lock until the SSE returns, producing a multi-second stall in OAuth-authenticated MCP connections.
This commit splits the single coarse lock into purpose-specific scopes:
- Phase 1 (
context.lock): initialize state, captureprotocol_version, and decide whether a refresh is needed. Short-held; no HTTP I/O. - Phase 2 (
refresh_lock, new): single-flight token refresh. The refreshyieldhappens outside any lock. A double-check insidecontext.lockensures concurrent waiters do not redundantly refresh after another coroutine completed one. - Phase 3 (no lock): add the auth header and yield the actual request. GET SSE long-polls and other long-running requests no longer block unrelated traffic.
- Phase 4 (
context.lock): 401 / 403 full OAuth re-auth path. Conservatively kept under lock because this path is rare and its yielded sub-requests target the AS, not the resource server. A future change can narrow this further with the same pattern.
refresh_lock is added to OAuthContext (alongside the existing lock) so concurrent expirations trigger at most one refresh request. The double-check pattern inside refresh_lock makes the second waiter observe the freshly-updated token and skip its own refresh.
How Has This Been Tested?
Five new tests in tests/client/test_auth.py exercise the refactor:
test_concurrent_request_not_blocked_by_pending_long_running_request— the core regression test. Drives oneasync_auth_flowgenerator to its yield (simulating a GET SSE long-poll), then opens a second flow on the same provider and asserts it reaches its own yield withinanyio.fail_after(5). Pre-fix this hangs indefinitely.test_refresh_lock_double_check_skips_redundant_refresh— a flow started after another finished its refresh observes the fresh token in Phase 1 and skips Phase 2 entirely; no second refresh request is sent.test_double_check_inside_refresh_lock_skips_second_refresh— monkeypatchesis_token_validto return False in Phase 1 and True in the Phase 2 double-check, exercising the branch where a second coroutine's refresh is correctly elided insiderefresh_lock.test_refresh_with_failed_status_clears_tokens— covers the failed-refresh path (status_code != 200) including the_initialized = Falsereset.test_refresh_with_invalid_json_clears_tokens— covers theValidationErrorbranch when the refresh response body is malformed.
./scripts/test is clean: 1177 passed / 98 skipped / 1 xfailed, 100.00% coverage on src/mcp/client/auth/oauth2.py, strict-no-cover reports no leftover # pragma: no cover violations. Four previously-needed pragmas in _handle_refresh_response and the Phase 2 yield are now covered by the new tests and removed.
Breaking Changes
None. Public API is unchanged. Concurrency semantics narrow only — previously-serialized requests now proceed in parallel; token refresh remains serialized via refresh_lock.
Types of changes
- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Documentation update
Checklist
- [x] I have read the MCP Documentation
- [x] My code follows the repository's style guidelines
- [x] New and existing tests pass locally
- [x] I have added appropriate error handling
- [x] I have added or updated documentation as needed
Additional context
Targets main (v2 development). The same bug exists on v1.x; if a backport is wanted, that can land as a follow-up PR.
Fixes #1326
Re-confirmation + offer of a conflict-free rebase.
This fix is needed: #2847 just landed (June 12) as a second, independent production repro of the exact RuntimeError: The current task is not holding this lock this PR addresses — a gateway connecting to multiple OAuth MCP servers concurrently, where anyio.Lock (which records task identity at acquire() and enforces same-task release()) is held across the yield in async_auth_flow, so httpx driving the generator from a different task throws on release. The reporter explicitly asks for this PR to be reviewed/merged.
The PR currently shows CONFLICTING against main. The conflict is small and isolated to the Phase-1 refresh block (main still has the inline refresh under the held lock; this PR restructures it into Phase-1 decision / Phase-2 single-flight refresh outside the lock). I rebased the four commits onto current main (616476f-era) — the resolution is purely "take this PR's restructured refresh path" — and the result is green:
uv run pytest tests/client/test_auth.py -q
108 passed, 1 xfailed (0.29s)
uv run ruff check src/mcp/client/auth/oauth2.py tests/client/test_auth.py
All checks passed!
Conflict-free rebase (author/commits preserved): https://github.com/Bartok9/python-sdk/tree/salvage/2660-oauth-lock-rebase — happy to open it as a fresh PR if @peisuke is unavailable to push, or @peisuke can cherry-pick. The single-flight refresh_lock + re-check-under-lock pattern is the right shape; narrowing the lock so no HTTP yield (especially the long-poll GET SSE) runs while holding context.lock is exactly what unblocks the concurrent case.
Opened #2858 — a conflict-free rebase of this PR's four commits onto current main (your authorship preserved on all four), so the fix can be merged without waiting on this draft to be un-conflicted. Full credit is yours, @peisuke — I only resolved the rebase. It's green (108 auth tests pass, ruff clean) and closes #2847. Glad to close #2858 if you'd rather push the rebase here or if maintainers prefer to merge this PR directly — just didn't want the fix to keep sitting now that #2847 is a second production repro.
Hi @peisuke — wanted to give you a clear heads-up on what I did here and why, so nothing feels like it went around you.
What I did: I opened #2858, which is your four commits from this PR rebased cleanly onto current main. Your authorship is preserved on every commit ([email protected]), and the PR title and description both state plainly that the fix is yours — I only resolved the rebase, I didn't change the approach or claim the work.
Why I did it: This PR has been a CONFLICTING draft since May 22 with no maintainer review, and the conflict against main has been the thing blocking it. Then #2847 landed on June 12 as a second, independent production repro of the exact RuntimeError your fix addresses, with the reporter explicitly asking for this PR to be merged. Rather than let a correct, well-tested fix keep sitting behind a mechanical rebase conflict, I put up a ready-to-merge version so a maintainer can act on it today.
Your call from here: If you'd rather push the rebase to this branch yourself, or maintainers prefer to merge this PR directly, I'll close #2858 immediately — it exists only to unblock your fix, not to replace it. The credit is and should remain yours. Just let me know what you prefer.
Thanks for the original fix — the narrow-the-lock-scope + single-flight refresh_lock approach is the right shape, and it keeps trio portability (unlike the asyncio.Lock swap others floated).
Thanks @Bartok9 — really appreciate you picking this up, and especially the care around authorship and credit.
Let's go with #2858. It's already green, rebased cleanly onto main, and closes #2847, so it's the fastest path to getting this in front of a maintainer — no need to wait on me to un-conflict this draft.
I'm happy to treat #2858 as the canonical PR from here, and to close this one (#2660) as superseded if maintainers prefer a single thread — just say the word. The narrow-the-lock + single-flight refresh_lock shape is exactly what I intended, and keeping trio portability was deliberate, so I'm glad that carried through the rebase.
Thanks again for unblocking it.