
    kKj$"                        d Z ddlmZ ddl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  ee      Z G d de      Zy)a  Scalekit authentication provider for FastMCP.

This module provides ScalekitProvider - a complete authentication solution that integrates
with Scalekit's OAuth 2.1 and OpenID Connect services, supporting Resource Server
authentication for seamless MCP client authentication.
    )annotationsN)
AnyHttpUrl)JSONResponse)Route)RemoteAuthProviderTokenVerifier)JWTVerifier)parse_scopes)
get_loggerc            	      t     e Zd ZdZddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ	 d	 	 	 d fdZ xZS )	ScalekitProvidera  Scalekit resource server provider for OAuth 2.1 authentication.

    This provider implements Scalekit integration using resource server pattern.
    FastMCP acts as a protected resource server that validates access tokens issued
    by Scalekit's authorization server.

    IMPORTANT SETUP REQUIREMENTS:

    1. Create an MCP Server in Scalekit Dashboard:
       - Go to your [Scalekit Dashboard](https://app.scalekit.com/)
       - Navigate to MCP Servers section
       - Register a new MCP Server with appropriate scopes
       - Ensure the Resource Identifier matches exactly what you configure as MCP URL
       - Note the Resource ID

    2. Environment Configuration:
       - Set SCALEKIT_ENVIRONMENT_URL (e.g., https://your-env.scalekit.com)
       - Set SCALEKIT_RESOURCE_ID from your created resource
       - Set BASE_URL to your FastMCP server's public URL

    For detailed setup instructions, see:
    https://docs.scalekit.com/mcp/overview/

    Example:
        ```python
        from fastmcp.server.auth.providers.scalekit import ScalekitProvider

        # Create Scalekit resource server provider
        scalekit_auth = ScalekitProvider(
            environment_url="https://your-env.scalekit.com",
            resource_id="sk_resource_...",
            base_url="https://your-fastmcp-server.com",
        )

        # Use with FastMCP
        mcp = FastMCP("My App", auth=scalekit_auth)
        ```
    N)base_urlmcp_url	client_idrequired_scopesscopes_supportedresource_nameresource_documentationtoken_verifierc       
           |xs |}|st        d      |t        j                  d       |t        j                  d       t        |      j	                  d      | _        || _        |t        |      ng }|| _        t        |      }t        j                  d| j
                  | j                  || j                         |
yt        j                  d| j
                   d| j
                  | j                         t        | j
                   d| j
                  d	| j                  | j                  xs d
      }
nt        j                  d       t        | 1  |
t        | j
                   d| j                         g||||	       y)aL  Initialize Scalekit resource server provider.

        Args:
            environment_url: Your Scalekit environment URL (e.g., "https://your-env.scalekit.com")
            resource_id: Your Scalekit resource ID
            base_url: Public URL of this FastMCP server (or use mcp_url for backwards compatibility)
            mcp_url: Deprecated alias for base_url. Will be removed in a future release.
            client_id: Deprecated parameter, no longer required. Will be removed in a future release.
            required_scopes: Optional list of scopes that must be present in tokens
            scopes_supported: Optional list of scopes to advertise in OAuth metadata.
                If None, uses required_scopes. Use this when the scopes clients should
                request differ from the scopes enforced on tokens.
            resource_name: Optional name for the protected resource metadata.
            resource_documentation: Optional documentation URL for the protected resource.
            token_verifier: Optional token verifier. If None, creates JWT verifier for Scalekit
        z+Either base_url or mcp_url must be providedNztScalekitProvider parameter 'mcp_url' is deprecated and will be removed in a future release. Rename it to 'base_url'.zScalekitProvider no longer requires 'client_id'. The parameter is accepted only for backward compatibility and will be removed in a future release./z_Initializing ScalekitProvider: environment_url=%s resource_id=%s base_url=%s required_scopes=%szSCreating default JWTVerifier for Scalekit: jwks_uri=%s issuer=%s required_scopes=%sz/keysRS256)jwks_uriissuer	algorithmaudiencer   z0Using custom token verifier for ScalekitProviderz/resources/)r   authorization_serversr   r   r   r   )
ValueErrorloggerwarningstrrstripenvironment_urlresource_idr
   r   debugr	   super__init__r   )selfr#   r$   r   r   r   r   r   r   r   r   resolved_base_urlparsed_scopesbase_url_value	__class__s                 w/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/server/auth/providers/scalekit.pyr'   zScalekitProvider.__init__?   s   > %/ JKKNN+
  NNI
  #?3::3?&-<-HL)b 	  -./m    	
 !LLe''(.$$$$	 ) 0017++!)) $ 4 4 <N LLKL 	)d223;t?O?O>PQR# $-'#9 	 		
    c                     t            |      }t        j                  d| j                          fd}|j                  t        d|dg             |S )a  Get OAuth routes including Scalekit authorization server metadata forwarding.

        This returns the standard protected resource routes plus an authorization server
        metadata endpoint that forwards Scalekit's OAuth metadata to clients.

        Args:
            mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")
                This is used to advertise the resource URL in metadata.
        z>Preparing Scalekit metadata routes: mcp_path=%s resource_id=%sc                f  K   	 j                    dj                   }t        j                  d|       t	        j
                         4 d{   }|j                  |       d{   }|j                          |j                         }t        j                  dt        |j                                      t        |      cddd      d{    S 7 7 o7 	# 1 d{  7  sw Y   yxY w# t        $ r5}t        j                  d|        t        dd| dd	      cY d}~S d}~ww xY ww)
zQForward Scalekit OAuth authorization server metadata with FastMCP customizations.z2/.well-known/oauth-authorization-server/resources/z1Fetching Scalekit OAuth metadata: metadata_url=%sNz8Scalekit metadata fetched successfully: metadata_keys=%sz#Failed to fetch Scalekit metadata: server_error)errorerror_descriptioni  )status_code)r#   r$   r   r%   httpxAsyncClientgetraise_for_statusjsonlistkeysr   	Exceptionr2   )requestmetadata_urlclientresponsemetadataer(   s         r-   #oauth_authorization_server_metadatazHScalekitProvider.get_routes.<locals>.oauth_authorization_server_metadata   s	    "&"6"6!77ijnjzjzi{|G !,,..&%+ZZ%==H--/'}}HLLRX]]_- (1 /..= /...  B1#FG#!//RSTRU-V !$ s   D1A	C0 CC0 C'C(ACC0 CC0 D1C0 CC0 C-!C$"C-)C0 ,D1-C0 0	D.9*D)#D.$D1)D..D1z'/.well-known/oauth-authorization-serverGET)endpointmethods)r&   
get_routesr   r%   r$   appendr   )r(   mcp_pathroutesrC   r,   s   `   r-   rG   zScalekitProvider.get_routes   s\     #H-L	
	6 	9<	
 r.   )r#   zAnyHttpUrl | strr$   r!   r   AnyHttpUrl | str | Noner   rK   r   
str | Noner   list[str] | Noner   rM   r   rL   r   zAnyHttpUrl | Noner   zTokenVerifier | None)N)rI   rL   returnzlist[Route])__name__
__module____qualname____doc__r'   rG   __classcell__)r,   s   @r-   r   r      s    %X -1+/ $,0-1$(48/3[
 *[
 	[

 *[
 )[
 [
 *[
 +[
 "[
 !2[
 -[
~  $88 
8 8r.   r   )rR   
__future__r   r5   pydanticr   starlette.responsesr   starlette.routingr   fastmcp.server.authr   r   !fastmcp.server.auth.providers.jwtr	   fastmcp.utilities.authr
   fastmcp.utilities.loggingr   rO   r   r    r.   r-   <module>r]      s@    #   , # A 9 / 0	H	}) }r.   