
    iv@                       d Z ddlmZ ddlZddlZddlmZmZmZm	Z	 ddl
ZddlmZ erddlZddl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 ddlmZ ddl m!Z! ddl"m#Z#  ee$      Z%eejL                  jN                  ejL                  j                   z     Z( G d d      Z)	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ*y)z(Tool-related methods for FastMCP Client.    )annotationsN)TYPE_CHECKINGAnyLiteraloverload)	RootModel)CallToolResultClient)ProgressHandler)ToolTask)client_span)	ToolError)inject_trace_context)json_schema_to_type)
get_logger)normalize_timeout_to_timedelta)get_cached_typeadapterc            
         e Zd ZdZdd	 	 	 	 	 ddZddZ	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 	 	 ddZe	 ddddd	ddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z	e	 ddddd	dddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z		 ddddd	ddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ		 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ
y)ClientToolsMixinz0Mixin providing tool-related methods for Client.Ncursorc                  K   t         j                  d| j                   d       | j                  | j                  j                  |             d{   }|S 7 w)a  Send a tools/list request and return the complete MCP protocol result.

        Args:
            cursor: Optional pagination cursor from a previous request's nextCursor.

        Returns:
            mcp.types.ListToolsResult: The complete response object from the protocol,
                containing the list of tools and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
            McpError: If the request results in a TimeoutError | JSONRPCError
        [z] called list_toolsr   N)loggerdebugname_await_with_session_monitoringsession
list_tools)selfr   results      k/Users/bowang/.openclaw/workspace/ChatDev/.venv/lib/python3.12/site-packages/fastmcp/client/mixins/tools.pylist_tools_mcpzClientToolsMixin.list_tools_mcp%   sX       	q#678::LL##6#2
 
 
s   AAAAc                  K   g }d}t               }	 | j                  |       d{   }|j                  |j                         |j                  s	 |S |j                  |v r3t
        j                  d| j                   d|j                  d       	 |S |j                  |j                         |j                  }7 w)a.  Retrieve all tools available on the server.

        This method automatically fetches all pages if the server paginates results,
        returning the complete list. For manual pagination control (e.g., to handle
        large result sets incrementally), use list_tools_mcp() with the cursor parameter.

        Returns:
            list[mcp.types.Tool]: A list of all Tool objects.

        Raises:
            RuntimeError: If called while the client is not connected.
            McpError: If the request results in a TimeoutError | JSONRPCError
        Nr   r   z.] Server returned duplicate pagination cursor z$ for list_tools; stopping pagination)	setr#   extendtools
nextCursorr   warningr   add)r    	all_toolsr   seen_cursorsr!   s        r"   r   zClientToolsMixin.list_tools<   s      +-	!!$..f.==FV\\*$$    L0		{ #)),,PR   V../&&F =s   %CB?BCc           
       K   t        d| d|| j                  j                               5  t        j	                  d| j
                   d|        t        |      }| j                  | j                  j                  ||t        |      |xs | j                  |r|nd             d{   }|cddd       S 7 # 1 sw Y   yxY ww)a  Send a tools/call request and return the complete MCP protocol result.

        This method returns the raw CallToolResult object, which includes an isError flag
        and other metadata. It does not raise an exception if the tool call results in an error.

        Args:
            name (str): The name of the tool to call.
            arguments (dict[str, Any]): Arguments to pass to the tool.
            timeout (datetime.timedelta | float | int | None, optional): The timeout for the tool call. Defaults to None.
            progress_handler (ProgressHandler | None, optional): The progress handler to use for the tool call. Defaults to None.
            meta (dict[str, Any] | None, optional): Additional metadata to include with the request.
                This is useful for passing contextual information (like user IDs, trace IDs, or preferences)
                that shouldn't be tool arguments but may influence server-side processing. The server
                can access this via `context.request_context.meta`. Defaults to None.

        Returns:
            mcp.types.CallToolResult: The complete response object from the protocol,
                containing the tool result and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
            McpError: If the tool call requests results in a TimeoutError | JSONRPCError
        ztools/call z
tools/call)
session_idr   z] called call_tool: N)r   	argumentsread_timeout_secondsprogress_callbackmeta)r   	transportget_session_idr   r   r   r   r   r   	call_toolr   _progress_handler)r    r   r/   progress_handlertimeoutr2   propagated_metar!   s           r"   call_tool_mcpzClientToolsMixin.call_tool_mcp`   s     > $ ~~446	
 LL1TYYK';D6BC 348O>>&&')G)P&6&P$:P:P,; '  F )
 

 
s/   +C	A>B=+B;,B=1
C	;B==CC	Fc                   K   t        ||| j                  j                  | j                  j                  | j                  |       d{   S 7 w)aJ  Parse an mcp.types.CallToolResult into our CallToolResult dataclass.

        Args:
            name: Tool name (for schema lookup)
            result: Raw MCP protocol result
            raise_on_error: Whether to raise ToolError on errors

        Returns:
            CallToolResult: Parsed result with structured data
        )r   r!   tool_output_schemaslist_tools_fnclient_nameraise_on_errorN)_parse_call_tool_resultr   _tool_output_schemasr   r   )r    r   r!   r?   s       r"   r@   z(ClientToolsMixin._parse_call_tool_result   sI     " - $ A A,,11		)
 
 	
 
s   AA	A
AT)versionr8   r7   r?   r2   taskc                  K   y wN )	r    r   r/   rB   r8   r7   r?   r2   rC   s	            r"   r5   zClientToolsMixin.call_tool   s         `  )rB   r8   r7   r?   r2   task_idttlc                  K   y wrE   rF   )r    r   r/   rB   r8   r7   r?   r2   rC   rI   rJ   s              r"   r5   zClientToolsMixin.call_tool   s      rG   )rB   r8   r7   r?   r2   rC   rI   rJ   c               :  K   |rt        |      ni }|i |j                  di       d|i|d<   |r"| j                  |||	|
|xs d       d{   S | j                  ||xs i |||xs d       d{   }| j	                  |||       d{   S 7 F7 "7 w)a  Call a tool on the server.

        Unlike call_tool_mcp, this method raises a ToolError if the tool call results in an error.

        Args:
            name (str): The name of the tool to call.
            arguments (dict[str, Any] | None, optional): Arguments to pass to the tool. Defaults to None.
            version (str | None, optional): Specific tool version to call. If None, calls highest version.
            timeout (datetime.timedelta | float | int | None, optional): The timeout for the tool call. Defaults to None.
            progress_handler (ProgressHandler | None, optional): The progress handler to use for the tool call. Defaults to None.
            raise_on_error (bool, optional): Whether to raise an exception if the tool call results in an error. Defaults to True.
            meta (dict[str, Any] | None, optional): Additional metadata to include with the request.
                This is useful for passing contextual information (like user IDs, trace IDs, or preferences)
                that shouldn't be tool arguments but may influence server-side processing. The server
                can access this via `context.request_context.meta`. Defaults to None.
            task (bool): If True, execute as background task (SEP-1686). Defaults to False.
            task_id (str | None): Optional client-provided task ID (auto-generated if not provided).
            ttl (int): Time to keep results available in milliseconds (default 60s).

        Returns:
            CallToolResult | ToolTask: The content returned by the tool if task=False,
                or a ToolTask object if task=True. If the tool returns structured
                outputs, they are returned as a dataclass (if an output schema
                is available) or a dictionary; otherwise, a list of content
                blocks is returned. Note: to receive both structured and
                unstructured outputs, use call_tool_mcp instead and access the
                raw result object.

        Raises:
            ToolError: If the tool call results in an error.
            McpError: If the tool call request results in a TimeoutError | JSONRPCError
            RuntimeError: If called while the client is not connected.
        NfastmcprB   )r2   )r   r/   r8   r7   r2   )r?   )dictget_call_tool_as_taskr:   r@   )r    r   r/   rB   r8   r7   r?   r2   rC   rI   rJ   request_metar!   s                r"   r5   zClientToolsMixin.call_tool   s     ` &*tDzr'""9b1'7'L#
 00i#L4HD 1    ))o2-% * 
 
 11& 2 
 
 	


s6   ABB%B4B5BBBBBc           	       K   t        |      }t        j                  j                  t        j                  j	                  ||xs i t        j                  j                  |      |            }| j                  | j                  j                  |t                     d{   }|j                  }	t        |	t        j                  j                        rd|	j                  j                  }
| j                  j!                  |
       t#        | |
|d      }t%        j&                  |      | j(                  |
<   |S | j+                  ||	       d{   }|xs t-        t/        j0                               }t#        | |||      S 7 7 6w)a  Call a tool for background execution (SEP-1686).

        Returns a ToolTask object that handles both background and immediate execution.
        If the server accepts background execution, ToolTask will poll for results.
        If the server declines (graceful degradation), ToolTask wraps the immediate result.

        Args:
            name: Tool name to call
            arguments: Tool arguments
            task_id: Optional client-provided task ID (ignored, for backward compatibility)
            ttl: Time to keep results available in milliseconds (default 60s)
            meta: Optional request metadata (e.g., version info)

        Returns:
            ToolTask: Future-like object for accessing task status and results
        )rJ   )r   r/   rC   _meta)params)requestresult_typeN)	tool_nameimmediate_result)r   mcptypesCallToolRequestCallToolRequestParamsTaskMetadatar   r   send_requestToolTaskResponseUnionroot
isinstanceCreateTaskResultrC   taskId_submitted_task_idsr*   r   weakrefref_task_registryr@   struuiduuid4)r    r   r/   rI   rJ   r2   r9   rU   wrapped_result
raw_resultserver_task_idtask_objparsed_resultsynthetic_task_ids                 r"   rP   z#ClientToolsMixin._call_tool_as_task  sc    4 /t4 ))++9922#/rYY+++4%	 3  , 
  $BBLL%%1 &  
 
 $((
j#))"<"<='__33N$$((8ntH 3:++h2GD/O #'">">tZ"PPM ' <3tzz|+<!!.	 -
( Qs%   B"F$F%B-FF	5F	F)r    r
   r   
str | Nonereturnzmcp.types.ListToolsResult)r    r
   rr   zlist[mcp.types.Tool])NNN)r    r
   r   rh   r/   zdict[str, Any]r7   ProgressHandler | Noner8   'datetime.timedelta | float | int | Noner2   dict[str, Any] | Nonerr   mcp.types.CallToolResult)F)
r    r
   r   rh   r!   rv   r?   boolrr   r	   rE   )r    r
   r   rh   r/   ru   rB   rq   r8   rt   r7   rs   r?   rw   r2   ru   rC   zLiteral[False]rr   r	   )r    r
   r   rh   r/   ru   rB   rq   r8   rt   r7   rs   r?   rw   r2   ru   rC   zLiteral[True]rI   rq   rJ   intrr   r   )r    r
   r   rh   r/   ru   rB   rq   r8   rt   r7   rs   r?   rw   r2   ru   rC   rw   rI   rq   rJ   rx   rr   zCallToolResult | ToolTask)NNrH   N)r    r
   r   rh   r/   ru   rI   rq   rJ   rx   r2   ru   rr   r   )__name__
__module____qualname____doc__r#   r   r:   r@   r   r5   rP   rF       r"   r   r       s   :
 /3!+	". P 48;?&*333 "3 1	3
 93 $3 
"3r  %	


 )
 	

 

4  ,0
 #;?37#&*$ )
  9 1  $  
   ,0
 #;?37#&*" )
  9 1  $    
 $ ,0E

 #;?37#&*"E
E
E
 )E

 E
 9E
 1E
 E
 $E
 E
 E
 E
 
#E
T ,0"&*CCC )C 	C
 C $C 
Cr}   r   c                *  K   ddl m} ddlm} d}|j                  rE|rC |t
        j                  j                  |j                  d         j                  }	t        |	      |j                  r	 | |vr |        d{    | |v r|j                  |       }
|
r|
j                  d      r=|
j                  di       j                  d      }
|j                  j                  d      }n|j                  }t        |
      }t        |      }|j                  |      }n|j                  } ||j                  |j                  |j&                  ||j                        S 7 # t         $ r)}t"        j%                  d|xs d	 d
|        Y d}~dd}~ww xY ww)a  Parse an mcp.types.CallToolResult into our CallToolResult dataclass.

    Args:
        name: Tool name (for schema lookup)
        result: Raw MCP protocol result
        tool_output_schemas: Dictionary mapping tool names to their output schemas
        list_tools_fn: Async function to refresh tool schemas if needed
        client_name: Optional client name for logging
        raise_on_error: Whether to raise ToolError on errors

    Returns:
        CallToolResult: Parsed result with structured data
    r   )cast)r	   Nzx-fastmcp-wrap-result
propertiesr!   r   clientz$] Error parsing structured content: )contentstructured_contentr2   datais_error)typingr   fastmcp.client.clientr	   isErrorrY   rZ   TextContentr   textr   structuredContentrO   r   r   validate_python	Exceptionr   errorr2   )r   r!   r<   r=   r>   r?   r   r	   r   msgoutput_schemar   output_typetype_adapteres                  r"   r@   r@   Z  s}    * 4D~~.399((&..*;<AAn		!	!	..#o%%** 3 7 7 = $(()@A(5(9(9,(K(O(O$) .4-E-E-I-I(-S*-3-E-E*"5m"DK#9+#FL'778JKD!33D !33[[ + &   	LLK+8,,PQRPST 	sC   A,F/E =E>B)E '5FE 	F'FFFF)NF)r   rh   r!   rv   r<   z dict[str, dict[str, Any] | None]r=   r   r>   rq   r?   rw   rr   r	   )+r|   
__future__r   ri   re   r   r   r   r   r   	mcp.typesrY   pydanticr   datetimer   r	   r
   fastmcp.client.progressr   fastmcp.client.tasksr   fastmcp.client.telemetryr   fastmcp.exceptionsr   fastmcp.telemetryr   "fastmcp.utilities.json_schema_typer   fastmcp.utilities.loggingr   fastmcp.utilities.timeoutr   fastmcp.utilities.typesr   ry   r   rZ   rb   r_   r   r@   rF   r}   r"   <module>r      s    . "   8 8  < 3 ) 0 ( 2 B 0 D :	H	 "#))"<"<syy?W?W"WX w w~	 # ;
;$; :; 	;
 ; ; ;r}   