Skip to content

fix(auth): get_access_token reflects current request in stateful sessions#2675

Open
Epochex wants to merge 4 commits into
modelcontextprotocol:mainfrom
Epochex:fix/streamable-http-auth-context-current-request
Open

fix(auth): get_access_token reflects current request in stateful sessions#2675
Epochex wants to merge 4 commits into
modelcontextprotocol:mainfrom
Epochex:fix/streamable-http-auth-context-current-request

Conversation

@Epochex
Copy link
Copy Markdown

@Epochex Epochex commented May 24, 2026

Fixes #2208.

Stateful Streamable HTTP sessions start the server task group on the first request. Anyio copies the request contextvars into that long-lived task, so get_access_token() could keep returning the token from the session-creating request even when later requests send a different Authorization header.

This change pushes the authenticated user into the auth contextvar at request-dispatch time (using the ServerMessageMetadata.request_context threaded through the transport), and resets it after the handler returns.

Tests:

  • uv run python -m pytest tests/server/auth/middleware/test_auth_context.py tests/server/auth/test_get_access_token_streamable_http.py

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

get_access_token() returns stale token in stateful streamable-HTTP sessions

1 participant