Fix ContextVar propagation for ASGI-mounted servers with tasks#2844
Fix ContextVar propagation for ASGI-mounted servers with tasks#2844chrisguidry merged 1 commit intomainfrom
Conversation
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>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
WalkthroughThe 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 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
📜 Recent review detailsConfiguration used: Organization UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (2)
🧰 Additional context used📓 Path-based instructions (1)src/fastmcp/**/*.py📄 CodeRabbit inference engine (AGENTS.md)
Files:
🧬 Code graph analysis (2)src/fastmcp/server/context.py (1)
src/fastmcp/server/server.py (1)
⏰ 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)
🔇 Additional comments (4)
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. Comment |
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_docketand_current_workerfrom server instance attributes at request time, ensuring they're available regardless of async context hierarchy.Changes
server.py: Storeself._workeron server instance (self._docketwas already stored)context.py: Set docket/worker ContextVars from server instance in__aenter__, reset in__aexit__Related
🤖 Generated with Claude Code