
    kKj*X                    \   U d dl mZ d dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZ d dlZd dl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mZ d d	lmZ d d
lm 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,m-Z-m.Z.m/Z/ 	 d dl0m1Z2 d dl3m4Z5 dZ6erd dl8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z?m@Z@  e&eA      ZBeegeCf   ZDdeEd<   d)dZFd*dZG G d de      ZH G d de$      Z	 d+	 	 	 	 	 d,d ZI	 d+	 	 	 	 	 d-d!ZJd"ZKd+d.d#ZLd+d/d$ZMd0d%ZNd+d1d&ZO	 d+	 	 	 	 	 d2d'ZPddgZQd3d(ZRy# e7$ r dZ6Y w xY w)4    )annotationsN)Callable)TYPE_CHECKING	AnnotatedAnyClassVar	TypeAliasoverload)validate_and_warn_tool_name)CallToolResultContentBlockIconTextContentToolAnnotationsToolExecution)Tool)	BaseModelFieldmodel_validator)SkipJsonSchema)FastMCPDeprecationWarning)	AuthCheck)FastMCPComponent)
get_logger)
TaskConfigTaskMeta)AudioFileImageNotSetNotSetT)	PrefabApp)	ComponentTF)Docket)	ExecutionFunctionTool)ArgTransformTransformedToolr	   ToolResultSerializerTypec                    t        | t              rt        | t              r| nd}nt        | t              rt        |       }nd}|y|j                  j                  d      }|dS |S )a  Resolve the effective ``by_alias`` setting for serializing *value*.

    Pydantic's low-level serialization helpers (``to_json``,
    ``to_jsonable_python``) default ``by_alias`` to ``True``, which silently
    ignores a model's ``serialize_by_alias`` config. When *value* is a Pydantic
    model we consult that config instead, falling back to ``True`` to preserve
    FastMCP's longstanding default of emitting aliases when no preference is
    declared.
    NTserialize_by_alias)
isinstancetype
issubclassr   model_configget)valuemodel
configureds      c/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/tools/base.pyresolve_serialize_by_aliasr6   A   se     %#E954	E9	%U}##''(<=J%45:5    c                h    t        j                  | t        t        |             j	                         S )N)fallbackby_alias)pydantic_coreto_jsonstrr6   decode)datas    r5   default_serializerr@   Y   s)      s%?%Efhr7   c                       e Zd ZU  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<   	 	 	 	 d	 	 	 	 	 	 	 d fdZ		 	 ddZ
 xZS )
ToolResultz*List of content blocks for the tool result)descriptionlist[ContentBlock]contentNz4Structured content matching the tool's output schema)defaultrC   dict[str, Any] | Nonestructured_contentz)Runtime metadata about the tool executionmetaFzWhether this result represents a tool execution error. When True, it maps to CallToolResult.isError so the error is returned to the client rather than raised.boolis_errorc                   ||t        d      ||}t        |      }|t        rAt        |t              rt        |      }n%t        |t              rt        t	        |            }	 t        j                  |t        |            }t        |t              s%t        dt        |      j                   d|d      t         | E  ||||	       y # t        j                  $ r}t        j                  d|         d }~ww xY w)
Nz5Either content or structured_content must be provided)resultview)r2   r:   zCould not serialize structured content. If this is unexpected, set your tool's output_schema to None to disable automatic serialization: z/structured_content must be a dict or None. Got z: zA. Tools should wrap non-dict values based on their output_schema.)rE   rH   rI   rK   )
ValueError_convert_to_content_HAS_PREFABr-   
_PrefabApp_prefab_to_json_PrefabComponentr;   to_jsonable_pythonr6   PydanticSerializationErrorloggererrordictr.   __name__super__init__)selfrE   rH   rI   rK   converted_contente	__class__s          r5   r]   zToolResult.__init__p   s>    ?19TUU_(G0C70S) 0*=)89K)L& 24DE)8"(:;*&	%2%E%E,78JK&" 0$7  23<<=R@R?U VVV  	%1	 	 	
 !;;  `  ab  `c  d 	s   + C D'D  Dc                    | j                   | j                  r7t        | j                  | j                  | j                  | j                         S | j                  | j                  S | j                  | j                  fS )N)structuredContentrE   isError_meta)rI   rK   r   rH   rE   r^   s    r5   to_mcp_resultzToolResult.to_mcp_result   sl     99 DMM!"&"9"9ii	  ""*<<||T4444r7   )NNNF)rE   zlist[ContentBlock] | Any | NonerH   zdict[str, Any] | Any | NonerI   rG   rK   rJ   )returnzOlist[ContentBlock] | tuple[list[ContentBlock], dict[str, Any]] | CallToolResult)r[   
__module____qualname__r   rE   __annotations__rH   rI   rK   r]   rg   __classcell__ra   s   @r5   rB   rB   _   s    "'@#G  16"X1-  #("M#D
  ,Hd  48:>&*/
0/
 8/
 $	/

 /
b5 	X5r7   rB   c                  4    e Zd ZU dZdZded<   ded<   dZded	<   dZd
ed<   dZded<   dZ	ded<   dZ
ded<   dZded<    ed      d&d       Z	 	 	 	 d'dZeddddddddeddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d(d       Zd)dZd*dZe	 d+	 	 	 	 	 d,d       Ze	 	 	 	 	 	 d-d       Z	 d+	 	 	 	 	 d.dZd/dZddd 	 	 	 	 	 	 	 	 	 	 	 d0d!Zedeedeededdd"
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d1d#       Zed2d$       Zd3 fd%Z xZS )4r   z Internal tool registration info.toolzClassVar[str]
KEY_PREFIXzOAnnotated[dict[str, Any], Field(description='JSON schema for tool parameters')]
parametersNzRAnnotated[dict[str, Any] | None, Field(description='JSON schema for tool output')]output_schemaz]Annotated[ToolAnnotations | None, Field(description='Additional annotations about the tool')]r   z]Annotated[ToolExecution | None, Field(description='Task execution configuration (SEP-1686)')]	executionzAnnotated[SkipJsonSchema[ToolResultSerializerType | None], Field(description='Deprecated. Return ToolResult from your tools for full control over serialization.')]
serializerzAnnotated[SkipJsonSchema[AuthCheck | list[AuthCheck] | None], Field(description='Authorization checks for this tool', exclude=True)]authzkAnnotated[float | None, Field(description='Execution timeout in seconds. If None, no timeout is applied.')]timeoutafter)modec                0    t        | j                         | S )z<Validate tool name according to MCP specification (SEP-986).)r   namerf   s    r5   _validate_tool_namezTool._validate_tool_name   s     	$DII.r7   c                :   d}| j                   r| j                   }n8| j                  r,| j                  j                   r| j                  j                   }t        |j                  d| j                        |j                  d|      |j                  d| j
                        |j                  d| j                        |j                  d| j                        |j                  d| j                        |j                  d| j                        |j                  d	| j                        |j                  d
| j                               	      }| j                  j                         r5d	|vr1| j                  s%t        | j                  j                        |_	        |S )z(Convert the FastMCP tool to an MCP tool.Nrz   titlerC   inputSchemaoutputSchemaiconsr   rs   re   )	rz   r}   rC   r~   r   r   r   rs   re   )taskSupport)r}   r   MCPToolr1   rz   rC   rq   rr   r   rs   get_metatask_configsupports_tasksr   rx   )r^   	overridesr}   mcp_tools       r5   to_mcp_toolzTool.to_mcp_tool   s5   
 ::JJE$"2"2"8"8$$**Evtyy1--/!mT5E5EF!mT__E"~t7I7IJ--4!mT5E5EFmmK@--
 ++-9,NN!.4;K;K;P;P!QHr7   )rz   versionr}   rC   r   tagsr   exclude_argsrr   rt   rI   taskrv   ru   run_in_threadc                   ddl m}  |j                  di d|d|d|d|d|d|d	|d
|d|	d|
d|d|d|d|d|d|S )zCreate a Tool from a function.r   r&   fnrz   r   r}   rC   r   r   r   r   rr   rt   rI   r   rv   ru   r    )fastmcp.tools.function_toolr'   from_function)clsr   rz   r   r}   rC   r   r   r   r   rr   rt   rI   r   rv   ru   r   r'   s                     r5   r   zTool.from_function  s    , 	=)|)) 


 
 	

 $
 
 
 $
 &
 (
 "
 
 
 
 
  (!
 	
r7   c                    K   t        d      w)a"  
        Run the tool with arguments.

        This method is not implemented in the base Tool class and must be
        implemented by subclasses.

        `run()` can EITHER return a list of ContentBlocks, or a tuple of
        (list of ContentBlocks, dict of structured output).
        zSubclasses must implement run())NotImplementedError)r^   	argumentss     r5   runzTool.run,  s      ""CDDs   c                   t        |t              r|S t        rVt        |t              rt	        |t        |             S t        |t              r t	        t        |      t        |             S t        || j                        }t        |t              rt        |      S | j                  Zt        |t        t        z  t        z  t        z        s)t        |t        t         z        rt#        d |D              rt        |      S 	 t%        j&                  |t)        |            }| j                  )t        |t.              rt        ||      S t        |      S | j                  j1                  d	      }t        ||rd
|in||rdddii      S d      S # t$        j*                  t,        f$ r t        |      cY S w xY w)zConvert a raw result to ToolResult.

        Handles ToolResult passthrough and converts raw values using the tool's
        attributes (serializer, output_schema) for proper conversion.
        fastmcp_app_namerN   )rt   )rE   Nc              3  <   K   | ]  }t        |t                y wNr-   r   .0items     r5   	<genexpr>z&Tool.convert_result.<locals>.<genexpr>Y  s     M94
469   )r:   rE   rH   zx-fastmcp-wrap-resultrM   fastmcpwrap_resultT)rE   rH   rI   )r-   rB   rR   rS   _prefab_to_tool_result_get_fastmcp_app_namerU   rQ   rt   bytesrr   r   r   r   r   listtupleanyr;   rV   r6   rW   UnicodeDecodeErrorrZ   r1   )r^   	raw_valuerE   
structuredr   s        r5   convert_resultzTool.convert_result8  s    i,)Z0-%:4%@  )%56-I.%:4%@ 
 &iDOOL i'g.. %y,"6">"EF9dUl3M9MM g..	/&99$>y$IJ %*d+!'jQQg.. ((,,-DE9D*5*7B)mT23
 	
 IM
 	
 88:LM 	/g..	/s   	 F %GGc                   K   y wr   r   r^   r   	task_metas      r5   _runz	Tool._runs  s     
    c                   K   y wr   r   r   s      r5   r   z	Tool._runz  s     
 &)r   c                   K   ddl m}  || d||       d{   }|r|S | j                  |       d{   S 7 !7 w)a-  Server entry point that handles task routing.

        This allows ANY Tool subclass to support background execution by setting
        task_config.mode to "supported" or "required". The server calls this
        method instead of run() directly.

        Args:
            arguments: Tool arguments
            task_meta: If provided, execute as background task and return
                CreateTaskResult. If None (default), execute synchronously and
                return ToolResult.

        Returns:
            ToolResult when task_meta is None.
            CreateTaskResult when task_meta is provided.

        Subclasses can override this to customize task routing behavior.
        For example, FastMCPProviderTool overrides to delegate to child
        middleware without submitting to Docket.
        r   )check_background_taskro   )	component	task_typer   r   N)fastmcp.server.tasks.routingr   r   )r^   r   r   r   task_results        r5   r   z	Tool._run  sO     2 	G1	
 
 XXi(((
 )s   >:><>>c                    | j                   j                         sy|j                  | j                  | j                  g       y)z8Register this tool with docket for background execution.N)names)r   r   registerr   key)r^   dockets     r5   register_with_docketzTool.register_with_docket  s1    ..0
3r7   )fn_keytask_keyc               ~   K   |xs | j                   }|r||d<     |j                  |fi ||       d{   S 7 w)ae  Schedule this tool for background execution via docket.

        Args:
            docket: The Docket instance
            arguments: Tool arguments
            fn_key: Function lookup key in Docket registry (defaults to self.key)
            task_key: Redis storage key for the result
            **kwargs: Additional kwargs passed to docket.add()
        r   N)r   add)r^   r   r   r   r   kwargs
lookup_keys          r5   add_to_docketzTool.add_to_docket  sE     $ 'txx
$F5M5ZVZZ
5f5i@@@@s   4=;=)
rz   r}   rC   r   r   rr   rt   rI   transform_argstransform_fnc       
        j    ddl m} | j                  |      } |j                  |||||
||||||	      S )Nr   )r)   )ro   r   rz   r}   r   rC   r   r   rr   rt   rI   )fastmcp.tools.tool_transformr)   _ensure_tool	from_tool)r   ro   rz   r}   rC   r   r   rr   rt   rI   r   r   r)   s                r5   r   zTool.from_tool  sN      	A%(((%)##'!
 	
r7   c                    t        |t              r|S ddlm} ddlm}m}  ||      }t        ||      r |j                  ||      S | j                  |      S )zCCoerce a callable into a Tool, respecting @tool decorator metadata.r   )get_fastmcp_meta)r'   ToolMeta)metadata)r-   r   fastmcp.decoratorsr   r   r'   r   r   )r   ro   r   r'   r   fmetas         r5   r   zTool._ensure_tool  sS     dD!K7F &eX&-<--dUCC  &&r7   c                ,    t         |          dddz  S )Nro   LocalProvider)zfastmcp.component.typezfastmcp.provider.type)r\   get_span_attributes)r^   ra   s    r5   r   zTool.get_span_attributes  s#    w*,&,%40
 
 	
r7   )rh   r   )r   r   rh   r   )"r   zCallable[..., Any]rz   
str | Noner   zstr | int | Noner}   r   rC   r   r   zlist[Icon] | Noner   set[str] | Noner   zToolAnnotations | Noner   zlist[str] | Nonerr   dict[str, Any] | NotSetT | Nonert   ToolResultSerializerType | NonerI   rG   r   zbool | TaskConfig | Nonerv   zfloat | Noneru   z"AuthCheck | list[AuthCheck] | Noner   zbool | Nonerh   r'   )r   dict[str, Any]rh   rB   )r   r   rh   rB   r   )r   r   r   Nonerh   rB   )r   r   r   r   rh   zmcp.types.CreateTaskResult)r   r   r   zTaskMeta | Nonerh   z'ToolResult | mcp.types.CreateTaskResult)r   r$   rh   r   )r   r$   r   r   r   r   r   r   r   r   rh   r%   )ro   Tool | Callable[..., Any]rz   r   r}   str | NotSetT | NonerC   r   r   r   r   z ToolAnnotations | NotSetT | Nonerr   r   rt   r   rI   r   r   zdict[str, ArgTransform] | Noner   zCallable[..., Any] | Nonerh   r)   )ro   r   rh   r   )rh   r   )r[   ri   rj   __doc__rp   rk   rr   r   rs   rt   ru   rv   r   r{   r   classmethodr    r   r   r   r
   r   r   r   r   r   r   rl   rm   s   @r5   r   r      sc   * &J& 
 	    	    	    	    	 	   	    '" #
!! 
!F 
  $( "&#' $.2)-9?6:&*)- $37%)%(
(
 	(

 "(
 (
  (
 !(
 (
 ,(
 '(
 7(
 4(
 $(
 '(
  !(
" 1#(
$ #%(
& 
'(
 (
T
E9
v  !  
	  )!) ) 
$	) ) &*$)!$) #$) 
1	$)L4 "#AA "A
 A A A 
A. 
  &,,2 $8>9?6:069=26
'
 	

 $
 *
 
 6
 7
 4
 .
 7
 0
 

 
B ' '
 
r7   r   c                    |		  ||       S t        |       S # t         $ r,}t        j                  d|d       Y d }~t        |       S d }~ww xY w)Nz!Error serializing tool result: %sT)exc_info)	ExceptionrX   warningr@   )rM   rt   r`   s      r5   _serialize_with_fallbackr     se     	f%% f%%  	NN3    f%%	s    	AAAc                $   t        | t              r| S t        | t              r| j                         S t        | t              r| j                         S t        | t              r| j                         S t        | t              rt        d|       S t        | t              r	 t        d| j                  d            S t        dt        | |            S # t        $ r2 dd l}t        d|j                  |       j                  d            cY S w xY w)Ntextr.   r   zutf-8r   ascii)r-   r   r   to_image_contentr   to_audio_contentr   to_resource_contentr=   r   r   r>   r   base64	b64encoder   )r   rt   r   s      r5    _convert_to_single_content_blockr     s     $%$$$&&$$$&&$''))$T22$	YFW1EFF F)A$
)STT " 	YF1A1A$1G1N1Nw1WXX	Ys   !C 8DDz[Rendered Prefab UI]c                >    	 ddl m}  ||       S # t        $ r Y yw xY w)z<Get the Prefab peer-reference resolver bound to an app name.r   )_make_resolverN)fastmcp.apps.appr   ImportError)app_namer   s     r5   _get_tool_resolverr   -  s'    3h'' s    	c                <    | j                  t        |            }|S )u`  Call PrefabApp.to_json() with the hash-based resolver.

    The resolver prefixes peer-tool references with a deterministic hash
    derived from the app name + tool name. The dispatcher recognizes that
    format and routes calls via ``get_tool_by_hash`` which walks the
    provider tree recursively — same pattern as the old ``get_app_tool``.
    )tool_resolver)r<   r   )appr   r?   s      r5   rT   rT   7  s      ;;%78H%I;JDKr7   c                    | j                   }|sy|j                  d      }t        |t              r#|j                  d      }t        |t              r|S y)z<Read the FastMCPApp name from a tool's metadata, if present.Nr   r   )rI   r1   r-   rZ   r=   )ro   rI   fastmcp_metar   s       r5   r   r   C  sK    99D88I&L,%u%c3Jr7   c                R    t        t        dt              gt        | |            S )z,Convert a PrefabApp to a FastMCP ToolResult.r   r   r   r   )rB   r   _PREFAB_TEXT_FALLBACKrT   )r   r   s     r5   r   r   P  s(    &/DEF*3AQR r7   c                0   | g S t        | t        t        z        st        | |      gS t	        d | D              r| S t        d | D              r,| D cg c]   }t        |t              st        ||      n|" c}S t        dt        | |            gS c c}w )z2Convert a result to a sequence of content objects.c              3  <   K   | ]  }t        |t                y wr   r   r   s     r5   r   z&_convert_to_content.<locals>.<genexpr>e  s     
=fd:dL)fr   c              3  f   K   | ])  }t        |t        t        z  t        z  t        z         + y wr   )r-   r   r   r   r   r   s     r5   r   z&_convert_to_content.<locals>.<genexpr>j  s'     
TVT:dL50584?@Vs   /1r   r   )	r-   r   r   r   allr   r   r   r   )rM   rt   r   s      r5   rQ   rQ   X  s     ~	fte|-0DEE 
=f
== 
TV
TT
 	
  dL1 -T:> 	
 	
 V*B6:*VWXX
s   %Bc                    dddd}| |v rLddl }|j                  j                  r t        j                  d|  dt
        d	
       ddlm} t        ||       S t        dt        d|       )z2Deprecated re-exports for backwards compatibility.r'   ParsedFunctionro   )r'   r  ro   r   Nz
Importing zX from fastmcp.tools.tool is deprecated. Import from fastmcp.tools.function_tool instead.   )
stacklevel)function_toolzmodule z has no attribute )r   settingsdeprecation_warningswarningswarnr   fastmcp.toolsr  getattrAttributeErrorr[   )rz   deprecated_exportsr   r  s       r5   __getattr__r  x  s     '* !!00MMTF #C D)	 	0}d++
78,.@I
JJr7   )r2   r   rh   rJ   )r?   r   rh   r=   r   )rM   r   rt   r   rh   r=   )r   r   rt   r   rh   r   )r   r   rh   zCallable[..., str] | None)r   r   r   r   rh   r   )ro   r   rh   r   )r   r   r   r   rh   rB   )rM   r   rt   r   rh   rD   )rz   r=   rh   r   )S
__future__r   r	  collections.abcr   typingr   r   r   r   r	   r
   	mcp.typesmcpr;   mcp.shared.tool_name_validationr   r   r   r   r   r   r   r   r   pydanticr   r   r   pydantic.json_schemar   fastmcp.exceptionsr   fastmcp.utilities.authorizationr   fastmcp.utilities.componentsr   fastmcp.utilities.loggingr   fastmcp.utilities.tasksr   r   fastmcp.utilities.typesr   r   r   r    r!   prefab_ui.appr"   rS   prefab_ui.components.baser#   rU   rR   r   r   r$   docket.executionr%   r   r'   r   r(   r)   r[   rX   r=   r*   rk   r6   r@   rB   r   r   r   r   rT   r   r   rQ   __all__r  r   r7   r5   <module>r"     s{   "  $    G  & 6 6 / 8 5 9 0 8 5GK *8J 
H	 '/ucz&: ) :60R5 R5jE
 E
R
 @D&&<&&$ 37U
U/U U< / 	
 37YY/Y Y: <
 KS  Ks   D! !D+*D+