
    i                        d dl Z d dlZd dlZd dlmZmZ d dlm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 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  ej8                  e      Z G d de      Z G d de      Z y)    N)AnyOptional)AsyncExitStack)cached_property)MCPAuthException)MCPClientBase)OAuthParamsAsyncOAuth2Client)MemoryObjectReceiveStreamMemoryObjectSendStream)
sse_client)SessionMessage)OAuth2Token)	BaseModelc                   V    e Zd ZU dZeed<   dZeeee	f      ed<   dZ
eed<   dZeed<   y)	SSEServerParamsz6Parameters required for a MCPClient with SSE transporturlNheaders   timeouti,  sse_read_timeout)__name__
__module____qualname____doc__str__annotations__r   r   dictr   r   floatr        U/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/mistralai/extra/mcp/sse.pyr   r      s6    @	H(,GXd38n%,GU$e$r!   r   c            
       :    e Zd ZU dZee   ed<   eed<   	 	 	 ddedee   dee   dee	   f fd	Z
ed
efd       ZdefdZded
eeef   fdZdededed
e	fdZd Zde	d
dfdZd
eeef   fdZd
efdZded
eeej4                  eef      ee   f   fdZ xZS )MCPClientSSEaL  MCP client that uses sse for communication.

    The client provides authentication for OAuth2 protocol following the current MCP authorization spec:
    https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization.

    This is possibly going to change in the future since the protocol has ongoing discussions.
    _oauth_params_sse_paramsN
sse_paramsnameoauth_params
auth_tokenc                 P    t         |   |       || _        || _        || _        y )N)r(   )super__init__r&   r%   _auth_token)selfr'   r(   r)   r*   	__class__s        r"   r-   zMCPClientSSE.__init__/   s-     	d#%4@2<r!   returnc                 L    | j                   j                  j                  d      S )Nz/sse)r&   r   rstrip)r/   s    r"   base_urlzMCPClientSSE.base_url;   s    ##**622r!   c                 n    | j                   "t        j                  d| j                          || _         y)z/Update the oauth params and client accordingly.Nz$Overriding current oauth params for )r%   loggerwarning_name)r/   r)   s     r"   set_oauth_paramszMCPClientSSE.set_oauth_params?   s.    )NNA$**NO)r!   redirect_urlc                    K   | j                   t        d      t        j                  | j                         }|j	                  | j                   j
                  j                  |      \  }}||fS w)z<Create the authorization url for client to start oauth flow.zmCan't generate an authorization url without oauth_params being set, make sure the oauth params have been set.)redirect_uri)r%   r   r
   from_oauth_paramscreate_authorization_urlschemeauthorization_url)r/   r:   oauth_clientauth_urlstates        r"   get_auth_url_and_statez#MCPClientSSE.get_auth_url_and_stateE   sy     %"<  )::4;M;MN&??%%77l @ 
% s   A/A1authorization_responserC   c                    K   | j                   t        d      t        j                  | j                         }|j	                  | j                   j
                  j                  ||ddi|       d{   }|S 7 w)z/Fetch the authentication token from the server.NzGCan't fetch a token without oauth_params, make sure they have been set.Content-Type!application/x-www-form-urlencoded)r   rE   r<   r   rC   )r%   r   r
   r=   fetch_tokenr?   	token_url)r/   rE   r:   rC   rA   oauth_tokens         r"   get_token_from_auth_responsez)MCPClientSSE.get_token_from_auth_responseR   s      %"Y  )::4;M;MN(44""))33#9%#%HI 5 
 
 
s   A0A;2A93A;c                   K   | j                    | j                   j                  j                  t        d      | j                  t        d      t        j                  | j                         }|j                  | j                   j                  j                  | j                  d   ddi       d{   }| j                  |       y7 w)zRefresh an expired token.NzUCan't refresh a token without a refresh url make sure the oauth params have been set.z]Can't refresh a token without a refresh token, use the `set_auth_token` to add a OAuth2Token.refresh_tokenrG   rH   )r   rN   r   )	r%   r?   refresh_urlr   r.   r
   r=   rN   set_auth_token)r/   rA   rK   s      r"   refresh_auth_tokenzMCPClientSSE.refresh_auth_tokeng   s     %););)B)B)N)N)V"g  #"o  )::4;M;MN(66""))55**?;#%HI 7 
 

 	K(
s   B2C4C5Ctokenc                     || _         y)z3Register the authentication token with this client.N)r.   )r/   rR   s     r"   rP   zMCPClientSSE.set_auth_tokeny   s
     r!   c                     i }| j                   j                  r|| j                   j                  z  }| j                  rd| j                  d    |d<   |S )NzBearer access_tokenAuthorization)r&   r   r.   )r/   r   s     r"   _format_headerszMCPClientSSE._format_headers}   sW    "$##t''///G)01A1A.1Q0R'SGO$r!   c                    K   t        j                  | j                  j                  | j	                         | j                  j
                        }|j                  t        j                  j                  k(  S w)zKCheck if the client requires authentication to communicate with the server.)r   r   )
httpxgetr&   r   rW   r   status_codehttp
HTTPStatusUNAUTHORIZED)r/   responses     r"   requires_authzMCPClientSSE.requires_auth   s[     99  ((*$$,,

 ##t'C'CCCs   A6A8
exit_stackc                   K   	 |j                  t        | j                  j                  | j	                         | j                  j
                  | j                  j                               d {   S 7 # t        $ ru}t        |t        j                        rU|j                  j                  t        j                  j                  k(  r$| j                   t#        d      |t#        d      | d }~ww xY ww)N)r   r   r   r   z4Authentication required but no auth params provided.zAuthentication required.)enter_async_contextr   r&   r   rW   r   r   	Exception
isinstancerY   HTTPStatusErrorr_   r[   r\   r]   r^   r%   r   )r/   ra   es      r"   _get_transportzMCPClientSSE._get_transport   s     	#77((,, 002 ,,44%)%5%5%F%F	     	!U223::))T__-I-II))1.R ! ++EFAM	s<   C7A+A6 /A40A6 3C74A6 6	C4?A0C//C44C7)NNN) r   r   r   r   r   r	   r   r   r   r   r-   r   r4   r9   tuplerD   rL   rQ   rP   r   rW   boolr`   r   r   typingUnionr   rd   r   rh   __classcell__)r0   s   @r"   r$   r$   #   sC    K((  
 #.2,0
=#
= sm
= {+	
=
 [)
= 3# 3 3*[ * sCx  #  	
 
*)$!K !D !c3h DT D(	!&,,~y/H"IJ~.	0
r!   r$   )!r\   loggingrk   r   r   
contextlibr   	functoolsr   rY   mistralai.extra.exceptionsr   mistralai.extra.mcp.baser   mistralai.extra.mcp.authr	   r
   anyio.streams.memoryr   r   mcp.client.sser   mcp.shared.messager   authlib.oauth2.rfc6749r   mistralai.typesr   	getLoggerr   r6   r   r$   r    r!   r"   <module>rz      sc         % %  7 D R % - . %			8	$%i %B= Br!   