Skip to content

Conversation

@pull
Copy link

@pull pull bot commented Jun 23, 2025

See Commits and Changes for more details.


Created by pull[bot] (v2.0.0-alpha.1)

Can you help keep this open source service alive? 💖 Please sponsor : )

Summary by Sourcery

Refactor OAuth client provider and server components to support OAuth 2.1 flows with PKCE, separate Authorization Server and Resource Server roles, and protected resource discovery (RFC 9728). Introduce structured context, token verifier protocol, new exception types, and comprehensive example implementations.

New Features:

  • Introduce OAuthContext and PKCEParameters for structured PKCE flow handling
  • Add TokenVerifier protocol and ProviderTokenVerifier for pluggable token validation
  • Implement support for split Authorization Server (AS) and Resource Server (RS) architecture with RFC 9728 Protected Resource Metadata
  • Expose new exception classes (OAuthFlowError, OAuthTokenError, OAuthRegistrationError) for OAuth flow errors

Enhancements:

  • Refactor OAuthClientProvider into HTTPX auth generator with separate request/response handlers
  • Add separate request-building methods (_discover_protected_resource, _discover_oauth_metadata, _register_client, etc.)
  • Improve FastMCP to accept token_verifier, validate auth configuration, and mount protected resource metadata endpoints
  • Add create_protected_resource_routes to expose RFC 9728 metadata
  • Replace direct AsyncClient mocks in tests with request construction assertions

Documentation:

  • Update README and example READMEs to document new AS/RS split architecture, token introspection, and RFC 9728 flows
  • Enhance example scripts and pyproject entries for separate AS/RS and legacy servers

Tests:

  • Add tests for PKCE parameter generation and uniqueness
  • Add tests for OAuthContext methods and HTTPX request builders
  • Update bearer auth middleware tests to use ProviderTokenVerifier and validate responses with WWW-Authenticate headers

…ver (RS) roles per spec PR #338 (#982)

Co-authored-by: Paul Carleton <paulc@anthropic.com>
@pull pull bot added the ⤵️ pull label Jun 23, 2025
@pull pull bot merged commit 17f9c00 into Stars1233:main Jun 23, 2025
@gitnotebooks
Copy link

gitnotebooks bot commented Jun 23, 2025

Review these changes at https://app.gitnotebooks.com/Stars1233/python-sdk/pull/84

@sourcery-ai
Copy link

sourcery-ai bot commented Jun 23, 2025

Reviewer's Guide

This PR overhauls the OAuth integration by introducing a dedicated OAuthContext and PKCEParameters model, refactoring the OAuth client provider into request-builder/response-handler steps, and extending the FastMCP server to support a clear Authorization Server (AS) vs Resource Server (RS) separation with RFC 9728 discovery and token introspection via a TokenVerifier protocol.

Sequence diagram for OAuth flow with AS/RS separation and token introspection

sequenceDiagram
    actor User
    participant Client
    participant ResourceServer as RS
    participant AuthorizationServer as AS

    User->>Client: Initiate authentication
    Client->>RS: Discover /.well-known/oauth-protected-resource
    RS-->>Client: Returns AS URL
    Client->>AS: Discover /.well-known/oauth-authorization-server
    AS-->>Client: Returns OAuth metadata
    Client->>AS: Register client
    AS-->>Client: Returns client info
    Client->>AS: Authorize (redirect via browser)
    User->>AS: Authenticate and consent
    AS-->>Client: Redirect with auth code
    Client->>AS: Exchange code for token
    AS-->>Client: Returns access token
    Client->>RS: Call protected resource with Bearer token
    RS->>AS: Introspect token
    AS-->>RS: Token info (active/claims)
    RS-->>Client: Returns resource
Loading

ER diagram for ProtectedResourceMetadata and OAuthMetadata

erDiagram
    PROTECTED_RESOURCE_METADATA {
        string resource
        string[] authorization_servers
        string[] scopes_supported
        string[] bearer_methods_supported
        string resource_documentation
    }
    OAUTH_METADATA {
        string issuer
        string authorization_endpoint
        string token_endpoint
        string registration_endpoint
        string[] scopes_supported
    }
    PROTECTED_RESOURCE_METADATA ||--o{ OAUTH_METADATA : "authorization_servers"
Loading

Class diagram for new OAuthContext and PKCEParameters

classDiagram
    class OAuthContext {
        +str server_url
        +OAuthClientMetadata client_metadata
        +TokenStorage storage
        +Callable redirect_handler
        +Callable callback_handler
        +float timeout
        +ProtectedResourceMetadata? protected_resource_metadata
        +OAuthMetadata? oauth_metadata
        +str? auth_server_url
        +OAuthClientInformationFull? client_info
        +OAuthToken? current_tokens
        +float? token_expiry_time
        +anyio.Lock lock
        +get_authorization_base_url(server_url: str) str
        +update_token_expiry(token: OAuthToken) None
        +is_token_valid() bool
        +can_refresh_token() bool
        +clear_tokens() None
    }
    class PKCEParameters {
        +str code_verifier
        +str code_challenge
        +generate() PKCEParameters
    }
Loading

Class diagram for TokenVerifier protocol and ProviderTokenVerifier

classDiagram
    class TokenVerifier {
        <<protocol>>
        +verify_token(token: str) AccessToken|None
    }
    class ProviderTokenVerifier {
        +OAuthAuthorizationServerProvider provider
        +verify_token(token: str) AccessToken|None
    }
    TokenVerifier <|.. ProviderTokenVerifier
Loading

Class diagram for IntrospectionTokenVerifier (Resource Server)

classDiagram
    class IntrospectionTokenVerifier {
        +str introspection_endpoint
        +verify_token(token: str) AccessToken|None
    }
    TokenVerifier <|.. IntrospectionTokenVerifier
Loading

Class diagram for ProtectedResourceMetadata (RFC 9728)

classDiagram
    class ProtectedResourceMetadata {
        +AnyHttpUrl resource
        +List[AnyHttpUrl] authorization_servers
        +List[str]? scopes_supported
        +List[str]? bearer_methods_supported
        +AnyHttpUrl? resource_documentation
    }
Loading

File-Level Changes

Change Details Files
Refactor OAuth client/provider into context-driven request/handler flow
  • Introduce OAuthContext to encapsulate server URL, metadata, client info, tokens and state
  • Add PKCEParameters model for verifier/challenge generation
  • Split OAuthClientProvider into methods that build httpx.Request objects (discover…, _register_client, _exchange_token, _refresh_token) and handlers that process responses
  • Replace inline state and token logic with OAuthContext and explicit async_auth_flow generator steps
src/mcp/client/auth.py
tests/client/test_auth.py
Enable Resource Server mode in FastMCP with TokenVerifier and RFC 9728 support
  • Add TokenVerifier protocol and ProviderTokenVerifier for backward compatibility
  • Allow FastMCP to accept either auth_server_provider or token_verifier and require auth settings accordingly
  • Inject protected resource metadata endpoint (/.well-known/oauth-protected-resource) when RS is configured
  • Adapt RequireAuthMiddleware to emit WWW-Authenticate headers with resource_metadata link
src/mcp/server/fastmcp/server.py
src/mcp/server/auth/middleware/bearer_auth.py
src/mcp/server/auth/routes.py
Split simple-auth example into separate AS, RS, and legacy servers
  • Create standalone auth_server.py with introspection and GitHub proxy endpoints
  • Create resource_server (mcp-simple-auth-rs) demonstrating RS-only operation and introspection
  • Provide legacy combined server (mcp-simple-auth-legacy) for backward compatibility
  • Adjust client example and scripts to use new split ports and callback URLs
examples/servers/simple-auth/mcp_simple_auth/server.py
examples/servers/simple-auth/mcp_simple_auth/auth_server.py
examples/servers/simple-auth/mcp_simple_auth/legacy_as_server.py
examples/clients/simple-auth-client/mcp_simple_auth_client/main.py
examples/servers/simple-auth/pyproject.toml
Update tests and README to align with new auth architecture
  • Revise test_auth.py to validate PKCEParameters and OAuthContext behaviors
  • Adapt bearer_auth middleware tests to use TokenVerifier and check WWW-Authenticate headers
  • Refresh documentation to describe AS/RS separation, RFC 9728 discovery, and TokenVerifier usage
tests/server/auth/middleware/test_bearer_auth.py
README.md
examples/servers/simple-auth/README.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant