xj6 dZddlZddlZddlZddlmZddlmZmZddl m Z ddl m Z m Z ddlZddlZddlZddlmZmZddlmZdd lmZmZdd lmZdd lmZdd lmZm Z m!Z!m"Z"m#Z#dd l$m%Z%ejLe'Z(ejRdk(rgdngdZ*dZ+dZ,dZ-dZ.dZ/de0e1e1ffdZ2GddeZ3eejhfde3de deedffdZ5de1de%e6zfdZ7deddfdZ8deddfdZ9d eddfd!Z:ded"e;dededdfd%Z?d&e1de1fd'Z@dejhdfd&e1d(eAe1d)e0e1e1fdzde d*e e1zdzdef d+ZBd,eddfd-ZCy).astdio client transport. Runs an MCP server as a subprocess and exchanges newline-delimited JSON-RPC messages with it over stdin/stdout. Two pipe tasks bridge the server's pipes to the session's in-memory streams; shutdown follows the MCP spec sequence (close stdin, wait, then kill the process tree) inside a cancellation shield with every wait bounded, so a cancelled caller can neither leak a live server process nor hang on one. N)AsyncGenerator)asynccontextmanagersuppress)Path)LiteralTextIO) AsyncResourceProcess)TextReceiveStream) BaseModelField)TransportStreams)terminate_posix_process_tree) ServerProcessclose_process_jobcreate_windows_processget_windows_executable_commandterminate_windows_process_tree)SessionMessagewin32) APPDATA HOMEDRIVEHOMEPATH LOCALAPPDATAPATHPATHEXTPROCESSOR_ARCHITECTURE SYSTEMDRIVE SYSTEMROOTTEMPUSERNAME USERPROFILE)HOMELOGNAMErSHELLTERMUSERg@g?g{Gz?returnci}tD];}tjj|}|%|j dr7|||<=|S)z@Returns only the environment variables that are safe to inherit.z())DEFAULT_INHERITED_ENV_VARSosenvironget startswith)envkeyvalues d/mnt/ssd/data/Dropbox/adrian/sandbox/mcp-query/venv/lib/python3.12/site-packages/mcp/client/stdio.pyget_default_environmentr3KsQC)  s# =    D ! C  JceZdZUeed< eeZeeed< dZe eefdzed< dZ ee zdzed< dZ eed< d Z ed ed <y) StdioServerParameterscommand)default_factoryargsNr/cwdzutf-8encodingstrict)r<ignorereplaceencoding_error_handler)__name__ __module__ __qualname__str__annotations__r listr9r/dictr:rr;r?rr4r2r6r6]sq L4D1D$s)1;!%Cc3h$ %M!Ctd !AHc.stdout_readers~~AAA~"7>>FOOTZTqTqr \) 1 1 1F'-''e!'% 6 6t <!&$)'D'&8&=&=k$>O&P P P' 1' !Q$)$=$=u?X?X#Y' &'000 1 1 1' (.(000-000 1 1 1 1 1((  ))?; \!  !Z[! \s2AF%E B, EEDDB.D*DB2$B0 %B2)D,E.D0B22#C? DE&C)'E, E7C:8E=F%>C? ?DEDED/(D+ )D//E2 E=E>EF%E E EEF%EF",F%./F"F%!F""F%cnKjsJd 4d{23d{}|jjdd}|dzjjj }jj |d{t7z7q7 6dddd{7n#1d{7swYnxYwnG#tjtjtf$rjd{7YnwxYwjy#jwxYww)NzOpened process is missing stdinT)by_alias exclude_unsetrPrM) stdinmessagemodel_dump_jsonencoder;r?rTrVrWrXOSErroracloseset)session_messagejsondatararbrHwrite_stream_reader writer_dones r2 stdin_writerz"stdio_client..stdin_writers}}???} * 3 3-@33/*22BBD`dBeD 4K//QWQnQn/oD!--,,T222  333.A 3 3 3 3 3 ))5+D+DgN .%++- - - . OO KOO sD5CBCB2BBBA&B2BB2CBB2B2 C+B.,C2C8B; 9CCD ;D DD  D D  D D5 D22D5cKjjtjt5}j d{dddj r&tj jd{td{td{tj jd{y7#1swYxYw7b7Q7=7w)zTWinds the transport down: stop traffic, flush, stop the server, release the streams.N) closerV move_on_after_WRITER_FLUSH_TIMEOUTwaitcancelled_caughtlowlevelcancel_shielded_checkpoint_stop_server_process _aclose_all checkpoint) flush_scopera read_streamrb write_streamrrrss r2shutdownzstdio_client..shutdowns   !6 7 %;""$ $ $ %  ' '..;;= = ="7++++|5GI\]]]nn''))) % % % >+])sp:C6C"C C"5C6 C. C6C0C64C25%C6C4C6 C""C+'C60C62C64C6Tshield)r(N)_get_executable_commandr7#_create_platform_compatible_processr9r3r/r:rVcreate_memory_object_streamr ExceptionEventcreate_task_group start_soon CancelScope cancel_scopecancelr{r|)rHrIr7rdrtrtgrarrbrcrrrrss` @@@@@@@r2 stdio_clientrqs&fnn5G7 [[ # %)9r : JJ G',&G&GYbHb&cde&f# (-(I(I.(YZ[(\%L%M++-K\\6 ** &&( % %B m$ l# %|+ + M""$/ !j   ! OO " " $ % % .. 3 3 555uV %! ! ! !M""$/ !j   ! ! ! OO " " $ % % % %6sAH/ F&!BH/6F)7H/:#HF9%H= F-F+ F- "H/ H/:H;%H/ H-!H/)H/+F--F6 2H9H G, G G, # H,G5 1"HHH/H*H! H*&H/r`c tjj|d}t |S#t$r!}tj d|cYd}~Sd}~wwxYw)zTParses one stdout line, returning parse errors as values for the session to surface.F)by_namez+Failed to parse JSONRPC message from serverN)typesjsonrpc_message_adapter validate_json ValueErrorr[r\r)r`riexcs r2rUrUsU//==dE=R ' "" FG s!. AA AArachK|jsJtjd5ttjtj tj tt5 |jjd{#7#1swYnxYw dddy#1swYyxYww)zConsumes and discards the server's remaining stdout. Keeps a server flushing buffered output from blocking on a full pipe and missing its chance to exit; shielded, raw bytes, ends when shutdown closes the pipe. TrN) rQrVrr EndOfStreamrWrXrZrlreceiveras r2rYrYs >>>   $ ' /      % %  % %     /nn,,.... / / / / / /s;%B2AB&)BB BB B& B2&B/+B2cK|jr |jsJdt|jd{t|td{sKt |d{t|t d{s tjd|jt|t|jd{t|y777t7^7w)zCloses stdin, waits out the grace period, then kills the whole tree. The escalation order is spec text; timeouts and tree-wide scope are SDK policy: https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#shutdown z$server process is spawned with pipesNzMMCP server process %d is still alive after the kill escalation; abandoning it) rhrQ _close_pipe_wait_for_process_exitPROCESS_TERMINATION_TIMEOUT_terminate_process_tree_KILL_REAP_TIMEOUTr[warningpidr_close_subprocess_transportrs r2r}r}s ==W^^S-SS + gmm $$$'1LM M M%g...+G5GHHH NNjlslwlw xg gnn %%%(% M.H &sX8C CC CC %C&C =C>AC CC C C C C streamcKtttjtj5|j d{dddy7 #1swYyxYww)zJCloses a pipe stream, tolerating one already closed, broken, or contended.N)rrlrVrXrWrm)rs r2rrsJ '544e6O6O Pmmos..A AAA A AAA timeoutcKtj|z}|jFtj|k\rytjtd{|jFy7w)zReturns whether the process died within the timeout, by polling returncode. Not process.wait(): on asyncio 3.11+ it also waits for pipe EOF, and a child that inherited the pipes makes an exited server look hung. NFT)rV current_time returncodesleep_EXIT_POLL_INTERVAL)rardeadlines r2rrsf !!#g-H    $    8 +kk-...    $  /sAA/A-A/,A/cKtjdk(rt|d{yt|tsJt |t d{y707w)zKills the process and all its descendants. POSIX: SIGTERM to the process group, SIGKILL after FORCE_KILL_TIMEOUT. Windows: immediate Job Object termination (already a hard kill). rN)sysplatformr isinstancer rFORCE_KILL_TIMEOUTrs r2rr"sQ  ||w,W555'7+++*74FGGG 6 Hs!"AA*AAAActt|dddd}t|dd}t|r tt5|dddyy#1swYyxYw)a Closes the asyncio subprocess transport, if there is one. The transport otherwise stays open (and warns at GC) while a surviving descendant holds a pipe end; nothing public exposes it, hence the attribute walk. No-op on trio and the Windows fallback. _processN _transportrv)getattrcallablerPermissionError)ra transportrvs r2rr0s\T:L$OI Iw -E o &  G    s AAr7cBtjdk(r t|S|S)z0Normalizes the command for the current platform.r)rrr)r7s r2rr@s ||w-g66r4r9r/r:cKtjdk(rt|||||d{Stj|g||||dd{S7)7w)zqSpawns the server in its own kill scope. A new session/process group on POSIX, a Job Object on Windows. rNT)r/stderrr:start_new_session)rrrrV open_processrKs r2rrHse ||w+GT3LLL''  t "    M s!&AA$A AAAstreamscNK|D]}|jd{y7w)zCloses every given stream.N)rm)rrs r2r~r~_s'mmos %#%)D__doc__loggingr+rcollections.abcr contextlibrrpathlibrtypingrrrVanyio.lowlevel mcp_typesr anyio.abcr r anyio.streams.textr pydanticr r mcp.client._transportrmcp.os.posix.utilitiesrmcp.os.win32.utilitiesrrrrrmcp.shared.messager getLoggerr@r[rr*rrrrxrrFrCr3r6rrrrUrYr}rfloatboolrrrrrErr~rGr4r2rs% *4" ,0%2?.   8 $$ ||w  >!("c3h$dId(47JJe6 !e6+1e6$d*+e6e6P#c#ny8#//4/() )$),m - % D  H= HT H  4  SS"&ZZ!   s)  c3h$     d     . $r4