René's URL Explorer Experiment


Title: get_access_token() returns stale token in stateful streamable-HTTP sessions · Issue #2208 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: get_access_token() returns stale token in stateful streamable-HTTP sessions · Issue #2208 · modelcontextprotocol/python-sdk

X Title: get_access_token() returns stale token in stateful streamable-HTTP sessions · Issue #2208 · modelcontextprotocol/python-sdk

Description: Summary get_access_token() returns the bearer token from the session-creating request for the entire lifetime of a stateful streamable-HTTP session, regardless of what Authorization header later requests send. Repro Open for code import ...

Open Graph Description: Summary get_access_token() returns the bearer token from the session-creating request for the entire lifetime of a stateful streamable-HTTP session, regardless of what Authorization header later re...

X Description: Summary get_access_token() returns the bearer token from the session-creating request for the entire lifetime of a stateful streamable-HTTP session, regardless of what Authorization header later re...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"get_access_token() returns stale token in stateful streamable-HTTP sessions","articleBody":"## Summary\n\n`get_access_token()` returns the bearer token from the **session-creating request** for the entire lifetime of a stateful streamable-HTTP session, regardless of what `Authorization` header later requests send.\n\n## Repro\n\n\u003cdetails\u003e\u003csummary\u003eOpen for code\u003c/summary\u003e\n\n```python\nimport multiprocessing\nimport socket\nimport time\n\nimport httpx\nimport pytest\nimport uvicorn\nfrom starlette.applications import Starlette\nfrom starlette.middleware import Middleware\nfrom starlette.middleware.authentication import AuthenticationMiddleware\nfrom starlette.routing import Mount\n\nfrom mcp.client.session import ClientSession\nfrom mcp.client.streamable_http import streamable_http_client\nfrom mcp.server import Server, ServerRequestContext\nfrom mcp.server.auth.middleware.auth_context import AuthContextMiddleware, get_access_token\nfrom mcp.server.auth.middleware.bearer_auth import BearerAuthBackend\nfrom mcp.server.auth.provider import AccessToken\nfrom mcp.server.streamable_http_manager import StreamableHTTPSessionManager\nfrom mcp.server.transport_security import TransportSecuritySettings\nfrom mcp.types import (\n    CallToolRequestParams,\n    CallToolResult,\n    ListToolsResult,\n    PaginatedRequestParams,\n    TextContent,\n    Tool,\n)\n\n\nclass _EchoTokenVerifier:\n    \"\"\"Accepts any bearer and echoes it back so we can tell tokens apart.\"\"\"\n\n    async def verify_token(self, token: str) -\u003e AccessToken | None:\n        return AccessToken(token=token, client_id=token, scopes=[], expires_at=int(time.time()) + 3600)\n\n\nasync def _handle_whoami(ctx: ServerRequestContext, params: CallToolRequestParams) -\u003e CallToolResult:\n    # The user-facing contract of get_access_token(): call it from a handler,\n    # get the token for the current request.\n    access = get_access_token()\n    text = access.token if access else \"\u003cnone\u003e\"\n    return CallToolResult(content=[TextContent(type=\"text\", text=text)])\n\n\nasync def _handle_list_tools(ctx: ServerRequestContext, params: PaginatedRequestParams | None) -\u003e ListToolsResult:\n    return ListToolsResult(tools=[Tool(name=\"whoami\", input_schema={\"type\": \"object\", \"properties\": {}})])\n\n\ndef _run_auth_server(port: int) -\u003e None:\n    server = Server(name=\"auth_test_server\", on_call_tool=_handle_whoami, on_list_tools=_handle_list_tools)\n    security = TransportSecuritySettings(allowed_hosts=[\"127.0.0.1:*\"], allowed_origins=[\"http://127.0.0.1:*\"])\n    session_manager = StreamableHTTPSessionManager(app=server, security_settings=security, stateless=False)\n\n    # Same middleware chain lowlevel Server.streamable_http_app builds when auth is on\n    asgi_app = Starlette(\n        routes=[Mount(\"/mcp\", app=session_manager.handle_request)],\n        middleware=[\n            Middleware(AuthenticationMiddleware, backend=BearerAuthBackend(_EchoTokenVerifier())),\n            Middleware(AuthContextMiddleware),\n        ],\n        lifespan=lambda app: session_manager.run(),\n    )\n    uvicorn.run(asgi_app, host=\"127.0.0.1\", port=port, log_level=\"error\")\n\n\nclass _MutableBearerAuth(httpx.Auth):\n    \"\"\"Reads the bearer from a mutable attribute at send-time so we can swap mid-session.\"\"\"\n\n    def __init__(self, token: str) -\u003e None:\n        self.token = token\n\n    def auth_flow(self, request: httpx.Request):\n        request.headers[\"Authorization\"] = f\"Bearer {self.token}\"\n        yield request\n\n\n@pytest.mark.anyio\nasync def test_get_access_token_reflects_current_request_in_stateful_session() -\u003e None:\n    with socket.socket() as s:\n        s.bind((\"127.0.0.1\", 0))\n        port = s.getsockname()[1]\n\n    proc = multiprocessing.Process(target=_run_auth_server, args=(port,), daemon=True)\n    proc.start()\n    try:\n        # wait for server\n        for _ in range(200):\n            try:\n                with socket.socket() as s:\n                    s.connect((\"127.0.0.1\", port))\n                break\n            except OSError:\n                time.sleep(0.01)\n\n        url = f\"http://127.0.0.1:{port}/mcp\"\n        auth = _MutableBearerAuth(\"token-A\")\n\n        async with httpx.AsyncClient(auth=auth, timeout=httpx.Timeout(30, read=30), follow_redirects=True) as http_client:\n            async with streamable_http_client(url, http_client=http_client) as (read_stream, write_stream):\n                async with ClientSession(read_stream, write_stream) as session:\n                    await session.initialize()\n\n                    # Request 1: session created, _receive_loop spawns with token-A in its context\n                    r1 = await session.call_tool(\"whoami\", {})\n                    assert isinstance(r1.content[0], TextContent)\n                    assert r1.content[0].text == \"token-A\"\n\n                    # Request 2: same session, different bearer — reuses the existing _receive_loop\n                    auth.token = \"token-B\"\n                    r2 = await session.call_tool(\"whoami\", {})\n                    assert isinstance(r2.content[0], TextContent)\n                    # EXPECTED: \"token-B\" — handler should see the token sent with THIS request\n                    # ACTUAL:   \"token-A\" — handler sees the session-creating request's token\n                    assert r2.content[0].text == \"token-B\"\n    finally:\n        proc.kill()\n        proc.join(timeout=2)\n```\n\n**Result on `main`:**\n\n```\nAssertionError: assert 'token-A' == 'token-B'\n  - token-B\n  ?       ^\n  + token-A\n  ?       ^\n```\n\n\u003c/details\u003e\n\n## Root cause\n\n`AuthContextMiddleware` sets `auth_context_var` inside the ASGI request's task. But the tool handler doesn't run in that task — it runs in a task spawned by `Server.run()`'s `tg.start_soon(_handle_message, ...)`, which is itself inside `run_server`, which was spawned at session creation: https://github.com/modelcontextprotocol/python-sdk/blob/528abfab86f1f3c003bd7d54a1f0bbd65d81c59c/src/mcp/server/streamable_http_manager.py#L267\n\n`tg.start()` copies the caller's `contextvars.Context` at call time. So `run_server` (and every task it spawns) carries a snapshot from request 1. Requests 2..N write to the transport's read stream from the new ASGI task, but the reader is `_receive_loop` — still running with the request-1 snapshot. The ContextVar set in request N's ASGI task never reaches the handler.\n\n```\nASGI req 1 (auth_context_var=A)\n  └─ tg.start(run_server)                           ← context copied: A\n       └─ ServerSession.__aenter__\n            └─ tg.start_soon(_receive_loop)         ← inherits A\n       └─ async for msg in session.incoming_messages:\n            └─ tg.start_soon(_handle_message)       ← inherits A\n                 └─ tool handler: get_access_token() → A  ✓\n\nASGI req 2 (auth_context_var=B)\n  └─ transport.handle_request(...)                  ← writes to read_stream\n       ... _receive_loop (still ctx A) reads it ...\n       ... tg.start_soon(_handle_message)           ← inherits A, not B\n            └─ tool handler: get_access_token() → A  ✗\n```\n\nThe existing unit test passes because `MockApp` runs inline in the same task as the middleware — no stream crossing: https://github.com/modelcontextprotocol/python-sdk/blob/528abfab86f1f3c003bd7d54a1f0bbd65d81c59c/tests/server/auth/middleware/test_auth_context.py#L33\n\n## Impact\n\n- **Token refresh mid-session**: refreshed token is invisible to handlers.\n- **Compounds #2100**: if a session ID is hijacked, the attacker's requests execute with the victim's token visible to `get_access_token()`.\n- **Stateless HTTP is unaffected** — new session per request means a fresh context snapshot each time.\n\n## The correct path already exists\n\nThe Starlette `Request` is threaded explicitly through `ServerMessageMetadata.request_context` → `ServerRequestContext.request`. Inside a handler:\n\n```python\nrequest: Request = ctx.request_context.request\nuser = request.user                       # set by AuthenticationMiddleware\ntoken = user.access_token                 # per-request, correct\n```\n\n## Proposed fix\n\nGiven `get_access_token()` has no callers in `src/` or `examples/` and isn't documented: remove `auth_context_var`, `get_access_token()`, and `AuthContextMiddleware`. Expose auth on `Context` as part of #2098 using the explicit `request` threading above.\n\nAlternative (if we want to keep the API): thread the `AuthenticatedUser` alongside `request` on `ServerMessageMetadata` and set the contextvar at the `tg.start_soon` site in `Server.run()`. But that's re-inventing what `request.user` already provides.\n\n## Related\n\n- #2098 — expose session/auth/transport on `Context`\n- #2100 — bind authenticated identity to sessions\n- #1743 — auth rework\n- #1969 — general user-ContextVar propagation through streams (different scope: arbitrary user vars, not just auth)\n\n\u003csub\u003e[AI Disclaimer](https://gist.github.com/maxisbey/6123d132484e4c533eab519a2800693d)\u003c/sub\u003e","author":{"url":"https://github.com/maxisbey","@type":"Person","name":"maxisbey"},"datePublished":"2026-03-04T18:50:27.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":0},"url":"https://github.com/2208/python-sdk/issues/2208"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:b3a128ab-3d4c-a48d-3a46-473eddc097ce
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id9DE4:38536E:2564A2F:36059B4:6A60C475
html-safe-nonce3f5e0a4d5401d3661eb3de0d7390909f6326f8a60d95f064c865cb06a78a3154
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5REU0OjM4NTM2RToyNTY0QTJGOjM2MDU5QjQ6NkE2MEM0NzUiLCJ2aXNpdG9yX2lkIjoiNDI5MzczNTU0NDExMzkwNjgwNSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac40f0cc7a5b7ea2fd8a45e11392b036a747c28785f09950266cb3f65ed6969281
hovercard-subject-tagissue:4023554693
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/2208/issue_layout
twitter:imagehttps://opengraph.githubassets.com/19a2cab3545102fac5ce9d2be6a7c8396aeb0818780a4456a7f857db79b9c780/modelcontextprotocol/python-sdk/issues/2208
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/19a2cab3545102fac5ce9d2be6a7c8396aeb0818780a4456a7f857db79b9c780/modelcontextprotocol/python-sdk/issues/2208
og:image:altSummary get_access_token() returns the bearer token from the session-creating request for the entire lifetime of a stateful streamable-HTTP session, regardless of what Authorization header later re...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamemaxisbey
hostnamegithub.com
expected-hostnamegithub.com
Nonee30aeaafb59b2438b8b0aaa24f4c6777e8e86dae0737625adfc928cac5443cd5
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
release34b43e23ce2dc970fbfce25d0e96500f2af8266d
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/2208#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F2208
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%2F2208
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/2208
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/2208
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/2208
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/issues/2208
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 267 https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests 312 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
#2675https://github.com/modelcontextprotocol/python-sdk/pull/2675
get_access_token() returns stale token in stateful streamable-HTTP sessionshttps://github.com/modelcontextprotocol/python-sdk/issues/2208#top
#2675https://github.com/modelcontextprotocol/python-sdk/pull/2675
authIssues and PRs related to Authentication / OAuthhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22auth%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%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/maxisbey
maxisbeyhttps://github.com/maxisbey
on Mar 4, 2026https://github.com/modelcontextprotocol/python-sdk/issues/2208#issue-4023554693
python-sdk/src/mcp/server/streamable_http_manager.pyhttps://github.com/modelcontextprotocol/python-sdk/blob/528abfab86f1f3c003bd7d54a1f0bbd65d81c59c/src/mcp/server/streamable_http_manager.py#L267
528abfahttps://github.com/modelcontextprotocol/python-sdk/commit/528abfab86f1f3c003bd7d54a1f0bbd65d81c59c
python-sdk/tests/server/auth/middleware/test_auth_context.pyhttps://github.com/modelcontextprotocol/python-sdk/blob/528abfab86f1f3c003bd7d54a1f0bbd65d81c59c/tests/server/auth/middleware/test_auth_context.py#L33
528abfahttps://github.com/modelcontextprotocol/python-sdk/commit/528abfab86f1f3c003bd7d54a1f0bbd65d81c59c
Bind authenticated identity to sessions in StreamableHTTPSessionManager #2100https://github.com/modelcontextprotocol/python-sdk/issues/2100
#2098https://github.com/modelcontextprotocol/python-sdk/issues/2098
Expose session, auth, and transport information on handler Context #2098https://github.com/modelcontextprotocol/python-sdk/issues/2098
Bind authenticated identity to sessions in StreamableHTTPSessionManager #2100https://github.com/modelcontextprotocol/python-sdk/issues/2100
Extract OAuth flow logic into reusable components for proxy use cases #1743https://github.com/modelcontextprotocol/python-sdk/issues/1743
Propagate ContextVars to Transport Layer in MCP Clients #1969https://github.com/modelcontextprotocol/python-sdk/issues/1969
AI Disclaimerhttps://gist.github.com/maxisbey/6123d132484e4c533eab519a2800693d
authIssues and PRs related to Authentication / OAuthhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22auth%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%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.