
    {h&              	          d dl mZ d dlmZmZmZmZ d dlmZm	Z	m
Z
mZ d dlmZmZ d dlmZmZ  G d de      Z G d d	e      Z G d
 de      Z G d de      Zed   Z ed       G d de             Zed   Z ed       G d de             Zed   Z ed       G d de             Z G d de      Z ede      Z ede      Z ede      Z  G d d eeeee f         Z!d!e"d"e"d#z  d$e"fd%Z# G d& d'e      Z$y#)(    )	dataclass)GenericLiteralProtocolTypeVar)parse_qs	urlencodeurlparse
urlunparse)AnyUrl	BaseModel)OAuthClientInformationFull
OAuthTokenc                   f    e Zd ZU edz  ed<   ee   dz  ed<   eed<   eed<   eed<   dZedz  ed<   y)AuthorizationParamsNstatescopescode_challengeredirect_uri redirect_uri_provided_explicitlyresource)	__name__
__module____qualname__str__annotations__listr   boolr        Y/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/mcp/server/auth/provider.pyr   r   
   s;    :I&**HcDjr    r   c                   n    e Zd ZU eed<   ee   ed<   eed<   eed<   eed<   eed<   eed<   dZ	edz  ed	<   y)
AuthorizationCodecoder   
expires_at	client_idr   r   r   Nr   )
r   r   r   r   r   r   floatr   r   r   r   r    r!   r#   r#      s<    
IIN&**HcDjr    r#   c                   F    e Zd ZU eed<   eed<   ee   ed<   dZedz  ed<   y)RefreshTokentokenr&   r   Nr%   )r   r   r   r   r   r   r%   intr   r    r!   r)   r)      s$    JNI!Jd
!r    r)   c                   Z    e Zd ZU eed<   eed<   ee   ed<   dZedz  ed<   dZedz  ed<   y)AccessTokenr*   r&   r   Nr%   r   )	r   r   r   r   r   r   r%   r+   r   r   r    r!   r-   r-   %   s2    JNI!Jd
!HcDjr    r-   )invalid_redirect_uriinvalid_client_metadatainvalid_software_statementunapproved_software_statementT)frozenc                   ,    e Zd ZU eed<   dZedz  ed<   y)RegistrationErrorerrorNerror_description)r   r   r   RegistrationErrorCoder   r6   r   r   r    r!   r4   r4   5   s      $(sTz(r    r4   )invalid_requestunauthorized_clientaccess_deniedunsupported_response_typeinvalid_scopeserver_errortemporarily_unavailablec                   ,    e Zd ZU eed<   dZedz  ed<   y)AuthorizeErrorr5   Nr6   )r   r   r   AuthorizationErrorCoder   r6   r   r   r    r!   r@   r@   F   s    !!$(sTz(r    r@   )r8   invalid_clientinvalid_grantr9   unsupported_grant_typer<   c                   ,    e Zd ZU eed<   dZedz  ed<   y)
TokenErrorr5   Nr6   )r   r   r   TokenErrorCoder   r6   r   r   r    r!   rF   rF   V   s    $(sTz(r    rF   c                   &    e Zd ZdZdededz  fdZy)TokenVerifierz%Protocol for verifying bearer tokens.r*   returnNc                    K   yw)z6Verify a bearer token and return access info if valid.Nr   selfr*   s     r!   verify_tokenzTokenVerifier.verify_token_           )r   r   r   __doc__r   r-   rN   r   r    r!   rI   rI   \   s     /E Ed0B Er    rI   AuthorizationCodeT)boundRefreshTokenTAccessTokenTc                       e Zd Zdededz  fdZdeddfdZdededefd	Zded
ede	dz  fdZ
ded
e	defdZdedededz  fdZ	 dededee   defdZdededz  fdZdeez  ddfdZy) OAuthAuthorizationServerProviderr&   rJ   Nc                    K   yw)ae  
        Retrieves client information by client ID.

        Implementors MAY raise NotImplementedError if dynamic client registration is
        disabled in ClientRegistrationOptions.

        Args:
            client_id: The ID of the client to retrieve.

        Returns:
            The client information, or None if the client does not exist.
        Nr   )rM   r&   s     r!   
get_clientz+OAuthAuthorizationServerProvider.get_clientk         	rP   client_infoc                    K   yw)af  
        Saves client information as part of registering it.

        Implementors MAY raise NotImplementedError if dynamic client registration is
        disabled in ClientRegistrationOptions.

        Args:
            client_info: The client metadata to register.

        Raises:
            RegistrationError: If the client metadata is invalid.
        Nr   )rM   r[   s     r!   register_clientz0OAuthAuthorizationServerProvider.register_clientz   rZ   rP   clientparamsc                    K   yw)a  
        Called as part of the /authorize endpoint, and returns a URL that the client
        will be redirected to.
        Many MCP implementations will redirect to a third-party provider to perform
        a second OAuth exchange with that provider. In this sort of setup, the client
        has an OAuth connection with the MCP server, and the MCP server has an OAuth
        connection with the 3rd-party provider. At the end of this flow, the client
        should be redirected to the redirect_uri from params.redirect_uri.

        +--------+     +------------+     +-------------------+
        |        |     |            |     |                   |
        | Client | --> | MCP Server | --> | 3rd Party OAuth   |
        |        |     |            |     | Server            |
        +--------+     +------------+     +-------------------+
                            |   ^                  |
        +------------+      |   |                  |
        |            |      |   |    Redirect      |
        |redirect_uri|<-----+   +------------------+
        |            |
        +------------+

        Implementations will need to define another handler on the MCP server return
        flow to perform the second redirect, and generate and store an authorization
        code as part of completing the OAuth authorization step.

        Implementations SHOULD generate an authorization code with at least 160 bits of
        entropy,
        and MUST generate an authorization code with at least 128 bits of entropy.
        See https://datatracker.ietf.org/doc/html/rfc6749#section-10.10.

        Args:
            client: The client requesting authorization.
            params: The parameters of the authorization request.

        Returns:
            A URL to redirect the client to for authorization.

        Raises:
            AuthorizeError: If the authorization request is invalid.
        Nr   )rM   r^   r_   s      r!   	authorizez*OAuthAuthorizationServerProvider.authorize   s     R 	rP   authorization_codec                    K   yw)a)  
        Loads an AuthorizationCode by its code.

        Args:
            client: The client that requested the authorization code.
            authorization_code: The authorization code to get the challenge for.

        Returns:
            The AuthorizationCode, or None if not found
        Nr   rM   r^   rb   s      r!   load_authorization_codez8OAuthAuthorizationServerProvider.load_authorization_code   rZ   rP   c                    K   yw)a  
        Exchanges an authorization code for an access token and refresh token.

        Args:
            client: The client exchanging the authorization code.
            authorization_code: The authorization code to exchange.

        Returns:
            The OAuth token, containing access and refresh tokens.

        Raises:
            TokenError: If the request is invalid
        Nr   rd   s      r!   exchange_authorization_codez<OAuthAuthorizationServerProvider.exchange_authorization_code          	rP   refresh_tokenc                    K   yw)a*  
        Loads a RefreshToken by its token string.

        Args:
            client: The client that is requesting to load the refresh token.
            refresh_token: The refresh token string to load.

        Returns:
            The RefreshToken object if found, or None if not found.
        Nr   )rM   r^   ri   s      r!   load_refresh_tokenz3OAuthAuthorizationServerProvider.load_refresh_token   rO   rP   r   c                    K   yw)a
  
        Exchanges a refresh token for an access token and refresh token.

        Implementations SHOULD rotate both the access token and refresh token.

        Args:
            client: The client exchanging the refresh token.
            refresh_token: The refresh token to exchange.
            scopes: Optional scopes to request with the new access token.

        Returns:
            The OAuth token, containing access and refresh tokens.

        Raises:
            TokenError: If the request is invalid
        Nr   )rM   r^   ri   r   s       r!   exchange_refresh_tokenz7OAuthAuthorizationServerProvider.exchange_refresh_token   s     , 	rP   r*   c                    K   yw)z
        Loads an access token by its token.

        Args:
            token: The access token to verify.

        Returns:
            The AuthInfo, or None if the token is invalid.
        Nr   rL   s     r!   load_access_tokenz2OAuthAuthorizationServerProvider.load_access_token   s      	rP   c                    K   yw)a}  
        Revokes an access or refresh token.

        If the given token is invalid or already revoked, this method should do nothing.

        Implementations SHOULD revoke both the access token and its corresponding
        refresh token, regardless of which of the access token or refresh token is
        provided.

        Args:
            token: the token to revoke
        Nr   rL   s     r!   revoke_tokenz-OAuthAuthorizationServerProvider.revoke_token  rh   rP   )r   r   r   r   r   rY   r]   r   ra   rR   re   r   rg   rT   rk   r   rm   rU   ro   rq   r   r    r!   rW   rW   j   s   # 2Lt2S 1K PT )&@ )J] )be )V0FI	d	"0FX	$
/I 
Z] 
borvbv 
 * % S		
 
0
S 
\D5H 
m+ 
r    rW   redirect_uri_baser_   NrJ   c                 2   t        |       }t        |j                        D cg c]  \  }}|D ]  }||f  }}}}|j                         D ]  \  }}|	|j	                  ||f        t        |j                  t        |                  }|S c c}}}w )N)query)r
   r   rt   itemsappendr   _replacer	   )rr   r_   
parsed_urikvsvquery_paramsr   s           r!   construct_redirect_urir}     s    +,J(01A1A(BOOuq"BOqQFOFOLO (1=A'( j11	,8O1PQL Ps   Bc                   .    e Zd ZdZddZdededz  fdZy)ProviderTokenVerifieraJ  Token verifier that uses an OAuthAuthorizationServerProvider.

    This is provided for backwards compatibility with existing auth_server_provider
    configurations. For new implementations using AS/RS separation, consider using
    the TokenVerifier protocol with a dedicated implementation like IntrospectionTokenVerifier.
    c                     || _         y )N)provider)rM   r   s     r!   __init__zProviderTokenVerifier.__init__-  s	     r    r*   rJ   Nc                 T   K   | j                   j                  |       d{   S 7 w)z;Verify token using the provider's load_access_token method.N)r   ro   rL   s     r!   rN   z"ProviderTokenVerifier.verify_token0  s!     ]]44U;;;;s   (&()r   zNOAuthAuthorizationServerProvider[AuthorizationCode, RefreshToken, AccessToken])r   r   r   rQ   r   r   r-   rN   r   r    r!   r   r   %  s$    !< <d0B <r    r   )%dataclassesr   typingr   r   r   r   urllib.parser   r	   r
   r   pydanticr   r   mcp.shared.authr   r   r   r#   r)   r-   r7   	Exceptionr4   rA   r@   rG   rF   rI   rR   rT   rU   rW   r   r}   r   r   r    r!   <module>r      s_   ! 6 6 B B & B )   	  "9 " )    %  $)	 ) )
 !  $)Y ) )
  $) ) )
EH E 19JK |<~[9mx9K]\h9h1i m`c S4Z C <M <r    