o
    i"                     @   s  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 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 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efddZ)dZ*dZ+dZ,dZ-deegeee B f de.e/ defddZ0	 	 	 d4d!e!eeef d"ed#ed B d$e#d B d%e$d B de.e fd&d'Z1d"ed#ed B d$e#d%e$de(f
d(d)Z2d*edefd+d,Z3	 	 	 d4d-ed.e.e d/e.e/ d B d0e/d B d1ed B de.e fd2d3Z4d S )5    )	AwaitableCallable)Any)urlparse)
AnyHttpUrl)CORSMiddleware)Request)Response)Routerequest_response)ASGIApp)AuthorizationHandler)MetadataHandler)RegistrationHandler)RevocationHandler)TokenHandler)ClientAuthenticator) OAuthAuthorizationServerProvider)ClientRegistrationOptionsRevocationOptions)MCP_PROTOCOL_VERSION_HEADER)OAuthMetadataurlc                 C   sR   | j dkr| jdkr| jdur| jdstd| jr td| jr'tddS )z
    Validate that the issuer URL meets OAuth 2.0 requirements.

    Args:
        url: The issuer URL to validate

    Raises:
        ValueError: If the issuer URL is invalid
    https	localhostNz	127.0.0.1zIssuer URL must be HTTPSz#Issuer URL must not have a fragmentz'Issuer URL must not have a query string)schemehost
startswith
ValueErrorfragmentquery)r    r!   \/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/mcp/server/auth/routes.pyvalidate_issuer_url   s   

r#   z
/authorizez/tokenz	/registerz/revokehandlerallow_methodsreturnc                 C   s   t t| d|tgd}|S )N*)appallow_originsr%   allow_headers)r   r   r   )r$   r%   cors_appr!   r!   r"   cors_middleware8   s   r,   Nprovider
issuer_urlservice_documentation_urlclient_registration_optionsrevocation_optionsc           
      C   s   t | |pt }|pt }t||||}t| }tdtt|jddgddgdtt	t
| jddgdtttt| |jddgddgdg}|jrbt| |d}|ttt|jddgddgd |jr|t| |}	|ttt|	jddgddgd |S )Nz'/.well-known/oauth-authorization-serverGETOPTIONSendpointmethodsPOST)options)r#   r   r   build_metadatar   r
   r,   r   handleAUTHORIZATION_PATHr   
TOKEN_PATHr   enabledr   appendREGISTRATION_PATHr   REVOCATION_PATH)
r-   r.   r/   r0   r1   metadataclient_authenticatorroutesregistration_handlerrevocation_handlerr!   r!   r"   create_auth_routesE   sx   



rF   c                 C   s   t t| dt }t t| dt }t| |||jdgd ddgdgd |d d d d dgd}|jr>t t| dt |_	|jrQt t| dt
 |_dg|_|S )N/codeauthorization_coderefresh_tokenclient_secret_postS256)issuerauthorization_endpointtoken_endpointscopes_supportedresponse_types_supportedresponse_modes_supportedgrant_types_supported%token_endpoint_auth_methods_supported0token_endpoint_auth_signing_alg_values_supportedservice_documentationui_locales_supportedop_policy_uri
op_tos_uriintrospection_endpoint code_challenge_methods_supported)r   strrstripr;   r<   r   valid_scopesr=   r?   registration_endpointr@   revocation_endpoint*revocation_endpoint_auth_methods_supported)r.   r/   r0   r1   authorization_url	token_urlrA   r!   r!   r"   r9      s2   r9   resource_server_urlc                 C   s<   t t| }|jdkr|jnd}t|j d|j d| S )u  
    Build RFC 9728 compliant protected resource metadata URL.

    Inserts /.well-known/oauth-protected-resource between host and resource path
    as specified in RFC 9728 §3.1.

    Args:
        resource_server_url: The resource server URL (e.g., https://example.com/mcp)

    Returns:
        The metadata URL (e.g., https://example.com/.well-known/oauth-protected-resource/mcp)
    rG    z://z%/.well-known/oauth-protected-resource)r   r\   pathr   r   netloc)rd   parsedresource_pathr!   r!   r"   build_resource_metadata_url   s   rj   resource_urlauthorization_serversrP   resource_nameresource_documentationc                 C   sl   ddl m} ddlm} || ||||d}||}t| }	tt|	}
|
j}t|t	|j
ddgddgdgS )a}  
    Create routes for OAuth 2.0 Protected Resource Metadata (RFC 9728).

    Args:
        resource_url: The URL of this resource server
        authorization_servers: List of authorization servers that can issue tokens
        scopes_supported: Optional list of scopes supported by this resource

    Returns:
        List of Starlette routes for protected resource metadata
    r   ) ProtectedResourceMetadataHandler)ProtectedResourceMetadata)resourcerl   rP   rm   rn   r2   r3   r4   )!mcp.server.auth.handlers.metadataro   mcp.shared.authrp   rj   r   r\   rf   r
   r,   r:   )rk   rl   rP   rm   rn   ro   rp   rA   r$   metadata_urlrh   well_known_pathr!   r!   r"    create_protected_resource_routes   s&   	rv   )NNN)5collections.abcr   r   typingr   urllib.parser   pydanticr   starlette.middleware.corsr   starlette.requestsr   starlette.responsesr	   starlette.routingr
   r   starlette.typesr   "mcp.server.auth.handlers.authorizer   rr   r   !mcp.server.auth.handlers.registerr   mcp.server.auth.handlers.revoker   mcp.server.auth.handlers.tokenr   &mcp.server.auth.middleware.client_authr   mcp.server.auth.providerr   mcp.server.auth.settingsr   r   mcp.server.streamable_httpr   rs   r   r#   r;   r<   r?   r@   listr\   r,   rF   r9   rj   rv   r!   r!   r!   r"   <module>   s    

Q
(
