o
    i                     @  s   d Z ddlmZ ddl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 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 deZG dd deZdS )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)BaseSettingsSettingsConfigDict)JSONResponse)Route)RemoteAuthProviderTokenVerifier)JWTVerifier)ENV_FILE)
get_logger)NotSetNotSetTc                   @  s<   e Zd ZU ededdZded< ded< ded< ded	< d
S )ScalekitProviderSettings%FASTMCP_SERVER_AUTH_SCALEKITPROVIDER_ignore)
env_prefixenv_fileextrar   environment_urlstr	client_idresource_idmcp_urlN)__name__
__module____qualname__r   r   model_config__annotations__ r   r   l/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/server/auth/providers/scalekit.pyr      s   
 r   c                      sB   e Zd ZdZeeeeddd fddZ	dd fddZ  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_CLIENT_ID from your OAuth application
       - Set SCALEKIT_RESOURCE_ID from your created resource
       - Set MCP_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",
            client_id="sk_client_...",
            resource_id="sk_resource_...",
            mcp_url="https://your-fastmcp-server.com",
        )

        # Use with FastMCP
        mcp = FastMCP("My App", auth=scalekit_auth)
        ```
    N)r   r   r   r   token_verifierr   AnyHttpUrl | str | NotSetTr   str | NotSetTr   r   r"   TokenVerifier | Nonec                  s   t dd ||||d D }t|jd| _|j| _|j| _t|j| _|du r:t	| j d| jd| jd}t
 j|t| j d	| j g| jd
 dS )a  Initialize Scalekit resource server provider.

        Args:
            environment_url: Your Scalekit environment URL (e.g., "https://your-env.scalekit.com")
            client_id: Your Scalekit OAuth client ID
            resource_id: Your Scalekit resource ID
            mcp_url: Public URL of this FastMCP server (used as audience)
            token_verifier: Optional token verifier. If None, creates JWT verifier for Scalekit
        c                 S  s   i | ]\}}|t ur||qS r   )r   ).0kvr   r   r    
<dictcomp>c   s
    z-ScalekitProvider.__init__.<locals>.<dictcomp>)r   r   r   r   /Nz/keysRS256)jwks_uriissuer	algorithmaudiencez/resources/)r"   authorization_serversbase_url)r   model_validateitemsr   r   rstripr   r   r   r
   super__init__r   )selfr   r   r   r   r"   settings	__class__r   r    r6   P   s6   

zScalekitProvider.__init__mcp_path
str | Nonereturnlist[Route]c                   s2   t  |} fdd}|td|dgd |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.
        c              
     s   z=t  4 I dH '}| j d j I dH }|  | }t|W  d  I dH  W S 1 I dH s7w   Y  W dS  tyd } zt	
d|  tdd| dddW  Y d}~S d}~ww )zQForward Scalekit OAuth authorization server metadata with FastMCP customizations.Nz2/.well-known/oauth-authorization-server/resources/z#Failed to fetch Scalekit metadata: server_error)errorerror_descriptioni  )status_code)httpxAsyncClientgetr   r   raise_for_statusjsonr   	Exceptionloggerr@   )requestclientresponsemetadataer7   r   r    #oauth_authorization_server_metadata   s(   
4zHScalekitProvider.get_routes.<locals>.oauth_authorization_server_metadataz'/.well-known/oauth-authorization-serverGET)endpointmethods)r5   
get_routesappendr   )r7   r;   routesrP   r9   rO   r    rT      s   zScalekitProvider.get_routes)
r   r#   r   r$   r   r$   r   r#   r"   r%   )N)r;   r<   r=   r>   )r   r   r   __doc__r   r6   rT   __classcell__r   r   r9   r    r!   &   s    ,8r!   )rW   
__future__r   rC   pydanticr   pydantic_settingsr   r   starlette.responsesr   starlette.routingr   fastmcp.server.authr   r	   !fastmcp.server.auth.providers.jwtr
   fastmcp.settingsr   fastmcp.utilities.loggingr   fastmcp.utilities.typesr   r   r   rI   r   r!   r   r   r   r    <module>   s    