
    $jJ                       d Z ddlmZ ddlmZ ddlmZmZmZm	Z	 ddl
ZddlmZ ddlmZ ddlmZmZmZmZmZ dd	lmZ erdd
lmZ ddlmZ ddlmZ ddlmZ  e	dd          Z dZ!dZ" G d de          Z#d5dZ$erddlmZ d6dZ%ddd7d"Z&d8d$Z'd9d%Z(dddddd&d'd:d/Z)dddddd&d'd:d0Z*d;d1Z+ e	d2d          Z,d<d4Z-dS )=a  Visibility transform for marking component visibility state.

Each Visibility instance marks components via internal metadata. Multiple
visibility transforms can be stacked - later transforms override earlier ones.
Final filtering happens at the Provider level.
    )annotations)Sequence)TYPE_CHECKINGAnyLiteralTypeVarN)Resource)ResourceTemplate)GetPromptNextGetResourceNextGetResourceTemplateNextGetToolNext	Transform)VersionSpec)Prompt)Context)Tool)FastMCPComponentTr   )boundfastmcp	_internalc                      e Zd ZdZdddddddd6dZd7dZd8dZd9dZd:dZddd;d"Z	d<d%Z
ddd=d)Zd>d,Zddd?d/Zd@d2ZdddAd5ZdS )B
Visibilitya  Sets visibility state on matching components.

    Does NOT filter inline - just marks components with visibility state.
    Later transforms in the chain can override earlier marks.
    Final filtering happens at the Provider level after all transforms run.

    Example:
        ```python
        # Disable components tagged "internal"
        Visibility(False, tags={"internal"})

        # Re-enable specific tool (override earlier disable)
        Visibility(True, names={"safe_tool"})

        # Allowlist via composition:
        Visibility(False, match_all=True)  # disable everything
        Visibility(True, tags={"public"})  # enable public
        ```
    NFnameskeysversiontags
components	match_allenabledboolr   set[str] | Noner   r   VersionSpec | Noner   r    =set[Literal['tool', 'resource', 'template', 'prompt']] | Noner!   returnNonec               h    || _         || _        || _        || _        || _        || _        || _        dS )ax  Initialize a visibility marker.

        Args:
            enabled: If True, mark matching as enabled; if False, mark as disabled.
            names: Component names or URIs to match.
            keys: Component keys to match (e.g., {"tool:my_tool@v1"}).
            version: Component version spec to match. Unversioned components (version=None)
                will NOT match a version spec.
            tags: Tags to match (component must have at least one).
            components: Component types to match (e.g., {"tool", "prompt"}).
            match_all: If True, matches all components regardless of other criteria.
        N)_enabledr   r   r   r   r    r!   )selfr"   r   r   r   r   r    r!   s           l/home/rurouni/.hermes/hermes-agent/venv/lib/python3.11/site-packages/fastmcp/server/transforms/visibility.py__init__zVisibility.__init__<   s9    0  
		$"    strc                X   | j         rdnd}| j        rd| j          dS g }| j        r*|                    dt	          | j                              | j        r*|                    dt	          | j                              | j        r|                    d| j                   | j        r*|                    dt	          | j                              | j        r*|                    d	t	          | j                              |rd| d
d
	                    |           dS d| dS )NenabledisablezVisibility(z, match_all=True)znames=zkeys=zversion=zcomponents=ztags=z, ))
r*   r!   r   appendsetr   r   r    r   join)r+   actionpartss      r,   __repr__zVisibility.__repr__\   sP   !]9	> 	BAAAAA: 	5LL3#dj//334449 	3LL1TY11222< 	6LL4DL44555? 	?LL=s4?';';==>>>9 	3LL1TY11222 	?>>>499U+;+;>>>>&V&&&&r.   	componentr   c                p   | j         rdS | j        | j        | j        | j        	| j        dS | j        +|j                            d          d         }|| j        vrdS | j        |j        | j        vrdS | j        j|j        | j        v }d}t          |t                    rt          |j                  | j        v }n#t          |t                    r|j        | j        v }|s|sdS | j        #| j                            |j        d          sdS | j        du pt!          |j        | j        z            S )an  Check if this transform applies to the component.

        All specified criteria must match (intersection semantics).
        An empty rule (no criteria) matches nothing.
        Use match_all=True to match everything.

        Args:
            component: Component to check.

        Returns:
            True if this transform should mark the component.
        TNF:r   )
match_none)r!   r   r   r   r    r   keysplitname
isinstancer	   r/   urir
   uri_templatematchesr#   )r+   r:   component_typematches_namematches_uris        r,   _matcheszVisibility._matcheso   su    > 	4 J	!$'	!5 ?&&]0055N T_44u 9 }DI--u :!$>TZ7LK)X.. C!)-00DJ>I'788 C'4
B  K u <#DL,@,@% -A -
 -
# 5 yD DD$))C$D$DDr.   r   c                l   |                      |          s|S |j        t          t          d| j        iii}ng|j                            t          i           }|                    t          i           }i |d| j        i}i |t          |i}i |j        t          |i}|                    d|i          S )zSet visibility state in component metadata if rule matches.

        Returns a copy of the component with updated metadata to avoid
        mutating shared objects cached in providers.
        N
visibilitymeta)update)rH   rK   _FASTMCP_KEY_INTERNAL_KEYr*   get
model_copy)r+   r:   new_metaold_fastmcpold_internalnew_internalnew_fastmcps          r,   _mark_componentzVisibility._mark_component   s     }}Y'' 	>!$}|T]6S&TUHH#.,,\2>>K&??="==LHlHL$-HHLF[F-FFKD).D,DDH##FH+=#>>>r.   toolsSequence[Tool]c                $    K    fd|D             S )zMark tools by visibility state.c                :    g | ]}                     |          S  rV   .0tr+   s     r,   
<listcomp>z)Visibility.list_tools.<locals>.<listcomp>   s'    777A$$Q''777r.   r[   )r+   rW   s   ` r,   
list_toolszVisibility.list_tools   s!      77777777r.   r   r@   	call_nextr   Tool | Nonec               ^   K    |||           d{V }|dS |                      |          S )zMark tool if found.rb   Nr\   )r+   r@   rc   r   tools        r,   get_toolzVisibility.get_tool   sL       YtW555555555<4##D)))r.   	resourcesSequence[Resource]c                $    K    fd|D             S )z#Mark resources by visibility state.c                :    g | ]}                     |          S r[   r\   )r^   rr+   s     r,   r`   z-Visibility.list_resources.<locals>.<listcomp>   '    ;;;A$$Q'';;;r.   r[   )r+   rh   s   ` r,   list_resourceszVisibility.list_resources   s!      ;;;;;;;;r.   rB   r   Resource | Nonec               ^   K    |||           d{V }|dS |                      |          S )zMark resource if found.rb   Nr\   )r+   rB   rc   r   resources        r,   get_resourcezVisibility.get_resource   M       #38888888884##H---r.   	templatesSequence[ResourceTemplate]c                $    K    fd|D             S )z,Mark resource templates by visibility state.c                :    g | ]}                     |          S r[   r\   r]   s     r,   r`   z6Visibility.list_resource_templates.<locals>.<listcomp>   rm   r.   r[   )r+   rt   s   ` r,   list_resource_templatesz"Visibility.list_resource_templates   s#       <;;;;;;;r.   r   ResourceTemplate | Nonec               ^   K    |||           d{V }|dS |                      |          S )z Mark resource template if found.rb   Nr\   )r+   rB   rc   r   templates        r,   get_resource_templatez Visibility.get_resource_template   rs   r.   promptsSequence[Prompt]c                $    K    fd|D             S )z!Mark prompts by visibility state.c                :    g | ]}                     |          S r[   r\   )r^   pr+   s     r,   r`   z+Visibility.list_prompts.<locals>.<listcomp>  s'    999A$$Q''999r.   r[   )r+   r}   s   ` r,   list_promptszVisibility.list_prompts  s!      99999999r.   r   Prompt | Nonec               ^   K    |||           d{V }|dS |                      |          S )zMark prompt if found.rb   Nr\   )r+   r@   rc   r   prompts        r,   
get_promptzVisibility.get_prompt  sL       !yw777777777>4##F+++r.   )r"   r#   r   r$   r   r$   r   r%   r   r$   r    r&   r!   r#   r'   r(   )r'   r/   r:   r   r'   r#   )r:   r   r'   r   )rW   rX   r'   rX   )r@   r/   rc   r   r   r%   r'   rd   )rh   ri   r'   ri   )rB   r/   rc   r   r   r%   r'   ro   )rt   ru   r'   ru   )rB   r/   rc   r   r   r%   r'   ry   )r}   r~   r'   r~   )r@   r/   rc   r   r   r%   r'   r   )__name__
__module____qualname____doc__r-   r9   rH   rV   ra   rg   rn   rr   rx   r|   r   r   r[   r.   r,   r   r   '   sr        0 "& $&* $# # # # # #@' ' ' '&<E <E <E <E|? ? ? ?.8 8 8 8
 SW* * * * * *< < < < '+. . . . . ."< < < < '+. . . . . .": : : :
 UY, , , , , , , ,r.   r   r:   r'   r#   c                    | j         pi }|                    t          i           }|                    t          i           }|                    dd          S )a<  Check if component is enabled.

    Returns True if:
    - No visibility mark exists (default is enabled)
    - Visibility mark is True

    Returns False if visibility mark is False.

    Args:
        component: Component to check.

    Returns:
        True if component should be enabled/visible to clients.
    rJ   T)rK   rO   rM   rN   )r:   rK   r   internals       r,   
is_enabledr     sJ     >RDhh|R((G{{="--H<<d+++r.   contextr   list[dict[str, Any]]c                @   K   |                      d           d{V pg S )z.Load visibility rule dicts from session state._visibility_rulesN)	get_stater   s    r,   get_visibility_rulesr   ,  s2      ""#677777777=2=r.   r    rulesr    r&   r(   c                 K   |                      d|           d{V  |d|v r7|                     t          j                                                   d{V  |d|v sd|v r7|                     t          j                                                   d{V  |d|v r9|                     t          j                                                   d{V  dS dS )a  Save visibility rule dicts to session state and send notifications.

    Args:
        context: The context to save rules for.
        rules: The visibility rules to save.
        components: Optional hint about which component types are affected.
            If None, sends notifications for all types (safe default).
            If provided, only sends notifications for specified types.
    r   Nrf   rq   r{   r   )	set_statesend_notificationmcptypesToolListChangedNotificationResourceListChangedNotificationPromptListChangedNotification)r   r   r    s      r,   save_visibility_rulesr   1  s      

/
7
77777777 Vz11''	(M(M(O(OPPPPPPPPPZ:55z9Q9Q''	(Q(Q(S(STTTTTTTTTX33''	(O(O(Q(QRRRRRRRRRRR 43r.   list[Visibility]c                   g }| D ]X}d}|                     d          rS|d         }t          |                     d          |                     d          |                     d                    }|                    t          |d         |                     d          rt	          |d                   nd|                     d	          rt	          |d	                   nd||                     d
          rt	          |d
                   nd|                     d          rt	          |d                   nd|                     dd                               Z|S )z,Convert rule dicts to Visibility transforms.Nr   gtelteqr   r   r   r"   r   r   r   r    r!   Fr   )rO   r   r4   r   r5   )r   
transformsparamsr   version_dicts        r,   create_visibility_transformsr   L  sj   J 
 
::i   	!),L! $$U++##D))##D))  G
 	y!.4jj.A.AKc&/***t,2JJv,>,>HS(((D,2JJv,>,>HS(((D17L1I1ISC|,---t **[%88
 
 
	
 	
 	
 	
 r.   c                   K   	 | j         }n# t          $ r g cY S w xY wt          |            d{V }t          |          S )z<Get session-specific Visibility transforms from state store.N)
session_idRuntimeErrorr   r   )r   _r   s      r,   get_session_transformsr   h  sh         			 'w////////E'...s    Fr   r   r$   r   r   r%   r   r!   c               d  K   |r|nd}t          |            d{V }d|rt          |          nd|rt          |          nd|r|j        |j        |j        dnd|rt          |          nd|rt          |          nd|d}|                    |           t          | ||           d{V  dS )aE  Enable components matching criteria for this session only.

    Session rules override global transforms. Rules accumulate - each call
    adds a new rule to the session. Later marks override earlier ones
    (Visibility transform semantics).

    Sends notifications to this session only: ToolListChangedNotification,
    ResourceListChangedNotification, and PromptListChangedNotification.

    Args:
        context: The context for this session.
        names: Component names or URIs to match.
        keys: Component keys to match (e.g., {"tool:my_tool@v1"}).
        version: Component version spec to match.
        tags: Tags to match (component must have at least one).
        components: Component types to match (e.g., {"tool", "prompt"}).
        match_all: If True, matches all components regardless of other criteria.
    NTr   r"   r   r   r   r   r    r!   r   r   listr   r   r   r4   r   	r   r   r   r   r   r    r!   r   rules	            r,   enable_componentsr   t  s      :  *3tJ 'w////////E  %/e4",T


 GKwzDDD",T


*4>d:&&&$ D 
LL
:
F
F
FFFFFFFFFFr.   c               d  K   |r|nd}t          |            d{V }d|rt          |          nd|rt          |          nd|r|j        |j        |j        dnd|rt          |          nd|rt          |          nd|d}|                    |           t          | ||           d{V  dS )aF  Disable components matching criteria for this session only.

    Session rules override global transforms. Rules accumulate - each call
    adds a new rule to the session. Later marks override earlier ones
    (Visibility transform semantics).

    Sends notifications to this session only: ToolListChangedNotification,
    ResourceListChangedNotification, and PromptListChangedNotification.

    Args:
        context: The context for this session.
        names: Component names or URIs to match.
        keys: Component keys to match (e.g., {"tool:my_tool@v1"}).
        version: Component version spec to match.
        tags: Tags to match (component must have at least one).
        components: Component types to match (e.g., {"tool", "prompt"}).
        match_all: If True, matches all components regardless of other criteria.
    NFr   r   r   r   r   s	            r,   disable_componentsr     s      :  *3tJ 'w////////E  %/e4",T


 GKwzDDD",T


*4>d:&&&$ D 
LL
:
F
F
FFFFFFFFFFr.   c                6   K   t          | g            d{V  dS )a9  Clear all session visibility rules.

    Use this to reset session visibility back to global defaults.

    Sends notifications to this session only: ToolListChangedNotification,
    ResourceListChangedNotification, and PromptListChangedNotification.

    Args:
        context: The context for this session.
    N)r   r   s    r,   reset_visibilityr     s0        
,
,,,,,,,,,,r.   
ComponentTSequence[ComponentT]c                   K   ddl m} |                                }|| S t          |           d{V }|s| S t	          |           }|D ]fd|D             }|S )a  Apply session-specific visibility transforms to components.

    This helper applies session-level enable/disable rules by marking
    components with their visibility state. Session transforms override
    global transforms due to mark-based semantics (later marks win).

    Args:
        components: The components to apply session transforms to.

    Returns:
        The components with session transforms applied.
    r   )_current_contextNc                :    g | ]}                     |          S r[   r\   )r^   c	transforms     r,   r`   z,apply_session_transforms.<locals>.<listcomp>  s'    ???1)++A..???r.   )fastmcp.server.contextr   rO   r   r   )r    r   current_ctxsession_transformsresultr   s        @r,   apply_session_transformsr     s       877777"&&((K5kBBBBBBBB  *F' @ @	???????Mr.   r   )r   r   r'   r   )r   r   r   r   r    r&   r'   r(   )r   r   r'   r   )r   r   r'   r   )r   r   r   r$   r   r$   r   r%   r   r$   r    r&   r!   r#   r'   r(   )r   r   r'   r(   )r    r   r'   r   ).r   
__future__r   collections.abcr   typingr   r   r   r   	mcp.typesr   fastmcp.resources.baser	   fastmcp.resources.templater
   fastmcp.server.transformsr   r   r   r   r   fastmcp.utilities.versionsr   fastmcp.prompts.baser   r   r   fastmcp.tools.baser   fastmcp.utilities.componentsr   r   rM   rN   r   r   r   r   r   r   r   r   r   r   r   r[   r.   r,   <module>r      s    # " " " " " $ $ $ $ $ $ 7 7 7 7 7 7 7 7 7 7 7 7     + + + + + + 7 7 7 7 7 7              3 2 2 2 2 2 >++++++......''''''======GC)*** e, e, e, e, e, e, e, e,P, , , ,2  /......> > > > QU	S S S S S S6   8	/ 	/ 	/ 	/ " "& PT3G 3G 3G 3G 3G 3Gr " "& PT3G 3G 3G 3G 3G 3Gl- - - - W\);<<<
     r.   