SIGN IN SIGN UP

The official Python SDK for Model Context Protocol servers and clients

22456 0 0 Python

feat(auth): add BearerAuth for minimal bearer-token authentication

Adds BearerAuth, a lightweight httpx.Auth implementation with a two-method
contract (token() + optional on_unauthorized()). This covers the many deployments
that don't fit the OAuth authorization-code flow: gateway/proxy patterns, service
accounts with pre-provisioned tokens, enterprise SSO where tokens come from a
separate pipeline.

For simple cases, it's a one-liner:

    auth = BearerAuth("my-api-key")
    async with Client(url, auth=auth) as client: ...

For token rotation, pass a callable (sync or async):

    auth = BearerAuth(lambda: os.environ.get("MCP_TOKEN"))

For custom 401 handling, pass or override on_unauthorized(). The handler receives
the 401 response (body pre-read, WWW-Authenticate available), refreshes
credentials, and the request retries once. Retry state is naturally per-operation
via httpx's generator-per-request pattern — no shared counter to reset or leak.

OAuthClientProvider is unchanged. Both are httpx.Auth subclasses and plug into
the same auth parameter — no adapter or type guard needed.

Also adds:
- auth= convenience parameter on streamable_http_client() and Client (mutually
  exclusive with http_client=, raises ValueError if both given)
- UnauthorizedError exception for unrecoverable 401s
- sync_auth_flow override that raises a clear error instead of silently no-oping
- docs/authorization.md with bearer-token and OAuth sections
- examples/snippets/clients/bearer_auth_client.py
- 21 tests covering generator-driven unit tests and httpx wire-level integration
M
Max Isbey committed
c85501ac65bb424d30b079be25ba619ce85d6d02
Parent: 92c693b