
    [ǻi=              	         U d Z ddlmZ 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mZmZ ddl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 erddlmZ ddlmZ ddlZddl m!Z!  ejD                  e#      Z$ ejJ                  d      Z&	 d/dZ'ed   Z(dZ)dZ*de+d<   dZ,dZ- e	d      Z. e	d      Z/ G d de      Z0 G d de      Z1 G d de      Z2 G d  d!e      Z3 G d" d#e      Z4e1e2z  e3z  e4z  Z5edde)e*dd$	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d0d%       Z6ede,e-dddd&	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d1d'       Z7ede.e/d(dddd)	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d2d*       Z8edd+	 	 	 	 	 d3d,       Z9edd-	 	 	 	 	 d4d.       Z:y)5zSession management for different MCP transport types.

This module provides connection configurations and session management for various
MCP transport types including stdio, SSE, WebSocket, and streamable HTTP.
    )annotationsN)asynccontextmanager)	timedelta)TYPE_CHECKINGAnyLiteralProtocol)ClientSessionStdioServerParameters)
sse_client)stdio_client)streamablehttp_client)NotRequired	TypedDict)AsyncIterator)Path)_MCPCallbacksz\$\{([^}]+)\}c                0    t         j                  d |       S )av  Expand `${VAR}` references in *value* using the current environment.

    Only braced syntax is expanded; bare `$VAR` references are left untouched so
    that literal dollar signs in passwords or other values are never silently
    corrupted by an unrelated environment variable.

    Undefined variables are preserved as-is (e.g. `${MISSING}` stays
    `${MISSING}`).
    c                ~    t         j                  j                  | j                  d      | j                  d            S )N   r   )osenvirongetgroup)ms    ]/opt/lhia/marcimex/agent/venv/lib/python3.12/site-packages/langchain_mcp_adapters/sessions.py<lambda>z"_expand_env_vars.<locals>.<lambda>.   s%    

qwwqz1771:(N     )_BRACED_VAR_REsub)values    r   _expand_env_varsr"   $   s     NPUVVr   )strictignorereplacezutf-8r#   EncodingErrorHandlerDEFAULT_ENCODING_ERROR_HANDLER   i,     )secondsc                  .    e Zd ZdZ	 	 	 d	 	 	 	 	 	 	 ddZy)McpHttpClientFactoryzFProtocol for creating httpx.AsyncClient instances for MCP connections.Nc                     y)a   Create an httpx.AsyncClient instance.

        Args:
            headers: HTTP headers to include in requests.
            timeout: Request timeout configuration.
            auth: Authentication configuration.

        Returns:
            Configured httpx.AsyncClient instance.
        N )selfheaderstimeoutauths       r   __call__zMcpHttpClientFactory.__call__@   s      	r   )NNN)r0   dict[str, str] | Noner1   zhttpx.Timeout | Noner2   httpx.Auth | Nonereturnzhttpx.AsyncClient)__name__
__module____qualname____doc__r3   r.   r   r   r,   r,   =   s;    P *.(,"&	& &  	
 
r   r,   c                  n    e Zd ZU dZded<   ded<   	 ded<   	 ded	<   	 d
ed<   	 ded<   	 ded<   	 ded<   y)StdioConnectionz=Configuration for stdio transport connections to MCP servers.zLiteral['stdio']	transportstrcommand	list[str]argsz"NotRequired[dict[str, str] | None]envzNotRequired[str | Path | None]cwdzNotRequired[str]encodingz!NotRequired[EncodingErrorHandler]encoding_error_handler"NotRequired[dict[str, Any] | None]session_kwargsNr7   r8   r9   r:   __annotations__r.   r   r   r<   r<   S   sT    GL4
O;	++
 
('A
 >= 76Dr   r<   c                  n    e Zd ZU dZded<   ded<   	 ded<   	 ded	<   	 ded
<   	 ded<   	 ded<   	 ded<   y)SSEConnectionzHConfiguration for Server-Sent Events (SSE) transport connections to MCP.zLiteral['sse']r=   r>   urlrF   r0   zNotRequired[float]r1   sse_read_timeoutrG   (NotRequired[McpHttpClientFactory | None]httpx_client_factoryNotRequired[httpx.Auth]r2   NrH   r.   r   r   rK   rK      sQ    R	H4//3 )( 76DBB:
!!6r   rK   c                  z    e Zd ZU dZded<   ded<   	 ded<   	 ded	<   	 ded
<   	 ded<   	 ded<   	 ded<   	 ded<   y)StreamableHttpConnectionz7Connection configuration for Streamable HTTP transport.zLiteral['streamable_http']r=   r>   rL   rF   r0   zNotRequired[timedelta]r1   rM   zNotRequired[bool]terminate_on_closerG   rN   rO   rP   r2   NrH   r.   r   r   rR   rR      sV    A))	H0///##,,> *)466DBB:
!!6r   rR   c                  2    e Zd ZU dZded<   ded<   	 ded<   y)	WebsocketConnectionzAConfiguration for WebSocket transport connections to MCP servers.zLiteral['websocket']r=   r>   rL   rF   rG   NrH   r.   r   r   rU   rU      s    K##	H:66Cr   rU   )rB   rC   rD   rE   rG   c               :  K   |-|j                         D ci c]  \  }}|t        |       c}}nd}	|	E|	j                         D ]2  \  }}t        j                  |      st        j                  d||       4 t        | ||	|||      }
t        |
      4 d{   \  }}t        ||fi |xs i 4 d{   }| ddd      d{    ddd      d{    yc c}}w 7 M7 27 # 1 d{  7  sw Y   /xY w7 &# 1 d{  7  sw Y   yxY ww)a  Create a new session to an MCP server using stdio.

    Args:
        command: Command to execute.
        args: Arguments for the command.
        env: Environment variables for the command. Values containing
            `${VAR}` references are expanded from the current environment. Only
            braced syntax is supported; bare `${VAR}` is **not** expanded so
            that literal dollar signs in passwords or other values are never
            silently corrupted. Only values (not keys) are expanded;
            `${command}` and `${args}` are passed through unchanged.

            If not specified, inherits a subset of the current environment.

            The details are implemented in the MCP sdk.
        cwd: Working directory for the command.
        encoding: Character encoding.
        encoding_error_handler: How to handle encoding errors.
        session_kwargs: Additional keyword arguments to pass to the ClientSession.

    Yields:
        An initialized ClientSession.
    Nz2env[%r] contains unexpanded variable reference: %r)r?   rA   rB   rC   rD   rE   )	itemsr"   r   searchloggerwarningr   r   r
   )r?   rA   rB   rC   rD   rE   rG   kvresolved_envserver_paramsreadwritesessions                 r   _create_stdio_sessionrb      s2    J =@OCIIK8DAqQ	8QU   &&( 	DAq$$Q'H!Q	
 *5M 	]# '4edE<n&:< @G	    % 	9$         s   DC#3D"9DC)DD8C+9D<C/DC-DDDD+D-D/D	5C86D	=DDDDDD)r0   r1   rM   rG   rO   r2   c               :  K   i }|||d<   t        | |||fd|i|4 d{   \  }}	t        ||	fi |xs i 4 d{   }
|
 ddd      d{    ddd      d{    y7 G7 ,7 # 1 d{  7  sw Y   )xY w7  # 1 d{  7  sw Y   yxY ww)a  Create a new session to an MCP server using SSE.

    Args:
        url: URL of the SSE server.
        headers: HTTP headers to send to the SSE endpoint.
        timeout: HTTP timeout.
        sse_read_timeout: SSE read timeout.
        session_kwargs: Additional keyword arguments to pass to the ClientSession.
        httpx_client_factory: Custom factory for httpx.AsyncClient (optional).
        auth: Authentication for the HTTP client.

    Yields:
        An initialized ClientSession.
    NrO   r2   )r   r
   )rL   r0   r1   rM   rG   rO   r2   kwargsr_   r`   ra   s              r   _create_sse_sessionre     s     4 F')=%& 	3*:PPP U
dE<n&:< 
 AH             s   BA)BBA+BA/BA-BB#B$B+B-B/B	5A86B	=BBBBBBT)r0   r1   rM   rS   rG   rO   r2   c               >  K   i }|||d<   t        | ||||fd|i|4 d{   \  }	}
}t        |	|
fi |xs i 4 d{   }| ddd      d{    ddd      d{    y7 H7 ,7 # 1 d{  7  sw Y   )xY w7  # 1 d{  7  sw Y   yxY ww)a  Create a new session to an MCP server using Streamable HTTP.

    Args:
        url: URL of the endpoint to connect to.
        headers: HTTP headers to send to the endpoint.
        timeout: HTTP timeout.
        sse_read_timeout: How long the client will wait for a new event before
            disconnecting.
        terminate_on_close: Whether to terminate the session on close.
        session_kwargs: Additional keyword arguments to pass to the ClientSession.
        httpx_client_factory: Custom factory for httpx.AsyncClient (optional).
        auth: Authentication for the HTTP client.

    Yields:
        An initialized ClientSession.
    NrO   r2   )r   r
   )rL   r0   r1   rM   rS   rG   rO   r2   rd   r_   r`   _ra   s                r   _create_streamable_http_sessionrh   ;  s     : F')=%& 		
 	
 	
  dE1dE<n&:<  AH             s    BA+BB A-BA1
BA/BB%B&B-B/B1B	7A:8B	?BBBBBB)rG   c               Z  K   	 ddl m}  ||       4 d{   \  }}t        ||fi |xs i 4 d{   }| ddd      d{    ddd      d{    y# t        $ r d}t        |      dw xY w7 b7 G7 4# 1 d{  7  sw Y   DxY w7 ;# 1 d{  7  sw Y   yxY ww)aC  Create a new session to an MCP server using Websockets.

    Args:
        url: URL of the Websocket endpoint.
        session_kwargs: Additional keyword arguments to pass to the ClientSession.

    Yields:
        An initialized ClientSession.

    Raises:
        ImportError: If websockets package is not installed.
    r   )websocket_clientzCould not import websocket_client. To use Websocket connections, please install the required dependency: 'pip install mcp[ws]' or 'pip install websockets'N)mcp.client.websocketrj   ImportErrorr
   )rL   rG   rj   msgr_   r`   ra   s          r   _create_websocket_sessionrn   k  s     $)9 	 !.$dE<n&:< @G	      )@ 	
 #D()         s   B+A B+A9B+BA;BA?BA=	BB+BB+A66B+;B=B?B	BB	BB+B(BB($B+)mcp_callbacksc              F  K   d| vrd}t        |      | d   }| j                         D ci c]  \  }}|dk7  s|| }}}|Q|j                  di       |d<   |j                  |j                  |d   d<   |j                  |j                  |d   d<   |dk(  r;d|vrd	}t        |      t        di |4 d{   }| ddd      d{    y|d
v r;d|vrd}t        |      t        di |4 d{   }| ddd      d{    y|dk(  rLd|vrd}t        |      d|vrd}t        |      t        di |4 d{   }| ddd      d{    y|dk(  r;d|vrd}t        |      t        di |4 d{   }| ddd      d{    yd| d}t        |      c c}}w 7 7 # 1 d{  7  sw Y   yxY w7 7 # 1 d{  7  sw Y   yxY w7 7 # 1 d{  7  sw Y   yxY w7 }7 j# 1 d{  7  sw Y   yxY ww)a  Create a new session to an MCP server.

    Args:
        connection: Connection config to use to connect to the server
        mcp_callbacks: mcp sdk compatible callbacks to use for the ClientSession

    Raises:
        ValueError: If transport is not recognized
        ValueError: If required parameters for the specified transport are missing

    Yields:
        A ClientSession
    r=   zConfiguration error: Missing 'transport' key in server configuration. Each server must include 'transport' with one of: 'stdio', 'sse', 'websocket', 'http'. Please refer to the langchain-mcp-adapters documentation for more details.NrG   logging_callbackelicitation_callbacksserL   z.'url' parameter is required for SSE connection>   streamable-httphttpstreamable_httpz:'url' parameter is required for Streamable HTTP connectionstdior?   z4'command' parameter is required for stdio connectionrA   z1'args' parameter is required for stdio connection	websocketz4'url' parameter is required for Websocket connectionzUnsupported transport: z5. Must be one of: 'stdio', 'sse', 'websocket', 'http'r.   )	
ValueErrorrW   r   rq   rr   re   rh   rb   rn   )
connectionro   rm   r=   r[   r\   paramsra   s           r   create_sessionr|     s    " *$Y 	 o;'I)//1Ftq!Q+5EadFFF #)::.>#C ))5.. #$%78 --922 #$%;< EBCS/!&00 	 	GM	 	 		D	DNCS/!2<V< 	 	M	 	 		g	F"HCS/!ECS/!(262 	 	gM	 	 		k	!HCS/!,6v6 	 	'M	 	 	 &i[ 1B C 	 o[ G"	 	 	 	 		 	 	 	 		 	 	 	 		 	 	 	 	s  *H!F6F6A;H!:F<;H!>GH!F?)H!9G:H!=GH!G;H!
G/H!G3H!G1 *H!
HH!HH!H
 H!?H!GG
GH!H!G, G#!G,(H!1H!3H9G<:HH!
H!HHHH!)r!   r>   r6   r>   )r?   r>   rA   r@   rB   r4   rC   zstr | Path | NonerD   r>   rE   z&Literal['strict', 'ignore', 'replace']rG   dict[str, Any] | Noner6   AsyncIterator[ClientSession])rL   r>   r0   r}   r1   floatrM   r   rG   r}   rO   McpHttpClientFactory | Noner2   r5   r6   r~   )rL   r>   r0   r}   r1   r   rM   r   rS   boolrG   r}   rO   r   r2   r5   r6   r~   )rL   r>   rG   r}   r6   r~   )rz   
Connectionro   z_MCPCallbacks | Noner6   r~   );r:   
__future__r   loggingr   re
contextlibr   datetimer   typingr   r   r   r	   mcpr
   r   mcp.client.sser   mcp.client.stdior   mcp.client.streamable_httpr   typing_extensionsr   r   collections.abcr   pathlibr   httpx langchain_mcp_adapters.callbacksr   	getLoggerr7   rY   compiler   r"   r&   DEFAULT_ENCODINGr'   rI   DEFAULT_HTTP_TIMEOUTDEFAULT_SSE_READ_TIMEOUTDEFAULT_STREAMABLE_HTTP_TIMEOUT(DEFAULT_STREAMABLE_HTTP_SSE_READ_TIMEOUTr,   r<   rK   rR   rU   r   rb   re   rh   rn   r|   r.   r   r   <module>r      s   #  	 	 *  8 8 4 % ) < 4->			8	$,- =
W <=  7?  4 ? ! "+B"7 +4V+D (8 ,,Ei ,E^ 7I  7F7y 7>	D) 	D m#&>>ATT 
 
 "&!$ 	',0:: : 
	:
 
: :: *: ": :z  &*)6,08<"$	$ #$ 	$
 $ *$ 6$ $ "$ $N  &*8"J#,08<",	, #, 	,
  , , *, 6, , ", ,^  -1	 * "	 D EIGG.BG!G Gr   