René's URL Explorer Experiment


Title: Per-Request Transport Configuration for MCP Clients · Issue #1966 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: Per-Request Transport Configuration for MCP Clients · Issue #1966 · modelcontextprotocol/python-sdk

X Title: Per-Request Transport Configuration for MCP Clients · Issue #1966 · modelcontextprotocol/python-sdk

Description: Summary Add support for configuring transport settings (e.g., authentication headers, tracing context) dynamically on a per-request basis. This is essential for use cases where settings like authentication tokens or trace IDs need to cha...

Open Graph Description: Summary Add support for configuring transport settings (e.g., authentication headers, tracing context) dynamically on a per-request basis. This is essential for use cases where settings like authen...

X Description: Summary Add support for configuring transport settings (e.g., authentication headers, tracing context) dynamically on a per-request basis. This is essential for use cases where settings like authen...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Per-Request Transport Configuration for MCP Clients","articleBody":"## Summary\n\nAdd support for configuring transport settings (e.g., authentication headers, tracing context) dynamically on a per-request basis. This is essential for use cases where settings like authentication tokens or trace IDs need to change between requests.\n\n## Problem Statement\n\nCurrently, MCP clients only supports setting context at initialization time:\n\n1. **HTTP headers** are configured on the `httpx.AsyncClient` at connection establishment\n2. **Session-level context** is fixed at `ClientSession` creation\n3. **Transport-level configuration** is determined when the transport context manager is entered\n\nThis architecture doesn't support common production requirements:\n- **Per-Request Authentication**: Auth tokens that need to be propagated per-request based on the calling user's context\n- **Request Tracing**: Trace IDs/span IDs that change per request\n- **Dynamic Headers**: Headers that vary based on request context (tenant IDs, correlation IDs, etc.)\n\n### Current Workaround Attempts\n\nUsers attempting to propagate context via `contextvars` face challenges:\n- Context vars are copied at session start, not per-request\n- The background thread pattern means context vars set after initialization are not visible\n- Even with context propagation to the background thread, there's no mechanism to pass that context to the HTTP transport layer\n\n### Current API Limitations\n\nThe existing `read_timeout_seconds` parameter on `call_tool()` is a transport-specific concern (HTTP timeout) that was added directly to the session method. This approach doesn't scale as different transports have different configuration needs, and adding transport-specific parameters to session methods leads to API bloat. A generic per-request configuration mechanism would offer more extensibility. \n\nIn addition, this functionality should extend beyond just tool calls, as headers or timeout configurations may be required for all requests to the server. \n\n## Proposed Solution\n\nThere are two levels where context can be provided:\n1. **Per-request** - Pass configuration directly when calling a method\n2. **Session-level provider** - A callback that provides configuration automatically for every request\n\nFor both levels, there are two design approaches for how configuration flows to the transport.\n\n## Design Option A: Transport-Specific Configuration (Recommended)\n\nEach transport exports its own configuration type. Users provide settings in the transport's expected format.\n\n### Complete Example (Option A)\n\n```python\nfrom mcp import ClientSession\nfrom mcp.client.streamable_http import streamable_http_client, HTTPTransportConfig\n\n# === Per-Request Usage ===\nasync def handle_single_request(session: ClientSession, user_token: str):\n    \"\"\"Pass transport config directly on each call.\"\"\"\n    result = await session.call_tool(\n        \"my_tool\",\n        arguments={\"foo\": \"bar\"},\n        # Pass transport config directly - can use typed class or dict\n        transport_config=HTTPTransportConfig(\n            headers={\"Authorization\": f\"Bearer {user_token}\"}\n        )\n        # Or simply: transport_config={\"headers\": {\"Authorization\": f\"Bearer {user_token}\"}}\n    )\n    return result\n\n\n# === Session-Level Provider Usage ===\nasync def my_transport_provider(request: types.ClientRequest) -\u003e HTTPTransportConfig | None:\n    \"\"\"Called automatically before each request with request details.\"\"\"\n    try:\n        token = auth_token_var.get()\n        headers = {\"Authorization\": f\"Bearer {token}\"}\n        \n        # Can make decisions based on request type/content\n        if isinstance(request.root, types.CallToolRequest):\n            headers[\"X-Tool-Name\"] = request.root.params.name\n        \n        return HTTPTransportConfig(headers=headers)\n    except LookupError:\n        return None\n\n\nasync def handle_requests_with_provider():\n    \"\"\"Transport config automatically added to all requests via provider.\"\"\"\n    async with streamable_http_client(\"https://mcp.example.com\") as (read, write, _):\n        async with ClientSession(\n            read,\n            write,\n            transport_config_provider=my_transport_provider,  # NEW\n        ) as session:\n            await session.initialize()\n            \n            # Context vars set here will be read by the provider\n            auth_token_var.set(\"user-123-token\")\n            result1 = await session.call_tool(\"tool1\", arguments={})\n            \n            auth_token_var.set(\"user-456-token\") \n            result2 = await session.call_tool(\"tool2\", arguments={})\n```\n\n### Transport Configuration Types (Option A)\n\n```python\n# Exported by mcp/client/streamable_http.py\n@dataclass\nclass HTTPTransportConfig:\n    \"\"\"Configuration for HTTP transport. Optional type hint for users.\"\"\"\n    headers: dict[str, str] | None = None\n    timeout: timedelta | None = None\n\n# Other transports can export their own configuration types\n```\n\n*Pros:* Simple, type hints available for IDE support, users can pass dict if they prefer  \n*Cons:* Provider code coupled to specific transport type (acceptable trade-off for simplicity)\n\n## Design Option B: Generic Context + Transport Mapper\n\nUser defines their own context type. Transport configuration requires a mapper function to convert to transport-specific format.\n\n### Example (Option B)\n\n```python\nfrom dataclasses import dataclass\nfrom mcp import ClientSession\nfrom mcp.client.streamable_http import streamable_http_client\n\n\n# User defines their own context type\n@dataclass\nclass MyAppContext:\n    user_token: str\n    trace_id: str\n\n\n# Transport mapper converts user context to transport format\ndef http_context_mapper(ctx: MyAppContext | None) -\u003e dict[str, Any] | None:\n    if ctx is None:\n        return None\n    return {\n        \"headers\": {\n            \"Authorization\": f\"Bearer {ctx.user_token}\",\n            \"X-Trace-ID\": ctx.trace_id,\n        }\n    }\n\n\n# Per-request usage\nasync def handle_single_request(session: ClientSession, user_token: str, trace_id: str):\n    result = await session.call_tool(\n        \"my_tool\",\n        arguments={\"foo\": \"bar\"},\n        request_context=MyAppContext(user_token=user_token, trace_id=trace_id)\n    )\n    return result\n```\n\nSession-level provider usage would work similarly to Option A.\n\n*Pros:* Strong contract, user owns context type, session-level code is transport-agnostic  \n*Cons:* Additional configuration, mapper required for transport to function\n\n---\n\n**Recommendation: Option A** for its simplicity. While it couples the provider to the transport type, this is acceptable since transport choice is typically fixed per deployment.\n\n## API Changes Summary\n\n### Session Changes\n\n```python\nclass TransportConfigProviderFnT(Protocol):\n    \"\"\"Provider callback that receives the request and returns transport configuration.\"\"\"\n    async def __call__(self, request: types.ClientRequest) -\u003e Any | None:\n        \"\"\"\n        Provide transport configuration for a request.\n        \n        Args:\n            request: The ClientRequest being sent (CallToolRequest, ListToolsRequest, etc.)\n                     Allows provider to inspect request type, method name, arguments, etc.\n        \n        Returns:\n            Transport configuration (typed or dict), or None for no configuration.\n        \"\"\"\n        ...\n\n\nclass ClientSession:\n    def __init__(\n        self,\n        # ... existing params ...\n        transport_config_provider: TransportConfigProviderFnT | None = None,  # NEW\n    ):\n        ...\n```\n\n### Method Changes (applies to call_tool, list_tools, etc.)\n\n```python\nasync def call_tool(\n    self,\n    name: str,\n    arguments: dict[str, Any] | None = None,\n    # ... existing params ...\n    transport_config: Any | None = None,  # NEW\n) -\u003e types.CallToolResult:\n    ...\n```\n\n**Note:** Transport configuration is separate from `RequestParams.Meta` (the `meta` parameter) which is protocol-level metadata serialized into the JSON-RPC message and sent to the MCP server. Transport configuration is consumed by the transport layer (e.g., HTTP headers) and never reaches the server.\n\n## Implementation Considerations\n\n### Backwards Compatibility\n- All new parameters should be optional with `None` defaults\n- Existing behavior unchanged when new features not used\n- Transport implementations can ignore `transport_config` if not supported\n\n### Deprecation\n- The existing `read_timeout_seconds` parameter on `call_tool()` should be deprecated in favor of passing timeout via `transport_config`\n\n### Functionality\n- Context provider callbacks should be async to support I/O (e.g., token refresh)\n\n## Related Issues\n- https://github.com/modelcontextprotocol/python-sdk/issues/1509\n\n\n### References\n\n_No response_","author":{"url":"https://github.com/somaraani","@type":"Person","name":"somaraani"},"datePublished":"2026-01-27T17:37:12.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":1},"url":"https://github.com/1966/python-sdk/issues/1966"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:8ba46faa-8e16-c093-343b-9f159f263d80
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id953A:3223CD:64FAC1:8A1DBD:6A61B1DB
html-safe-noncef3c1cd48462968cc763d76ec4195b9ed9b63360c51dc3087c3cd13b6988df1d0
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5NTNBOjMyMjNDRDo2NEZBQzE6OEExREJEOjZBNjFCMURCIiwidmlzaXRvcl9pZCI6IjgyNjQyOTE4MzEyNTk0NDM2NzUiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmacfd55506d9043872cce9452be77529c20313701ff2dffa4ad9d17da10d7b31d90
hovercard-subject-tagissue:3861689842
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/1966/issue_layout
twitter:imagehttps://opengraph.githubassets.com/ff58157ae6503de3aeb57eb0a9d09d2261973a34dd7582fe2c55c3061cd7cd7e/modelcontextprotocol/python-sdk/issues/1966
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/ff58157ae6503de3aeb57eb0a9d09d2261973a34dd7582fe2c55c3061cd7cd7e/modelcontextprotocol/python-sdk/issues/1966
og:image:altSummary Add support for configuring transport settings (e.g., authentication headers, tracing context) dynamically on a per-request basis. This is essential for use cases where settings like authen...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamesomaraani
hostnamegithub.com
expected-hostnamegithub.com
None6f4633bcf01c1ad14b73fd07dd39ac31d61f3d3c2578ee08ec1792b7b351eeb9
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
releaseac296ae7f21856f1f92adbad22f870b6fbb4b907
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/1966#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F1966
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%2F1966
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/1966
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1966
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1966
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/issues/1966
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 313 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
Per-Request Transport Configuration for MCP Clientshttps://github.com/modelcontextprotocol/python-sdk/issues/1966#top
documentationImprovements or additions to documentationhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22documentation%22
enhancementRequest for a new feature that's not currently supportedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22enhancement%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 27, 2026https://github.com/modelcontextprotocol/python-sdk/issues/1966#issue-3861689842
Support Per-Request HTTP Headers in call_tool() #1509https://github.com/modelcontextprotocol/python-sdk/issues/1509
documentationImprovements or additions to documentationhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22documentation%22
enhancementRequest for a new feature that's not currently supportedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22enhancement%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.