fix(proxy): restore _current_server in _restore_request_context#4168
Merged
Conversation
…4054) 🤖 Generated with Claude Code
jlowin
approved these changes
May 20, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
StatefulProxyClientruns proxy callbacks (sampling, elicitation, roots, log, progress) inside a long-lived receive-loop task._restore_request_contextrepairs that task's stale ContextVars before each handler runs — it restoredrequest_ctxand_current_context, but never_current_server. Any user-supplied callback that resolves the server through dependency injection — e.g.get_server()— therefore raisedRuntimeError: No FastMCP server instance in context, because_current_serveris normally populated byContext.__aenter__, which this path deliberately does not call.The fix restores
_current_serverdirectly, alongside_current_context, mirroring exactly whatContext.__aenter__does (_current_server.set(weakref.ref(fastmcp))). It stays set-only on purpose: this path is an in-place repair of a long-lived task's ContextVars, not a scoped lifecycle. Routing throughContext.__aenter__/__aexit__would invent a per-handler scope around something deliberately unscoped and reintroduce the problems that come with it — exception info lost through__aexit__(None, None, None), per-notificationSharedContextchurn, and cross-session_request_statebleed when the receive loop's_current_contextbelongs to another session. None of those exist when no scope is opened; the only actual gap was the missing_current_serverwrite.This supersedes #4078, which fixed the same gap by entering the
Contextas a context manager; see that PR's closing comment for the full rationale. Refs #4054 (Bug 4).