
    kh=                     r   U d dl Z d dlZd dlmZ 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mZmZmZ d dlmZmZmZm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"m#Z# e	rd dl$m%Z%  ejL                  e'      Z(e)Z*ee+d<   ed   Z,ee+d<    G d de      Z- G d de      Z. G d de      Z/ G d d      Z0y)    N)AsyncExitStack)	timedelta)Path)	TYPE_CHECKINGAnyAsyncIterableDictListLiteralOptionalUnionoverload)NotRequired	TypeAlias	TypedDictUnpack   )get_hf_hub_version   )AsyncInferenceClient)ChatCompletionInputMessageChatCompletionInputToolChatCompletionStreamOutput'ChatCompletionStreamOutputDeltaToolCall)PROVIDER_OR_POLICY_T   )format_result)ClientSessionToolName)stdiossehttp
ServerTypec                   d    e Zd ZU eed<   eee      ed<   eeeef      ed<   eeee	df      ed<   y)StdioServerParameters_TcommandargsenvNcwd)
__name__
__module____qualname__str__annotations__r   r
   r	   r   r        e/var/www/teggl/fontify/venv/lib/python3.12/site-packages/huggingface_hub/inference/_mcp/mcp_client.pyr%   r%   !   s?    L
d3i
  	T#s(^	$$	U3d?+	,,r0   r%   c                   R    e Zd ZU eed<   eeeef      ed<   ee   ed<   ee   ed<   y)SSEServerParameters_Turlheaderstimeoutsse_read_timeoutN)	r*   r+   r,   r-   r.   r   r	   r   floatr/   r0   r1   r3   r3   (   s0    	Hc3h((!%((r0   r3   c                   b    e Zd ZU eed<   eeeef      ed<   ee   ed<   ee   ed<   ee	   ed<   y)StreamableHTTPParameters_Tr4   r5   r6   r7   terminate_on_closeN)
r*   r+   r,   r-   r.   r   dictr   r   boolr/   r0   r1   r:   r:   /   s;    	Hc3h((##!),,#D))r0   r:   c                   *   e Zd ZdZddddddee   dee   dee   dee   fdZd	 Zd
 Z	d Z
eded   dee   fd       Zeded   dee   fd       Zeded   dee   fd       ZdedefdZ	 	 ddeeeef      deee      dedeeeef      fdZy)	MCPClienta  
    Client for connecting to one or more MCP servers and processing chat completions with tools.

    <Tip warning={true}>

    This class is experimental and might be subject to breaking changes in the future without prior notice.

    </Tip>

    Args:
        model (`str`, `optional`):
            The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `meta-llama/Meta-Llama-3-8B-Instruct`
            or a URL to a deployed Inference Endpoint or other local or remote endpoint.
        provider (`str`, *optional*):
            Name of the provider to use for inference. Defaults to "auto" i.e. the first of the providers available for the model, sorted by the user's order in https://hf.co/settings/inference-providers.
            If model is a URL or `base_url` is passed, then `provider` is not used.
        base_url (`str`, *optional*):
            The base URL to run inference. Defaults to None.
        api_key (`str`, `optional`):
            Token to use for authentication. Will default to the locally Hugging Face saved token if not provided. You can also use your own provider API key to interact directly with the provider's service.
    N)modelproviderbase_urlapi_keyr@   rA   rB   rC   c                    i | _         t               | _        g | _        ||t	        d      || _        t        |d n||||      | _        y )NzCAt least one of `model` or `base_url` should be set in `MCPClient`.)r@   rA   rC   rB   )sessionsr   
exit_stackavailable_tools
ValueErrorpayload_modelr   client)selfr@   rA   rB   rC   s        r1   __init__zMCPClient.__init__N   sZ     :<(*>@=X-bcc"*".$E	
r0   c                    K   | j                   j                          d{    | j                  j                          d{    | S 7 (7 w)zEnter the context managerN)rJ   
__aenter__rF   rK   s    r1   rN   zMCPClient.__aenter__e   s@     kk$$&&&oo((*** 	'*s!   AA	!AAAAc                    K   | j                   j                  |||       d{    | j                          d{    y7 7 w)zExit the context managerN)rJ   	__aexit__cleanup)rK   exc_typeexc_valexc_tbs       r1   rQ   zMCPClient.__aexit__k   s:     kk##Hgv>>>lln 	?s   !AAAAAAc                    K   | j                   j                          d{    | j                  j                          d{    y7 '7 w)zClean up resourcesN)rJ   closerF   acloserO   s    r1   rR   zMCPClient.cleanupp   s;     kk!!!oo$$&&& 	"&s!   AA!AA
A
Atyper    paramsc                    K   y wNr/   rK   rY   rZ   s      r1   add_mcp_serverzMCPClient.add_mcp_serveru   s	     gj   r!   c                    K   y wr\   r/   r]   s      r1   r^   zMCPClient.add_mcp_serverx   s	     cfr_   r"   c                    K   y wr\   r/   r]   s      r1   r^   zMCPClient.add_mcp_server{   s	     ilr_   c                   K   ddl m}m} ddl m} |dk(  rddlm} t        j                  d|d    d|j                  d	g               d|d   i}d
D ]  }|j                  |      ||   ||<     |d i |}	| j                  j                   ||	             d{   \  }
}n|dk(  rvddlm} t        j                  d|d           d|d   i}dD ]  }|j                  |      ||   ||<    | j                  j                   |d i |       d{   \  }
}n|dk(  rwddlm} t        j                  d|d           d|d   i}dD ]  }|j                  |      ||   ||<    | j                  j                   |d i |       d{   \  }
}}nt        d|       | j                  j                   ||
||j!                  dt#                                  d{   }t        j%                  d       |j'                          d{    |j)                          d{   }t        j%                  d|j*                  D cg c]  }|j,                   c}       |j*                  D ]  }|j,                  | j.                  v r$t        j1                  d|j,                   d       ?|| j.                  |j,                  <   | j2                  j5                  t7        j8                  d|j,                  |j:                  |j<                  dd              y7 7 7 7 E7 7 c c}w w)!aU  Connect to an MCP server

        Args:
            type (`str`):
                Type of the server to connect to. Can be one of:
                - "stdio": Standard input/output server (local)
                - "sse": Server-sent events (SSE) server
                - "http": StreamableHTTP server
            **params (`Dict[str, Any]`):
                Server parameters that can be either:
                    - For stdio servers:
                        - command (str): The command to run the MCP server
                        - args (List[str], optional): Arguments for the command
                        - env (Dict[str, str], optional): Environment variables for the command
                        - cwd (Union[str, Path, None], optional): Working directory for the command
                    - For SSE servers:
                        - url (str): The URL of the SSE server
                        - headers (Dict[str, Any], optional): Headers for the SSE connection
                        - timeout (float, optional): Connection timeout
                        - sse_read_timeout (float, optional): SSE read timeout
                    - For StreamableHTTP servers:
                        - url (str): The URL of the StreamableHTTP server
                        - headers (Dict[str, Any], optional): Headers for the StreamableHTTP connection
                        - timeout (timedelta, optional): Connection timeout
                        - sse_read_timeout (timedelta, optional): SSE read timeout
                        - terminate_on_close (bool, optional): Whether to terminate on close
        r   )r   StdioServerParameters)typesr    )stdio_clientz-Connecting to stdio MCP server with command: r&    r'   )r'   r(   r)   Nr!   )
sse_clientz!Connecting to SSE MCP server at: r4   )r5   r6   r7   r"   )streamablehttp_clientz,Connecting to StreamableHTTP MCP server at: )r5   r6   r7   r;   zUnsupported server type: zhuggingface_hub.MCPClient)nameversion)read_streamwrite_streamclient_infozInitializing session...zConnected to server with tools:zTool 'z.' already defined by another server. Skipping.function)ri   description
parameters)rY   rn   r/   )mcpr   rc   rd   mcp.client.stdiore   loggerinfogetrF   enter_async_contextmcp.client.sserg   mcp.client.streamable_httprh   rH   Implementationr   debug
initialize
list_toolstoolsri   rE   warningrG   appendr   parse_obj_as_instancero   inputSchema)rK   rY   rZ   r   rc   	mcp_typesre   client_kwargskeyserver_paramsreadwriterg   rh   _sessionresponsetools                     r1   r^   zMCPClient.add_mcp_server~   s1    8 	=* 7?5KKGyHYGZZ[\b\f\fgmoq\r[stu&y(9:M- 5::c?.)/M#&5 2BMBM $ C CLQ^D_ ``KD%U]1KK;F5M?KL"F5M2MA 5::c?.)/M#&5 !% C CJD_Q^D_ ``KD%V^HKKFve}oVW"F5M2MW 5::c?.)/M#&5 $(??#F#FG\Gm_lGm#nnND% 8?@@;; "%444.0 5 	
 	
 	./  """ !++--6x~~8^t8^_NN 	DyyDMM)		{2`ab (/DMM$))$   '''== *$(II+/+;+;*.*:*:%		[ a a o
	
 	# .8^s   A%M (6M L)AM ,.M L,AM '.M L/AM -L2.,M L5M 2L83"M L;
(CM ,M /M 2M 5M 8M ;M messagesexit_loop_toolsexit_if_first_chunk_no_toolreturnc                  K   | j                   }|g || j                   }| j                  j                  j                  j	                  | j
                  ||dd       d{   }ddd}i }d}|2 3 d{   }	|d	z  }|	j                  r1t        |	j                        dkD  r|	j                  d   j                  nd}
|
sP|
j                  r|
j                  |d
<   |
j                  r|dxx   |
j                  z  cc<   |
j                  r|
j                  D ]  }|j                  |vrP|j                  j                  |j                  j                  dk(  rd|j                  _        |||j                  <   a|j                  j                  sx||j                     j                  xj                  |j                  j                  z  c_         |r|dk  rt        |      dk(  r y|	 ~7 7 }6 |d   s|r|j                  d
      dk(  rd|d
<   |rjg }|j!                         D ]P  }|j#                  |j$                  d|j                  j&                  |j                  j                  xs ddd       R ||d<   |j#                  |       |j!                         D ]  }|j                  j&                  }	 t)        j*                  |j                  j                  xs d      }n_# t(        j,                  $ rI}d|j$                  |d| d}t/        j0                  |      }|j#                  |       | Y d}~d}~ww xY wd|j$                  d|d}|rY||D cg c]  }|j                  j&                   nc c}w c}v r-t/        j0                  |      }|j#                  |       |  y| j2                  j                  |      }|I	 |j5                  ||       d{  7  }t7        |      |d<   n&# t8        $ r}d| |d<   Y d}~nd}~ww xY wd| |d<   t/        j0                  |      }|j#                  |       |  yw)au  Process a query using `self.model` and available tools, yielding chunks and tool outputs.

        Args:
            messages (`List[Dict]`):
                List of message objects representing the conversation history
            exit_loop_tools (`List[ChatCompletionInputTool]`, *optional*):
                List of tools that should exit the generator when called
            exit_if_first_chunk_no_tool (`bool`, *optional*):
                Exit if no tool is present in the first chunks. Default to False.

        Yields:
            [`ChatCompletionStreamOutput`] chunks or [`ChatCompletionInputMessage`] objects
        NautoT)r@   r   r}   tool_choicestreamunknown )rolecontentr   r   r   r   z{}r   	assistantrn   )ri   	arguments)idrY   rn   
tool_callsr   z%Invalid JSON generated by the model: )r   tool_call_idri   r   )r   r   r   ri   z0Error: MCP tool call failed with error message: z"Error: No session found for tool: )rG   rJ   chatcompletionscreaterI   choiceslendeltar   r   r   indexrn   r   ru   valuesr   r   ri   jsonloadsJSONDecodeErrorr   r   rE   	call_toolr   	Exception)rK   r   r   r   r}   r   messagefinal_tool_callsnum_of_chunkschunkr   	tool_calltool_calls_listtcfunction_namefunction_argserrtool_messagetool_message_as_objtr   results                         r1   process_single_turn_with_toolsz(MCPClient.process_single_turn_with_tools   s@    ( $$&=o=(<(<=E ))55<<$$ = 
 
 ,5"DOQ $ 	 	%QM.3mmEMM@RUV@VEMM!$**\`E zz"'**}}	"emm3" !&!1!1 
mI .>>%..88@IDVDVD`D`dhDh;=I..8<E(9"++55(9BBLLPYPbPbPlPllL
m +}/AcJZF[_`F` KY
	8D 9!1{{6"i/"-8:*113 
B#**"$%%$.(*(8(8-/[[-B-B-Jd)	
 )8%OOG$ *002 '	&I%..33M $

9+=+=+G+G+O4 P'' 
"$-LL)!FseL	  'A&V&VWc&d# 34))
 %+ILLUWanoL =o4^QZZ__4^4^#^&@&V&VWc&d# 34)) mm''6G"g#*#4#4]M#RRRF.;F.CL+  g0`ad`e.fL+g -O}o*^Y' #="R"RS_"`OO/0%%O'	&s   A Q"G0#Q2G66G37G6:DQA!Q3G66CQ?-K-,Q-M	 ?M?QM		Q$NAQP +O.,P ?Q 	P	PQP:Q)NF)r*   r+   r,   __doc__r   r-   r   rL   rN   rQ   rR   r   r   r   r%   r^   r3   r:   r#   r   r
   r   r	   r   r   r=   r   r   r   r/   r0   r1   r?   r?   7   sI   2  $37"&!%
 }
 /0	

 3-
 #
.
'
 j)9jVLcEdj jff6J_C`f fllFKeDfl ll ls lb DH,1	E&uT#==>?E& "$'>"?@E& &*	E&
 
u79SST	UE&r0   r?   )1r   logging
contextlibr   datetimer   pathlibr   typingr   r   r   r	   r
   r   r   r   r   typing_extensionsr   r   r   r   utils._runtimer   _generated._async_clientr   _generated.typesr   r   r   r   
_providersr   utilsr   rq   r   	getLoggerr*   rs   r-   r   r.   r#   r%   r3   r:   r?   r/   r0   r1   <module>r      s      %   d d d G G 0 ;  .   !			8	$ )  67
I 7-i -)I )* *z& z&r0   