
    kKjH3                        d Z ddlmZ ddl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mZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZmZmZ ddlmZmZ ddl m!Z!  ejD                  e#      Z$ddZ% G d de      Z&y)a  Authorization middleware for FastMCP.

This module provides middleware-based authorization using callable auth checks.
AuthMiddleware applies auth checks globally to all components on the server.

Example:
    ```python
    from fastmcp import FastMCP
    from fastmcp.server.auth import require_scopes, restrict_tag
    from fastmcp.server.middleware import AuthMiddleware

    # Require specific scope for all components
    mcp = FastMCP(middleware=[
        AuthMiddleware(auth=require_scopes("api"))
    ])

    # Tag-based: components tagged "admin" require "admin" scope
    mcp = FastMCP(middleware=[
        AuthMiddleware(auth=restrict_tag("admin", scopes=["admin"]))
    ])
    ```
    )annotationsN)Sequence)AuthorizationError)PromptPromptResult)ResourceResourceResult)ResourceTemplate)	AuthCheckAuthContextrun_auth_checks)get_access_token)CallNext
MiddlewareMiddlewareContext)Tool
ToolResult)VersionSpecc                   | y | j                  d      }|j                  d      }t        |t              sy |j                  d      }t        |t              rt        |      S t        |t              rW|j                  d      }|j                  d      }|j                  d      }t        d	 |||fD              sy t        |||
      S y )NT)exclude_nonefastmcpversion)eqgteltr   c              3  H   K   | ]  }|d u xs t        |t                y wN)
isinstancestr).0values     x/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/server/middleware/authorization.py	<genexpr>z%_requested_version.<locals>.<genexpr>F   s$     Vu5D=:Juc$::s    ")r   r   r   )
model_dumpgetr   dictr   r   all)meta	meta_dictfastmcp_metar   r   r   r   s          r"   _requested_versionr+   4   s    |T2I==+LlD)y)G'3g&&'4 kk% [[[[VbRTVVsrb11    c                      e Zd ZdZddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ		 	 	 	 	 	 ddZ
	 	 	 	 	 	 dd	Zy
)AuthMiddlewarea  Global authorization middleware using callable checks.

    This middleware applies auth checks to all components (tools, resources,
    prompts) on the server. It uses the same callable API as component-level
    auth checks.

    The middleware:
    - Filters tools/resources/prompts from list responses based on auth checks
    - Checks auth before tool execution, resource read, and prompt render
    - Skips all auth checks for STDIO transport (no OAuth concept)

    Args:
        auth: A single auth check function or list of check functions.
            All checks must pass for authorization to succeed (AND logic).

    Example:
        ```python
        from fastmcp import FastMCP
        from fastmcp.server.auth import require_scopes

        # Require specific scope for all components
        mcp = FastMCP(middleware=[AuthMiddleware(auth=require_scopes("api"))])

        # Multiple scopes (AND logic)
        mcp = FastMCP(middleware=[
            AuthMiddleware(auth=require_scopes("read", "api"))
        ])
        ```
    c                    || _         y r   )auth)selfr0   s     r"   __init__zAuthMiddleware.__init__m   s	    	r,   c                *  K    ||       d{   }ddl m} |j                         dk(  r|S t               }g }|D ]?  }t	        ||      }	 t        | j                  |       d{   r|j                  |       A |S 7 q7 # t        $ r Y Sw xY ww)z0Filter tools/list response based on auth checks.Nr   _current_transportstdiotoken	component	fastmcp.server.contextr5   r%   r   r   r   r0   appendr   )	r1   context	call_nexttoolsr5   r8   authorized_toolstoolctxs	            r"   on_list_toolszAuthMiddleware.on_list_toolsp   s       (( 	>!!#w.L "')DET:C(C888$++D1	   ) ) 9% E   BB =BB&B'B<BB	BBBBc                V  K   ddl m} |j                         dk(  r ||       d{   S |j                  j                  }|j
                  }|(t        j                  d| d       t        d| d      t        |j                  j                        }|j                  j                  ||	       d{   }|t        d| d
      t               }t        ||      }	t        | j                   |	       d{   st        d| d       ||       d{   S 7 7 k7 '7 
w)z!Check auth before tool execution.r   r4   r6   Nz2AuthMiddleware: fastmcp_context is None for tool ''. Denying access for security.zAuthorization failed for tool '': missing contextr   ': not found or not authorizedr7   ': insufficient permissions)r;   r5   r%   messagenamefastmcp_contextloggerwarningr   r+   r(   r   get_toolr   r   r   r0   )
r1   r=   r>   r5   	tool_namer   r   rA   r8   rB   s
             r"   on_call_toolzAuthMiddleware.on_call_tool   sG     	>!!#w."7+++ OO((	))?NNDYK P/ / %1)<NO  %W__%9%9:__--i-II<$1) =. .  !"6$TYY444$1)<WX  w'''G ,( J 5
 (G   %D)D!BD)7D#8AD)=D%>D)D'D)#D)%D)'D)c                *  K    ||       d{   }ddl m} |j                         dk(  r|S t               }g }|D ]?  }t	        ||      }	 t        | j                  |       d{   r|j                  |       A |S 7 q7 # t        $ r Y Sw xY ww)z4Filter resources/list response based on auth checks.Nr   r4   r6   r7   r:   )	r1   r=   r>   	resourcesr5   r8   authorized_resourcesresourcerB   s	            r"   on_list_resourcesz AuthMiddleware.on_list_resources   s      $G,,	 	>!!#w. "/1!HEX>C(C888(//9	 " $#' - 9% rD   c                  K   ddl m} |j                         dk(  r ||       d{   S |j                  j                  }|j
                  }|(t        j                  d| d       t        d| d      t        |j                  j                        }|j                  j                  t        |      |	       d{   }|.|j                  j                  t        |      |	       d{   }|t        d| d
      t               }t!        ||      }	t#        | j$                  |	       d{   st        d| d       ||       d{   S 7 37 7 n7 *7 w)z Check auth before resource read.r   r4   r6   Nz6AuthMiddleware: fastmcp_context is None for resource 'rF   z#Authorization failed for resource 'rG   rH   rI   r7   rJ   )r;   r5   r%   rK   urirM   rN   rO   r   r+   r(   r   get_resourcer   get_resource_templater   r   r   r0   )
r1   r=   r>   r5   rZ   r   r   r9   r8   rB   s
             r"   on_read_resourcezAuthMiddleware.on_read_resource   s     	>!!#w."7+++ oo!!))?NNH N/ / %5cU:LM  %W__%9%9:!//66s3x6QQ	%ooCCC D  I $5cU ;. .  !";$TYY444$5cU:UV  w'''O ,& R 5
 (sY   %E%EBE% E/E%0E1AE%6E!7E%E#E%E%E%!E%#E%c                *  K    ||       d{   }ddl m} |j                         dk(  r|S t               }g }|D ]?  }t	        ||      }	 t        | j                  |       d{   r|j                  |       A |S 7 q7 # t        $ r Y Sw xY ww)z=Filter resource templates/list response based on auth checks.Nr   r4   r6   r7   r:   )	r1   r=   r>   	templatesr5   r8   authorized_templatestemplaterB   s	            r"   on_list_resource_templatesz)AuthMiddleware.on_list_resource_templates
  s      $G,,	 	>!!#w. "79!HEX>C(C888(//9	 " $#' - 9% rD   c                *  K    ||       d{   }ddl m} |j                         dk(  r|S t               }g }|D ]?  }t	        ||      }	 t        | j                  |       d{   r|j                  |       A |S 7 q7 # t        $ r Y Sw xY ww)z2Filter prompts/list response based on auth checks.Nr   r4   r6   r7   r:   )	r1   r=   r>   promptsr5   r8   authorized_promptspromptrB   s	            r"   on_list_promptszAuthMiddleware.on_list_prompts'  s      "'** 	>!!#w.N "+-FEV<C(C888&--f5	  "!' + 9% rD   c                V  K   ddl m} |j                         dk(  r ||       d{   S |j                  j                  }|j
                  }|(t        j                  d| d       t        d| d      t        |j                  j                        }|j                  j                  ||	       d{   }|t        d| d
      t               }t        ||      }	t        | j                   |	       d{   st        d| d       ||       d{   S 7 7 k7 '7 
w)z Check auth before prompt render.r   r4   r6   Nz4AuthMiddleware: fastmcp_context is None for prompt 'rF   z!Authorization failed for prompt 'rG   rH   rI   r7   rJ   )r;   r5   r%   rK   rL   rM   rN   rO   r   r+   r(   r   
get_promptr   r   r   r0   )
r1   r=   r>   r5   prompt_namer   r   rf   r8   rB   s
             r"   on_get_promptzAuthMiddleware.on_get_promptB  sH     	>!!#w."7+++ oo**))?NNF{m T/ / %3K=@RS  %W__%9%9:11+w1OO>$3K= A. .  !"8$TYY444$3K=@[\  w'''E ,& P 5
 (rS   N)r0   zAuthCheck | list[AuthCheck]returnNone)r=   z&MiddlewareContext[mt.ListToolsRequest]r>   z-CallNext[mt.ListToolsRequest, Sequence[Tool]]rl   zSequence[Tool])r=   z+MiddlewareContext[mt.CallToolRequestParams]r>   z.CallNext[mt.CallToolRequestParams, ToolResult]rl   r   )r=   z*MiddlewareContext[mt.ListResourcesRequest]r>   z5CallNext[mt.ListResourcesRequest, Sequence[Resource]]rl   zSequence[Resource])r=   z/MiddlewareContext[mt.ReadResourceRequestParams]r>   z6CallNext[mt.ReadResourceRequestParams, ResourceResult]rl   r	   )r=   z2MiddlewareContext[mt.ListResourceTemplatesRequest]r>   zECallNext[mt.ListResourceTemplatesRequest, Sequence[ResourceTemplate]]rl   zSequence[ResourceTemplate])r=   z(MiddlewareContext[mt.ListPromptsRequest]r>   z1CallNext[mt.ListPromptsRequest, Sequence[Prompt]]rl   zSequence[Prompt])r=   z,MiddlewareContext[mt.GetPromptRequestParams]r>   z1CallNext[mt.GetPromptRequestParams, PromptResult]rl   r   )__name__
__module____qualname____doc__r2   rC   rR   rX   r]   rb   rg   rk    r,   r"   r.   r.   N   s    < 7  A  
	 8.(<.( B.( 
	.(`$;$ I$ 
	$61(@1( J1( 
	1(f$C$
$ 
$$:"9" E" 
	"6,(=,( E,( 
	,(r,   r.   )r(   zmt.RequestParams.Meta | Nonerl   zVersionSpec | None)'rq   
__future__r   loggingcollections.abcr   	mcp.typestypesmtfastmcp.exceptionsr   fastmcp.prompts.baser   r   fastmcp.resources.baser   r	   fastmcp.resources.templater
   !fastmcp.server.auth.authorizationr   r   r   fastmcp.server.dependenciesr   $fastmcp.server.middleware.middlewarer   r   r   fastmcp.tools.baser   r   fastmcp.utilities.versionsr   	getLoggerrn   rN   r+   r.   rr   r,   r"   <module>r      sj   . #  $  1 5 ; 7 
 9 
 0 2			8	$4`(Z `(r,   