
    i"                        d dl mZ d dlmZ d dlmZmZmZmZm	Z	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 erd d	lmZ d d
lmZ  ede      Z G d de	d      ZddZddZddZ G d de      Z y)    )annotations)Sequence)TYPE_CHECKING	AnnotatedAnyClassVar	TypedDictcast)Icon)BeforeValidatorField)SelfTypeVar
TaskConfig)FastMCPBaseModel)Docket)	ExecutionT)defaultc                  ,    e Zd ZU ded<   ded<   ded<   y)FastMCPMetaz	list[str]tagsstrversionversionsN)__name__
__module____qualname____annotations__     l/Users/bowang/.openclaw/workspace/ChatDev/.venv/lib/python3.12/site-packages/fastmcp/utilities/components.pyr   r      s    
OLr"   r   F)totalc                v    | si S t        t        | j                  d      xs | j                  d      xs i       S )zExtract FastMCP metadata from a component's meta dict.

    Handles both the current `fastmcp` namespace and the legacy `_fastmcp`
    namespace for compatibility with older FastMCP servers.
    fastmcp_fastmcp)r
   r   get)metas    r#   get_fastmcp_metadatar*      s5     	TXXi0NDHHZ4HNBOOr"   c                T    | 
t               S t        | t               r| S t        |       S )z@Convert a sequence to a set, defaulting to an empty set if None.)set
isinstance)	maybe_sets    r#   _convert_set_default_noner/   %   s)    u)S!y>r"   c                F    | yt        |       }d|v rt        d|      |S )z|Coerce version to string, accepting int or str.

    Raises ValueError if version contains '@' (used as key delimiter).
    N@z;Version string cannot contain '@' (used as key delimiter): )r   
ValueError)vr   s     r#   _coerce_versionr4   .   s:    
 	y!fG
g~I'U
 	
 Nr"   c                      e Zd ZU dZdZded<   d- fdZ ed      Zded	<    ed
d      Z	ded<    ed
d      Z
ded<    ed
d      Zded<    ed
d      Zded<    eed      Zded<    ed
d      Zded<    ed       Zd ed!<   ed.d"       Zed/d#       Zd0d$Zd1d%Zd/d&Zd2d'Zd2d(Zd3d)Zd4d*Z	 	 	 	 	 	 	 	 d5d+Zd0d,Z xZS )6FastMCPComponentzIBase class for FastMCP tools, prompts, resources, and resource templates. zClassVar[str]
KEY_PREFIXc                    t        |   di | | j                  s*dd l}|j	                  | j
                   dt        d       y y )Nr   zb does not define KEY_PREFIX. Component keys will not be type-prefixed, which may cause collisions.   )
stacklevelr!   )super__init_subclass__r8   warningswarnr   UserWarning)clskwargsr>   	__class__s      r#   r=   z"FastMCPComponent.__init_subclass__B   sN    !+F+~~MM<<. !X Y	   r"   zThe name of the component.)descriptionr   nameNzpOptional version identifier for this component. Multiple versions of the same component (same name) can coexist.)r   rD   z7Annotated[str | None, BeforeValidator(_coerce_version)]r   z0The title of the component for display purposes.
str | Nonetitlez!The description of the component.rD   zHOptional list of icons for this component to display in user interfaces.zlist[Icon] | NoneiconszTags for the component.)default_factoryrD   z?Annotated[set[str], BeforeValidator(_convert_set_default_none)]r   z$Meta information about the componentdict[str, Any] | Noner)   c                     t        d      S )N	forbidden)moder   r!   r"   r#   <lambda>zFastMCPComponent.<lambda>m   s	    jk&Br"   )rI   z_Annotated[TaskConfig, Field(description='Background task execution configuration (SEP-1686).')]task_configc                @    | j                   r| j                    d| S |S )zConstruct the lookup key for this component type.

        Args:
            identifier: The raw identifier (name for tools/prompts, uri for resources)

        Returns:
            A prefixed key like "tool:name" or "resource:uri"
        :)r8   )rA   
identifiers     r#   make_keyzFastMCPComponent.make_keyo   s'     >>nn%Qzl33r"   c                b    | j                  | j                        }| d| j                  xs d S )a  The globally unique lookup key for this component.

        Format: "{key_prefix}:{identifier}@{version}" or "{key_prefix}:{identifier}@"
        e.g. "tool:my_tool@v2", "tool:my_tool@", "resource:file://x.txt@"

        The @ suffix is ALWAYS present to enable unambiguous parsing of keys
        (URIs may contain @ characters, so we always include the delimiter).

        Subclasses should override this to use their specific identifier.
        Base implementation uses name.
        r1   r7   )rS   rE   r   )selfbase_keys     r#   keyzFastMCPComponent.key}   s1     ==+1T\\/R011r"   c                   | j                   rt        | j                         ni }dt        | j                        i}| j                  | j                  |d<   |j                  d      x}ct        |t              st        d      |j                         D ci c]  \  }}|j                  d      r|| }}}t        t        ||z        }||d<   |S c c}}w )a8  Get the meta information about the component.

        Returns a dict that always includes a `fastmcp` key containing:
        - `tags`: sorted list of component tags
        - `version`: component version (only if set)

        Internal keys (prefixed with `_`) are stripped from the fastmcp namespace.
        r   r   r&   zmeta['fastmcp'] must be a dict_)r)   dictsortedr   r   r(   r-   	TypeErroritems
startswithr
   r   )rU   r)   fastmcp_metaupstream_metakr3   public_upstreams          r#   get_metazFastMCPComponent.get_meta   s     #'))tDII%+VDII->$?<<#&*llL# "XXi00M=mT2 @AA "/!4!4!6!6Aall3>O1!6    _|-KLL&Ys   C1Cc                    t        |       t        |      uryt        |t        |             sy| j                         |j                         k(  S )NF)typer-   
model_dump)rU   others     r#   __eq__zFastMCPComponent.__eq__   sA    :T%[(%d, E$4$4$666r"   c                B   d| j                   g}| j                  r|j                  d| j                         |j                  d| j                  d| j
                  d| j                   g       | j                  j                   ddj                  |       dS )	Nzname=zversion=ztitle=zdescription=ztags=(z, ))
rE   r   appendextendrG   rD   r   rC   r   join)rU   partss     r#   __repr__zFastMCPComponent.__repr__   s    &'<<LL8DLL#345't//23		{#	
 ..))*!DIIe,<+=Q??r"   c                4    t        d| j                   d      )z6Removed in 3.0. Use server.enable(keys=[...]) instead.zHComponent.enable() was removed in FastMCP 3.0. Use server.enable(keys=['']) instead.NotImplementedErrorrW   rU   s    r#   enablezFastMCPComponent.enable   s$    !((,z?
 	
r"   c                4    t        d| j                   d      )z7Removed in 3.0. Use server.disable(keys=[...]) instead.zJComponent.disable() was removed in FastMCP 3.0. Use server.disable(keys=['rr   rs   ru   s    r#   disablezFastMCPComponent.disable   s%    !))-
,@
 	
r"   c                "    | j                         S )zCreate a copy of the component.)
model_copyru   s    r#   copyzFastMCPComponent.copy   s      r"   c                     y)zRegister this component with docket for background execution.

        No-ops if task_config.mode is "forbidden". Subclasses override to
        register their callable (self.run, self.read, self.render, or self.fn).
        Nr!   )rU   dockets     r#   register_with_docketz%FastMCPComponent.register_with_docket   s    r"   c                   K   | j                   j                         s0t        d| j                  j                   d| j
                   d      t        | j                  j                   d      w)a  Schedule this component for background execution via docket.

        Subclasses override this to handle their specific calling conventions:
        - Tool: add_to_docket(docket, arguments: dict, **kwargs)
        - Resource: add_to_docket(docket, **kwargs)
        - ResourceTemplate: add_to_docket(docket, params: dict, **kwargs)
        - Prompt: add_to_docket(docket, arguments: dict | None, **kwargs)

        The **kwargs are passed through to docket.add() (e.g., key=task_key).
        zCannot add z 'z)' to docket: task execution not supportedz# does not implement add_to_docket())rO   supports_tasksRuntimeErrorrC   r   rE   rt   )rU   r}   argsrB   s       r#   add_to_docketzFastMCPComponent.add_to_docket   ss      ..0dnn556b D/ 0  "~~&&''JK
 	
s   A-A/c                    d| j                   iS )z{Return span attributes for telemetry.

        Subclasses should call super() and merge their specific attributes.
        zfastmcp.component.key)rW   ru   s    r#   get_span_attributesz$FastMCPComponent.get_span_attributes   s    
 (22r"   )rB   r   returnNone)rR   r   r   r   )r   r   )r   zdict[str, Any])rg   objectr   bool)r   r   )r   r   )r}   r   r   r   )r}   r   r   r   rB   r   r   r   )r   r   r   __doc__r8   r    r=   r   rE   r   rG   rD   rH   r,   r   r)   rO   classmethodrS   propertyrW   rc   rh   rp   rv   rx   r{   r~   r   r   __classcell__)rC   s   @r#   r6   r6   =   s_   S "J" 0D#  HMKHGD 
 FE:  $7K   %^ E  MR-MD
I  #("H#D
  	BC   D
   2 287@

!

%(
47
	
,3r"   r6   N)r)   rJ   r   r   )r.   zset[T] | Sequence[T] | Noner   zset[T])r3   zstr | int | Noner   rF   )!
__future__r   collections.abcr   typingr   r   r   r   r	   r
   	mcp.typesr   pydanticr   r   typing_extensionsr   r   fastmcp.server.tasks.configr   fastmcp.utilities.typesr   r}   r   docket.executionr   r   r   r*   r/   r4   r6   r!   r"   r#   <module>r      sb    " $ K K  + + 2 4*C)5 Pu3' u3r"   