
    6?i3              	      z   U d Z ddlm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ed   ZdZdZ de!d<   dZ"dZ# ed      Z$ ed      Z% G d de      Z& G d de      Z' G d de      Z( G d de      Z) G d d e      Z*e'e(z  e)z  e*z  Z+eddee dd!	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d+d"       Z,ede"e#dddd#	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d,d$       Z-ede$e%d%dddd&	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d-d'       Z.edd(	 	 	 	 	 d.d)       Z/ed/d*       Z0y)0zSession 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)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       a/opt/tws/coop-23/cliente-mcp/venv/lib/python3.12/site-packages/langchain_mcp_adapters/sessions.py__call__zMcpHttpClientFactory.__call__)   s      	    )NNN)r    dict[str, str] | Noner!   zhttpx.Timeout | Noner"   httpx.Auth | Nonereturnzhttpx.AsyncClient)__name__
__module____qualname____doc__r$   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r)   r*   r+   r,   __annotations__r   r%   r#   r.   r.   <   sP    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)SSEConnectionzPConfiguration for Server-Sent Events (SSE) transport connections to MCP servers.zLiteral['sse']r/   r0   urlr8   r    zNotRequired[float]r!   sse_read_timeoutr9   (NotRequired[McpHttpClientFactory | None]httpx_client_factoryNotRequired[httpx.Auth]r"   Nr:   r   r%   r#   r=   r=   a   sQ    Z	H4//3 )( 76DBB:
!!6r%   r=   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/   r0   r>   r8   r    zNotRequired[timedelta]r!   r?   zNotRequired[bool]terminate_on_closer9   r@   rA   rB   r"   Nr:   r   r%   r#   rD   rD      sV    A))	H0///##,,> *)466DBB:
!!6r%   rD   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/   r0   r>   r8   r9   Nr:   r   r%   r#   rG   rG      s    K##	H:66Cr%   rG   )r4   r5   r6   r7   r9   c                 K   |xs i }d|vr#t         j                  j                  dd      |d<   t        | |||||      }t	        |      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 stdio.

    Args:
        command: Command to execute.
        args: Arguments for the command.
        env: Environment variables for the command.
        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.
    PATH )r1   r3   r4   r5   r6   r7   N)osenvirongetr   r   r
   )r1   r3   r4   r5   r6   r7   r9   server_paramsreadwritesessions              r#   _create_stdio_sessionrR      s     8 )CSjjnnVR0F)5M 	]# '4edE<n&:< @G	             s   AC
BC
B5-B.B51B7B5BB5C
B3C
B5B5B0	$B'%B0	,B53C
5C;B><CC
)r    r!   r?   r9   rA   r"   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.
    NrA   r"   )r   r
   )r>   r    r!   r?   r9   rA   r"   kwargsrO   rP   rQ   s              r#   _create_sse_sessionrU      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)r    r!   r?   rE   r9   rA   r"   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.
    NrA   r"   )r   r
   )r>   r    r!   r?   rE   r9   rA   r"   rT   rO   rP   _rQ   s                r#   _create_streamable_http_sessionrX     s     8 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)r9   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 with: 'pip install mcp[ws]' or 'pip install websockets'N)mcp.client.websocketrZ   ImportErrorr
   )r>   r9   rZ   msgrO   rP   rQ   s          r#   _create_websocket_sessionr^   :  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+c                 K   d| vrd}t        |      | d   }| j                         D ci c]  \  }}|dk7  s|| }}}|dk(  r;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	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)a4  Create a new session to an MCP server.

    Args:
        connection: Connection config to use to connect to the server

    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', 'streamable_http'. Please refer to the langchain-mcp-adapters documentation for more details.sser>   z.'url' parameter is required for SSE connectionNstreamable_httpz:'url' parameter is required for Streamable HTTP connectionstdior1   z4'command' parameter is required for stdio connectionr3   z1'args' parameter is required for stdio connection	websocketz4'url' parameter is required for Websocket connectionzUnsupported transport: z@. Must be one of: 'stdio', 'sse', 'websocket', 'streamable_http'r   )
ValueErroritemsrU   rX   rR   r^   )
connectionr]   r/   kvparamsrQ   s          r#   create_sessionrj   ]  s8     *$Y 	 o;'I)//1Ftq!Q+5EadFFFEBCS/!&00 	 	GM	 	 		'	'NCS/!2<V< 	 	M	 	 		g	F"HCS/!ECS/!(262 	 	gM	 	 		k	!HCS/!,6v6 	 	'M	 	 	 &i[ 1M N 	 oE G	 	 	 	 		 	 	 	 		 	 	 	 		 	 	 	 	s  *GE$E$(G'E*(G+E/1G<E-=*G'F(G+F1G<F=;G8F9G<F!GF*G8F69G<F:GF8G-G/F5E86F=GGFFFGG!F3'F*(F3/G8G:G GGG)r1   r0   r3   r2   r4   r&   r5   zstr | Path | Noner6   r0   r7   z&Literal['strict', 'ignore', 'replace']r9   dict[str, Any] | Noner(   AsyncIterator[ClientSession])r>   r0   r    rk   r!   floatr?   rm   r9   rk   rA   McpHttpClientFactory | Noner"   r'   r(   rl   )r>   r0   r    rk   r!   r   r?   r   rE   boolr9   rk   rA   rn   r"   r'   r(   rl   )r>   r0   r9   rk   r(   rl   )rf   
Connectionr(   rl   )1r,   
__future__r   rK   
contextlibr   datetimer   typingr   r   r   r	   mcpr
   r   mcp.client.sser   mcp.client.stdior   mcp.client.streamable_httpr   typing_extensionsr   r   collections.abcr   pathlibr   httpxr   DEFAULT_ENCODINGr   r;   DEFAULT_HTTP_TIMEOUTDEFAULT_SSE_READ_TIMEOUTDEFAULT_STREAMABLE_HTTP_TIMEOUT(DEFAULT_STREAMABLE_HTTP_SSE_READ_TIMEOUTr   r.   r=   rD   rG   rp   rR   rU   rX   r^   rj   r   r%   r#   <module>r      s   # 	 *  8 8 4 % ) < 4-<=  7?  4 ? ! "+B"7 +4V+D (8 ,"Ei "EJ 7I  7F7y 7>	D) 	D },/GGJ]]
 
 "&!$Ec,0-- - 
	-
 
- - C- *- "- -`  &*)6,08<"$	$ #$ 	$
 $ *$ 6$ $ "$ $N  &*8"J#,08<"+	+ #+ 	+
  + + *+ 6+ + "+ +\  -1	 * "	 D 9 9r%   