Skip to content

fix(proxy): restore _current_server in _restore_request_context#4168

Merged
jlowin merged 1 commit into
mainfrom
fix/proxy-restore-current-server
May 20, 2026
Merged

fix(proxy): restore _current_server in _restore_request_context#4168
jlowin merged 1 commit into
mainfrom
fix/proxy-restore-current-server

Conversation

@strawgate
Copy link
Copy Markdown
Collaborator

StatefulProxyClient runs proxy callbacks (sampling, elicitation, roots, log, progress) inside a long-lived receive-loop task. _restore_request_context repairs that task's stale ContextVars before each handler runs — it restored request_ctx and _current_context, but never _current_server. Any user-supplied callback that resolves the server through dependency injection — e.g. get_server() — therefore raised RuntimeError: No FastMCP server instance in context, because _current_server is normally populated by Context.__aenter__, which this path deliberately does not call.

The fix restores _current_server directly, alongside _current_context, mirroring exactly what Context.__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 through Context.__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-notification SharedContext churn, and cross-session _request_state bleed when the receive loop's _current_context belongs to another session. None of those exist when no scope is opened; the only actual gap was the missing _current_server write.

# inside a stateful-proxy elicitation/sampling/roots handler
from fastmcp.server.dependencies import get_server

async def my_handler(message, response_type, params, ctx):
    server = get_server()   # before: RuntimeError; after: the proxy's FastMCP
    ...

This supersedes #4078, which fixed the same gap by entering the Context as a context manager; see that PR's closing comment for the full rationale. Refs #4054 (Bug 4).

@strawgate strawgate added bug Something isn't working. Reports of errors, unexpected behavior, or broken functionality. server Related to FastMCP server implementation or server-side functionality. labels May 17, 2026
@jlowin jlowin merged commit 1c4069e into main May 20, 2026
10 checks passed
@jlowin jlowin deleted the fix/proxy-restore-current-server branch May 20, 2026 14:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working. Reports of errors, unexpected behavior, or broken functionality. server Related to FastMCP server implementation or server-side functionality.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants