
    j
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j"        e#          Z$ ej%        d          Z&	 dOd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'dPd5            Z6ede,e-dddd6dQd@            Z7ede.e/dAddddBdRdF            Z8eddGdSdH            Z9eddIdTdN            Z:dS )UzSession 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\$\{([^}]+)\}valuestrreturnc                :    t                               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                            |                     d          |                     d                    S )N   r   )osenvirongetgroup)ms    C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\langchain_mcp_adapters/sessions.py<lambda>z"_expand_env_vars.<locals>.<lambda>.   s*    
qwwqzz1771::(N(N     )_BRACED_VAR_REsub)r   s    r   _expand_env_varsr$   $   s     NNPUVVVr!   )strictignorereplacezutf-8r%   EncodingErrorHandlerDEFAULT_ENCODING_ERROR_HANDLER   i,     )secondsc                  "    e Zd ZdZ	 	 	 dddZdS )McpHttpClientFactoryzFProtocol for creating httpx.AsyncClient instances for MCP connections.Nheadersdict[str, str] | Nonetimeouthttpx.Timeout | Noneauthhttpx.Auth | Noner   httpx.AsyncClientc                    dS )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 )selfr/   r1   r3   s       r   __call__zMcpHttpClientFactory.__call__@   s	      	r!   )NNN)r/   r0   r1   r2   r3   r4   r   r5   )__name__
__module____qualname____doc__r9   r7   r!   r   r.   r.   =   s>        PP *.(,"&	      r!   r.   c                  p    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S )StdioConnectionz=Configuration for stdio transport connections to MCP servers.zLiteral['stdio']	transportr   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__r7   r!   r   r?   r?   S   s         GGLLL4OOO;++++
 ('''A
 >=== 7666DDr!   r?   c                  p    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S )SSEConnectionzHConfiguration for Server-Sent Events (SSE) transport connections to MCP.zLiteral['sse']r@   r   urlrH   r/   zNotRequired[float]r1   sse_read_timeoutrI   (NotRequired[McpHttpClientFactory | None]httpx_client_factoryNotRequired[httpx.Auth]r3   NrJ   r7   r!   r   rM   rM      s         RRHHH4////3 )((( 7666DBBBB:!!!!66r!   rM   c                  |    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<   dS )StreamableHttpConnectionz7Connection configuration for Streamable HTTP transport.zLiteral['streamable_http']r@   r   rN   rH   r/   zNotRequired[timedelta]r1   rO   zNotRequired[bool]terminate_on_closerI   rP   rQ   rR   r3   NrJ   r7   r!   r   rT   rT      s         AA))))HHH0/////####,,,,> *)))46666DBBBB:!!!!66r!   rT   c                  4    e Zd ZU dZded<   ded<   	 ded<   dS )	WebsocketConnectionzAConfiguration for WebSocket transport connections to MCP servers.zLiteral['websocket']r@   r   rN   rH   rI   NrJ   r7   r!   r   rW   rW      s<         KK####HHH:6666CCr!   rW   )rD   rE   rF   rG   rI   rA   rC   rB   rD   r0   rE   str | Path | NonerF   rG   &Literal['strict', 'ignore', 'replace']rI   dict[str, Any] | NoneAsyncIterator[ClientSession]c                 K   |d |                                 D             nd}|P|                                 D ];\  }}	t                              |	          rt                              d||	           <t          | |||||          }
t          |
          4 d{V 	 \  }}t          ||fi |pi 4 d{V 	 }|W V  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 )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.
    Nc                4    i | ]\  }}|t          |          S r7   )r$   .0kvs      r   
<dictcomp>z)_create_stdio_session.<locals>.<dictcomp>   s'    888DAqQ888r!   z2env[%r] contains unexpanded variable reference: %r)rA   rC   rD   rE   rF   rG   )itemsr"   searchloggerwarningr   r   r
   )rA   rC   rD   rE   rF   rG   rI   resolved_envr`   ra   server_paramsreadwritesessions                 r   _create_stdio_sessionrl      se     J =@O88CIIKK8888QU   &&(( 	 	DAq$$Q'' H!Q   *5  M 	]##       '4edE<<n&:<<       @G	                                                        s6   "C9=CC9
C	C9"C	#C99
DD)r/   r1   rO   rI   rQ   r3   rN   r/   r1   floatrO   rQ   McpHttpClientFactory | Noner3   r4   c                 K   i }|||d<   t          | |||fd|i|4 d{V 	 \  }}	t          ||	fi |pi 4 d{V 	 }
|
W V  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 )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.
    NrQ   r3   )r   r
   )rN   r/   r1   rO   rI   rQ   r3   kwargsri   rj   rk   s              r   _create_sse_sessionrq     s     4 F')=%& 	3*:PPPPP       U
dE<<n&:<<       
 AH                                                        s5   A< AA<
A"	"A<%A"	&A<<
B	BT)r/   r1   rO   rU   rI   rQ   r3   r   rU   boolc               "  K   i }|||d<   t          | ||||fd|i|4 d{V 	 \  }	}
}t          |	|
fi |pi 4 d{V 	 }|W V  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 )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.
    NrQ   r3   )r   r
   )rN   r/   r1   rO   rU   rI   rQ   r3   rp   ri   rj   _rk   s                r   _create_streamable_http_sessionru   ;  s     : F')=%& 		
 	
 	
 	
 	
        dE1dE<<n&:<<        AH                                                        s5   A>AA>
A$	$A>'A$	(A>>
BB)rI   c               N  K   	 ddl m} n # t          $ r d}t          |          dw xY w ||           4 d{V 	 \  }}t          ||fi |pi 4 d{V 	 }|W V  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 )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.websocketrw   ImportErrorr
   )rN   rI   rw   msgri   rj   rk   s          r   _create_websocket_sessionr{   k  s
     $)9999999 ) ) )@ 	
 #D() 	       !.$dE<<n&:<<       @G	                                                        s=    (BA0B0
A:	:B=A:	>B
B!B)mcp_callbacks
connection
Connectionr|   _MCPCallbacks | Nonec              &  K   d| vrd}t          |          | d         }d |                                 D             }|G|                    di           |d<   |j        |j        |d         d<   |j        |j        |d         d<   |dk    rSd	|vrd
}t          |          t          di |4 d{V }|W V  ddd          d{V  dS # 1 d{V swxY w Y   dS |dv rSd	|vrd}t          |          t          di |4 d{V }|W V  ddd          d{V  dS # 1 d{V swxY w Y   dS |dk    rhd|vrd}t          |          d|vrd}t          |          t          di |4 d{V }|W V  ddd          d{V  dS # 1 d{V swxY w Y   dS |dk    rSd	|vrd}t          |          t          di |4 d{V }|W V  ddd          d{V  dS # 1 d{V swxY w Y   dS d| d}t          |          )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.c                &    i | ]\  }}|d k    ||S )r@   r7   r^   s      r   rb   z"create_session.<locals>.<dictcomp>  s(    FFFtq!Q+5E5Ea5E5E5Er!   NrI   logging_callbackelicitation_callbacksserN   z.'url' parameter is required for SSE connection>   streamable-httphttpstreamable_httpz:'url' parameter is required for Streamable HTTP connectionstdiorA   z4'command' parameter is required for stdio connectionrC   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'r7   )	
ValueErrorrc   r   r   r   rq   ru   rl   r{   )r}   r|   rz   r@   paramsrk   s         r   create_sessionr     s     " *$$Y 	 oo;'IFFz//11FFFF #)::.>#C#C )5. #$%78 -92 #$%;< EBCS//!&0000 	 	 	 	 	 	 	GMMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 		D	D	DNCS//!2<<V<< 	 	 	 	 	 	 	MMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 		g		F""HCS//!ECS//!(22622 	 	 	 	 	 	 	gMMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 		k	!	!HCS//!,66v66 	 	 	 	 	 	 	'MMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	Ci C C C 	 oosH   4C
CCD$$
D.1D.9F
FFG++
G58G5)r   r   r   r   )rA   r   rC   rB   rD   r0   rE   rX   rF   r   rG   rY   rI   rZ   r   r[   )rN   r   r/   rZ   r1   rm   rO   rm   rI   rZ   rQ   rn   r3   r4   r   r[   )rN   r   r/   rZ   r1   r   rO   r   rU   rr   rI   rZ   rQ   rn   r3   r4   r   r[   )rN   r   rI   rZ   r   r[   )r}   r~   r|   r   r   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   	getLoggerr:   re   compiler"   r$   r(   DEFAULT_ENCODINGr)   rK   DEFAULT_HTTP_TIMEOUTDEFAULT_SSE_READ_TIMEOUTDEFAULT_STREAMABLE_HTTP_TIMEOUT(DEFAULT_STREAMABLE_HTTP_SSE_READ_TIMEOUTr.   r?   rM   rT   rW   r~   rl   rq   ru   r{   r   r7   r!   r   <module>r      s     # " " " " "  				 				 * * * * * *       8 8 8 8 8 8 8 8 8 8 8 8 4 4 4 4 4 4 4 4 % % % % % % ) ) ) ) ) ) < < < < < < 4 4 4 4 4 4 4 4 ?------LLL>>>>>>		8	$	$,-- =
W 
W 
W 
W <=  7?  ? ? ? ? ! "+)B"7"7"7 +49V+D+D+D (    8   ,,E ,E ,E ,E ,Ei ,E ,E ,E^ 7  7  7  7  7I  7  7  7F7 7 7 7 7y 7 7 7>	D 	D 	D 	D 	D) 	D 	D 	D m#&>>ATT 
 
 "&!$ 	',0: : : : : :z  &*)6,08<"$ $ $ $ $ $N  &*8"J#,08<", , , , , ,^  -1     D EIG G G G G G G Gr!   