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  Descope authentication provider for FastMCP.

This module provides DescopeProvider - a complete authentication solution that integrates
with Descope's OAuth 2.1 and OpenID Connect services, supporting Dynamic Client Registration (DCR)
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< edZded	< d
S )DescopeProviderSettings$FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_ignore)
env_prefixenv_fileextrastr
project_idr   base_urlzhttps://api.descope.comdescope_base_urlN)	__name__
__module____qualname__r   r   model_config__annotations__r   r    r   r   k/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/server/auth/providers/descope.pyr      s   
 r   c                      s@   e Zd ZdZeeeddd fddZ	dd fddZ  ZS )DescopeProvidera  Descope metadata provider for DCR (Dynamic Client Registration).

    This provider implements Descope integration using metadata forwarding.
    This is the recommended approach for Descope DCR
    as it allows Descope to handle the OAuth flow directly while FastMCP acts
    as a resource server.

    IMPORTANT SETUP REQUIREMENTS:

    1. Enable Dynamic Client Registration in Descope Console:
       - Go to the [Inbound Apps page](https://app.descope.com/apps/inbound) of the Descope Console
       - Click **DCR Settings**
       - Enable **Dynamic Client Registration (DCR)**
       - Define allowed scopes

    2. Note your Project ID:
       - Save your Project ID from [Project Settings](https://app.descope.com/settings/project)
       - Example: P2abc...123

    For detailed setup instructions, see:
    https://docs.descope.com/identity-federation/inbound-apps/creating-inbound-apps#method-2-dynamic-client-registration-dcr

    Example:
        ```python
        from fastmcp.server.auth.providers.descope import DescopeProvider

        # Create Descope metadata provider (JWT verifier created automatically)
        descope_auth = DescopeProvider(
            project_id="P2abc...123",
            base_url="https://your-fastmcp-server.com",
            descope_base_url="https://api.descope.com",
        )

        # Use with FastMCP
        mcp = FastMCP("My App", auth=descope_auth)
        ```
    N)r   r   r   token_verifierr   str | NotSetTr   AnyHttpUrl | str | NotSetTr   r!   TokenVerifier | Nonec                  s   t dd |||d D }|j| _tt|jd| _t|jd| _|du rDt	| j d| j d| j d| j d| jd	}t
 j|t| j d| j g| jd
 dS )as  Initialize Descope metadata provider.

        Args:
            project_id: Your Descope Project ID (e.g., "P2abc...123")
            base_url: Public URL of this FastMCP server
            descope_base_url: Descope API base URL (defaults to https://api.descope.com)
            token_verifier: Optional token verifier. If None, creates JWT verifier for Descope
        c                 S  s   i | ]\}}|t ur||qS r   )r   ).0kvr   r   r   
<dictcomp>]   s
    z,DescopeProvider.__init__.<locals>.<dictcomp>)r   r   r   /Nz/.well-known/jwks.json	/v1/apps/RS256)jwks_uriissuer	algorithmaudience)r!   authorization_serversr   )r   model_validateitemsr   r   r   r   rstripr   r
   super__init__)selfr   r   r   r!   settings	__class__r   r   r5   L   s2   
zDescopeProvider.__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 Descope authorization server metadata forwarding.

        This returns the standard protected resource routes plus an authorization server
        metadata endpoint that forwards Descope'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 dI dH }|  | }t|W  d  I dH  W S 1 I dH s8w   Y  W dS  ty] } ztdd| dddW  Y d}~S d}~ww )	zPForward Descope OAuth authorization server metadata with FastMCP customizations.Nr*   '/.well-known/oauth-authorization-serverserver_errorz"Failed to fetch Descope metadata: )errorerror_descriptioni  )status_code)	httpxAsyncClientgetr   r   raise_for_statusjsonr   	Exception)requestclientresponsemetadataer6   r   r   #oauth_authorization_server_metadata   s&   
4zGDescopeProvider.get_routes.<locals>.oauth_authorization_server_metadatar>   GET)endpointmethods)r4   
get_routesappendr   )r6   r:   routesrO   r8   rN   r   rS   ~   s   zDescopeProvider.get_routes)r   r"   r   r#   r   r#   r!   r$   )N)r:   r;   r<   r=   )r   r   r   __doc__r   r5   rS   __classcell__r   r   r8   r   r    %   s    )4r    )rV   
__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   loggerr   r    r   r   r   r   <module>   s    