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!   M/home/app/Keep/.python/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*)appZallow_originsr%   Zallow_headers)r   r   r   )r$   r%   Z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Z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,   r-   r.   metadataZclient_authenticatorZroutesZregistration_handlerZrevocation_handlerr!   r!   r"   create_auth_routesE   sx   



r>   c                 C   s   t t| dt }t t| dt }t| |||jdgd ddgddgd |d d d d dgd}|jr?t t| dt |_	|jrSt t| dt
 |_ddg|_|S )	N/codeZauthorization_codeZrefresh_tokenZclient_secret_postZclient_secret_basicZS256)ZissuerZauthorization_endpointZtoken_endpointscopes_supportedZresponse_types_supportedZresponse_modes_supportedZgrant_types_supportedZ%token_endpoint_auth_methods_supportedZ0token_endpoint_auth_signing_alg_values_supportedZservice_documentationZui_locales_supportedZop_policy_uriZ
op_tos_uriZintrospection_endpointZ code_challenge_methods_supported)r   strrstripr7   r8   r   Zvalid_scopesr9   r;   Zregistration_endpointr<   Zrevocation_endpointZ*revocation_endpoint_auth_methods_supported)r+   r,   r-   r.   Zauthorization_urlZ	token_urlr=   r!   r!   r"   r5      s2   
r5   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)
    r?    z://z%/.well-known/oauth-protected-resource)r   rB   pathr   r   netloc)rD   parsedresource_pathr!   r!   r"   build_resource_metadata_url   s   rJ   resource_urlauthorization_serversrA   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   rA   rM   rN   r/   r0   r1   )!mcp.server.auth.handlers.metadatarO   mcp.shared.authrP   rJ   r   rB   rF   r
   r)   r6   )rK   rL   rA   rM   rN   rO   rP   r=   r$   Zmetadata_urlrH   Zwell_known_pathr!   r!   r"    create_protected_resource_routes   s&   	rT   )NNN)5collections.abcr   r   typingr   urllib.parser   Zpydanticr   Zstarlette.middleware.corsr   Zstarlette.requestsr   Zstarlette.responsesr	   Zstarlette.routingr
   r   Zstarlette.typesr   Z"mcp.server.auth.handlers.authorizer   rR   r   Z!mcp.server.auth.handlers.registerr   Zmcp.server.auth.handlers.revoker   Zmcp.server.auth.handlers.tokenr   Z&mcp.server.auth.middleware.client_authr   Zmcp.server.auth.providerr   Zmcp.server.auth.settingsr   r   Zmcp.server.streamable_httpr   rS   r   r#   r7   r8   r;   r<   listrB   r)   r>   r5   rJ   rT   r!   r!   r!   r"   <module>   s    

Q
(
