
    Ki$                        d dl Z d dlZd dlZd dlmZ d dlmZ d dl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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   e jB                  e"      Z#ejH                  dk(  rg dng dZ%dZ&de'e(e(f   fdZ) G d de      Z*eejV                  fde*de	fd       Z,de(de(fdZ-dejV                  dfde(de.e(   de'e(e(f   dz  de	dee(z  dz  f
dZ/d deez  de0ddfdZ1y)!    N)asynccontextmanager)Path)LiteralTextIO)Process)MemoryObjectReceiveStreamMemoryObjectSendStream)TextReceiveStream)	BaseModelField)terminate_posix_process_tree)FallbackProcesscreate_windows_processget_windows_executable_commandterminate_windows_process_tree)SessionMessagewin32)APPDATA	HOMEDRIVEHOMEPATHLOCALAPPDATAPATHPATHEXTPROCESSOR_ARCHITECTURESYSTEMDRIVE
SYSTEMROOTTEMPUSERNAMEUSERPROFILE)HOMELOGNAMEr   SHELLTERMUSER       @returnc                      i } t         D ];  }t        j                  j                  |      }|%|j	                  d      r7|| |<   = | S )zo
    Returns a default environment object including only environment variables deemed
    safe to inherit.
    z())DEFAULT_INHERITED_ENV_VARSosenvironget
startswith)envkeyvalues      e/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/mcp/client/stdio/__init__.pyget_default_environmentr1   3   sS    
 C) 	

s#=D!C	 J    c                       e Zd ZU eed<   	  ee      Zee   ed<   	 dZe	eef   dz  ed<   	 dZ
eez  dz  ed<   	 dZeed<   	 d	Zed
   ed<   y)StdioServerParameterscommand)default_factoryargsNr-   cwdzutf-8encodingstrict)r:   ignorereplaceencoding_error_handler)__name__
__module____qualname__str__annotations__r   listr7   r-   dictr8   r   r9   r=   r    r2   r0   r4   r4   H   s}    L4D1D$s)1;!%Cc3h$	% "Ctd	!AHc FNG$ABMr2   r4   servererrlogc           
     6   	
K   t        j                  d      \  	}t        j                  d      \  }
	 t         j                        }t	        | j
                   j                  i t                j                  n	t               | j                         d{   	 fd} 
fd}t        j                         4 d{   }4 d{    |j                  |       |j                  |       	 ||f j                  r#	 j                  j                          d{    	 t        j                  t               5  j#                          d{    ddd       |j                          d{    |j                          d{    	j                          d{    
j                          d{    ddd      d{    ddd      d{    y7 P# t        $ rf |j                          d{  7   |j                          d{  7   	j                          d{  7   
j                          d{  7    w xY w7 7 7 <# t        $ r Y Fw xY w7 # 1 sw Y   xY w# t$        $ r t'               d{  7   Y ?t(        $ r Y Jw xY w7 ;7 &7 7 # j                  r4	 j                  j                          d{  7   n# t        $ r Y nw xY w	 t        j                  t               5  j#                          d{  7   ddd       n# 1 sw Y   nxY wn-# t$        $ r t'               d{  7   Y nt(        $ r Y nw xY w|j                          d{  7   |j                          d{  7   	j                          d{  7   
j                          d{  7   w xY w7 # 1 d{  7  sw Y   xY w7 # 1 d{  7  sw Y   yxY ww)z
    Client transport for stdio: this will connect to a server by spawning a
    process and communicating with it over stdin/stdout.
    r   N)r5   r7   r-   rG   r8   c                    K   j                   sJ d       	 4 d {    d} t        j                   	j                  	j                        2 3 d {   }| |z   j	                  d      }|j                         } |D ]F  }	 t        j                  j                  |      }t        |      }j                  |       d {    H y7 7 v# t        $ r9}t        j                  d       j                  |       d {  7   Y d }~d }~ww xY w7 P6 d d d       d {  7   y # 1 d {  7  sw Y   y xY w# t        j                  $ r* t        j                   j#                          d {  7   Y y w xY ww)Nz Opened process is missing stdout r9   errors
z+Failed to parse JSONRPC message from server)stdoutr
   r9   r=   splitpoptypesJSONRPCMessagemodel_validate_json	Exceptionlogger	exceptionsendr   anyioClosedResourceErrorlowlevel
checkpoint)
bufferchunklineslinemessageexcsession_messageprocessread_stream_writerrF   s
          r0   stdout_readerz#stdio_client.<locals>.stdout_reader   sg    ~~AAA~	.) G G#4NN#__!88$ G G%
 $e^2248E"YY[F % 	G%&+&:&:&N&Nt&TG +9*A055oFFF	GGG  ) %",,-Z["4"9"9#">>>$% G#$G G G G G( (( 	...++---	.s   E=D= C
D= /D(DCD*D(C#D(D
D(
D= D	D	)D	 DD	D(D	D(D(D= !D$"D= 'E=(D:.D1/D:6D= 9E=:D= =4E:1E42E:7E=9E::E=c                    K   j                   sJ d       	 4 d {    2 3 d {   } | j                  j                  dd      }j                   j                  |dz   j	                  j
                  j                               d {    r7 x7 o7 	6 d d d       d {  7   y # 1 d {  7  sw Y   y xY w# t        j                  $ r* t        j                  j                          d {  7   Y y w xY ww)NzOpened process is missing stdinT)by_aliasexclude_nonerM   rK   )stdinr`   model_dump_jsonrW   encoder9   r=   rX   rY   rZ   r[   )rb   jsonrc   rF   write_stream_readers     r0   stdin_writerz"stdio_client.<locals>.stdin_writer   s     }}???}	.*  -@  /*22BBD_cBdD!--,,,,%+__#)#@#@ -    .A     (( 	...++---	.s   DC BC B0BBBA$B0BB0C BB0B0C )B,*C /D0C6B97C>C DC 4D9C<:D?DDD)rX   create_memory_object_stream_get_executable_commandr5   #_create_platform_compatible_processr7   r-   r1   r8   OSErroraclosecreate_task_group
start_soonri   rT   
fail_afterPROCESS_TERMINATION_TIMEOUTwaitTimeoutError_terminate_process_treeProcessLookupError)rF   rG   read_streamwrite_streamr5   re   rn   tgrc   rd   rm   s   `       @@@r0   stdio_clientr   i   s     ',&G&G&J#(-(I(I!(L%L%)&..9 <@F

@V<+-<<\s\u


 
.6." 	!"/ "/%'"/ "/ 	m$
l#	/|++ }}!--..000

%%&AB )!,,.(() $$&&&%%'''$++---%,,...E"/ "/ "/ "/ "/u
    """!!### '')))!((***f"/ "/ 1   )) ) 7 .g666%  ''-.+ }}!--..000  
%%&AB )!,,.(() ) ) 7 .g666%  $$&&&%%'''$++---%,,...E"/ "/ "/ "/ "/ "/ "/ "/s  1PA(G3  G0!G3 %&PI%PPI(P#O+>KO+I./I+0I.5JJ"I>
#J'J/O+J=O+K O+2K3O+
KO+PO(PP*P+P0G3 3I"HI"(H+)I"II"II""P(P+I..	I;7O+:I;;O+>JJJJ:%J(
&J:+O+.J:6O+9J::O+ O+O+O+O%K:3K64K:9O%:	LO%LO%
M#M7L:8M=	MMMO%M=*M-+M=0O%2M=:O%<M==O%NO%,N/-O%OO%O!O%%O+(P+O>	1O42O>	9PPP
PPPr5   c                 B    t         j                  dk(  rt        |       S | S )z
    Get the correct executable command normalized for the current platform.

    Args:
        command: Base command (e.g., 'uvx', 'npx')

    Returns:
        str: Platform-appropriate command
    r   )sysplatformr   )r5   s    r0   rp   rp      s      ||w-g66r2   r7   r-   r8   c                    K   t         j                  dk(  rt        | ||||       d{   }|S t        j                  | g||||d       d{   }|S 7 -7 w)z
    Creates a subprocess in a platform-compatible way.

    Unix: Creates process in a new session/process group for killpg support
    Windows: Creates process in a Job Object for reliable child termination
    r   NT)r-   stderrr8   start_new_session)r   r   r   rX   open_process)r5   r7   r-   rG   r8   rc   s         r0   rq   rq      sq      ||w.wc63OO N **t"
 
 N P
s!   &AA&AAAArc   timeout_secondsc                    K   t         j                  dk(  rt        | |       d{    yt        | t              sJ t        | |       d{    y7 ,7 w)af  
    Terminate a process and all its children using platform-specific methods.

    Unix: Uses os.killpg() for atomic process group termination
    Windows: Uses Job Objects via pywin32 for reliable child process cleanup

    Args:
        process: The process to terminate
        timeout_seconds: Timeout in seconds before force killing (default: 2.0)
    r   N)r   r   r   
isinstancer   r   )rc   r   s     r0   rz   rz     sS      ||w,WoFFF '7+++*7ODDD	 	G 	Es!   #AA&AAAA)r%   )2loggingr)   r   
contextlibr   pathlibr   typingr   r   rX   anyio.lowlevel	anyio.abcr   anyio.streams.memoryr   r	   anyio.streams.textr
   pydanticr   r   	mcp.typesrQ   mcp.os.posix.utilitiesr   mcp.os.win32.utilitiesr   r   r   r   mcp.shared.messager   	getLoggerr>   rU   r   r(   rw   rD   rA   r1   r4   r   r   rp   rC   rq   floatrz   rE   r2   r0   <module>r      sY    	 
 *  "    R 0 %  ?  .			8	$$ ||w 
>! ( " c3h *I B GJzz n/4 n/f n/ n/bS S & "&ZZ!
s) 
c3h$	 	
 
d	6E7_+D EW\ Egk Er2   