René's URL Explorer Experiment


Title: Support Per-Request HTTP Headers in call_tool() · Issue #1509 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: Support Per-Request HTTP Headers in call_tool() · Issue #1509 · modelcontextprotocol/python-sdk

X Title: Support Per-Request HTTP Headers in call_tool() · Issue #1509 · modelcontextprotocol/python-sdk

Description: Description Related Issues: #638, #600, #1305 Summary Add support for passing custom HTTP headers on a per-request basis when calling MCP tools via ClientSession.call_tool(). This is needed for multi-tenant applications where different r...

Open Graph Description: Description Related Issues: #638, #600, #1305 Summary Add support for passing custom HTTP headers on a per-request basis when calling MCP tools via ClientSession.call_tool(). This is needed for mul...

X Description: Description Related Issues: #638, #600, #1305 Summary Add support for passing custom HTTP headers on a per-request basis when calling MCP tools via ClientSession.call_tool(). This is needed for mul...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Support Per-Request HTTP Headers in call_tool()","articleBody":"### Description\n\n\n**Related Issues**: #638, #600, #1305\n\n\nSummary\n\nAdd support for passing custom HTTP headers on a per-request basis when calling MCP tools via `ClientSession.call_tool()`. This is needed for multi-tenant applications where different requests require different authentication tokens or request-specific metadata headers while maintaining a single persistent MCP connection.\n\nUse Case: Multi-Tenant SaaS Applications\n\nIn multi-tenant deployments, a single application instance serves multiple users/tenants concurrently. Each user request needs to include tenant-specific authentication headers when calling MCP tools, but creating a new MCP connection per request introduces unacceptable latency:\n\n- Connection establishment: ~500ms overhead per request\n- At 1000 concurrent users: 8.3 minutes of cumulative overhead per minute\n- Connection pooling doesn't help because each user needs different headers\n\nCurrent State: Headers can only be set at connection initialization in `streamablehttp_client()`, making them static for the connection lifetime.\n\nDesired State: Ability to pass custom headers per `call_tool()` invocation while maintaining a single persistent connection.\n\nRelated Use Cases\n\nThis pattern appears in several scenarios:\n\n1. Per-request authentication - Different auth tokens per user (Issue #638)\n2. Request tracing - Correlation IDs, trace IDs for distributed systems\n3. Rate limiting - User-specific rate limit tokens\n4. A/B testing - Feature flags or experiment IDs\n5. Tenant isolation - Tenant identifiers for data partitioning\n\nCurrent Behavior\n\n```python\nfrom mcp.client.streamable_http import streamablehttp_client\n\n# Headers set at connection time - static for connection lifetime\nasync with streamablehttp_client(\n    url=\"https://mcp.example.com\",\n    headers={\"Authorization\": \"Bearer static-token\"},  # Cannot change per-request\n) as (read_stream, write_stream, get_session_id):\n    async with ClientSession(read_stream, write_stream) as session:\n        # User A's request\n        result = await session.call_tool(\"list_sites\", {})  # Uses static token\n        \n        # User B's request (needs different token)\n        result = await session.call_tool(\"list_sites\", {})  # Still uses static token\n```\n\nProposed Solution\n\nOption 1: Add `extra_headers` Parameter to `call_tool()`\n\nSimilar to how `read_timeout_seconds` was added for per-request timeout configuration (Issue #600), add an optional parameter for per-request headers:\n\n```python\nasync def call_tool(\n    self,\n    name: str,\n    arguments: dict[str, Any] | None = None,\n    read_timeout_seconds: timedelta | None = None,\n    progress_callback: ProgressFnT | None = None,\n    *,\n    meta: dict[str, Any] | None = None,\n    extra_headers: dict[str, str] | None = None,  # NEW\n) -\u003e types.CallToolResult:\n    \"\"\"\n    Send a tools/call request.\n    \n    Args:\n        extra_headers: Additional HTTP headers to include in this specific request.\n                      These are merged with connection-level headers, with extra_headers\n                      taking precedence for duplicate keys.\n    \"\"\"\n```\n\n**Usage Example**:\n\n```python\nasync with streamablehttp_client(\n    url=\"https://mcp.example.com\",\n    headers={\"Authorization\": \"Bearer org-token\"},  # Organization-level auth\n) as (read_stream, write_stream, get_session_id):\n    async with ClientSession(read_stream, write_stream) as session:\n        # User A's request\n        result = await session.call_tool(\n            \"list_sites\",\n            {},\n            extra_headers={\"X-Auth-Token\": \"user-a-token\", \"X-Trace-Id\": \"trace-123\"}\n        )\n        \n        # User B's request\n        result = await session.call_tool(\n            \"list_sites\",\n            {},\n            extra_headers={\"X-Auth-Token\": \"user-b-token\", \"X-Trace-Id\": \"trace-456\"}\n        )\n```\n\nImplementation Notes:\n\n1. Modify `ClientSession.call_tool()` signature to accept `extra_headers`\n2. Pass headers to transport layer via request context\n3. In `StreamableHTTPTransport._handle_post_request()`, merge extra_headers with base headers\n4. Extra headers take precedence over connection-level headers for duplicate keys\n\n\nOption 2: Extend Transport Context\n\nAdd headers to the existing `RequestContext` mechanism:\n\n```python\n# In StreamableHTTPTransport\nasync def _handle_post_request(\n    self, \n    ctx: RequestContext,\n    extra_headers: dict[str, str] | None = None  # NEW\n) -\u003e None:\n    headers = self._prepare_request_headers(ctx.headers)\n    if extra_headers:\n        headers.update(extra_headers)  # Merge per-request headers\n    \n    async with ctx.client.stream(\"POST\", self.url, json=message, headers=headers):\n        ...\n```\n\nBackward Compatibility\n\nAll proposed solutions are backward compatible:\n\n- `extra_headers` parameter is optional (defaults to `None`)\n- Existing code continues to work unchanged\n- No breaking changes to MCP protocol or message format\n- Headers are HTTP transport-specific, not part of JSON-RPC messages\n\nPrecedent\n\nThe SDK already supports per-request configuration for timeouts:\n\n```python\nresult = await session.call_tool(\n    \"slow_operation\",\n    {},\n    read_timeout_seconds=timedelta(seconds=120)  # Per-request timeout\n)\n```\n\nThis establishes a pattern that certain aspects of tool invocation may need per-request customization beyond the JSON-RPC protocol itself.\n\n\nNon-Solution: Per-Request Connections\n\nCreating a new connection per request defeats the purpose of persistent connections and introduces significant latency overhead.\n\n\nImplementation Considerations\n\nHeader Merging Strategy\n\nConnection-level headers should be merged with per-request headers:\n\n```python\ndef _merge_headers(\n    base_headers: dict[str, str],\n    extra_headers: dict[str, str] | None\n) -\u003e dict[str, str]:\n    \"\"\"Merge headers with extra_headers taking precedence.\"\"\"\n    merged = base_headers.copy()\n    if extra_headers:\n        merged.update(extra_headers)\n    return merged\n```\n\nTransport-Specific\n\nThis feature should only affect HTTP-based transports (Streamable HTTP, SSE). Stdio transport would ignore `extra_headers` as it has no HTTP layer.\n\nSecurity Considerations\n\nPer-request headers enable proper security patterns:\n\n- Least-privilege: Each request carries only the permissions it needs\n- Token rotation: Different tokens can be used without reconnecting\n- Audit trails: Request-specific correlation IDs for logging\n\n\nRelated Issues\n\n- #638 - FastMCP Auth Context in tools (same root problem)\n- #600 - Per-request timeout configuration (precedent for per-request parameters)\n- #1305 - Secure Tool/Resource/Prompt Decorators with Auth (related auth concern)\n\n\nI'm willing to contribute a pull request implementing this feature if the approach is acceptable to maintainers. Our production use case requires this functionality, and we believe it would benefit the broader MCP community.\n\nThanks,\nDamian.\n\n### References\n\n_No response_","author":{"url":"https://github.com/damianoneill","@type":"Person","name":"damianoneill"},"datePublished":"2025-10-23T13:07:34.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":8},"url":"https://github.com/1509/python-sdk/issues/1509"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:e2716274-4d5e-9268-2b31-d21d7b4039c3
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idD714:1E2ADA:161AFA4:1F3D3F2:6A61D064
html-safe-nonced2a5479a2005c2d120c7ad89a2ae1be6db9255993f389b43c4b807a2876b9de9
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJENzE0OjFFMkFEQToxNjFBRkE0OjFGM0QzRjI6NkE2MUQwNjQiLCJ2aXNpdG9yX2lkIjoiMzU5NzMzMjg5MDg1NzM2MTUwOCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac8a9da08a8e0df7847cd5073844d63ba7da623f8de0bd3a0781315eadc9a2ab0f
hovercard-subject-tagissue:3544627843
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/1509/issue_layout
twitter:imagehttps://opengraph.githubassets.com/4b08c4eb0af2595530bb25ed73bfe3b6e1d3c8ec88a2f1038a6f151049fc10e1/modelcontextprotocol/python-sdk/issues/1509
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/4b08c4eb0af2595530bb25ed73bfe3b6e1d3c8ec88a2f1038a6f151049fc10e1/modelcontextprotocol/python-sdk/issues/1509
og:image:altDescription Related Issues: #638, #600, #1305 Summary Add support for passing custom HTTP headers on a per-request basis when calling MCP tools via ClientSession.call_tool(). This is needed for mul...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamedamianoneill
hostnamegithub.com
expected-hostnamegithub.com
Noneb2de8c74e5e61e893155ba46ee41bc66170c1644cb795adefa8386d490f7781c
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
released1866027ded575df8a15c731dd8b9986c9483ceb
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/1509#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F1509
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%2F1509
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/1509
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1509
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1509
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/issues/1509
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 314 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
Support Per-Request HTTP Headers in call_tool()https://github.com/modelcontextprotocol/python-sdk/issues/1509#top
P1Significant bug affecting many users, highly requested featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P1%22
enhancementRequest for a new feature that's not currently supportedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22enhancement%22
needs decisionIssue is actionable, needs maintainer decision on whether to implementhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22needs%20decision%22
https://github.com/damianoneill
damianoneillhttps://github.com/damianoneill
on Oct 23, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1509#issue-3544627843
#638https://github.com/modelcontextprotocol/python-sdk/issues/638
#600https://github.com/modelcontextprotocol/python-sdk/issues/600
#1305https://github.com/modelcontextprotocol/python-sdk/issues/1305
FastMCP Auth Context in tools #638https://github.com/modelcontextprotocol/python-sdk/issues/638
#600https://github.com/modelcontextprotocol/python-sdk/issues/600
FastMCP Auth Context in tools #638https://github.com/modelcontextprotocol/python-sdk/issues/638
SDKs and other middleware SHOULD allow these timeouts to be configured on a per-request basis. #600https://github.com/modelcontextprotocol/python-sdk/issues/600
Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O #1305https://github.com/modelcontextprotocol/python-sdk/issues/1305
P1Significant bug affecting many users, highly requested featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P1%22
enhancementRequest for a new feature that's not currently supportedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22enhancement%22
needs decisionIssue is actionable, needs maintainer decision on whether to implementhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22needs%20decision%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.