
    iJ                       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#d"dZ$erddlmZ d#dZ%dd	 	 	 	 	 	 	 d$dZ&d%dZ'd&dZ(ddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'dZ)ddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'dZ*d(dZ+ e	d d      Z,	 	 	 	 d)d!Z-y)*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	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZddZdd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dZdd
	 	 	 	 	 	 	 ddZy)
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_allc               f    || _         || _        || _        || _        || _        || _        || _        y)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!   )selfenabledr   r   r   r   r    r!   s           t/Users/bowang/.openclaw/workspace/ChatDev/.venv/lib/python3.12/site-packages/fastmcp/server/transforms/visibility.py__init__zVisibility.__init__<   s5    0  
		$"    c                   | j                   rdnd}| j                  rd| j                    dS g }| j                  r'|j                  dt	        | j                                | j
                  r'|j                  dt	        | j
                                | j                  r|j                  d| j                         | j                  r'|j                  dt	        | j                                | j                  r'|j                  d	t	        | j                                |rd| d
d
j                  |       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__\   s   !]]	>> /@AA::LL6#djj/!23499LL5TYY 012<<LL8DLL#345??LL;s4??';&<=>99LL5TYY 012 499U+;*<A>>VHA&&r(   c                (   | j                   ry| j                  1| j                  %| j                  | j                  | j
                  y| j                  -|j                  j                  d      d   }|| j                  vry| j                  |j                  | j                  vry| j                  y|j                  | j                  v }d}t        |t              r"t        |j                        | j                  v }n(t        |t              r|j                  | j                  v }|s|sy| j                  (| j                  j                  |j                  d      sy| j
                  du xs" 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	   strurir
   uri_templatematchesbool)r$   	componentcomponent_typematches_namematches_uris        r&   _matcheszVisibility._matcheso   sc    >> JJ		!$'		! ??&&]]005N T__4 99 }}DII- ::!$>>TZZ7LK)X.!)--0DJJ>I'78'44

B K <<#DLL,@,@% -A -
  yyD DD$)))C$DDr(   c                r   | j                  |      s|S |j                  t        t        d| j                  iii}nj|j                  j                  t        i       }|j                  t        i       }i |d| j                  i}i |t        |i}i |j                  t        |i}|j                  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.
        
visibilitymeta)update)rC   rF   _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UH#..,,\2>K&??="=LHlHL$--HLF[F-FKD)..D,DH##FH+=#>>r(   c                R   K   |D cg c]  }| j                  |       c}S c c}w w)zMark tools by visibility state.rQ   )r$   toolsts      r&   
list_toolszVisibility.list_tools   s)     167A$$Q'777   '"'r   c               Z   K    |||       d{   }|y| j                  |      S 7 w)zMark tool if found.rX   NrS   )r$   r8   	call_nextr   tools        r&   get_toolzVisibility.get_tool   s5      tW55<##D)) 6   +)+c                R   K   |D cg c]  }| j                  |       c}S c c}w w)z#Mark resources by visibility state.rS   )r$   	resourcesrs      r&   list_resourceszVisibility.list_resources   s)     1:;A$$Q';;;rW   c               Z   K    |||       d{   }|y| j                  |      S 7 w)zMark resource if found.rX   NrS   )r$   r;   rZ   r   resources        r&   get_resourcezVisibility.get_resource   6      #388##H-- 9r]   c                R   K   |D cg c]  }| j                  |       c}S c c}w w)z,Mark resource templates by visibility state.rS   )r$   	templatesrU   s      r&   list_resource_templatesz"Visibility.list_resource_templates   s+      2;;A$$Q';;;rW   c               Z   K    |||       d{   }|y| j                  |      S 7 w)z Mark resource template if found.rX   NrS   )r$   r;   rZ   r   templates        r&   get_resource_templatez Visibility.get_resource_template   re   r]   c                R   K   |D cg c]  }| j                  |       c}S c c}w w)z!Mark prompts by visibility state.rS   )r$   promptsps      r&   list_promptszVisibility.list_prompts  s)     189A$$Q'999rW   c               Z   K    |||       d{   }|y| j                  |      S 7 w)zMark prompt if found.rX   NrS   )r$   r8   rZ   r   prompts        r&   
get_promptzVisibility.get_prompt  s5      !w77>##F++ 8r]   )r%   r>   r   set[str] | Noner   rs   r   VersionSpec | Noner   rs   r    =set[Literal['tool', 'resource', 'template', 'prompt']] | Noner!   r>   returnNone)rv   r:   r?   r   rv   r>   )r?   r   rv   r   )rT   Sequence[Tool]rv   ry   )r8   r:   rZ   r   r   rt   rv   zTool | None)r_   Sequence[Resource]rv   rz   )r;   r:   rZ   r   r   rt   rv   zResource | None)rg   Sequence[ResourceTemplate]rv   r{   )r;   r:   rZ   r   r   rt   rv   zResourceTemplate | None)rm   Sequence[Prompt]rv   r|   )r8   r:   rZ   r   r   rt   rv   zPrompt | None)__name__
__module____qualname____doc__r'   r2   rC   rQ   rV   r\   ra   rd   rh   rk   ro   rr    r(   r&   r   r   '   s\   0 "& $&* $## 	#
 # $# ## # 
#@'&<E|?.8
 SW**$/*=O*	*< '+.. #.
 $. 
."<3<	#< '+.. +.
 $. 
!.":
 UY,,$1,?Q,	,r(   r   c                    | j                   xs i }|j                  t        i       }|j                  t        i       }|j                  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.
    rE   T)rF   rJ   rH   rI   )r?   rF   r   internals       r&   
is_enabledr     sC     >>RDhh|R(G{{="-H<<d++r(   c                H   K   | j                  d       d{   xs g S 7 w)z.Load visibility rule dicts from session state._visibility_rulesN)	get_statecontexts    r&   get_visibility_rulesr   ,  s#     ""#677=2=7s   " 	"r    c                 K   | j                  d|       d{    |d|v r5| j                  t        j                  j	                                d{    |d|v sd|v r5| j                  t        j                  j                                d{    |d|v r6| j                  t        j                  j                                d{    yy7 7 7 E7 w)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   Nr[   rc   rj   rq   )	set_statesend_notificationmcptypesToolListChangedNotificationResourceListChangedNotificationPromptListChangedNotification)r   rulesr    s      r&   save_visibility_rulesr   1  s      

/
777 Vz1''		(M(M(OPPPZ:5z9Q''		(Q(Q(STTTX3''		(O(O(QRRR 4 8
 	QTRsE   CC:CC>CC:CCCCCCc                "   g }| D ]  }d}|j                  d      r@|d   }t        |j                  d      |j                  d      |j                  d            }|j                  t        |d   |j                  d      rt	        |d         nd|j                  d	      rt	        |d	         nd||j                  d
      rt	        |d
         nd|j                  d      rt	        |d         nd|j                  dd                   	 |S )z,Convert rule dicts to Visibility transforms.Nr   gtelteqr   r   r   r%   r   r   r   r    r!   Fr   )rJ   r   r-   r   r.   )r   
transformsparamsr   version_dicts        r&   create_visibility_transformsr   L  s    J::i !),L! $$U+##D)##D)G
 	y!.4jj.Ac&/*t,2JJv,>S(D,2JJv,>S(D17L1IC|,-t **[%8
	
 , r(   c                   K   	 | j                   }t        |        d{   }t        |      S # t        $ r g cY S w xY w7  w)z<Get session-specific Visibility transforms from state store.N)
session_idRuntimeErrorr   r   )r   _r   s      r&   get_session_transformsr   h  sK      'w//E'..	  	 0s)   A. A?A<A<AFr   c               \  K   |r|nd}t        |        d{   }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}|j                  |       t        | ||       d{    y7 7 w)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   r-   r   	r   r   r   r   r   r    r!   r   rules	            r&   enable_componentsr   t  s     :  *tJ 'w//E  %e4"T
  KKwzzD"T
*4d:&$D 
LL
:
FFF' 0& G"   B,B(B
B,"B*#B,*B,c               \  K   |r|nd}t        |        d{   }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}|j                  |       t        | ||       d{    y7 7 w)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     :  *tJ 'w//E  %e4"T
  KKwzzD"T
*4d:&$D 
LL
:
FFF' 0& Gr   c                8   K   t        | g        d{    y7 w)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     s       
,,,s   
ComponentTc                   K   ddl m} |j                         }|| S t        |       d{   }|s| S t	        |       }|D ]   }|D cg c]  }|j                  |       }}" |S 7 :c c}w w)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_contextN)fastmcp.server.contextr   rJ   r   r   rQ   )r    r   current_ctxsession_transformsresult	transformcs          r&   apply_session_transformsr     s      8"&&(K5kBB *F'	8>?1)++A.? (M C @s!   )A-A&A-A( A-(A-rx   )r   r   rv   list[dict[str, Any]])r   r   r   r   r    ru   rv   rw   )r   r   rv   list[Visibility])r   r   rv   r   )r   r   r   rs   r   rs   r   rt   r   rs   r    ru   r!   r>   rv   rw   )r   r   rv   rw   )r    Sequence[ComponentT]rv   r   ).r   
__future__r   collections.abcr   typingr   r   r   r   	mcp.typesr   fastmcp.resources.resourcer	   fastmcp.resources.templater
   fastmcp.server.transformsr   r   r   r   r   fastmcp.utilities.versionsr   fastmcp.prompts.promptr   r   r   fastmcp.tools.toolr   fastmcp.utilities.componentsr   r   rH   rI   r   r   r   r   r   r   r   r   r   r   r   r   r(   r&   <module>r      s   # $ 7 7  / 7  3-.'=C)* e, e,P,2 .> QU	SSS N	S
 
S68	/ " "& PT3G3G 3G 	3G
  3G 3G N3G 3G 
3Gr " "& PT3G3G 3G 	3G
  3G 3G N3G 3G 
3Gl- \);<
$r(   