
    $j              	      X   d dl mZ d dlZd dlmZmZmZ d dlmZ d dl	m
Z
 d dl	mZ d dlmZ d dlmZ d d	lmZ d d
lmZmZ d dlmZ d dlmZ d dlmZmZmZ d dlmZ d dlm Z m!Z!m"Z" d dl#m$Z$m%Z% d dl&m'Z' d dl(m)Z)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4 erd dl5m6Z6  e4e7          Z8 G d de          Z G d de          ZdZ9 G d de          Z: G d  d!e          Z; G d" d#e;          Z G d$ d%e;          Z< G d& d'e;          Z= G d( d)e;eeeef                   Z>dS )*    )annotationsN)TYPE_CHECKINGAnycast)urlparse)TokenErrorResponse)TokenHandler)PydanticJSONResponse)AuthContextMiddleware)BearerAuthBackend)AuthenticationErrorClientAuthenticator)r   )AccessToken)AuthorizationCode OAuthAuthorizationServerProviderRefreshToken)TokenVerifier)cors_middlewarecreate_auth_routes create_protected_resource_routes)ClientRegistrationOptionsRevocationOptions)OAuthClientInformationFull)
AnyHttpUrlField)
Middleware)AuthenticationMiddleware)Request)Route)
get_logger)CIMDClientManagerc                  6    e Zd ZU dZ ee          Zded<   dS )r   z)AccessToken that includes all JWT claims.)default_factoryzdict[str, Any]claimsN)__name__
__module____qualname____doc__r   dictr$   __annotations__     `/home/rurouni/.hermes/hermes-agent/venv/lib/python3.11/site-packages/fastmcp/server/auth/auth.pyr   r   6   s6         33"U4888F888888r,   r   c                  $     e Zd ZdZd fdZ xZS )r	   a  TokenHandler that returns MCP-compliant error responses.

    This handler addresses two SDK issues:

    1. Error code: The SDK returns `unauthorized_client` for client authentication
       failures, but RFC 6749 Section 5.2 requires `invalid_client` with HTTP 401.
       This distinction matters for client re-registration behavior.

    2. Status code: The SDK returns HTTP 400 for all token errors including
       `invalid_grant` (expired/invalid tokens). However, the MCP spec requires:
       "Invalid or expired tokens MUST receive a HTTP 401 response."

    This handler transforms responses to be compliant with both OAuth 2.1 and MCP specs.
    requestr   c                  K   t                                          |           d{V }|j        dk    r	 t          j        |j                  }|                    d          dk    r7t          t          d|                    d                    ddd	d
          S n# t          j	        t          f$ r Y nw xY w|j        dk    r	 t          j        |j                  }|                    d          dk    r7t          t          d|                    d                    ddd	d
          S n# t          j	        t          f$ r Y nw xY w|S )z5Wrap SDK handle() and transform auth error responses.Ni  errorunauthorized_clientinvalid_clienterror_description)r1   r4   zno-storezno-cache)zCache-ControlPragma)contentstatus_codeheadersi  invalid_grant)superhandler7   jsonloadsbodygetr
   r   JSONDecodeErrorAttributeError)selfr/   responser>   	__class__s       r-   r;   zTokenHandler.handleL   s     00000000 3&&z(-0088G$$(===/ 2"2.2hh7J.K.K! ! ! %(-7&0! !
 
 
 
 > (.9   
 3&&z(-0088G$$77/ 2"1.2hh7J.K.K! ! ! %(-7&0! !
 
 
 
 8 (.9    s%   A(B! !B:9B:	A(D3 3EE)r/   r   )r%   r&   r'   r(   r;   __classcell__rD   s   @r-   r	   r	   <   sG         + + + + + + + + + +r,   r	   z6urn:ietf:params:oauth:client-assertion-type:jwt-bearerc                  0     e Zd ZdZd fdZd fdZ xZS ) PrivateKeyJWTClientAuthenticatora  Client authenticator with private_key_jwt support for CIMD clients.

    Extends the SDK's ClientAuthenticator to add support for the `private_key_jwt`
    authentication method per RFC 7523. This is required for CIMD (Client ID Metadata
    Document) clients that use asymmetric keys for authentication.

    The authenticator:
    1. Delegates to SDK for standard methods (client_secret_basic, client_secret_post, none)
    2. Adds private_key_jwt handling for CIMD clients
    3. Validates JWT assertions against client's JWKS
    provider/OAuthAuthorizationServerProvider[Any, Any, Any]cimd_managerr!   token_endpoint_urlstrc                f    t                                          |           || _        || _        dS )zInitialize the authenticator.

        Args:
            provider: OAuth provider for client lookups
            cimd_manager: CIMD manager for private_key_jwt validation
            token_endpoint_url: Token endpoint URL for audience validation
        N)r:   __init___cimd_manager_token_endpoint_url)rB   rI   rK   rL   rD   s       r-   rO   z)PrivateKeyJWTClientAuthenticator.__init__   s3     	""")#5   r,   r/   r   returnr   c                  K   |                                  d{V }|                    d          }|s't                                          |           d{V S | j                            t          |                     d{V }|st          d          |j        dk    r|                    d          }|                    d          }|t          k    rt          dt                     |rt          |t                    st          d          	 | j                            ||| j        	           d{V  n%# t          $ r}t          d
|           |d}~ww xY w|S t                                          |           d{V S )a  Authenticate a client from an HTTP request.

        Extends SDK authentication to support private_key_jwt for CIMD clients.
        Delegates to SDK for client_secret_basic (Authorization header) and
        client_secret_post (form body) authentication.
        N	client_idzInvalid client_idprivate_key_jwtclient_assertion_typeclient_assertionz(Invalid client_assertion_type: expected zMissing client_assertion)	assertionclienttoken_endpointzInvalid client assertion: )formr?   r:   authenticate_requestrI   
get_clientrM   r   token_endpoint_auth_methodJWT_BEARER_ASSERTION_TYPE
isinstancerP   validate_private_key_jwtrQ   
ValueError)	rB   r/   	form_datarT   rY   assertion_typerX   erD   s	           r-   r\   z5PrivateKeyJWTClientAuthenticator.authenticate_request   s      ",,..((((((	MM+..	  	?55g>>>>>>>>>}//I???????? 	;%&9::: ,0AAA&]]+BCCN!&899I!:::)Z?XZZ    FJy#$>$> F)*DEEES(AA'!#'#; B          
  S S S)*Jq*J*JKKQRRS M WW11':::::::::s   (E 
E#EE#)rI   rJ   rK   r!   rL   rM   )r/   r   rR   r   )r%   r&   r'   r(   rO   r\   rE   rF   s   @r-   rH   rH   ~   se        
 
6 6 6 6 6 6"0; 0; 0; 0; 0; 0; 0; 0; 0; 0;r,   rH   c                  \    e Zd ZdZ	 	 	 dddZddZddZ	 dddZ	 dddZd dZ	dd!dZ
dS )"AuthProvideraF  Base class for all FastMCP authentication providers.

    This class provides a unified interface for all authentication providers,
    whether they are simple token verifiers or full OAuth authorization servers.
    All providers must be able to verify tokens and can optionally provide
    custom authentication routes.
    Nbase_urlAnyHttpUrl | str | Nonerequired_scopeslist[str] | Noneresource_base_urlc                    t          |t                    rt          |          }t          |t                    rt          |          }|| _        || _        |pg | _        d| _        d| _        dS )ar  
        Initialize the auth provider.

        Args:
            base_url: The base URL of this server (e.g., http://localhost:8000).
                This is used for constructing .well-known endpoints and OAuth metadata.
            resource_base_url: Optional public base URL for the protected resource.
                When provided, the resource URL advertised in protected resource
                metadata (RFC 9728) is derived from this URL instead of ``base_url``,
                while operational OAuth routes remain rooted at ``base_url``.
                Providers that mint their own downstream tokens (e.g. ``OAuthProxy``)
                also use this as the minted token audience. Upstream token audience
                validation is configured separately on the token verifier.
            required_scopes: List of OAuth scopes required for all requests.
        N)r`   rM   r   rh   rl   rj   	_mcp_path_resource_url)rB   rh   rj   rl   s       r-   rO   zAuthProvider.__init__   sv    * h$$ 	,!(++H'-- 	> *+< = = !2.4"%)04r,   tokenrM   rR   AccessToken | Nonec                $   K   t          d          )a  Verify a bearer token and return access info if valid.

        All auth providers must implement token verification.

        Args:
            token: The token string to validate

        Returns:
            AccessToken object if valid, None if invalid or expired
        &Subclasses must implement verify_tokenNotImplementedErrorrB   rp   s     r-   verify_tokenzAuthProvider.verify_token   s       ""JKKKr,   mcp_path
str | NoneNonec                H    || _         |                     |          | _        dS )a  Set the MCP endpoint path and compute resource URL.

        This method is called by get_routes() to configure the expected
        resource URL before route creation. Subclasses can override to
        perform additional initialization that depends on knowing the
        MCP endpoint path.

        Args:
            mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")
        N)rn   _get_resource_urlro   rB   rx   s     r-   set_mcp_pathzAuthProvider.set_mcp_path  s'     "!33H==r,   list[Route]c                    g S )a0  Get all routes for this authentication provider.

        This includes both well-known discovery routes and operational routes.
        Each provider is responsible for creating whatever routes it needs:
        - TokenVerifier: typically no routes (default implementation)
        - RemoteAuthProvider: protected resource metadata routes
        - OAuthProvider: full OAuth authorization server routes
        - Custom providers: whatever routes they need

        Args:
            mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")
                This is used to advertise the resource URL in metadata, but the
                provider does not create the actual MCP endpoint route.

        Returns:
            List of all routes for this provider (excluding the MCP endpoint itself)
        r+   r}   s     r-   
get_routeszAuthProvider.get_routes  s	    * 	r,   c                D    |                      |          }d |D             S )a  Get well-known discovery routes for this authentication provider.

        This is a utility method that filters get_routes() to return only
        well-known discovery routes (those starting with /.well-known/).

        Well-known routes provide OAuth metadata and discovery endpoints that
        clients use to discover authentication capabilities. These routes should
        be mounted at the root level of the application to comply with RFC 8414
        and RFC 9728.

        Common well-known routes:
        - /.well-known/oauth-authorization-server (authorization server metadata)
        - /.well-known/oauth-protected-resource/* (protected resource metadata)

        Args:
            mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")
                This is used to construct path-scoped well-known URLs.

        Returns:
            List of well-known discovery routes (typically mounted at root level)
        c                p    g | ]3}t          |t                    |j                            d           1|4S )z/.well-known/)r`   r   path
startswith).0routes     r-   
<listcomp>z6AuthProvider.get_well_known_routes.<locals>.<listcomp>C  sR     
 
 
%''
 -2J,A,A/,R,R

 
 
r,   )r   )rB   rx   
all_routess      r-   get_well_known_routesz"AuthProvider.get_well_known_routes)  s6    2 __X..

 
#
 
 
 	
r,   listc                p    t          t          t          |                     t          t                    gS )zGet HTTP application-level middleware for this auth provider.

        Returns:
            List of Starlette Middleware instances to apply to the HTTP app
        )backend)r   r   r   r   rB   s    r-   get_middlewarezAuthProvider.get_middlewareI  s<     ()$//   ,--
 	
r,   r   AnyHttpUrl | Nonec                    | j         p| j        }|dS |rKt          |                              d          }|                    d          }t          | d|           S |S )a4  Get the actual resource URL being protected.

        Uses ``resource_base_url`` if set; otherwise falls back to
        ``base_url``.

        Args:
            path: The path where the resource endpoint is mounted (e.g., "/mcp")

        Returns:
            The full URL of the protected resource
        N/)rl   rh   rM   rstriplstripr   )rB   r   rl   prefixsuffixs        r-   r|   zAuthProvider._get_resource_urlW  sv     !2Cdm$4 	4*++22377F[[%%F22&22333  r,   NNNrh   ri   rj   rk   rl   ri   rp   rM   rR   rq   rx   ry   rR   rz   Nrx   ry   rR   r   )rR   r   )r   ry   rR   r   )r%   r&   r'   r(   rO   rw   r~   r   r   r   r|   r+   r,   r-   rg   rg      s          -1,059	5 5 5 5 5>L L L L> > > >   $    2  $
 
 
 
 
@
 
 
 
! ! ! ! ! ! !r,   rg   c                  L     e Zd ZdZ	 	 	 dd fdZedd            ZddZ xZS )r   zBase class for token verifiers (Resource Servers).

    This class provides token verification capability without OAuth server functionality.
    Token verifiers typically don't provide authentication routes by default.
    Nrh   ri   rj   rk   rl   c                P    t                                          |||           dS )u.  
        Initialize the token verifier.

        Args:
            base_url: The base URL of this server
            resource_base_url: Optional public base URL for the protected resource.
                When provided, the resource URL advertised in protected resource
                metadata is derived from this URL instead of ``base_url``. Does not
                configure upstream token audience validation — set ``audience`` on
                your verifier to match.
            required_scopes: Scopes that are required for all requests
        rh   rl   rj   N)r:   rO   )rB   rh   rj   rl   rD   s       r-   rO   zTokenVerifier.__init__u  s9    $ 	/+ 	 	
 	
 	
 	
 	
r,   rR   	list[str]c                    | j         pg S )a  Scopes to advertise in OAuth metadata.

        Defaults to required_scopes. Override in subclasses when the
        advertised scopes differ from the validation scopes (e.g., Azure AD
        where tokens contain short-form scopes but clients request full URI
        scopes).
        )rj   r   s    r-   scopes_supportedzTokenVerifier.scopes_supported  s     #)r)r,   rp   rM   rq   c                $   K   t          d          )z6Verify a bearer token and return access info if valid.rs   rt   rv   s     r-   rw   zTokenVerifier.verify_token  s      !"JKKKr,   r   r   )rR   r   r   )	r%   r&   r'   r(   rO   propertyr   rw   rE   rF   s   @r-   r   r   n  s          -1,059	
 
 
 
 
 
 
0 * * * X*L L L L L L L Lr,   r   c                  N     e Zd ZU dZded<   	 	 	 	 dd fdZddZ	 dddZ xZS ) RemoteAuthProvidera&  Authentication provider for resource servers that verify tokens from known authorization servers.

    This provider composes a TokenVerifier with authorization server metadata to create
    standardized OAuth 2.0 Protected Resource endpoints (RFC 9728). Perfect for:
    - JWT verification with known issuers
    - Remote token introspection services
    - Any resource server that knows where its tokens come from

    Use this when you have token verification logic and want to advertise
    the authorization servers that issue valid tokens.
    r   rh   Ntoken_verifierr   authorization_serverslist[AnyHttpUrl]AnyHttpUrl | strr   rk   rl   ri   resource_namery   resource_documentationr   c                    t                                          |||j                   || _        || _        || _        || _        || _        dS )u  Initialize the remote auth provider.

        Args:
            token_verifier: TokenVerifier instance for token validation
            authorization_servers: List of authorization servers that issue valid tokens
            base_url: The base URL of this server
            resource_base_url: Optional public base URL for the protected resource.
                When provided, the resource URL advertised in protected resource
                metadata is derived from this URL instead of ``base_url``. Does not
                configure the token verifier's audience — set ``audience`` on the
                verifier to match if you want validated tokens bound to the same
                resource.
            scopes_supported: Scopes to advertise in OAuth metadata. If None,
                uses the token verifier's scopes_supported property. Use this
                when the scopes clients request differ from the scopes that
                appear in tokens (e.g., Azure AD full URI scopes vs short-form).
            resource_name: Optional name for the protected resource
            resource_documentation: Optional documentation URL for the protected resource
        r   N)r:   rO   rj   r   r   _scopes_supportedr   r   )	rB   r   r   rh   r   rl   r   r   rD   s	           r-   rO   zRemoteAuthProvider.__init__  sb    : 	/*: 	 	
 	
 	

 -%:"!1*&<###r,   rp   rM   rR   rq   c                F   K   | j                             |           d{V S )z1Verify token using the configured token verifier.N)r   rw   rv   s     r-   rw   zRemoteAuthProvider.verify_token  s/      (55e<<<<<<<<<r,   rx   r   c           	         |                      |           g }|                     |          }|rN|                    t          || j        | j        | j        n| j        j        | j        | j	                             |S )zfGet routes for this provider.

        Creates protected resource metadata routes (RFC 9728).
        N)resource_urlr   r   r   r   )
r~   r|   extendr   r   r   r   r   r   r   )rB   rx   routesr   s       r-   r   zRemoteAuthProvider.get_routes  s     	(### --h77 	MM0!-*.*D  1= ..!0A"&"4+/+F
 
 
   r,   )NNNN)r   r   r   r   rh   r   r   rk   rl   ri   r   ry   r   r   r   r   r   )	r%   r&   r'   r(   r*   rO   rw   r   rE   rF   s   @r-   r   r     s         
 
  .259$(48&= &= &= &= &= &= &=P= = = =  $# # # # # # # # #r,   r   c                  Z     e Zd ZdZddddddd fdZddZd fdZdddZdddZ xZ	S )	MultiAuthaf  Composes an optional auth server with additional token verifiers.

    Use this when a single server needs to accept tokens from multiple sources.
    For example, an OAuth proxy for interactive clients combined with a JWT
    verifier for machine-to-machine tokens.

    Token verification tries the server first (if present), then each verifier
    in order, returning the first successful result. Routes and OAuth metadata
    come from the server; verifiers contribute only token verification.

    Example:
        ```python
        from fastmcp.server.auth import MultiAuth, JWTVerifier, OAuthProxy

        auth = MultiAuth(
            server=OAuthProxy(issuer_url="https://login.example.com/..."),
            verifiers=[JWTVerifier(jwks_uri="https://example.com/.well-known/jwks.json")],
        )
        mcp = FastMCP("my-server", auth=auth)
        ```
    N)server	verifiersrh   rl   rj   r   AuthProvider | Noner   *list[TokenVerifier] | TokenVerifier | Nonerh   ri   rl   rj   rk   c                  |g }nt          |t                    r|g}||st          d          |p
|r|j        nd}|p
|r|j        nd}||n
|r|j        nd}t                                          |||           || _        t          |          | _
        || j        | j        | j        _        g | _        | j        | j                            | j                   | j                            | j
                   dS )a  Initialize the multi-auth provider.

        Args:
            server: Optional auth provider (e.g., OAuthProxy) that owns routes
                and OAuth metadata. Also participates in token verification as
                the first verifier tried.
            verifiers: One or more token verifiers to try after the server.
            base_url: Override the base URL. Defaults to the server's base_url.
            resource_base_url: Override the protected resource base URL. Defaults
                to the server's resource_base_url when available.
            required_scopes: Override required scopes. Defaults to the server's.
        Nz4MultiAuth requires at least a server or one verifierr   )r`   r   rb   rh   rl   rj   r:   rO   r   r   r   _sourcesappendr   )
rB   r   r   rh   rl   rj   effective_base_urleffective_resource_base_urleffective_scopesrD   s
            r-   rO   zMultiAuth.__init__  s=   * II	=11 	$"I>)>STTT%NV*M&//&7 '
(.8F$$D 	$
 * O,2<&(( 	 	'9, 	 	
 	
 	

 i
 (T[-D,0,BDK),.;"M  ---T^,,,,,r,   rp   rM   rR   rq   c                   K   | j         D ]c}	 |                    |           d{V }||c S %# t          $ r2 t                              dt          |          j        d           Y `w xY wdS )a  Verify a token by trying the server, then each verifier in order.

        Each source is tried independently. If a source raises an exception,
        it is logged and treated as a non-match so that remaining sources
        still get a chance to verify the token.
        Nz4Token verification failed for %s, trying next sourceT)exc_info)r   rw   	Exceptionloggerdebugtyper%   )rB   rp   sourceresults       r-   rw   zMultiAuth.verify_tokenO  s       m 
	 
	F	%22599999999%!MMM &   JLL)!       ts   /9A+*A+rx   ry   rz   c                    t                                          |           | j        | j                            |           | j        D ]}|                    |           dS )z3Propagate MCP path to the server and all verifiers.N)r:   r~   r   r   )rB   rx   verifierrD   s      r-   r~   zMultiAuth.set_mcp_pathd  sk    X&&&;"K$$X... 	, 	,H!!(++++	, 	,r,   r   c                H    | j         | j                             |          S g S )z&Delegate route creation to the server.)r   r   r}   s     r-   r   zMultiAuth.get_routesl  s%    ;";))(333	r,   c                H    | j         | j                             |          S g S )zDelegate well-known route creation to the server.

        This ensures that server-specific well-known route logic (e.g.,
        OAuthProvider's RFC 8414 path-aware discovery) is preserved.
        )r   r   r}   s     r-   r   zMultiAuth.get_well_known_routesr  s'     ;";44X>>>	r,   )
r   r   r   r   rh   ri   rl   ri   rj   rk   r   r   r   r   )
r%   r&   r'   r(   rO   rw   r~   r   r   rE   rF   s   @r-   r   r     s         2 '+@D,059,08- 8- 8- 8- 8- 8- 8- 8-t   *, , , , , ,            r,   r   c                  \     e Zd ZdZdddddddd fdZddZ	 dd fdZ	 dd fdZ xZS )OAuthProviderzOAuth Authorization Server provider.

    This class provides full OAuth server functionality including client registration,
    authorization flows, token issuance, and token verification.
    N)rl   
issuer_urlservice_documentation_urlclient_registration_optionsrevocation_optionsrj   rh   r   rl   ri   r   r   r    ClientRegistrationOptions | Noner   RevocationOptions | Nonerj   rk   c          	     @   t                                          |||           || j        | _        n1t	          |t
                    rt          |          | _        n|| _        | j        d| j        ]t          | j                  t          | j                  k    r3t                              d| j         d| j         d| j         d           t          j        |            t	          |t
                    rt          |          }|| _
        || _        || _        dS )a  
        Initialize the OAuth provider.

        Args:
            base_url: The public URL of this FastMCP server
            resource_base_url: Optional public base URL for the protected resource.
                When provided, the protected resource metadata and token audience are
                derived from this URL instead of ``base_url``.
            issuer_url: The issuer URL for OAuth metadata (defaults to base_url)
            service_documentation_url: The URL of the service documentation.
            client_registration_options: The client registration options.
            revocation_options: The revocation options.
            required_scopes: Scopes that are required for all requests.
        r   NzOAuth endpoints at z, issuer at z3. Ensure well-known routes are accessible at root (zY/.well-known/). See: https://gofastmcp.com/deployment/http#mounting-authenticated-servers)r:   rO   rh   r   r`   rM   r   r   infor   r   r   r   )	rB   rh   rl   r   r   r   r   rj   rD   s	           r-   rO   zOAuthProvider.__init__  sD   4 	/+ 	 	
 	
 	
 "mDOO
C(( 	)(44DOO(DO M%+DM""c$/&:&:::KK]dm ] ] ] ]DHO] ] ]   	)1$777/55 	N(23L(M(M%)B&+F("4r,   rp   rM   rR   rq   c                <   K   |                      |           d{V S )aX  
        Verify a bearer token and return access info if valid.

        This method implements the TokenVerifier protocol by delegating
        to our existing load_access_token method.

        Args:
            token: The token string to validate

        Returns:
            AccessToken object if valid, None if invalid or expired
        N)load_access_tokenrv   s     r-   rw   zOAuthProvider.verify_token  s.       ++E222222222r,   rx   ry   r   c                @   |                      |           | j        J | j        J t          | | j        | j        | j        | j                  }g }|D ]}t          |t                    rv|j	        dk    rk|j
        dd|j
        v r[t          | t          |                     }|                    t          dt          |j        ddg          ddg                     |                    |           | j        rk| j        r| j        j        r| j        j        n| j        }t'          | j        t)          t*          | j                  g|          }|                    |           |                    t/                                          |                     |S )	at  Get OAuth authorization server routes and optional protected resource routes.

        This method creates the full set of OAuth routes including:
        - Standard OAuth authorization server routes (/.well-known/oauth-authorization-server, /authorize, /token, etc.)
        - Optional protected resource routes

        Returns:
            List of OAuth routes
        N)rI   r   r   r   r   z/tokenPOST)rI   client_authenticatorOPTIONS)r   endpointmethods)r   r   r   )r~   rh   r   r   r   r   r   r`   r   r   r   r	   r   r   r   r;   ro   valid_scopesrj   r   r   r   r   r:   r   )	rB   rx   
sdk_routesoauth_routesr   token_handlersupported_scopesprotected_routesrD   s	           r-   r   zOAuthProvider.get_routes  s    	(### }(((O''' (}&*&D(,(H#6
 
 

 %' 	+ 	+E5%((+J(**M-em++ !-!8KD8Q8Q! ! ! ##%!0)0692E" " "( 3      ##E****  	2 3*4A*0== )	   @!/'+J'H'H&I!1     
  0111 	EGG..x88999r,   c                   t                                          |          }| j        rt          t	          | j                            }|j                            d          }|rd|dk    r^g }|D ]W}|j        dk    r5d| }|                    t          ||j	        |j
                             B|                    |           X|S |S )a  Get well-known discovery routes with RFC 8414 path-aware support.

        Overrides the base implementation to support path-aware authorization
        server metadata discovery per RFC 8414. If issuer_url has a path component,
        the authorization server metadata route is adjusted to include that path.

        For example, if issuer_url is "http://example.com/api", the discovery
        endpoint will be at "/.well-known/oauth-authorization-server/api" instead
        of just "/.well-known/oauth-authorization-server".

        Args:
            mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")

        Returns:
            List of well-known discovery routes
        r   z'/.well-known/oauth-authorization-server)r   r   )r:   r   r   r   rM   r   r   r   r   r   r   )	rB   rx   r   parsedissuer_path
new_routesr   new_pathrD   s	           r-   r   z#OAuthProvider.get_well_known_routes"  s    ( ..x88 ? 	"c$/2233F +,,S11K "{c11
# 1 1Ez%NNNSkSS ! #))! ().(-      #))%0000!!r,   )rh   r   rl   ri   r   ri   r   ri   r   r   r   r   rj   rk   r   r   r   )	r%   r&   r'   r(   rO   rw   r   r   rE   rF   s   @r-   r   r   }  s          6:.2=AHL7;,0;5 ;5 ;5 ;5 ;5 ;5 ;5 ;5z3 3 3 3"  $M M M M M M Mb  $. . . . . . . . . . .r,   r   )?
__future__r   r<   typingr   r   r   urllib.parser   mcp.server.auth.handlers.tokenr   r	   _SDKTokenHandlermcp.server.auth.json_responser
   'mcp.server.auth.middleware.auth_contextr   &mcp.server.auth.middleware.bearer_authr   &mcp.server.auth.middleware.client_authr   r   _SDKClientAuthenticatormcp.server.auth.providerr   _SDKAccessTokenr   r   r   r   TokenVerifierProtocolmcp.server.auth.routesr   r   r   mcp.server.auth.settingsr   r   mcp.shared.authr   pydanticr   r   starlette.middlewarer   #starlette.middleware.authenticationr   starlette.requestsr   starlette.routingr   fastmcp.utilities.loggingr    fastmcp.server.auth.cimdr!   r%   r   r_   rH   rg   r   r   r   r+   r,   r-   <module>r      s   " " " " " "  + + + + + + + + + + ! ! ! ! ! ! = = = = = = K K K K K K > > > > > > I I I I I I D D D D D D                          
              
        7 6 6 6 6 6 & & & & & & & & + + + + + + H H H H H H & & & & & & # # # # # # 0 0 0 0 0 0 ;::::::	H		9 9 9 9 9/ 9 9 9; ; ; ; ;# ; ; ;~ U N; N; N; N; N;'> N; N; N;b\! \! \! \! \!( \! \! \!~,L ,L ,L ,L ,LL ,L ,L ,L^^ ^ ^ ^ ^ ^ ^ ^B| | | | | | | |~S S S S S$%6k%QRS S S S Sr,   