
    Kih#                        d Z ddlmZ ddl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 ddl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mZ  ee      Z G d d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field_validatormodel_validator)BaseSettingsSettingsConfigDict)JSONResponse)Route)RemoteAuthProviderTokenVerifier)JWTVerifier)ENV_FILEparse_scopes)
get_logger)NotSetNotSetTc                      e Zd ZU  eded      Zded<   ded<   dZd	ed
<   dZd	ed<   dZ	ded<    e
dd      edd              Z ed      d        Zy)ScalekitProviderSettings%FASTMCP_SERVER_AUTH_SCALEKITPROVIDER_ignore)
env_prefixenv_fileextrar   environment_urlstrresource_idNzAnyHttpUrl | Nonebase_urlmcp_urlzlist[str] | Nonerequired_scopesbefore)modec                    t        |      S Nr   )clsvalues     r/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/fastmcp/server/auth/providers/scalekit.py_parse_scopesz&ScalekitProviderSettings._parse_scopes'   s     E""    afterc                    | j                   xs | j                  }|d}t        |      t        j	                  | d|       | S )Nz@Either base_url or mcp_url must be provided for ScalekitProviderr   )r   r   
ValueErrorobject__setattr__)selfresolvedmsgs      r'   _resolve_base_urlz*ScalekitProviderSettings._resolve_base_url,   s@    ==0DLLTCS/!4X6r)   )r&   r-   )__name__
__module____qualname__r   r   model_config__annotations__r   r   r    r   classmethodr(   r   r2    r)   r'   r   r      s    %:L  "&H&!%G%(,O%,&X6#  7# '" #r)   r   c                  f     e Zd ZdZeeeeee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)r   	client_idr   r   r   r    token_verifierc                  |t         u}t        j                  |||||dj                         D 	
ci c]  \  }	}
|
t         ur|	|
 c}
}	      }|j                  t
        j                  d       |rt
        j                  d       t        |j                        j                  d      | _        |j                  | _
        |j                  xs g | _        t        |j                        }t
        j                  d| j                  | j                  || j                         |nt
        j                  d| j                   d| j                  | j                         t        | j                   d| j                  d	| j                  xs d
      }nt
        j                  d       t        | A  |t#        | j                   d| j                         g|       yc c}
}	w )a  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
            required_scopes: Optional list of scopes that must be present in tokens
            token_verifier: Optional token verifier. If None, creates JWT verifier for Scalekit
        )r   r   r   r   r    NztScalekitProvider 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	algorithmr    z0Using custom token verifier for ScalekitProviderz/resources/)r=   authorization_serversr   )r   r   model_validateitemsr   loggerwarningr   r   rstripr   r    r   debugr   super__init__r   )r/   r   r<   r   r   r   r    r=   legacy_client_idkvsettingsbase_url_value	__class__s                r'   rL   zScalekitProvider.__init___   s   ( %F2+:: (7#. (&'6 %'
Aq F? 1

 'NN+
 NNI
  #8#;#;<CCCH#//'77=2X../m    	
 !LLe''(.$$$$	 ) 0017++! $ 4 4 <	N LLKL 	)d223;t?O?O>PQR# $ 	 	
q
s   G
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   rG   rJ   httpxAsyncClientgetraise_for_statusjsonlistkeysr	   	ExceptionrV   )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 !,,. 2 2&%+ZZ%==H--/'}}HLLRX]]_- (12 2 2=2 2 2 2  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)rK   
get_routesrG   rJ   r   appendr
   )r/   mcp_pathroutesrg   rR   s   `   r'   rk   zScalekitProvider.get_routes   s\     #H-L	
	6 	9<	
 r)   )r   AnyHttpUrl | str | NotSetTr<   str | NotSetTr   rp   r   ro   r   ro   r    zlist[str] | NotSetTr=   zTokenVerifier | Noner$   )rm   z
str | Nonereturnzlist[Route])r3   r4   r5   __doc__r   rL   rk   __classcell__)rR   s   @r'   r;   r;   7   s    %T 7=#)%+/5.4/5/3U
 4U
 !	U

 #U
 -U
 ,U
 -U
 -U
r  $88 
8 8r)   r;   )!rr   
__future__r   rY   pydanticr   r   r   pydantic_settingsr   r   starlette.responsesr	   starlette.routingr
   fastmcp.server.authr   r   !fastmcp.server.auth.providers.jwtr   fastmcp.settingsr   fastmcp.utilities.authr   fastmcp.utilities.loggingr   fastmcp.utilities.typesr   r   r3   rG   r   r;   r9   r)   r'   <module>r      sX    #  A A > , # A 9 % / 0 3	H	| :w) wr)   