Skip to content

Fix ContextVar propagation for ASGI-mounted servers with tasks#2844

Merged
chrisguidry merged 1 commit intomainfrom
fix-asgi-contextvar-propagation
Jan 12, 2026
Merged

Fix ContextVar propagation for ASGI-mounted servers with tasks#2844
chrisguidry merged 1 commit intomainfrom
fix-asgi-contextvar-propagation

Conversation

@chrisguidry
Copy link
Copy Markdown
Collaborator

Summary

Fixes background tasks failing with "Background tasks require a running FastMCP server context" when FastMCP is mounted to another ASGI application (FastAPI, Starlette, etc.) or deployed to serverless environments (Lambda, Cloud Run).

Root cause: ContextVars set during lifespan don't propagate to request handlers in ASGI environments because they run in sibling async contexts, not parent-child.

Fix: Context.__aenter__ now sets _current_docket and _current_worker from server instance attributes at request time, ensuring they're available regardless of async context hierarchy.

Changes

  • server.py: Store self._worker on server instance (self._docket was already stored)
  • context.py: Set docket/worker ContextVars from server instance in __aenter__, reset in __aexit__

Related

🤖 Generated with Claude Code

Fixes background tasks failing with "Background tasks require a running
FastMCP server context" when FastMCP is mounted to another ASGI app
(FastAPI, Starlette) or deployed to serverless environments (Lambda).

Root cause: ContextVars set during lifespan don't propagate to request
handlers in ASGI environments because they run in sibling async contexts.

Fix: Context.__aenter__ now sets _current_docket and _current_worker from
server instance attributes at request time, ensuring they're available
regardless of async context hierarchy.

Changes:
- server.py: Store self._worker on server instance (self._docket was already stored)
- context.py: Set docket/worker ContextVars from server instance in __aenter__

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@marvin-context-protocol marvin-context-protocol Bot added bug Something isn't working. Reports of errors, unexpected behavior, or broken functionality. server Related to FastMCP server implementation or server-side functionality. http Related to HTTP transport, networking, or web server functionality. labels Jan 12, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 12, 2026

Walkthrough

The changes extend context variable management in the FastMCP server to support docket and worker alongside the existing server context. The Context manager now imports and sets ContextVar tokens for _current_docket and _current_worker from the server instance during initialization, with corresponding cleanup in the exit handler. Additionally, the server stores Worker and Docket instances as internal attributes during their respective lifespans for cross-context access. These modifications enable proper context propagation in ASGI environments where context variables need to traverse different execution scopes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix ContextVar propagation for ASGI-mounted servers with tasks' clearly and specifically describes the main change: fixing ContextVar propagation for ASGI-mounted servers that use task features.
Description check ✅ Passed The PR description is comprehensive and complete: it includes a clear summary, root cause analysis, the fix implementation, specific file changes, and related issue references.
Linked Issues check ✅ Passed The PR fully addresses the linked issue #2671 by fixing ContextVar propagation so background tasks work correctly when FastMCP is mounted to ASGI apps, enabling task mode in nested lifespan scenarios.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the issue: storing worker instance and setting/resetting ContextVars at request time in both server.py and context.py are necessary and directly related to the fix.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 797297a and 923ff5e.

📒 Files selected for processing (2)
  • src/fastmcp/server/context.py
  • src/fastmcp/server/server.py
🧰 Additional context used
📓 Path-based instructions (1)
src/fastmcp/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

src/fastmcp/**/*.py: Python ≥ 3.10 with full type annotations required
Prioritize readable, understandable code - clarity over cleverness. Avoid obfuscated or confusing patterns even if shorter
Follow existing patterns and maintain consistency in code implementation
Be intentional about re-exports - don't blindly re-export everything to parent namespaces. Core types defining a module's purpose should be exported. Specialized features can live in submodules. Only re-export to fastmcp.* for most fundamental types
Never use bare except - be specific with exception types

Files:

  • src/fastmcp/server/context.py
  • src/fastmcp/server/server.py
🧬 Code graph analysis (2)
src/fastmcp/server/context.py (1)
src/fastmcp/server/low_level.py (2)
  • fastmcp (45-50)
  • fastmcp (146-151)
src/fastmcp/server/server.py (1)
src/fastmcp/cli/tasks.py (1)
  • worker (61-110)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Run tests: Python 3.10 on windows-latest
  • GitHub Check: Run tests: Python 3.10 on ubuntu-latest
  • GitHub Check: Run tests: Python 3.13 on ubuntu-latest
  • GitHub Check: Run tests with lowest-direct dependencies
🔇 Additional comments (4)
src/fastmcp/server/context.py (2)

188-204: LGTM! Correct approach for ASGI ContextVar propagation.

The implementation correctly addresses the root cause where ContextVars set during lifespan don't propagate to request handlers in ASGI environments. Setting docket/worker from the server instance at request time ensures the ContextVars are available in the request's async context.

The conditional checks (if server._docket is not None) are appropriate since docket/worker are only set when task infrastructure is active.


224-239: LGTM! Proper cleanup with LIFO token reset order.

The reset order (worker → docket → server) correctly reverses the set order. Using hasattr() checks with delattr() cleanup is appropriate since tokens are conditionally created.

src/fastmcp/server/server.py (2)

248-250: LGTM! Symmetric initialization for cross-context access.

Both _docket and _worker are now initialized to None with a descriptive comment. This ensures attributes exist before lifespan runs and enables the Context manager to propagate these values to request handlers in ASGI environments.


541-556: LGTM! Worker storage mirrors existing docket pattern.

The implementation correctly stores the Worker instance on the server for cross-context access, following the same pattern established for _docket. The cleanup in the finally block ensures _worker is cleared even if exceptions occur during the worker lifecycle.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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. http Related to HTTP transport, networking, or web server functionality. server Related to FastMCP server implementation or server-side functionality.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Background tasks fail with 'require a running FastMCP server context' when using http_app() mounted to FastAPI

1 participant