
    k7i,                        S r SSKJr  SSKJr  SSKJr  SSKJ	r	  SSK
Jr  SSKJr  SSKJr  SS	KJrJrJrJrJr  \(       a  SS
KJr  \" \5      r   S             SS jjr " S S\5      rg)a   Enhanced authorization handler with improved error responses.

This module provides an enhanced authorization handler that wraps the MCP SDK's
AuthorizationHandler to provide better error messages when clients attempt to
authorize with unregistered client IDs.

The enhancement adds:
- Content negotiation: HTML for browsers, JSON for API clients
- Enhanced JSON responses with registration endpoint hints
- Styled HTML error pages with registration links/forms
- Link headers pointing to registration endpoints
    )annotations)TYPE_CHECKING)AuthorizationHandler)
AnyHttpUrl)Request)Response)
get_logger)INFO_BOX_STYLESTOOLTIP_STYLEScreate_logocreate_pagecreate_secure_html_response) OAuthAuthorizationServerProviderNc                    SSK nUR                  U 5      nSU S3nSn	Sn
S[        XC=(       d    SS	9 S
U SU SU	 SU
 S3n[        [        -   S-   n[        UUUS9$ )a  Create styled HTML error page for unregistered client attempts.

Args:
    client_id: The unregistered client ID that was provided
    registration_endpoint: URL of the registration endpoint
    discovery_endpoint: URL of the OAuth metadata discovery endpoint
    server_name: Optional server name for branding
    server_icon_url: Optional server icon URL
    title: Page title

Returns:
    HTML string for the error page
r   NzI
        <div class="info-box error">
            <p>The client ID <code>zN</code> was not found in the server's client registry.</p>
        </div>
    a  
        <div class="info-box warning">
            <p>Your MCP client opened this page to complete OAuth authorization,
            but the server did not recognize its client ID. To fix this:</p>
            <ul>
                <li>Close this browser window</li>
                <li>Clear authentication tokens in your MCP client (or restart it)</li>
                <li>Try connecting again - your client should automatically re-register</li>
            </ul>
        </div>
    a  
        <div class="help-link-container">
            <span class="help-link">
                Why am I seeing this?
                <span class="tooltip">
                    OAuth 2.0 requires clients to register before authorization.
                    This server returned a 400 error because the provided client
                    ID was not found.
                    <br><br>
                    In browser-delegated OAuth flows, your application cannot
                    detect this error automatically; it's waiting for a
                    callback that will never arrive. You must manually clear
                    auth tokens and reconnect.
                </span>
            </span>
        </div>
    z-
        <div class="container">
            FastMCP)icon_urlalt_textz
            <h1>z</h1>
            z
            z
        </div>
        z
    aU  
        /* Error variant for info-box */
        .info-box.error {
            background: #fef2f2;
            border-color: #f87171;
        }
        .info-box.error strong {
            color: #991b1b;
        }
        /* Warning variant for info-box (yellow) */
        .info-box.warning {
            background: #fffbeb;
            border-color: #fbbf24;
        }
        .info-box.warning strong {
            color: #92400e;
        }
        .info-box code {
            background: rgba(0, 0, 0, 0.05);
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
            font-size: 0.9em;
        }
        .info-box ul {
            margin: 10px 0;
            padding-left: 20px;
        }
        .info-box li {
            margin: 6px 0;
        }
        )contenttitleadditional_styles)htmlescaper   r
   r   r   )	client_idregistration_endpointdiscovery_endpointserver_nameserver_icon_urlr   html_moduleclient_id_escaped	error_boxwarning_box	help_linkr   r   s                `/home/james-whalen/.local/lib/python3.13/site-packages/fastmcp/server/auth/handlers/authorize.pycreate_unregistered_client_htmlr$   (   s    * #**95$$5#6 7I
KI&/<T9UV W K M 		 G 	
	!	 J +     c                  p   ^  \ rS rSrSr  S       SU 4S jjjrS	U 4S jjr        S
S jrSrU =r	$ )r      a  Authorization handler with enhanced error responses for unregistered clients.

This handler extends the MCP SDK's AuthorizationHandler to provide better UX
when clients attempt to authorize without being registered. It implements
content negotiation to return:

- HTML error pages for browser requests
- Enhanced JSON with registration hints for API clients
- Link headers pointing to registration endpoints

This maintains OAuth 2.1 compliance (returns 400 for invalid client_id)
while providing actionable guidance to fix the error.
c                z   > [         TU ]  U5        [        U5      R                  S5      U l        X0l        X@l        g)a  Initialize the enhanced authorization handler.

Args:
    provider: OAuth authorization server provider
    base_url: Base URL of the server for constructing endpoint URLs
    server_name: Optional server name for branding
    server_icon_url: Optional server icon URL for branding
/N)super__init__strrstrip	_base_url_server_name_server_icon_url)selfproviderbase_urlr   r   	__class__s        r#   r+   AuthorizationHandler.__init__   s4     	"X--c2' /r%   c                t  >#    [         TU ]  U5      I Sh  vN nUR                  S:X  a  SnUR                  S:X  a  UR                  R                  S5      nO)UR                  5       I Sh  vN nUR                  S5      nU(       a   [        US5      (       a  SSKnUR                  UR                  5      nUR                  S5      S:X  aM  S	UR                  S
S5      R                  5       ;   a)  U R                  XUR                  S5      5      I Sh  vN $ U$ U$  GN
 N N! [         a     U$ f = f7f)a]  Handle authorization request with enhanced error responses.

This method extends the SDK's authorization handler and intercepts
errors for unregistered clients to provide better error responses
based on the client's Accept header.

Args:
    request: The authorization request

Returns:
    Response (redirect on success, error response on failure)
N  GETr   bodyr   errorinvalid_requestz	not founderror_description state)r*   handlestatus_codemethodquery_paramsgetformhasattrjsonloadsr9   lower_create_enhanced_error_response	Exception)r1   requestresponser   rD   rF   r9   r4   s          r#   r?   AuthorizationHandler.handle   s      00 3&I~~&#0044[A	$\\^+ HH[1	 x00##zz(--8 HHW-1BB +txx8KR/P/V/V/X X)-)M)M 'DHHW4E* $  xA 1 , $ ! 	sY   D8D AD8,D#-D8
BD' D%D' D8#D8%D' '
D51D84D55D8c                  #    U R                    S3nU R                    S3nSSKJn  [        UR                  R
                  SS5      n[        Xv5      (       a1  UR                  nUR                  n	U	(       a  U	S   R                  OSn
OU R                  nU R                  n
UR                  R                  SS5      nS	U;   a  [        UUUUU
S
9n[        USS9nO;SSKJn  U" SSU S3US9nUR%                  SS9nUUS'   UUS'   SSKJn  U" SUSS0S9nSU S3UR                  S'   [*        R-                  SUS	U;   a  S5        U$ S5        U$ 7f) zCreate enhanced error response with content negotiation.

Args:
    request: The original request
    client_id: The unregistered client ID
    state: The state parameter from the request

Returns:
    HTML or JSON error response based on Accept header
z	/registerz'/.well-known/oauth-authorization-serverr   )r   fastmcp_serverNacceptr=   z	text/html)r   r   r   r   r   r7   )r@   )AuthorizationErrorResponser;   zClient ID 'z' is not registered with this server. MCP clients should automatically re-register by sending a POST request to the registration_endpoint and retry authorization. If this persists, clear cached authentication tokens and reconnect.)r:   r<   r>   T)exclude_noner   authorization_server_metadata)JSONResponsezCache-Controlzno-store)r@   r   headers<z0>; rel="http://oauth.net/core/2.1/#registration"Linkz5Unregistered client_id=%s, returned %s error responseHTMLJSON)r.   fastmcp.server.serverr   getattrappr>   
isinstancenameiconssrcr/   r0   rU   rC   r$   r   "mcp.server.auth.handlers.authorizerQ   
model_dumpstarlette.responsesrT   loggerinfo)r1   rK   r   r>   r   r   r   fastmcpr   r_   r   rP   r   rL   rQ   
error_data
error_dictrT   s                     r#   rI   4AuthorizationHandler._create_enhanced_error_response   s     $(>>"2) < $//VW 	2'++++-=tDg''!,,KMME.3eAhllO++K"33O $$Xr2 & 2#&;#5' /D 34SIH V3'!) -Z [
 	J $..D.AJ2GJ./:LJ678#"(*5H %&&VW 	  	C!V+F	
  28	
 s   EE)r.   r0   r/   )NN)r2   r   r3   zAnyHttpUrl | strr   
str | Noner   rj   )rK   r   returnr   )rK   r   r   r,   r>   rj   rk   r   )
__name__
__module____qualname____firstlineno____doc__r+   r?   rI   __static_attributes____classcell__)r4   s   @r#   r   r      sv    $ #'&*020 #0  	0
 $0 0(.`QQ+.Q7AQ	Q Qr%   r   )NNzClient Not Registered)r   r,   r   r,   r   r,   r   rj   r   rj   r   r,   rk   r,   )rp   
__future__r   typingr   ra   r   SDKAuthorizationHandlerpydanticr   starlette.requestsr   rc   r   fastmcp.utilities.loggingr	   fastmcp.utilities.uir
   r   r   r   r   mcp.server.auth.providerr   rl   rd   r$    r%   r#   <module>r|      s    #     & ( 0  I	H	 #"&(uuu u 	u
  u u 	upd2 dr%   