
    )`i$                        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 j!        e"          Z#ej$        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j+        fde*de	fd            Z,de(de(fdZ-dej+        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Z1dS )!    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                            |          }|$|                    d          r:|| |<   @| S )zo
    Returns a default environment object including only environment variables deemed
    safe to inherit.
    Nz())DEFAULT_INHERITED_ENV_VARSosenvironget
startswith)envkeyvalues      m/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/mcp/client/stdio/__init__.pyget_default_environmentr1   3   s\    
 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<   dS )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         LLL4eD111D$s)111;!%Cc3h$	%%% "Ctd	!!!AHc FNG$ABMMM r2   r4   servererrlogc           
        	
K   t          j        d          \  	}t          j        d          \  }
	 t           j                  }t	          | j         j        i t                       j        nt                      | j                   d{V nw# t          $ rj |
                                 d{V  |
                                 d{V  	
                                 d{V  

                                 d{V   w xY w	 fd} 
fd}t          j                    4 d{V 	 }4 d{V  |                    |           |                    |           	 ||fW V  j        r1	 j        
                                 d{V  n# t          $ r Y nw xY w	 t          j        t                     5                                   d{V  ddd           n# 1 swxY w Y   n0# t$          $ r t'                     d{V  Y nt(          $ r Y nw xY w|
                                 d{V  |
                                 d{V  	
                                 d{V  

                                 d{V  n"# j        r1	 j        
                                 d{V  n# t          $ r Y nw xY w	 t          j        t                     5                                   d{V  ddd           n# 1 swxY w Y   n0# t$          $ r t'                     d{V  Y nt(          $ r Y nw xY w|
                                 d{V  |
                                 d{V  	
                                 d{V  

                                 d{V  w xY w	 ddd          d{V  n# 1 d{V swxY w Y   ddd          d{V  dS # 1 d{V swxY w Y   dS )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 {V  d} t          j         	j        	j                  2 3 d {V }| |z                       d          }|                                } |D ]}	 t          j                            |          }nL# t          $ r?}t                              d                               |           d {V  Y d }~gd }~ww xY wt          |          }                    |           d {V  6 	 d d d           d {V  d S # 1 d {V swxY w Y   d S # t          j        $ r( t          j                                         d {V  Y d S w xY 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   s     ~AAAAA~	.) G G G G G G G G#4N#_!8$ $ $ G G G G G G G%
 $e^22488E"YY[[F % 	G 	G%&+&:&N&Nt&T&TGG( % % %",,-Z[[["4"9"9#">">>>>>>>>$HHHH%
 +9*A*A055oFFFFFFFFFF	G$ $G G G G G G G G G G G G G G G G G G G G G G G G G G G G G G( ( 	. 	. 	..++------------	.sj   D: $D'D1D':BD'
C#	$5C	D'C#	#0D'D: '
D11D: 4D15D: :3E10E1c                    K   j         s
J d            	 4 d {V  2 3 d {V } | j                            dd          }j                             |dz                       j        j                             d {V  f6 	 d d d           d {V  d S # 1 d {V swxY w Y   d S # t          j        $ r( t          j	        
                                 d {V  Y d S w xY 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BBD_cBddD!-,,,,%+_#)#@ -            .A-@                              ( 	. 	. 	..++------------	.s?   B/ BBA!B	B/ 
B&&B/ )B&*B/ /3C&%C&)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&J&J#(-(I!(L(L%L%)&.99 <@F
@V<+--<<<\s\u\u

 
 
 
 
 
 
 
 
      """""""""!!######### '')))))))))!((*********. . . . . . .6. . . . . . ." 	!!"/ "/ "/ "/ "/ "/ "/ "/%'"/ "/ "/ "/ "/ "/ "/ "/ 	m$$$
l###	/|+++++ } !-..0000000000    D
%&ABB ) )!,,..((((((() ) ) ) ) ) ) ) ) ) ) ) ) ) ) 7 7 7 .g66666666666%    $$&&&&&&&&&%%'''''''''$++---------%,,..........+ } !-..0000000000    D
%&ABB ) )!,,..((((((() ) ) ) ) ) ) ) ) ) ) ) ) ) ) 7 7 7 .g66666666666%    $$&&&&&&&&&%%'''''''''$++---------%,,...........E"/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/ "/sM  A"B A4D8	O,+O-J4O<FO
F)&O(F))O-G9G-!G9-G11G94G15G98O9H&O	H&#O%H&&A-ON2J<;N2<
K	N2K		N2L&LLLLLLN2M8N2:	MN2MA,N22O6O,
O	O,O	O,,
O69O6r5   c                 D    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6r2   r7   r-   r8   c                    K   t           j        dk    rt          | ||||           d{V }n"t          j        | g||||d           d{V }|S )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      s       |w.wc63OOOOOOOO*t"
 
 
 
 
 
 
 
 
 Nr2   rc   timeout_secondsc                    K   t           j        dk    rt          | |           d{V  dS t          | t                    sJ t          | |           d{V  dS )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     s}       |w,WoFFFFFFFFFFF '7+++++*7ODDDDDDDDDDDr2   )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      s    				 



 * * * * * *       " " " " " " " "            R R R R R R R R 0 0 0 0 0 0 % % % % % % % %       ? ? ? ? ? ?            . - - - - -		8	$	$$ |w    
>	=	=! ( " c3h    *    I   B GJz n/ n/4 n/f n/ n/ n/ n/bS S    & "&Z! 
s) 
c3h$	 	
 
d	   6E E7_+D EW\ Egk E E E E E Er2   