Skip to content

Conversation

@cagataycali
Copy link
Member

Description

This PR fixes the issue where MCPClient does not propagate contextvars to its background thread, causing context variables set in the calling thread to be inaccessible in custom transports or auth logic.

Related Issues

Root Cause

In MCPClient.start(), the background thread is created without copying the current context:

# Before (problematic)
self._background_thread = threading.Thread(target=self._background_task, args=[], daemon=True)

This means any contextvars set in the calling thread are not accessible in the background thread.

Solution

Apply the same pattern used in PR #1146 (src/strands/_async.py) - copy the context and run the background task via context.run():

# After (fixed)
ctx = contextvars.copy_context()
self._background_thread = threading.Thread(target=ctx.run, args=(self._background_task,), daemon=True)

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

  • I ran hatch run prepare
  • The fix follows the exact same pattern that was tested and validated in PR share thread context #1146
  • Tested scenarios:
    • Context variables set before MCPClient.start() are now accessible in the transport callable
    • Context variables are available for auth logic that runs in the background thread

Checklist

  • I have read the CONTRIBUTING document
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

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 🦆

Fixes strands-agents#1440

The MCP client creates a background thread for connection management
but doesn't propagate contextvars from the calling thread. This prevents
custom transports and auth logic from accessing context variables set
before the MCP client is started.

The fix follows the same pattern established in PR strands-agents#1146 (src/strands/_async.py)
by copying the current context with contextvars.copy_context() and running
the background task via context.run().
@codecov
Copy link

codecov bot commented Jan 10, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] MCP Client does not propagate contextvars

1 participant