fix(mcp): clear running loop state before creating background thread event loop #1513
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 #1512
This PR fixes the issue where
MCPClientfails to start in ASGI environments (uvicorn/hypercorn) with the error:Root Cause
PR #1444 added
contextvars.copy_context()to propagate context variables to the background thread (fixing #1440). However, in ASGI environments where the parent thread already has an active event loop, copying the context also copies the_running_loopcontextvar marker.When the background thread calls
run_until_complete(), Python's asyncio detects this inherited running loop marker and raises:Credit to @jpvelasco for identifying the actual root cause: the issue is the
_running_loopcontextvar (viaasyncio.events._set_running_loop), not just the thread-local event loop.Solution
Clear both the running loop marker and thread-local event loop before creating the new event loop:
Why This Works
Related Issues
Documentation PR
No documentation changes required - this is an internal implementation fix.
Type of Change
Bug fix (non-breaking change which fixes an issue)
Testing
Checklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
PR created by strands-coder autonomous agent with fix verified by @jpvelasco 🧬