
    [ǻin                        d Z ddlZddl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mZ ddl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mZm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%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,  ejZ                  e.      Z/e#e0z  Z1ee1   Z2ee#   Z3eg e4dz  f   Z5dZ6dZ7dZ8dZ9dZ:dZ;dZ<dZ=dZ> e?       Z@ G d de0      ZA G d deA      ZBe	 G d d             ZC G d d       ZDedd!d"d#e4d$ej                  dz  d%eFd&eeGee#e0z     ee#   e5f   df   fd'       ZHe ed(      dd)d*d!e dfd#e4d+eIe4e4f   dz  d,eJez  d-eJez  d%eFd.ed/ej                  dz  d&eeGee#e0z     ee#   e5f   df   fd0              ZLy)1z
StreamableHTTP Client Transport Module

This module implements the StreamableHTTP transport for MCP clients,
providing support for HTTP POST requests with optional SSE streaming responses
and session management.
    N)AsyncGenerator	AwaitableCallable)asynccontextmanager)	dataclass)	timedelta)Anyoverload)warn)	TaskGroup)MemoryObjectReceiveStreamMemoryObjectSendStream)EventSourceServerSentEventaconnect_sse)
deprecated)McpHttpClientFactorycreate_mcp_http_client)ClientMessageMetadataSessionMessage)	ErrorDataInitializeResultJSONRPCErrorJSONRPCMessageJSONRPCNotificationJSONRPCRequestJSONRPCResponse	RequestIdzmcp-session-idzmcp-protocol-versionzlast-event-idi     zcontent-typeacceptzapplication/jsonztext/event-streamc                       e Zd ZdZy)StreamableHTTPErrorz3Base exception for StreamableHTTP transport errors.N__name__
__module____qualname____doc__     X/opt/lhia/marcimex/agent/venv/lib/python3.12/site-packages/mcp/client/streamable_http.pyr"   r"   C   s    =r)   r"   c                       e Zd ZdZy)ResumptionErrorz*Raised when resumption request is invalid.Nr#   r(   r)   r*   r,   r,   G   s    4r)   r,   c                       e Zd ZU dZej
                  ed<   edz  ed<   eed<   e	dz  ed<   e
ed<   dZeeef   dz  ed<   dZedz  ed	<   y)
RequestContextz Context for a request operation.clientN
session_idsession_messagemetadataread_stream_writerheaderssse_read_timeout)r$   r%   r&   r'   httpxAsyncClient__annotations__strr   r   StreamWriterr4   dictr5   floatr(   r)   r*   r.   r.   K   sX    *d
###d**$$%)GT#s(^d")%)edl)r)   r.   c                      e Zd ZdZededdfd       Ze ed      	 	 	 	 d0dedeeef   dz  de	e
z  d	e	e
z  d
ej                  dz  ddfd              Zeeeefdededed	ed
eddfdZdeeef   fdZdedefdZdedefdZdej(                  ddfdZdeddfdZ	 	 	 d1dedededz  deeged   f   dz  dedefdZdej:                  deddfdZdeddfdZ deddfdZ!	 d2dej(                  dededdfdZ"	 d2dej(                  dededdfd Z#	 	 d3ded!ed"e$dz  d#e$ddf
d$Z%d%ededdfd&Z&ded'eddfd(Z'dej:                  d)e(ded*e)e*   d+eg df   d,e+ddfd-Z,dej:                  ddfd.Z-dedz  fd/Z.y)4StreamableHTTPTransportz/StreamableHTTP client transport implementation.urlreturnNc                      y Nr(   )selfr?   s     r*   __init__z StreamableHTTPTransport.__init__[   s    *-r)   zyParameters headers, timeout, sse_read_timeout, and auth are deprecated. Configure these on the httpx.AsyncClient instead.r4   timeoutr5   authc                      y rB   r(   )rC   r?   r4   rE   r5   rF   s         r*   rD   z StreamableHTTPTransport.__init__^   s     r)   c                 H   g }|t         ur|j                  d       |t         ur|j                  d       |t         ur|j                  d       |t         ur|j                  d       |r%t        ddj                  |       dt        d	       || _        d
| _        d
| _        y
)aS  Initialize the StreamableHTTP transport.

        Args:
            url: The 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.
        r4   rE   r5   rF   zParameters , zV are deprecated and will be ignored. Configure these on the httpx.AsyncClient instead.r   )
stacklevelN)_UNSETappendr   joinDeprecationWarningr?   r0   protocol_version)rC   r?   r4   rE   r5   rF   deprecated_paramss          r*   rD   z StreamableHTTPTransport.__init__l   s    $ (*& $$Y/& $$Y/6)$$%78v$$V,dii(9:; <D D"	  $r)   c                     i }t          dt         |t        <   t         |t        <   | j                  r| j                  |t
        <   | j                  r| j                  |t        <   |S )zBuild MCP-specific request headers.

        These headers will be merged with the httpx.AsyncClient's default headers,
        with these MCP-specific headers taking precedence.
        rI   )JSONSSEACCEPTCONTENT_TYPEr0   MCP_SESSION_IDrO   MCP_PROTOCOL_VERSION)rC   r4   s     r*   _prepare_headersz(StreamableHTTPTransport._prepare_headers   s[     #%!F"SE* $??&*ooGN#  ,0,A,AG()r)   messagec                 l    t        |j                  t              xr |j                  j                  dk(  S )z2Check if the message is an initialization request.
initialize)
isinstancerootr   methodrC   rY   s     r*   _is_initialization_requestz2StreamableHTTPTransport._is_initialization_request   s(    ',,7_GLL<O<OS_<__r)   c                 l    t        |j                  t              xr |j                  j                  dk(  S )z4Check if the message is an initialized notification.znotifications/initialized)r\   r]   r   r^   r_   s     r*   _is_initialized_notificationz4StreamableHTTPTransport._is_initialized_notification   s)    ',,(;<sATATXsAssr)   responsec                     |j                   j                  t              }|r*|| _        t        j                  d| j                          yy)z3Extract and store session ID from response headers.zReceived session ID: N)r4   getrV   r0   loggerinfo)rC   rc   new_session_ids      r*   '_maybe_extract_session_id_from_responsez?StreamableHTTPTransport._maybe_extract_session_id_from_response   sB    
 "))--n=,DOKK//@AB r)   c                    t        |j                  t              r~|j                  j                  rg	 t	        j
                  |j                  j                        }t        |j                        | _        t        j                  d| j                          yyy# t        $ rN}t        j                  d|        t        j                  d|j                  j                          Y d}~yd}~ww xY w)z>Extract protocol version from initialization response message.zNegotiated protocol version: z=Failed to parse initialization response as InitializeResult: zRaw result: N)r\   r]   r   resultr   model_validater9   protocolVersionrO   rf   rg   	Exceptionwarning)rC   rY   init_resultexcs       r*   ,_maybe_extract_protocol_version_from_messagezDStreamableHTTPTransport._maybe_extract_protocol_version_from_message   s    
 gllO49L9L	E.==gll>Q>QR(+K,G,G(H%;D<Q<Q;RST :M4  ESTWSXY gll.A.A-BCDD	Es   A%B 	C1#AC,,C1sser3   original_request_idresumption_callbackis_initializationc                 J  K   |j                   dk(  r!|j                  s)|j                  r|r ||j                         d{    y	 t        j                  |j                        }t
        j                  d|        |r| j                  |       |2t        |j                  t        t        z        r||j                  _        t        |      }|j                  |       d{    |j                  r|r ||j                         d{    t        |j                  t        t        z        S t
        j!                  d|j                           y7 7 s7 M# t        $ r9}t
        j                  d       |j                  |       d{  7   Y d}~yd}~ww xY ww)z@Handle an SSE event, returning True if the response is complete.rY   NFzSSE message: zError parsing SSE messagezUnknown SSE event: )eventdataidr   model_validate_jsonrf   debugrr   r\   r]   r   r   r   sendrn   	exceptionro   )	rC   rs   r3   rt   ru   rv   rY   r1   rq   s	            r*   _handle_sse_eventz)StreamableHTTPTransport._handle_sse_event   sY     99	!88661-cff555(<<SXXF}WI67 %EEgN '2z',,P_bnPn7o&9GLLO"0"9(--o>>> 661-cff555 "',,,0NOO NN0<=? 6 ? 6    !<=(--c222sm   A F#EF#	BE &E''E E$E 3%F#E E 	F ')FFFF#F  F#r/   c                   K   d}d}d}|t         k  r	 | j                  sy| j                         }|r	||t        <   t	        |d| j
                  |      4 d{   }|j                  j                          t        j                  d       |j                         2 3 d{   }|j                  r|j                  }|j                  |j                  }| j                  ||       d{    Tyy7 7 S7 6 d}ddd      d{  7   n# 1 d{  7  sw Y   nxY wn3# t        $ r'}	t        j                  d|	        |dz  }Y d}	~	nd}	~	ww xY w|t         k\  rt        j                  dt          d	       y||nt        }
t        j!                  d
|
 d       t#        j$                  |
dz         d{  7   |t         k  rݭw)zDHandle GET stream for server-initiated messages with auto-reconnect.Nr   GETr4   zGET SSE connection establishedzGET stream error:    z&GET stream max reconnection attempts (
) exceededz)GET stream disconnected, reconnecting in zms...     @@)MAX_RECONNECTION_ATTEMPTSr0   rX   LAST_EVENT_IDr   r?   rc   raise_for_statusrf   r|   	aiter_sserz   retryr   rn   DEFAULT_RECONNECTION_DELAY_MSrg   anyiosleep)rC   r/   r3   last_event_idretry_interval_msattemptr4   event_sourcers   rq   delay_mss              r*   handle_get_streamz)StreamableHTTPTransport.handle_get_stream   s     %)(,11 //1 -:GM*'HH#	    
 " ))::<LL!AB%1%;%;%= N Nc66,/FFM99003		-"44S:LMMM5 2 N N &>  G)         ,  1#781 33EF_E``jkl ->,I(OlHKKCH:UST++h/000U 11s   GD# G8D# C2D# A DC8 C4!C8$AD*C6+D0G2D# 4C86D8D;D# D	D# DDDD# "G#	E,E	GEA(G;F><Gctxc                   K   | j                         }|j                  r4|j                  j                  r|j                  j                  |t        <   nt	        d      d}t        |j                  j                  j                  t              r*|j                  j                  j                  j                  }t        |j                  d| j                  |      4 d{   }|j                  j                          t         j#                  d       |j%                         2 3 d{   }| j'                  ||j(                  ||j                  r|j                  j*                  nd       d{   }|sT|j                  j-                          d{     ddd      d{    y7 7 7 ?7 6 7 # 1 d{  7  sw Y   yxY ww)z/Handle a resumption request using GET with SSE.z.Resumption request requires a resumption tokenNr   r   z)Resumption GET SSE connection established)rX   r2   resumption_tokenr   r,   r\   r1   rY   r]   r   rz   r   r/   r?   rc   r   rf   r|   r   r   r3   on_resumption_token_updateaclose)rC   r   r4   rt   r   rs   is_completes          r*   _handle_resumption_requestz2StreamableHTTPTransport._handle_resumption_request-  s    '')<<CLL99%(\\%B%BGM"!"RSS #c))1166G"%"5"5"="="B"B"E"EJJHH	
 	 	
 !!224LLDE)335 	 	c$($:$:**'?B||CLL;;QU	%  &//66888%	 	 		 9 6	 	 	 	s   CGF+ G#A F7#F3'F-(F3+AF7/F/0F77F7F1F7G%F5&G-F3/F71F73F75G7G	=G >G	Gc           	        K   | j                         }|j                  j                  }| j                  |      }|j                  j                  d| j                  |j                  ddd      |      4 d{   }|j                  dk(  r't        j                  d       	 ddd      d{    y|j                  d	k(  rdt        |j                  t              r8| j                  |j                  |j                  j                          d{    	 ddd      d{    y|j#                          |r| j%                  |       t        |j                  t              r|j&                  j)                  t*        d
      j-                         }|j/                  t0              r&| j3                  ||j                  |       d{    nU|j/                  t4              r| j7                  |||       d{    n$| j9                  ||j                         d{    ddd      d{    y7 7 7 )7 7 w7 H7 %7 # 1 d{  7  sw Y   yxY ww)z/Handle a POST request with response processing.POSTTjson)by_aliasmodeexclude_none)r   r4   N   zReceived 202 Acceptedi   )rX   r1   rY   r`   r/   streamr?   
model_dumpstatus_coderf   r|   r\   r]   r   _send_session_terminated_errorr3   rz   r   ri   r4   re   rU   lower
startswithrR   _handle_json_responserS   _handle_sse_response_handle_unexpected_content_type)rC   r   r4   rY   rv   rc   content_types          r*   _handle_post_requestz,StreamableHTTPTransport._handle_post_requestN  s    '')%%-- ;;GD::$$HH##TT#R	 % 
 "	 "	
 ##s*45"	 "	 "	 ##s*gllN;==..   !"	 "	 "	$ %%' <<XF ',,7'//33L"EKKM**4044Xs?U?UWhiii!,,S133HcCTUUU>>$..  ?"	 "	 "	 "	"	6 jU?"	 "	 "	 "	s   A7I9H3:I=&I#I.H6/I4AIH9II!H<"I'B IH?0I8I9$III"I-I.I6I9I<I?IIIIIIIIc                 h  K   	 |j                          d{   }t        j                  |      }|r| j                  |       t	        |      }|j                  |       d{    y7 Q7 # t        $ r9}t        j                  d       |j                  |       d{  7   Y d}~yd}~ww xY ww)z%Handle JSON response from the server.NzError parsing JSON response)	areadr   r{   rr   r   r}   rn   rf   r~   )rC   rc   r3   rv   contentrY   r1   rq   s           r*   r   z-StreamableHTTPTransport._handle_json_responsex  s     	/$NN,,G$88AG !AA'J,W5O$))/::: - ; 	/:;$))#...	/s]   B2A- A)AA- #A+$A- (B2)A- +A- -	B/6)B*B" B*%B2*B//B2c                 ^  K   d}d}	 t        |      }|j                         2 3 d{   }|j                  r|j                  }|j                  |j                  }| j	                  ||j
                  |j                  r|j                  j                  nd|       d{   }|s|j                          d{     y7 7 #7 
6 n.# t        $ r"}	t        j                  d|	        Y d}	~	nd}	~	ww xY w|2t        j                  d       | j                  |||       d{  7   yyw)z$Handle SSE response from the server.N)ru   rv   zSSE stream ended: (SSE stream disconnected, reconnecting...)r   r   rz   r   r   r3   r2   r   r   rn   rf   r|   rg   _handle_reconnection)
rC   rc   r   rv   r   r   r   rs   r   es
             r*   r   z,StreamableHTTPTransport._handle_sse_response  s,     %)(,	3&x0L)335  c66$'FFM 99((+		%$($:$:**TWT`T`)P)Pfj&7	 %; %  "//+++' ,% 6(  	3LL-aS122	3 $KKBC++C@QRRR %s   D-C
 CCCA5C
  C!C
 (C
 ;C<C
 D-CC
 C
 C
 	D-
	C5C0+D-0C550D-%D(&D-r   r   r   c                 N  K   |t         k\  rt        j                  dt          d       y||nt        }t	        j
                  |dz         d{    | j                         }||t        <   d}t        |j                  j                  j                  t              r*|j                  j                  j                  j                  }	 t        |j                  d| j                   |      4 d{   }|j"                  j%                          t        j'                  d       |}	|}
|j)                         2 3 d{   }|j                  r|j                  }	|j*                  |j*                  }
| j-                  ||j.                  ||j0                  r|j0                  j2                  nd       d{   }|s|j"                  j5                          d{     ddd      d{    y7 7 7 7 C7  7 6 t        j'                  d       | j7                  ||	|
d	       d{  7   ddd      d{  7   y# 1 d{  7  sw Y   yxY w# t8        $ rB}t        j                  d
|        | j7                  ||||dz          d{  7   Y d}~yd}~ww xY ww)zFReconnect with Last-Event-ID to resume stream after server disconnect.zMax reconnection attempts (r   Nr   r   r   zReconnected to SSE streamr   r   zReconnection failed: r   )r   rf   r|   r   r   r   rX   r   r\   r1   rY   r]   r   rz   r   r/   r?   rc   r   rg   r   r   r   r3   r2   r   r   r   rn   )rC   r   r   r   r   r   r4   rt   r   reconnect_last_event_idreconnect_retry_msrs   r   r   s                 r*   r   z,StreamableHTTPTransport._handle_reconnection  sv     //LL67P6QQ[\] ):(E$Khkk(V+,,,'')!. #c))1166G"%"5"5"="="B"B"E"E$	`#

	 e e
 %%66878 0='%6"!-!7!7!9  #vv25&&/yy,-0YY*(,(>(>..+CF<<??UY	) #K #*33::<<<7e e e 	-e# =5e ":" FG//5LN`bcddd?e e e e e@  	`LL045++C@QSZ]^S^___	`s  AJ%G/A7J%'I /G20I 3AI7G=;G5<G=?A4I3G74I;IG9II )G;*I .J%2I 5G=7I9I;I =-I*H-+I0I ;H><I J%II	II J%I 	J" 2JJJJ%J""J%r   c                    K   d| }t         j                  |       |j                  t        |             d{    y7 w)z+Handle unexpected content type in response.zUnexpected content type: N)rf   errorr}   
ValueError)rC   r   r3   	error_msgs       r*   r   z7StreamableHTTPTransport._handle_unexpected_content_type  s9      0~>	Y %%j&;<<<s   8AA A
request_idc                    K   t        d|t        dd            }t        t        |            }|j	                  |       d{    y7 w)z)Send a session terminated error response.z2.0iX  zSession terminated)coderY   )jsonrpcrz   r   N)r   r   r   r   r}   )rC   r3   r   jsonrpc_errorr1   s        r*   r   z6StreamableHTTPTransport._send_session_terminated_error  sH      %0DE

 ))FG %%o666s   AAA
Awrite_stream_readerwrite_streamstart_get_streamtgc           	      l   K   	 |4 d{    |2 3 d{   }|j                   }t        |j                  t              r|j                  nd}	t	        |	xr |	j
                        t        j                  d|         j                  |      r |        t        | j                  ||	|       fd}
t        |j                  t              r|j                  |
        |
        d{    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   |j!                          d{  7   y# |j!                          d{  7   |j!                          d{  7   w xY ww)z&Handle writing requests to the server.NzSending client message: )r/   r0   r1   r2   r3   c                     K   rj                          d {    y j                          d {    y 7 7 wrB   )r   r   )r   is_resumptionrC   s   r*   handle_request_asynczAStreamableHTTPTransport.post_writer.<locals>.handle_request_async1  s<     ("&"A"A#"FFF"&";";C"@@@ G@s   >:><>>zError in post_writer)rY   r\   r2   r   boolr   rf   r|   rb   r.   r0   r]   r   
start_soonrn   r~   r   )rC   r/   r   r3   r   r   r   r1   rY   r2   r   r   r   s   `          @@r*   post_writerz#StreamableHTTPTransport.post_writer  s    +	(* $5 $5-@ #5 #5/-55G &o&>&>@UV (00!  %))Oh6O6O$PMLL#;G9!EF 88A(*(%#'??(7!)+=CA "',,?&:;2444I$5#5F 5G .A$5 $5 $5 $5 $5L  	534	5 %++---%%''' %++---%%'''s   F4D& C7D& DC=C9C=CD1C;2D7D& 9C=;D=D>D& 	D
D& D"DD"D& %E= &EE= EE= 
F4E F46E97F4=F1FF1*F-+F11F4c                   K   | j                   sy	 | j                         }|j                  | j                  |       d{   }|j                  dk(  rt
        j                  d       y|j                  dvr#t
        j                  d|j                          yy7 [# t        $ r"}t
        j                  d|        Y d}~yd}~ww xY ww)z2Terminate the session by sending a DELETE request.Nr   i  z)Server does not allow session termination)      zSession termination failed: )	r0   rX   deleter?   r   rf   r|   ro   rn   )rC   r/   r4   rc   rq   s        r*   terminate_sessionz)StreamableHTTPTransport.terminate_sessionC  s     		A++-G#]]488W]EEH##s*HI%%Z7!=h>R>R=STU 8	 F  	ANN9#?@@	AsL   C0B B(B *C+0B CB 	C
(C CC

Cc                     | j                   S )zGet the current session ID.)r0   )rC   s    r*   get_session_idz&StreamableHTTPTransport.get_session_idS  s    r)   )N   ,  N)NNF)F)Nr   )/r$   r%   r&   r'   r
   r9   rD   r   r;   r<   r   r6   AuthrK   r	   rX   r   r   r`   rb   Responseri   rr   r   r:   r   r   r   r   r7   r   r.   r   r   r   r   intr   r   r   StreamReaderr   r   r   r   r   r   r(   r)   r*   r>   r>   X   s   9-C-D- -	< *.%'.4"& c3h$& "	
  )+ jj4 
	 
  &&%&% &% 	&%
 &% &% 
&%P$sCx. "`. `T `tN tt tC..C 
CEE 
E* 15GK"'-- )- '-	-
 &seYt_&<=D-  - 
-^41!!41 )41 
	41lN t B(n ( (\ #(	/../ )/  	/
 
/2 #(	&S..&S &S  	&S
 
&SX )-=`=` =` :	=`
 =` 
=`~== )= 
	=7(7 7 
	75(!!5( *5( )	5(
 -^<5( #2t8,5( 5( 
5(nAe.?.? AD A d
 r)   r>   Thttp_clientterminate_on_closer?   r   r   r@   c                 	
K   t        j                  t        t        z     d      \  
}t        j                  t           d      \  }}|du}|		
t	               	t        |       t        j                         4 d{   	 t        j                  d|         t        j                         4 d{   }|s|j                  	       d{    d	
fd}j                  j                  	|
||       	 ||j                  f j                  r|rj!                  	       d{    j"                  j%                          ddd      d{    
j'                          d{    |j'                          d{    ddd      d{    y7 %7 7 7 v# j                  r|rj!                  	       d{  7   j"                  j%                          w xY w7 # 1 d{  7  sw Y   xY w7 7 ~# 
j'                          d{  7   |j'                          d{  7   w xY w7 # 1 d{  7  sw Y   yxY ww)a8  
    Client transport for StreamableHTTP.

    Args:
        url: The MCP server endpoint URL.
        http_client: Optional pre-configured httpx.AsyncClient. If None, a default
            client with recommended MCP timeouts will be created. To configure headers,
            authentication, or other HTTP settings, create an httpx.AsyncClient and pass it here.
        terminate_on_close: If True, send a DELETE request to terminate the session
            when the context exits.

    Yields:
        Tuple containing:
            - read_stream: Stream for reading messages from the server
            - write_stream: Stream for sending messages to the server
            - get_session_id_callback: Function to retrieve the current session ID

    Example:
        See examples/snippets/clients/ for usage patterns.
    r   Nz'Connecting to StreamableHTTP endpoint: c                  @    j                  j                          y rB   )r   r   )r/   r3   r   	transports   r*   r   z0streamable_http_client.<locals>.start_get_stream  s    MM)"="=vGYZr)   )r@   N)r   create_memory_object_streamr   rn   r   r>   create_task_grouprf   r|   
contextlibAsyncExitStackenter_async_contextr   r   r   r0   r   cancel_scopecancelr   )r?   r   r   read_streamr   r   client_providedstackr   r/   r3   r   r   s            @@@@r*   streamable_http_clientr   X  s9    D ',&G&GYbHb&cde&f#(-(I(I.(YZ[(\%L% "-OF~')',I&&( "( "(B!	(LLB3%HI!002 - -e&33F;;;[ [ ))'& $	-#$!00  !++0B'99&AAAOO**,7- -: %++---%%'''E"( "( "(- <. B !++0B'99&AAAOO**,7- - - -: .' %++---%%'''E"( "( "( "(s,  A;IF&II
0H7F)8H;G8F+.G8F/"G86F-7G8H G6!H%I
8H9I
HI
I I!I)H+G8-G8/#G3G G33G86H8H
	>H?H
	HI
I
I%H(
&I>I
?II
I
IIIIz%Use `streamable_http_client` instead.r   r   r4   rE   r5   httpx_client_factoryrF   c                  K   t        |t              r|j                         n|}t        |t              r|j                         n|} ||t        j                  ||      |      }	|	4 d {    t        | |	|      4 d {   }
|
 d d d       d {    d d d       d {    y 7 A7 ,7 # 1 d {  7  sw Y   )xY w7  # 1 d {  7  sw Y   y xY ww)N)read)r4   rE   rF   r   )r\   r   total_secondsr6   Timeoutr   )r?   r4   rE   r5   r   r   rF   timeout_secondssse_read_timeout_secondsr/   streamss              r*   streamablehttp_clientr     s     & 2<GY1Og++-U\O,67G,S&&(Yi 
 "o4LMF   )1
 	 	 M	 	  	 	 	 	 	   s   A+C!-B/.C!1CB1CB5CB3CC!)C
*C!1C3C5C	;B><C	C
C!CCCC!)Mr'   r   loggingcollections.abcr   r   r   r   dataclassesr   datetimer   typingr	   r
   warningsr   r   r6   	anyio.abcr   anyio.streams.memoryr   r   	httpx_sser   r   r   typing_extensionsr   mcp.shared._httpx_utilsr   r   mcp.shared.messager   r   	mcp.typesr   r   r   r   r   r   r   r   	getLoggerr$   rf   rn   SessionMessageOrErrorr:   r   r9   GetSessionIdCallbackrV   rW   r   r   r   rU   rT   rR   rS   objectrK   r"   r,   r.   r>   r7   r   tupler   r;   r<   r   r   r(   r)   r*   <module>r     sy     ? ? * !        R @ @ ( E	 	 	 
		8	$ '2 %&;<(8C$J/ !-  !%  	  
>) >5) 5 	* 	* 	*} }@  -1#	P(	P( ""T)P( 	P(
 	!.9"<=~.	
 	
P( P(f 34 &*!#*0#1G"$	$#s(^d"$ Y$ i'	$
 $ /$ **t
$ 	!.9"<=~.	
 	
$ 5 $r)   