§
    ÚŽ’jÂ7  ã                   ó  — d Z ddlZddl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 ddlmZ ddl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mZ d
dlmZ d
dlmZm Z m!Z!m"Z"m#Z#  G d„ de¦  «        Z$ G d„ de¦  «        Z%dS )z<Adapters to convert functions and MCP tools to ToolProtocol.é    N)Ú_AsyncGeneratorContextManager)Ú	timedelta)ÚCallableÚAnyÚAsyncGeneratorÚ	Generator)ÚClientSessioné   )ÚFunction)ÚToolBaseÚToolMiddlewareBaseé   )ÚPermissionBehaviorÚPermissionDecision)Ú	ToolChunk)Ú_extract_func_descriptionÚ_extract_input_schema)Úlogger)Ú	TextBlockÚ	DataBlockÚBase64SourceÚ	URLSourceÚToolResultStatec                   ó  ‡ — e Zd ZU dZdZeed<   	 dZeed<   	 dZe	dz  ed<   	 	 	 	 	 	 	 dde
d	e	dz  d
e	dz  dedededee         dz  ddfˆ fd„Zdededefd„Zdedeeedf         z  fd„Zededefd„¦   «         Zˆ xZS )ÚFunctionToolaP  Adapter to convert a Python function to ToolProtocol.

    This class wraps a regular Python function and makes it compatible with
    the ToolProtocol interface. It automatically extracts metadata from the
    function's signature and docstring, and normalizes the return value to
    ToolChunk or AsyncGenerator[ToolChunk, None].
    FÚis_external_toolÚis_mcpNÚmcp_nameTÚfuncÚnameÚdescriptionÚis_concurrency_safeÚis_read_onlyÚis_state_injectedÚmiddlewaresÚreturnc                 ó  •— t          ¦   «                              |¬¦  «         |p|j        | _        |pt	          |j        pd¦  «        | _        t          |¦  «        | _        || _	        || _
        || _        d| _        d| _        || _        dS )aM  Initialize the FunctionTool.

        Args:
            func (`Callable`):
                The Python function to wrap.
            name (`str | None`, optional):
                Custom tool name. If None, uses the function name.
            description (`str | None`, optional):
                Custom tool description. If None, extracts from docstring.
            is_concurrency_safe (`bool`, optional):
                Whether this tool is safe to call concurrently.
            is_read_only (`bool`, optional):
                Whether this tool only reads data without side effects.
            is_state_injected (`bool`, optional):
                Whether this tool requires agent state injection.
            middlewares (`list[ToolMiddlewareBase] | None`, optional):
                Tool middlewares wrapping the tool execution.
        ©r%   Ú FN)ÚsuperÚ__init__Ú__name__r    r   Ú__doc__r!   r   Úinput_schemar"   r#   r$   r   r   Ú_func)	Úselfr   r    r!   r"   r#   r$   r%   Ú	__class__s	           €úGC:\Projects\DSCons\.venv\Lib\site-packages\agentscope\tool\_adapters.pyr+   zFunctionTool.__init__1   s–   ø€ õ8 	‰Œ×Ò [ÐÑ1Ô1Ð1ØÐ)˜DœMˆŒ	Ø&ð 
Õ*CØŒLÐ˜Bñ+
ô +
ˆÔõ 2°$Ñ7Ô7ˆÔØ#6ˆÔ Ø(ˆÔØ!2ˆÔØ %ˆÔØˆŒØˆŒ
ˆ
ˆ
ó    Ú_argsÚ_kwargsc              �   ó<   K  — t          t          j        d¬¦  «        S )zÑCheck permissions for the tool usage.

        Default implementation allows all operations.

        Returns:
            `PermissionDecision`:
                Permission decision (default: allowed).
        z=Custom function tools must be explicitly allowed by the user.©ÚbehaviorÚmessage)r   r   ÚASK©r0   r4   r5   s      r2   Úcheck_permissionszFunctionTool.check_permissionsZ   s*   è è € õ "Ý'Ô+ðð
ñ 
ô 
ð 	
r3   Úkwargsc              ‹   ó�  ‡ ‡K  — t          j        ‰ j        ¦  «        r ‰ j        di |¤Žƒ d{V —†Šn ‰ j        di |¤ŽŠt          ‰t          ¦  «        r%dt          t
          df         fˆˆ fd„} |¦   «         S t          ‰t          ¦  «        r%dt          t
          df         fˆˆ fd„} |¦   «         S ‰                      ‰¦  «        S )zÈInvoke the wrapped function in an async style.

        Returns:
            `ToolChunk` or `AsyncGenerator[ToolChunk, None]`:
                The normalized result of the function execution.
        Nr&   c                 óˆ   •K  — ‰2 3 d {V —†} t          | t          ¦  «        r| W V — Œ"‰                     | ¦  «        W V — Œ;6 d S ©N©Ú
isinstancer   Ú_convert_func_result_to_chunk©ÚchunkÚresultr0   s    €€r2   Ú_streamz"FunctionTool.call.<locals>._stream~   s   øè è € Ø#)ð Hð Hð Hð Hð Hð Hð H˜%Ý! %­Ñ3Ô3ð HØ#˜˜˜˜˜à"×@Ò@ÀÑGÔGÐGÐGÐGÐGÐGð	 $* 6 6s   †Ac                 ó|   •K  — ‰D ]5} t          | t          ¦  «        r| W V — Œ‰                     | ¦  «        W V — Œ6d S r@   rA   rD   s    €€r2   rG   z"FunctionTool.call.<locals>._stream‰   sd   øè è € Ø#ð Hð H�EÝ! %­Ñ3Ô3ð HØ#˜˜˜˜˜à"×@Ò@ÀÑGÔGÐGÐGÐGÐGÐGð	Hð Hr3   © )ÚinspectÚiscoroutinefunctionr/   rB   r   r   r   rC   )r0   r=   rG   rF   s   `  @r2   ÚcallzFunctionTool.callm   s+  øøè è € õ Ô& t¤zÑ2Ô2ð 	*Ø%˜4œ:Ð/Ð/¨Ð/Ð/Ð/Ð/Ð/Ð/Ð/Ð/ˆFˆFà�T”ZÐ)Ð) &Ð)Ð)ˆFå�f�nÑ-Ô-ð 		ðH¥>µ)¸T°/Ô#Bð Hð Hð Hð Hð Hð Hð Hð �7‘9”9Ðå�f�iÑ(Ô(ð 		ðH¥>µ)¸T°/Ô#Bð Hð Hð Hð Hð Hð Hð Hð �7‘9”9Ðà×1Ò1°&Ñ9Ô9Ð9r3   rF   c                 ó0  — t          | t          ¦  «        r| S t          | t          ¦  «        r| }n>	 t          j        | d¬¦  «        }n&# t
          t          f$ r t          | ¦  «        }Y nw xY wt          t          |¬¦  «        gt          j	        ¬¦  «        S )NF)Úensure_ascii©Útext©ÚcontentÚstate)
rB   r   ÚstrÚjsonÚdumpsÚ	TypeErrorÚ
ValueErrorr   r   ÚRUNNING)rF   rP   s     r2   rC   z*FunctionTool._convert_func_result_to_chunk”   s¬   € õ �f�iÑ(Ô(ð 	ØˆMÝ�f�cÑ"Ô"ð 	#ØˆDˆDð#Ý”z &°uÐ=Ñ=Ô=��øÝ�zÐ*ð #ð #ð #Ý˜6‘{”{���ð#øøøåÝ DÐ)Ñ)Ô)Ð*Ý!Ô)ð
ñ 
ô 
ð 	
s   ±A Á A+Á*A+)NNTFFN)r,   Ú
__module__Ú__qualname__r-   r   ÚboolÚ__annotations__r   r   rT   r   Úlistr   r+   r   r   r<   r   r   rL   ÚstaticmethodrC   Ú__classcell__©r1   s   @r2   r   r      sž  ø€ € € € € € ðð ð #Ð�dÐ"Ð"Ñ"ðNà€FˆDÐÐÑØKØ€Hˆc�D‰jÐÐÑð!ð  Ø"&Ø$(Ø"Ø"'Ø7;ð'ð 'àð'ð �D‰jð'ð ˜4‘Zð	'ð
 "ð'ð ð'ð  ð'ð Ð,Ô-°Ñ4ð'ð 
ð'ð 'ð 'ð 'ð 'ð 'ðR
àð
ð ð
ð 
ð	
ð 
ð 
ð 
ð&%:àð%:ð 
�^ I¨t OÔ4Ñ	4ð%:ð %:ð %:ð %:ðN ð
Øð
à	ð
ð 
ð 
ñ „\ð
ð 
ð 
ð 
ð 
r3   r   c                   ó  ‡ — e Zd ZU dZdZeed<   	 dZeed<   	 	 	 	 	 ddede	j
        j        d	ed
ee         f         dz  dedz  dedz  dee         dz  ddfˆ fd„Zdededefd„Zdedefd„Zededeeez           fd„¦   «         Zˆ xZS )ÚMCPToolzðAdapter to convert an MCP tool to ToolProtocol.

    This class wraps an MCP tool and makes it compatible with the ToolProtocol
    interface. It handles the conversion between MCP's result format and
    AgentScope's ToolChunk format.
    Tr   Fr$   Nr   ÚtoolÚ
client_gen.ÚsessionÚtimeoutr%   r&   c                 ó
  •— t          ¦   «                              |¬¦  «         || _        t          j        dd|j        ¦  «        }d|› d|› �| _        ||j        k    r t          j        d|j        | j        ¦  «         |j        pd| _        |j	        rt          |j	        ¦  «        ni }|                     dd	¦  «         |                     d
i ¦  «         |                     dg ¦  «         || _        d| _        d| _        d| _        |j        r(t#          |j        d¦  «        r|j        j        pd| _        || _        || _        || _        |rt-          |¬¦  «        | _        nd| _        |€|�|�|�t1          d¦  «        ‚dS dS )aj  Initialize the MCPTool.

        Args:
            mcp_name (`str`):
                The name of the MCP server instance.
            tool (`mcp.types.Tool`):
                The MCP tool definition.
            client_gen (`Callable[..., _AsyncGeneratorContextManager[Any]]             | None`, optional):
                The MCP client generator function for stateless clients.
                Either this or ``session`` must be provided.
            session (`mcp.ClientSession | None`, optional):
                The MCP client session for stateful clients.
                Either this or ``client_gen`` must be provided.
            timeout (`float | None`, optional):
                The timeout in seconds for tool execution.
            middlewares (`list[ToolMiddlewareBase] | None`, optional):
                Tool middlewares wrapping the tool execution.
        r(   z[^a-zA-Z0-9_-]ÚxÚmcp__Ú__z&MCP tool name sanitized: '%s' -> '%s'.r)   ÚtypeÚobjectÚ
propertiesÚrequiredFÚreadOnlyHint)ÚsecondsNz<Either client_gen or session must be provided, but not both.)r*   r+   r   ÚreÚsubr    r   Údebugr!   ÚinputSchemaÚdictÚ
setdefaultr.   r"   r   r#   ÚannotationsÚhasattrrp   Ú_toolÚ_client_genÚ_sessionr   Ú_timeoutrX   )
r0   r   rd   re   rf   rg   r%   Úsanitized_toolÚ_schemar1   s
            €r2   r+   zMCPTool.__init__´   sÄ  ø€ õ: 	‰Œ×Ò [ÐÑ1Ô1Ð1Ø ˆŒõ œÐ 1°3¸¼	ÑBÔBˆØ8˜HÐ8Ð8¨Ð8Ð8ˆŒ	Ø˜TœYÒ&Ð&ÝŒLØ8Ø”	Ø”	ñô ð ð  Ô+Ð1¨rˆÔð -1Ô,<ÐD•$�tÔ'Ñ(Ô(Ð(À"ˆØ×Ò˜6 8Ñ,Ô,Ð,Ø×Ò˜<¨Ñ,Ô,Ð,Ø×Ò˜: rÑ*Ô*Ð*Ø#ˆÔð $)ˆÔ Ø %ˆÔð "ˆÔØÔð 	G¥¨Ô(8¸.Ñ IÔ Ið 	GØ $Ô 0Ô =Ð FÀˆDÔð ˆŒ
Ø%ˆÔØˆŒàð 	!Ý%¨gÐ6Ñ6Ô6ˆDŒMˆMà ˆDŒMð Ð 7 ?ØÐ" wÐ':åØNñô ð ð #Ð"Ð':Ð':r3   r4   r5   c              �   ó€   K  — | j         rt          t          j        d¬¦  «        S t          t          j        d¬¦  «        S )zâCheck permissions for the MCP tool usage.

        Default implementation allows all operations.

        Returns:
            `PermissionDecision`:
                Permission decision (default: ask for confirmation).
        z1This is a read-only MCP tool. Allowing execution.r7   z1MCP tools must be explicitly allowed by the user.)r#   r   r   ÚALLOWr:   r;   s      r2   r<   zMCPTool.check_permissions
  sU   è è € ð Ôð 	Ý%Ý+Ô1ØKðñ ô ð õ "Ý'Ô+ØGð
ñ 
ô 
ð 	
r3   r=   c              ‹   ó¤  K  — | j         rÐ|                       ¦   «         4 ƒd{V —†}|d         |d         }}t          ||¦  «        4 ƒd{V —†}|                     ¦   «         ƒ d{V —† |                     | j        j        || j        ¬¦  «        ƒ d{V —†}ddd¦  «        ƒd{V —† n# 1 ƒd{V —†swxY w Y   ddd¦  «        ƒd{V —† n# 1 ƒd{V —†swxY w Y   n2| j                             | j        j        || j        ¬¦  «        ƒ d{V —†}t          |  	                    |j
        ¦  «        |j        rt          j        nt          j        ¬¦  «        S )zÙInvoke the MCP tool and convert the result to ToolChunk.

        Args:
            **kwargs: Arguments to pass to the MCP tool.

        Returns:
            `ToolChunk`: The converted tool execution result.
        Nr   r
   )Ú	argumentsÚread_timeout_secondsrQ   )r{   r	   Ú
initializeÚ	call_toolrz   r    r}   r|   r   Ú_convert_mcp_content_to_blocksrR   ÚisErrorr   ÚERRORrY   )r0   r=   ÚcliÚread_streamÚwrite_streamrf   rF   s          r2   rL   zMCPTool.call!  s™  è è € ð Ôð 	à×'Ò'Ñ)Ô)ð ð ð ð ð ð ð ¨SØ,/°¬F°C¸´F˜\�Ý(¨°lÑCÔCð ð ð ð ð ð ð ÀwØ!×,Ò,Ñ.Ô.Ð.Ð.Ð.Ð.Ð.Ð.Ð.Ø#*×#4Ò#4Øœ
œØ"(Ø-1¬]ð $5ñ $ô $ð ð ð ð ð ð �Fðð ð ñ ô ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð øøøð ð ð ð ðð ð ñ ô ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð øøøð ð ð ð øð  œ=×2Ò2Ø”
”Ø Ø%)¤]ð 3ñ ô ð ð ð ð ð ð ˆFõ Ø×7Ò7¸¼ÑGÔGàŒ~ð)•/Ô'Ð'å Ô(ð	
ñ 
ô 
ð 	
s6   ¤'CÁAB%ÂCÂ%
B/	Â/CÂ2B/	Â3CÃ
CÃCÚmcp_content_blocksc           
      óÖ  — g }| D �]â}t          |t          j        j        ¦  «        r)|                     t          |j        ¬¦  «        ¦  «         ŒKt          |t          j        j        t          j        j        f¦  «        r>|                     t          t          d|j        |j        ¬¦  «        ¬¦  «        ¦  «         Œ¹t          |t          j        j        ¦  «        r‹t          |j        t          j        j        ¦  «        r>|                     t          |j                             d¬¦  «        ¬¦  «        ¦  «         �Œ:t#          j        dt'          |j        ¦  «        ¦  «         �Œct          |t          j        j        ¦  «        r>|                     t          t+          |j        |j        ¬¦  «        ¬¦  «        ¦  «         �ŒÀt#          j        d	t'          |¦  «        ¦  «         �Œä|S )
z÷Convert MCP content to AgentScope blocks.

        Args:
            mcp_content_blocks (`list`):
                The MCP content blocks to convert.

        Returns:
            `list[TextBlock | DataBlock]`: Converted AgentScope blocks.
        rO   Úbase64)rl   Ú
media_typeÚdata)Úsourcer   )ÚindentzEUnsupported EmbeddedResource content type: %s. Skipping this content.)r�   Úurlz4Unsupported content type: %s. Skipping this content.)rB   ÚmcpÚtypesÚTextContentÚappendr   rP   ÚImageContentÚAudioContentr   r   ÚmimeTyper‘   ÚEmbeddedResourceÚresourceÚTextResourceContentsÚmodel_dump_jsonr   Úerrorrl   ÚResourceContentsr   ÚuriÚwarning)r�   Ú
as_contentrR   s      r2   r‡   z&MCPTool._convert_mcp_content_to_blocksJ  s  € ð ˆ
Ø)ð 0	ñ 0	ˆGÝ˜'¥3¤9Ô#8Ñ9Ô9ð /Ø×!Ò!¥)°´Ð">Ñ">Ô">Ñ?Ô?Ð?Ð?ÝØÝ”Ô'­¬Ô)?Ð@ñô ð -ð ×!Ò!ÝÝ+Ø!)Ø'.Ô'7Ø!(¤ð ñ  ô  ðñ ô ñô ð ð õ ˜G¥S¤YÔ%?Ñ@Ô@ð ÝØÔ$Ý”IÔ2ñô ð ð ×%Ò%Ý!Ø!(Ô!1×!AÒ!AÈÐ!AÑ!KÔ!Kðñ ô ñô ð ñ õ ”Lð1å˜WÔ-Ñ.Ô.ñô ð ñ õ ˜G¥S¤YÔ%?Ñ@Ô@ð Ø×!Ò!ÝÝ(Ø'.Ô'7Ø '¤ð ñ  ô  ðñ ô ñô ð ñ õ ”ØJÝ˜‘M”Mñô ð ñ ð Ðr3   )NNNN)r,   rZ   r[   r-   r   r\   r]   r$   rT   r•   r–   ÚToolr   r   r   Úfloatr^   r   r+   r   r<   r   rL   r_   r   r   r‡   r`   ra   s   @r2   rc   rc   §   s˜  ø€ € € € € € ðð ð €FˆDÐÐÑØ+Ø#Ð�tÐ#Ð#Ñ#ØHð Ø"Ø $Ø7;ðTð TàðTð ŒiŒnðTð ˜SÐ"?ÀÔ"DÐDÔEØ
ñð	Tð �t‘ðTð ˜‘ðTð Ð,Ô-°Ñ4ðTð 
ðTð Tð Tð Tð Tð Tðl
àð
ð ð
ð 
ð	
ð 
ð 
ð 
ð.'
àð'
ð 
ð'
ð '
ð '
ð '
ðR ð?Ø ð?à	ˆi˜)Ñ#Ô	$ð?ð ?ð ?ñ „\ð?ð ?ð ?ð ?ð ?r3   rc   )&r-   rJ   rU   rr   Ú
contextlibr   Údatetimer   Útypingr   r   r   r   r•   r	   Ú_typesr   Ú_baser   r   Ú
permissionr   r   Ú	_responser   Ú_utilsr   r   Ú_loggingr   r9   r   r   r   r   r   r   rc   rI   r3   r2   ú<module>r°      sÐ  ðà BÐ BØ €€€Ø €€€Ø 	€	€	€	Ø 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø Ð Ð Ð Ð Ð Ø ;Ð ;Ð ;Ð ;Ð ;Ð ;Ð ;Ð ;Ð ;Ð ;Ð ;Ð ;à Ð Ð Ð Ð Ð Ø 
€
€
€
à Ð Ð Ð Ð Ð Ø /Ð /Ð /Ð /Ð /Ð /Ð /Ð /ðð ð ð ð ð ð ð ð !Ð  Ð  Ð  Ð  Ð  Ø DÐ DÐ DÐ DÐ DÐ DÐ DÐ DØ Ð Ð Ð Ð Ð ðð ð ð ð ð ð ð ð ð ð ð ð ð ðE
ð E
ð E
ð E
ð E
�8ñ E
ô E
ð E
ðPcð cð cð cð cˆhñ cô cð cð cð cr3   