XjndZddlZddlZddlmZmZmZddlmZddlm Z ddl m Z ddl m Z mZddlmZddlZddlZdd lmZdd lmZmZdd lmZmZmZdd lmZdd lmZm Z ddl!m"Z"m#Z#ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,ejZe.Z/e#e0zZ1ee1Z2ee#Z3ege4dzfZ5dZ6dZ7dZ8dZ9dZ:dZ;dZe?Z@Gdde0ZAGddeAZBe GddZCGdd ZDedd!d"d#e4d$ejdzd%eFd&eeGee#e0zee#e5fdffd'ZHeed(dd)d*d!e dfd#e4d+eIe4e4fdzd,eJe zd-eJe zd%eFd.ed/ejdzd&eeGee#e0zee#e5fdffd0ZLy)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 AwaitableCallable)asynccontextmanager) dataclass) timedelta)Anyoverload)warn) TaskGroup)MemoryObjectReceiveStreamMemoryObjectSendStream) EventSourceServerSentEvent aconnect_sse) deprecated)McpHttpClientFactorycreate_mcp_http_client)ClientMessageMetadataSessionMessage) ErrorDataInitializeResult JSONRPCErrorJSONRPCMessageJSONRPCNotificationJSONRPCRequestJSONRPCResponse RequestIdzmcp-session-idzmcp-protocol-versionz last-event-idiz content-typeacceptzapplication/jsonztext/event-streamceZdZdZy)StreamableHTTPErrorz3Base exception for StreamableHTTP transport errors.N__name__ __module__ __qualname____doc__n/mnt/ssd/data/Dropbox/adrian/vault-secondbrain/venv/lib/python3.12/site-packages/mcp/client/streamable_http.pyr"r"Cs=r)r"ceZdZdZy)ResumptionErrorz*Raised when resumption request is invalid.Nr#r(r)r*r,r,Gs4r)r,ceZdZUdZej ed<edzed<eed<e dzed<e ed<dZ e eefdzed<dZ edzed <y) RequestContextz Context for a request operation.clientN session_idsession_messagemetadataread_stream_writerheaderssse_read_timeout)r$r%r&r'httpx AsyncClient__annotations__strrr StreamWriterr4dictr5floatr(r)r*r.r.KsX*   d ###d**$$%)GT#s(^d ")%)edl)r)r.ceZdZdZededdfdZeed d0dedeeefdzde e zd e e zd e jdzddf d Ze e e e fdededed ed eddf d Zdeeeffd ZdedefdZdedefdZde j(ddfdZdeddfdZ d1dedededzdeegedfdzdedef dZde j:deddfdZdeddfdZ deddfdZ! d2de j(dededdfdZ" d2de j(dededdfd Z# d3ded!ed"e$dzd#e$ddf d$Z%d%ededdfd&Z&ded'eddfd(Z'de j:d)e(ded*e)e*d+egdfd,e+ddfd-Z,de j:ddfd.Z-dedzfd/Z.y)4StreamableHTTPTransportz/StreamableHTTP client transport implementation.urlreturnNcyNr()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.r4timeoutr5authcyrBr()rCr?r4rEr5rFs r*rDz StreamableHTTPTransport.__init__^sr)cHg}|tur|jd|tur|jd|tur|jd|tur|jd|r%tddj|dtd ||_d |_d |_y ) aSInitialize 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. r4rEr5rFz Parameters , zV are deprecated and will be ignored. Configure these on the httpx.AsyncClient instead.r) stacklevelN)_UNSETappendr joinDeprecationWarningr?r0protocol_version)rCr?r4rEr5rFdeprecated_paramss r*rDz StreamableHTTPTransport.__init__ls$(* &  $ $Y / &  $ $Y / 6 )  $ $%7 8 v   $ $V ,  dii(9:;Extract protocol version from initialization response message.zNegotiated protocol version: z=Failed to parse initialization response as InitializeResult: z Raw result: N) r\r]rresultrmodel_validater9protocolVersionrOrfrg Exceptionwarning)rCrY init_resultexcs r*,_maybe_extract_protocol_version_from_messagezDStreamableHTTPTransport._maybe_extract_protocol_version_from_messages gllO 49L9L E.==gll>Q>QR (+K,G,G(H% ;D>>661-cff555"',,,0NOO NN0 < =?6?6    !<=(--c222 smAF#EF# BE&E''EE$E3%F#EE F ')FFFF#F  F#r/cKd}d}d}|tkr |jsy|j}|r ||t<t |d|j |4d{}|j jtjd|j23d{}|jr |j}|j |j}|j||d{Tyy77S7 6d}dddd{7n#1d{7swYnxYwn3#t$r'} tjd| |dz }Yd} ~ nd} ~ wwxYw|tk\rtjdtd y||nt} tj!d | d t#j$| d z d{7|tkrݭw) zDHandle GET stream for server-initiated messages with auto-reconnect.NrGETr4zGET SSE connection establishedzGET stream error: z&GET stream max reconnection attempts ( ) exceededz)GET stream disconnected, reconnecting in zms...@@)MAX_RECONNECTION_ATTEMPTSr0rX LAST_EVENT_IDrr?rcraise_for_statusrfr| aiter_sserzretryrrnDEFAULT_RECONNECTION_DELAY_MSrganyiosleep) rCr/r3 last_event_idretry_interval_msattemptr4 event_sourcersrqdelay_mss r*handle_get_streamz)StreamableHTTPTransport.handle_get_streams %) (,11 //1 -:GM*'HH#   " ))::<LL!AB%1%;%;%=NNc66,/FFM99003 -"44S:LMMM52 NN&> G)     ,  1#781  33 EF_E``jkl->,I(OlH KKCH:US T++h/0 0 0U11sG  D#G 8D#C2D#AD C8 C4!C8$AD *C6+D 0G 2D#4C86D 8D ; D#D D# DD DD#"G # E,E G EA(G ;F><G ctxcK|j}|jr4|jjr|jj|t<n t dd}t |j jjtr*|j jjj}t|jd|j|4d{}|jjt j#d|j%23d{}|j'||j(||jr|jj*ndd{}|sT|jj-d{dddd{y777?767#1d{7swYyxYww)z/Handle a resumption request using GET with SSE.z.Resumption request requires a resumption tokenNrrz)Resumption GET SSE connection established)rXr2resumption_tokenrr,r\r1rYr]rrzrr/r?rcrrfr|rrr3on_resumption_token_updateaclose)rCrr4rtrrs is_completes r*_handle_resumption_requestz2StreamableHTTPTransport._handle_resumption_request-s'') <G G c K|j}|jj}|j|}|jj d|j |jddd|4d{}|jdk(r'tjd dddd{y|jd k(rdt|jtr8|j|j|jj d{ dddd{y|j#|r|j%|t|jtr|j&j)t*d j-}|j/t0r&|j3||j|d{nU|j/t4r|j7|||d{n$|j9||jd{dddd{y777)77w7H7%7#1d{7swYyxYww) z/Handle a POST request with response processing.POSTTjson)by_aliasmode exclude_none)rr4NzReceived 202 Acceptedi)rXr1rYr`r/streamr? model_dump status_coderfr|r\r]r_send_session_terminated_errorr3rzrrir4rerUlower startswithrR_handle_json_responserS_handle_sse_response_handle_unexpected_content_type)rCrr4rYrvrc content_types r*_handle_post_requestz,StreamableHTTPTransport._handle_post_requestNs'')%%-- ;;GD::$$  HH##TT#R % " "  ##s* 45" " " ##s*gllN;==.. !" " " $  % % ' <>$..?" " " " " 6jU?" " " " sA7I9H3:I=&I# I.H6/I4AIH9I I!H<"I'B IH?0I8I9$III" I-I.I6I9I<I?IIIII I IIchK |jd{}tj|}|r|j|t |}|j |d{y7Q7#t $r9}tjd|j |d{7Yd}~yd}~wwxYww)z%Handle JSON response from the server.NzError parsing JSON response) areadrr{rrrr}rnrfr~)rCrcr3rvcontentrYr1rqs r*rz-StreamableHTTPTransport._handle_json_responsexs /$NN,,G$88AG!AA'J,W5O$))/: : :- ; /   : ;$))#. . . /s]B2A-A)A A-#A+$A-(B2)A-+A-- B/6)B*B" B*%B2*B//B2c^Kd}d} t|}|j23d{}|jr |j}|j |j}|j ||j |j r|j jnd|d{}|s|jd{y77#7 6n.#t$r"} tjd| Yd} ~ nd} ~ wwxYw|2tjd|j|||d{7yyw)z$Handle SSE response from the server.N)rurvzSSE stream ended: (SSE stream disconnected, reconnecting...)rrrzrrr3r2rrrnrfr|rg_handle_reconnection) rCrcrrvrrrrsres r*rz,StreamableHTTPTransport._handle_sse_responses,%) (, 3&x0L)335  c66$'FFM99((+ %$($:$:**TWT`T`)P)Pfj&7 %;% "//+++' ,%6( 3 LL-aS1 2 2 3  $ KKB C++C@QR R R %sD-C CCCA5C C!C (C ;C<C D-CC C C D- C5C0+D-0C550D-%D(&D-rrrcNK|tk\rtjdtdy||nt}t j |dz d{|j }||t<d}t|jjjtr*|jjjj} t|jd|j |4d{}|j"j%tj'd|} |} |j)23d{} | jr | j} | j* | j*} |j-| |j.||j0r|j0j2ndd{} | s|j"j5d{dddd{y7777C7 76tj'd|j7|| | d d{7dddd{7y#1d{7swYyxYw#t8$rB} tjd | |j7||||d zd{7Yd} ~ yd} ~ wwxYww) zFReconnect with Last-Event-ID to resume stream after server disconnect.zMax reconnection attempts (rNrrrzReconnected to SSE streamrrzReconnection failed: r)rrfr|rrrrXrr\r1rYr]rrzrr/r?rcrrgrrrr3r2rrrrn)rCrrrrrr4rtrreconnect_last_event_idreconnect_retry_msrsrrs r*rz,StreamableHTTPTransport._handle_reconnectionsv / / LL67P6QQ[\ ] ):(E$Khkk(V+,,,'')!. # c))1166 G"%"5"5"="="B"B"E"E $ `#   e e %%668 780='%6"!-!7!7!9#vv25&&/yy,-0YY*(,(>(>..+CF<< ??UY )#K #*33::<<<7 e e e - e #=5 e":" FG//5LN`bcddd? e e e e e@ ` LL04 5++C@QSZ]^S^_ _ _ `sA J%G/A7J%'I/G20I3AI7G=;G5<G=?A4I3G74I;IG9I I)G;*I.J%2I5G=7I9I;I=-I*H-+I0 I;H><IJ%II IIJ%I J" 2JJJJ%J""J%rcKd|}tj||jt|d{y7w)z+Handle unexpected content type in response.zUnexpected content type: N)rferrorr} ValueError)rCrr3 error_msgs r*rz7StreamableHTTPTransport._handle_unexpected_content_types9 0 ~>  Y %%j&;<<.handle_request_async1s<("&"A"A#"FFF"&";";C"@@@G@s>:><>>zError in post_writer)rYr\r2rboolrrfr|rbr.r0r]r start_soonrnr~r) rCr/rr3rrrr1rYr2rrrs ` @@r* post_writerz#StreamableHTTPTransport.post_writer s+ (*$ 5$ 5-@#5#5/-55G&o&>&>@UV(00!%))Oh6O6O$PMLL#;G9!EF88A(*(%#'??(7!)+= CA"',,? &:;2444I$ 5#5F5G.A$ 5$ 5$ 5$ 5$ 5L 5   3 4 5%++- - -%%' ' '%++- - -%%' ' 'sF4D&C7D&DC=C9C=CD1C;2D7D&9C=;D=D> D& D  D&D"D D"D&%E=&EE=EE= F4E F46E97F4=F1FF1*F-+F11F4cK|jsy |j}|j|j|d{}|jdk(rt j dy|jdvr#t jd|jyy7[#t$r"}t jd|Yd}~yd}~wwxYww)z2Terminate the session by sending a DELETE request.Nriz)Server does not allow session termination)zSession termination failed: ) r0rXdeleter?rrfr|rorn)rCr/r4rcrqs r*terminate_sessionz)StreamableHTTPTransport.terminate_sessionCs  A++-G#]]488W]EEH##s* HI%%Z7!=h>R>R=STU8 F  A NN9#? @ @ AsLC 0BB(B*C +0BC B C (CC C  C c|jS)zGet the current session ID.)r0)rCs r*get_session_idz&StreamableHTTPTransport.get_session_idSs r))N,N)NNF)F)Nr)/r$r%r&r'r r9rDrr;r<rr6AuthrKr rXrrr`rbResponserirrrr:rrrrr7rr.rrrrintrrr StreamReaderrrr rrrr(r)r*r>r>Xs9 -C-D--  <*.%'.4"&  c3h$&"   )+  jj4     & &% &%&% &%  &%  &% &%P$sCx."`.`T`tNtttC..C CEE E*15GK"' - -)-'- - &seYt_&<=D -  - -^41!!41)41  41lNtB(n((\#( /../)/ /  /2#( &S..&S&S &S  &SX)- =` =`=`: =`  =`  =`~==)=  = 7( 7 7  75(!!5(*5() 5( -^< 5( #2t8, 5( 5( 5(nAe.?.?ADA d r)r>T http_clientterminate_on_closer?rrr@c  Ktjttzd\ }tjtd\}}|du}| t t | tj 4d{ tjd|tj4d{}|s|j d{d fd } j j | ||  || jf jr|r j! d{ j"j%dddd{ j'd{|j'd{dddd{y7%777v# jr|r j! d{7 j"j%wxYw7#1d{7swYxYw77~# j'd{7|j'd{7wxYw7#1d{7swYyxYww)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. rNz'Connecting to StreamableHTTP endpoint: c@jjyrB)rr)r/r3r transportsr*rz0streamable_http_client..start_get_streamsMM)"="=vGYZr))r@N)rcreate_memory_object_streamrrnrr>create_task_grouprfr| contextlibAsyncExitStackenter_async_contextrrrr0r cancel_scopecancelr) r?rr read_streamrrclient_providedstackrr/r3rrs @@@@r*streamable_http_clientrXs9D',&G&GYbHb&cde&f# (-(I(I.(YZ[(\%L%"-O F ~')',I&&("("(B! ( LLB3%H I!002 - -e&33F;;;[[ ))'& $ -#$!00 !++0B'99&AAAOO**,7 - -:%++- - -%%' ' 'E"("("( -<.B!++0B'99&AAAOO**,7 - - - -: . '%++- - -%%' ' 'E"("("("(s,A;IF&II 0H7F)8H;G8F+.G8F/"G86F-7G8 H G6!H%I 8H 9I HI  I I!I)H+G8-G8/#G3G  G33G86H8H >H?H H I I I%H( &I>I ?II I II IIz%Use `streamable_http_client` instead.rrr4rEr5httpx_client_factoryrFcKt|tr|jn|}t|tr|jn|}||tj|||} | 4d{t || |4d{} | dddd{dddd{y7A7,7#1d{7swY)xYw7 #1d{7swYyxYww)N)read)r4rErFr)r\r total_secondsr6Timeoutr) r?r4rEr5rrrFtimeout_secondssse_read_timeout_secondsr/streamss r*streamablehttp_clientrs&2<C C  C! CC CC!)Mr'rloggingcollections.abcrrrr dataclassesrdatetimertypingr r warningsr rr6 anyio.abcr anyio.streams.memoryr r httpx_sserrrtyping_extensionsrmcp.shared._httpx_utilsrrmcp.shared.messagerr mcp.typesrrrrrrrr getLoggerr$rfrnSessionMessageOrErrorr:rr9GetSessionIdCallbackrVrWrrrrUrTrRrSobjectrKr"r,r.r>r7rtuplerr;r<rrr(r)r*rsy??*!  R@@(E      8 $'2%&;< (8 C$J/!- !%  >)>5)5  * *  *}}@-1# P( P(""T)P( P(  !.9"<=~.     P(P(f 34&*!#*0#1G"$ $ #s(^d "$Y $i' $  $ / $ **t $ !.9"<=~.    $5$r)