generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 607
fix(mcp): propagate contextvars to background thread #1444
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
pgrayy
merged 2 commits into
strands-agents:main
from
cagataycali:fix/mcp-contextvar-propagation
Jan 13, 2026
Merged
fix(mcp): propagate contextvars to background thread #1444
pgrayy
merged 2 commits into
strands-agents:main
from
cagataycali:fix/mcp-contextvar-propagation
Jan 13, 2026
Conversation
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
Fixes strands-agents#1440 The MCP client creates a background thread for connection management. Previously, context variables set in the main thread were not accessible in this background thread. This change copies the context from the main thread when starting the background thread, ensuring that contextvars are properly propagated. This is consistent with the fix in PR strands-agents#1146 which addressed the same issue for tool invocations. Changes: - Add contextvars import - Use contextvars.copy_context() and ctx.run() when creating background thread - Add test to verify context propagation
3 tasks
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
This was referenced Jan 10, 2026
mkmeral
approved these changes
Jan 13, 2026
afarntrog
approved these changes
Jan 13, 2026
pgrayy
approved these changes
Jan 13, 2026
3 tasks
strands-agent
added a commit
to strands-agent/sdk-python
that referenced
this pull request
Jan 19, 2026
Fixes strands-agents#1512 In ASGI environments (uvicorn/hypercorn) that already have an active event loop, the MCPClient background thread initialization can fail with: 'RuntimeWarning: coroutine was never awaited' because run_until_complete() cannot execute the coroutine. Root cause: PR strands-agents#1444 added contextvars.copy_context() to propagate context variables to the background thread. In ASGI environments, this can copy event loop references from the parent thread, causing conflicts when the background thread tries to create its own event loop. Solution: Explicitly clear any inherited event loop state by calling asyncio.set_event_loop(None) before creating the new event loop. This ensures the background thread starts with a clean slate regardless of what context was copied from the parent thread. This fix is defensive and handles partial initialization gracefully with a try/except block around set_event_loop(None). Testing: - Existing MCP tests pass (no regression) - Fixes MCPClient usage under uvicorn/ASGI environments - Compatible with OpenTelemetry instrumentation
9 tasks
strands-agent
added a commit
to strands-agent/sdk-python
that referenced
this pull request
Jan 20, 2026
…event loop Fixes strands-agents#1512 When MCPClient runs in ASGI environments (uvicorn, hypercorn), the parent thread has an active event loop. Since PR strands-agents#1444 uses contextvars.copy_context() to propagate context variables to the background thread, it also copies the _running_loop contextvar marker. When the background thread then calls run_until_complete(), Python's asyncio detects the inherited running loop marker and raises: 'Cannot run the event loop while another loop is running' The fix clears both: 1. The _running_loop contextvar via events._set_running_loop(None) 2. The thread-local event loop via asyncio.set_event_loop(None) This ensures the background thread starts with a clean slate while still preserving context variable propagation from PR strands-agents#1444. Solution verified by issue reporter @jpvelasco.
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.
Description
Fixes #1440
The MCP client creates a background thread for connection management. Previously, context variables set in the main thread were not accessible in this background thread.
This change copies the context from the main thread when starting the background thread, ensuring that contextvars are properly propagated. This is consistent with the fix in PR #1146 which addressed the same issue for tool invocations.
Changes
contextvarsimportcontextvars.copy_context()andctx.run()when creating background threadExample (from issue #1440)
Related Issues
Documentation PR
No documentation changes required - this is an internal implementation detail.
Type of Change
Bug fix
Testing
hatch run prepare(formatter and linter)hatch test tests/strands/tools/mcp/test_mcp_client.py- 50 tests passhatch test tests/strands/tools/mcp/test_mcp_client_contextvar.py- new test passesChecklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
Created by strands-coder autonomous agent 🦆