René's URL Explorer Experiment


Title: Propagate ContextVars to Transport Layer in MCP Clients · Issue #1969 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: Propagate ContextVars to Transport Layer in MCP Clients · Issue #1969 · modelcontextprotocol/python-sdk

X Title: Propagate ContextVars to Transport Layer in MCP Clients · Issue #1969 · modelcontextprotocol/python-sdk

Description: Description Summary Ensure that contextvars set in the calling thread are properly propagated to the transport layer at request time, enabling dynamic configuration of transport settings (e.g., HTTP headers, auth mechanism, etc.) on a pe...

Open Graph Description: Description Summary Ensure that contextvars set in the calling thread are properly propagated to the transport layer at request time, enabling dynamic configuration of transport settings (e.g., HTT...

X Description: Description Summary Ensure that contextvars set in the calling thread are properly propagated to the transport layer at request time, enabling dynamic configuration of transport settings (e.g., HTT...

Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/1969

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Propagate ContextVars to Transport Layer in MCP Clients","articleBody":"### Description\n\n## Summary\n\nEnsure that `contextvars` set in the calling thread are properly propagated to the transport layer at request time, enabling dynamic configuration of transport settings (e.g., HTTP headers, auth mechanism, etc.) on a per-request basis.\n\n## Problem Statement\n\nCurrently, `contextvars` set in the main thread are not visible in the transport layer when making requests. This is because:\n\n1. **Context isolation**: The `streamable_http_transport` runs in a different async context or thread, so context vars set after initialization are not visible\n2. **One-time copy**: Context may be copied only at session/transport creation time, not per-request\n\nThis prevents common use cases:\n- **Authentication**: Custom `httpx.Auth` implementations that read from context vars cannot access values set in the calling code\n- **Token Exchange**: Middleware that performs OAuth token exchange and stores the result in a context var cannot make that token available to outbound MCP requests\n- **Tracing**: Trace context set in request handlers isn't visible when the HTTP request is made\n- **Multi-tenancy**: Tenant context set per-request isn't available to the transport\n\n### Why ContextVars?\n\nPython's `contextvars` module is the standard mechanism for request-scoped state:\n- Already widely used in async frameworks (FastAPI, Starlette, aiohttp)\n- Thread-safe and async-safe by design\n- Values can be set in middleware/handlers and should be available downstream\n- Zero coupling between application code and transport internals\n\n## Proposed Solution\n\nEnsure that context vars are properly propagated from the calling code to the transport layer at request time. This would allow:\n\n1. Custom `httpx.Auth` implementations to read context vars\n2. Any code in the transport layer to access current context\n\n### Example Use Case: Custom Auth\n\n```python\nfrom contextvars import ContextVar\nimport httpx\nfrom mcp.client.streamable_http import streamable_http_client\n\n# Application defines context var for auth\nauth_token_var: ContextVar[str] = ContextVar('auth_token')\n\n\nclass ContextVarAuth(httpx.Auth):\n    \"\"\"Auth that reads token from context var.\"\"\"\n    \n    def auth_flow(self, request):\n        try:\n            token = auth_token_var.get()\n            request.headers[\"Authorization\"] = f\"Bearer {token}\"\n        except LookupError:\n            pass  # No token set\n        yield request\n\n\n# Create client with custom auth\nclient = httpx.AsyncClient(auth=ContextVarAuth())\n\nasync with streamable_http_client(\n    \"https://mcp.example.com\",\n    http_client=client,\n) as (read, write, _):\n    async with ClientSession(read, write) as session:\n        await session.initialize()\n        \n        # Request 1: Set context for user A\n        auth_token_var.set(\"user-a-token\")\n        await session.call_tool(\"tool1\", arguments={})  # Auth reads \"user-a-token\"\n        \n        # Request 2: Set context for user B  \n        auth_token_var.set(\"user-b-token\")\n        await session.call_tool(\"tool2\", arguments={})  # Auth reads \"user-b-token\"\n```\n\n### Current Behavior (Broken)\n\nThe above example doesn't work today because when `auth_flow` is called, it runs in a different context where `auth_token_var` doesn't have the value set in the calling code.\n\n### Expected Behavior\n\nContext vars set before calling `session.call_tool()` should be visible in:\n- The transport's HTTP request code\n- Custom `httpx.Auth` implementations\n- Any callbacks or handlers in the transport layer\n\n## Implementation Notes\n\nThe fix likely requires copying the context at request time (not just at session creation) using `contextvars.copy_context()` and running transport code within that context.\n\n## Relationship to Explicit Transport Configuration\n\nThere is a separate proposal (#1966) for explicit per-request transport configuration. Both approaches serve different purposes: context vars enable implicit, zero-touch propagation from middleware/handlers without changing caller code, while explicit configuration provides direct control with clear data flow. Both features are valuable and complementary. Additionally, fixing context var propagation would prevent breaking existing code that relies on context vars being visible in downstream code.\n\n## Related Issues\n\n- https://github.com/modelcontextprotocol/python-sdk/issues/1966\n\n\n### References\n\n_No response_","author":{"url":"https://github.com/somaraani","@type":"Person","name":"somaraani"},"datePublished":"2026-01-28T19:17:59.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":5},"url":"https://github.com/1969/python-sdk/issues/1969"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:85b96876-42f6-c0e8-ca76-09ef51de18e6
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idA71A:6973B:624B55:82DA1E:6A613F4E
html-safe-nonce9405d6fdd905f50cede71f13f717761e0917d4831fbb3ebe8f529d9626199b7f
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBNzFBOjY5NzNCOjYyNEI1NTo4MkRBMUU6NkE2MTNGNEUiLCJ2aXNpdG9yX2lkIjoiNjM2OTMwOTg2ODkzNzAwMjgzMCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac763364a6d897bf8fa7abcf8bdfa1422fecc57dcf1568e4cb2afd6580de7059ee
hovercard-subject-tagissue:3866977549
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/1969/issue_layout
twitter:imagehttps://opengraph.githubassets.com/7fadfb934dd4efe92d6144fc111fa386df8e84a829c8a81c7164e0f0472f7714/modelcontextprotocol/python-sdk/issues/1969
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/7fadfb934dd4efe92d6144fc111fa386df8e84a829c8a81c7164e0f0472f7714/modelcontextprotocol/python-sdk/issues/1969
og:image:altDescription Summary Ensure that contextvars set in the calling thread are properly propagated to the transport layer at request time, enabling dynamic configuration of transport settings (e.g., HTT...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamesomaraani
hostnamegithub.com
expected-hostnamegithub.com
None2b7a3d1e6770dc7153450d820fcfe9a7851c4cf2251dcc29c7ad3c5cd1b9e88b
turbo-cache-controlno-preview
go-importgithub.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git
octolytics-dimension-user_id182288589
octolytics-dimension-user_loginmodelcontextprotocol
octolytics-dimension-repository_id862584018
octolytics-dimension-repository_nwomodelcontextprotocol/python-sdk
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id862584018
octolytics-dimension-repository_network_root_nwomodelcontextprotocol/python-sdk
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release78cf9d43f120d1f03636ca22ab420bcbb1712804
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/1969#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F1969
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
Code QualityEnforce quality at mergehttps://github.com/features/code-quality
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F1969
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=modelcontextprotocol%2Fpython-sdk
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1969
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1969
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1969
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/issues/1969
modelcontextprotocol https://github.com/modelcontextprotocol
python-sdkhttps://github.com/modelcontextprotocol/python-sdk
Notifications https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Fork 3.7k https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Star 23.7k https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Code https://github.com/modelcontextprotocol/python-sdk
Issues 268 https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests 311 https://github.com/modelcontextprotocol/python-sdk/pulls
Actions https://github.com/modelcontextprotocol/python-sdk/actions
Projects https://github.com/modelcontextprotocol/python-sdk/projects
Models https://github.com/modelcontextprotocol/python-sdk/models
Security and quality 6 https://github.com/modelcontextprotocol/python-sdk/security
Insights https://github.com/modelcontextprotocol/python-sdk/pulse
Code https://github.com/modelcontextprotocol/python-sdk
Issues https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests https://github.com/modelcontextprotocol/python-sdk/pulls
Actions https://github.com/modelcontextprotocol/python-sdk/actions
Projects https://github.com/modelcontextprotocol/python-sdk/projects
Models https://github.com/modelcontextprotocol/python-sdk/models
Security and quality https://github.com/modelcontextprotocol/python-sdk/security
Insights https://github.com/modelcontextprotocol/python-sdk/pulse
#2298https://github.com/modelcontextprotocol/python-sdk/pull/2298
Propagate ContextVars to Transport Layer in MCP Clientshttps://github.com/modelcontextprotocol/python-sdk/issues/1969#top
#2298https://github.com/modelcontextprotocol/python-sdk/pull/2298
enhancementRequest for a new feature that's not currently supportedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22enhancement%22
needs confirmationNeeds confirmation that the PR is actually required or needed.https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22needs%20confirmation%22
v2Ideas, requests and plans for v2 of the SDK which will incorporate major changes and fixeshttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v2%22
https://github.com/somaraani
somaraanihttps://github.com/somaraani
on Jan 28, 2026https://github.com/modelcontextprotocol/python-sdk/issues/1969#issue-3866977549
#1966https://github.com/modelcontextprotocol/python-sdk/issues/1966
Per-Request Transport Configuration for MCP Clients #1966https://github.com/modelcontextprotocol/python-sdk/issues/1966
enhancementRequest for a new feature that's not currently supportedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22enhancement%22
needs confirmationNeeds confirmation that the PR is actually required or needed.https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22needs%20confirmation%22
v2Ideas, requests and plans for v2 of the SDK which will incorporate major changes and fixeshttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v2%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.