
    [ǻiA                      r   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
 d dlZd dlZd dlm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mZ d dlmZ  e j:                  e      Zde de fdZ!de de dz  fdZ"edddeddfde de#e ef   dz  de$de$dedejJ                  dz  dee gdf   dz  fd       Z&y)    N)Callable)asynccontextmanager)Any)parse_qsurljoinurlparse)
TaskStatus)MemoryObjectReceiveStreamMemoryObjectSendStream)aconnect_sse)SSEError)McpHttpClientFactorycreate_mcp_http_client)SessionMessageurlreturnc                 @    t        | t        |       j                        S )N)r   r   path)r   s    L/opt/lhia/marcimex/agent/venv/lib/python3.12/site-packages/mcp/client/sse.pyremove_request_paramsr      s    3**++    endpoint_urlc                     t        t        |       j                        }|j                  dd g      d   xs |j                  dd g      d   S )N	sessionIdr   
session_id)r   r   queryget)r   query_paramss     r   !_extract_session_id_from_endpointr      sM    H\2889LK$03`|7G7GW[V\7]^_7``r      i,  headerstimeoutsse_read_timeouthttpx_client_factoryauthon_session_createdc           	        K   t        j                  d      \  }t        j                  d      \  t        j                         4 d{   }	 t        j	                  dt                        |||t        j                  ||            4 d{   t        d       4 d{   j                  j                          t        j	                  d       t         j                  fdt        t           f fd	}	d
t        ffd}
|j                  |	       d{   }t        j	                  d|        |j                  |
|       	 |f |j                   j#                          ddd      d{    ddd      d{    j%                          d{    j%                          d{    ddd      d{    y7 7 G7 47 # |j                   j#                          w xY w7 # 1 d{  7  sw Y   xY w7 # 1 d{  7  sw Y   xY w7 7 o# j%                          d{  7   j%                          d{  7   w xY w7 # 1 d{  7  sw Y   yxY ww)a9  
    Client transport for SSE.

    `sse_read_timeout` determines how long (in seconds) the client will wait for a new
    event before disconnecting. All other HTTP operations are controlled by `timeout`.

    Args:
        url: The SSE endpoint URL.
        headers: Optional headers to include in requests.
        timeout: HTTP timeout for regular operations.
        sse_read_timeout: Timeout for SSE read operations.
        auth: Optional HTTPX authentication handler.
        on_session_created: Optional callback invoked with the session ID when received.
    r   NzConnecting to SSE endpoint: )read)r!   r%   r"   GETzSSE connection establishedtask_statusc                 H  K   	 j                         2 3 d {   }t        j                  d|j                          |j                  xdk(  r t	        |j
                        }t        j                  d|        t              }t        |      }|j                  |j                  k7  s|j                  |j                  k7  r%d| }t        j                  |       t        |      rt        |      }|r |       | j                  |       dk(  rv|j
                  s	 t        j                  j                  |j
                        }t        j                  d|        t'        |      }	j%                  |	       d {    {	 t        j)                  d|j                          7 # t         $ r:}t        j#                  d       j%                  |       d {  7   Y d }~d }~ww xY w7 t6 nh# t*        $ r}
t        j#                  d	       |
d }
~
wt         $ r9}t        j#                  d
       j%                  |       d {  7   Y d }~nd }~ww xY wj-                          d {  7   y # j-                          d {  7   w xY ww)NzReceived SSE event: endpointzReceived endpoint URL: z2Endpoint origin does not match connection origin: messagezReceived server message: zError parsing server messagezUnknown SSE event: zEncountered SSE exceptionzError in sse_reader)	aiter_sseloggerdebugeventr   datar   netlocschemeerror
ValueErrorr   startedtypesJSONRPCMessagemodel_validate_json	Exception	exceptionsendr   warningr   aclose)r*   sser   
url_parsedendpoint_parsed	error_msgr   r-   excsession_messagesse_excevent_sourcer&   read_stream_writerr   s              r   
sse_readerzsse_client.<locals>.sse_readerM   sF    4>-9-C-C-E +Z +Zc &/CCII;-O P&)ii)37>sCHH7M(.7N|n5](^5=c]
:B<:P,6,=,=AWAW,W/9/@/@ODZDZ/Z 3eeqdr0s -6 -3LL,C2<Y2G,G+=9Z[g9hJ/90B:0N(3(;(;L(I)2/2xx,4)56;6J6J6^6^037.G -3LL;TU\T]9^,_ ;I:Q.@.E.Eo.V(V(V)*(.9LSYYK7X(YW+ZF 09 )5,2,<,<=[,\2D2I2I#2N,N,N,4)5 )WS .FX  ( *",,-HI")M( ?",,-BC"4"9"9#">>>? #5";";"==="4";";"===s   J"H H F5H DH )AF8*H 	G>
+H 5H 8	G;)G6*G-+G60H 6G;;H  H J 	I'H""I'.)I"II"J "I''J *J"=J >J"JJJJ"r   c           
      T  K   	 4 d {    2 3 d {   }t         j                  d|        j                  | |j                  j	                  ddd             d {   }|j                          t         j                  d|j                          7 7 7 ;6 d d d       d {  7   n# 1 d {  7  sw Y   nxY wn$# t        $ r t         j                  d       Y nw xY wj                          d {  7   y # j                          d {  7   w xY ww)NzSending client message: Tjson)by_aliasmodeexclude_none)rK   z"Client message sent successfully: zError in post_writer)
r/   r0   postr-   
model_dumpraise_for_statusstatus_coder;   r<   r?   )r   rE   responseclientwrite_streamwrite_stream_readers      r   post_writerzsse_client.<locals>.post_writer   s*    8': n n=P !n !n/$*LL3KOK\1]$^5;[[(4-<-D-D-O-O59179= .P .* 6A 6& 0&H %-$=$=$?$*LL3UV^VjVjUk1l$mn!n0& >Qn n n n n  ) E",,-CDE #/"5"5"777,"5"5"777s   D(C BC B6B#BB#AB6%B!&7B6C B#!B6#B6$C /B20C 6C<B?=CC D
 C-*D
 ,C--D
 0D(DD(
D%D!D%%D(z(Starting post writer with endpoint URL: )anyiocreate_memory_object_streamcreate_task_groupr/   r0   r   httpxTimeoutr   rS   rQ   TASK_STATUS_IGNOREDr	   strstart
start_sooncancel_scopecancelr?   )r   r!   r"   r#   r$   r%   r&   read_streamtgrI   rW   r   rT   rG   rH   rU   rV   s   `     `     @@@@@r   
sse_clientre      s[    < ',&G&G&J#(-(I(I!(L%L%&&( e( e(Bd	(LL78Mc8R7STU+dEMM'P`4a _1 _1' \1 \1 " ))::<LL!=> 8=7P7P7>%/_7> 7>r8 8( *,*)=#=LLL#KL>!Z[MM+|<1)<77..0y\1 \1_1 _1B %++---%%'''Ke( e( e(_1\1j $> ..0y\1 \1 \1 \1_1 _1 _1 _1B .' %++---%%'''Ke( e( e( e(sX  A	JG!JI6AH=G$H=!H$3G'
4H$7A8H/G*
0.HG,&H H$HH$H=H"H= I63H94I6H;I6JI4J$H='H$*H,H	HH$HHHH$"H=$H6	*H-+H6	2H=9I6;I6=I1I
I1*I-
+I11I64J6J<I?=JJ)'loggingcollections.abcr   
contextlibr   typingr   urllib.parser   r   r   rX   r[   	anyio.abcr	   anyio.streams.memoryr
   r   	httpx_sser   httpx_sse._exceptionsr   	mcp.typesr8   mcp.shared._httpx_utilsr   r   mcp.shared.messager   	getLogger__name__r/   r^   r   r   dictfloatAuthre    r   r   <module>rx      s
    $ *  4 4     R " *  P -			8	$,s ,s ,aC aC$J a
  &*$1G"7;E(	E(#s(^d"E( E( 	E(
 /E( **t
E( !#-4E( E(r   