
    {h27                        U d Z ddlZddlZddlm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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 ddlmZ ddlmZ  G d de      Z G d de      Zeez  ez  Zeed<    G d d      Zy)a*  
SessionGroup concurrently manages multiple MCP session connections.

Tools, resources, and prompts are aggregated across servers. Servers may
be connected to or disconnected from at any point after initialization.

This abstractions can handle naming collisions using a custom user-provided
hook.
    N)Callable)	timedelta)TracebackType)Any	TypeAlias)	BaseModel)Self)types)
sse_client)StdioServerParameters)streamablehttp_client)McpErrorc                   V    e Zd ZU dZeed<   dZeeef   dz  ed<   dZ	e
ed<   dZe
ed<   y)	SseServerParametersz(Parameters for intializing a sse_client.urlNheaders   timeout,  sse_read_timeout)__name__
__module____qualname____doc__str__annotations__r   dictr   r   floatr        Y/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/mcp/client/session_group.pyr   r      s>    2 
H &*GT#s(^d") GU %e$r    r   c                       e Zd ZU dZeed<   dZeeef   dz  ed<    e	d      Z
e	ed<    e	d      Ze	ed	<   d
Zeed<   y)StreamableHttpParametersz3Parameters for intializing a streamablehttp_client.r   Nr      )secondsr   r   r   Tterminate_on_close)r   r   r   r   r   r   r   r   r   r   r   r   r&   boolr   r    r!   r#   r#   .   sU    = 
H &*GT#s(^d") #2.GY. #,F";i;  $#r    r#   ServerParametersc            	       B   e Zd ZU dZ G d de      Zeeej                  f   e
d<   eeej                  f   e
d<   eeej                  f   e
d<   eej                  ef   e
d<   eeej                  f   e
d<   ej                   e
d	<   eej                  ej                   f   e
d
<   eeej$                  gef   Zee
d<   edz  e
d<   	 	 d'dej                   dz  dedz  ddfdZdefdZdee   dz  dedz  dedz  dedz  fdZedeej                     fd       Zedeeej                  f   fd       Z edeeej                  f   fd       Z!edeeej                  f   fd       Z"dedeee#f   dejH                  fdZ%dej                  ddfdZ&d ej$                  dej                  dej                  fd!Z'd"e(dej                  fd#Z)d"e(de*ej$                  ej                  f   fd$Z+d ej$                  dej                  ddfd%Z,ded ej$                  defd&Z-y)(ClientSessionGroupa  Client for managing connections to multiple MCP servers.

    This class is responsible for encapsulating management of server connections.
    It aggregates tools, resources, and prompts from all connected servers.

    For auxiliary handlers, such as resource subscription, this is delegated to
    the client and can be accessed via the session.

    Example Usage:
        name_fn = lambda name, server_info: f"{(server_info.name)}_{name}"
        async with ClientSessionGroup(component_name_hook=name_fn) as group:
            for server_params in server_params:
                await group.connect_to_server(server_param)
            ...

    c                   l    e Zd ZU dZ e       Zee   ed<    e       Zee   ed<    e       Z	ee   ed<   y)"ClientSessionGroup._ComponentNamesz*Used for reverse index to find components.prompts	resourcestoolsN)
r   r   r   r   setr-   r   r   r.   r/   r   r    r!   _ComponentNamesr,   V   s5    8ES!!e	3s8#%s3xr    r1   _prompts
_resources_tools	_sessions_tool_to_session_exit_stack_session_exit_stacks_ComponentNameHookN_component_name_hook
exit_stackcomponent_name_hookreturnc                     i | _         i | _        i | _        i | _        i | _        |!t        j                         | _        d| _        n|| _        d| _        i | _	        || _
        y)zInitializes the MCP client.NTF)r4   r3   r2   r5   r6   
contextlibAsyncExitStackr7   _owns_exit_stackr8   r:   )selfr;   r<   s      r!   __init__zClientSessionGroup.__init__n   sg      ")88:D$(D!)D$)D!$&!$7!r    c                 n   K   | j                   r"| j                  j                          d {    | S 7 wN)rA   r7   
__aenter__rB   s    r!   rF   zClientSessionGroup.__aenter__   s1       ""--/// 0s   *535	_exc_type_exc_val_exc_tbc                 l  K   | j                   r"| j                  j                          d{    t        j                         4 d{   }| j
                  j                         D ]  }|j                  |j                          ddd      d{    y7 l7 Q7 	# 1 d{  7  sw Y   yxY ww)z?Closes session exit stacks and main exit stack upon completion.N)rA   r7   acloseanyiocreate_task_groupr8   values
start_soon)rB   rH   rI   rJ   tgr;   s         r!   	__aexit__zClientSessionGroup.__aexit__   s        ""))+++ **, 	1 	1"77>>@ 1
j//01	1 	1 	1 ,	1 	1 	1 	1 	1sW   *B4BB4	B
B4;BB4BB4B4B4B1%B(&B1-B4c                 H    t        | j                  j                               S )z+Returns the list of sessions being managed.)listr5   keysrG   s    r!   sessionszClientSessionGroup.sessions   s     DNN'')**r    c                     | j                   S )z8Returns the prompts as a dictionary of names to prompts.)r2   rG   s    r!   r-   zClientSessionGroup.prompts   s     }}r    c                     | j                   S )z<Returns the resources as a dictionary of names to resources.)r3   rG   s    r!   r.   zClientSessionGroup.resources   s     r    c                     | j                   S )z4Returns the tools as a dictionary of names to tools.)r4   rG   s    r!   r/   zClientSessionGroup.tools   s     {{r    nameargsc                    K   | j                   |   }| j                  |   j                  }|j                  ||       d{   S 7 w)z-Executes a tool given its name and arguments.N)r6   r/   rZ   	call_tool)rB   rZ   r[   sessionsession_tool_names        r!   r]   zClientSessionGroup.call_tool   sE     ''- JJt,11&&'8$????s   >A AAr^   c                   K   || j                   v }|| j                  v }|s0|s.t        t        j                  t        j
                  d            |r| j                   j                  |      }|j                  D ]  }|| j                  v s| j                  |=   |j                  D ]  }|| j                  v s| j                  |=   |j                  D ]9  }|| j                  v r| j                  |= || j                  v s-| j                  |= ; |r4| j                  j                  |      }|j                          d{    yy7 w)z%Disconnects from a single MCP server.z8Provided session is not managed or already disconnected.codemessageN)r5   r8   r   r
   	ErrorDataINVALID_PARAMSpopr-   r2   r.   r3   r/   r4   r6   rL   )rB   r^   session_known_for_componentssession_known_for_stackcomponent_namesrZ   session_stack_to_closes          r!   disconnect_from_serverz)ClientSessionGroup.disconnect_from_server   sK     (/$..'@$")T-F-F"F+4K--V  ("nn009O (// ,4==(d+, (11 .4??*-. (-- 44;;&D)4000--d3	4 #%)%>%>%B%B7%K"(//111 #1s%   B	E	,E	9AE	?E	 EE	server_infoc                 F   K   | j                  ||       d{    |S 7 wz Connects to a single MCP server.N)_aggregate_components)rB   rl   r^   s      r!   connect_with_sessionz'ClientSessionGroup.connect_with_session   s(      ((g>>> 	?s   !!server_paramsc                 ~   K   | j                  |       d{   \  }}| j                  ||       d{   S 7 !7 wrn   )_establish_sessionrp   )rB   rq   rl   r^   s       r!   connect_to_serverz$ClientSessionGroup.connect_to_server   s@     
 &*%<%<]%KKW..{GDDD  LDs   =9=;==c                   K   t        j                         }	 t        |t              r2t	        j
                  |      }|j                  |       d{   \  }}nt        |t              rTt        |j                  |j                  |j                  |j                        }|j                  |       d{   \  }}n_t        |j                  |j                  |j                  |j                  |j                        }|j                  |       d{   \  }}}|j                  t	        j                  ||             d{   }|j!                          d{   }|| j"                  |<   | j$                  j                  |       d{    |j&                  |fS 7 Q7 7 7 c7 M7 # t(        $ r |j+                          d{  7    w xY ww)z,Establish a client session to an MCP server.N)r   r   r   r   )r   r   r   r   r&   )r?   r@   
isinstancer   mcpstdio_cliententer_async_contextr   r   r   r   r   r   r   r&   ClientSession
initializer8   r7   
serverInfo	ExceptionrL   )	rB   rq   session_stackclientreadwrite_r^   results	            r!   rs   z%ClientSessionGroup._establish_session   s    
 #113&	-)>?))-8$1$E$Ef$MMeM+>?#%)))11)11%2%C%C	 %2$E$Ef$MMe.%)))11)11%2%C%C'4'G'G (5'H'H'P!PeQ)==c>O>OPTV[>\]]G"--//F 2?D%%g. ""66}EEE$$g--; N N "Q]/ F  	  &&(((		s   G9F/ F"A#F/ 5F%6AF/ F'0F/ F)F/ F+1F/ F-F/ !G"F/ %F/ 'F/ )F/ +F/ -F/ /GGGGc                 <  K   | j                         }i }i }i }i }	 |j                          d{   j                  }|D ]>  }	| j                  |	j                  |      }
|	||
<   |j                  j                  |
       @ 	 	 |j                          d{   j                  }|D ]>  }| j                  |j                  |      }
|||
<   |j                  j                  |
       @ 	 	 |j                          d{   j                  }|D ]C  }| j                  |j                  |      }
|||
<   |||
<   |j                  j                  |
       E 	 t        |||f      s| j                  |= |j                         | j                   j                         z  }|r1t        t#        j$                  t"        j&                  | d            |j                         | j(                  j                         z  }|r1t        t#        j$                  t"        j&                  | d            |j                         | j*                  j                         z  }|r1t        t#        j$                  t"        j&                  | d            || j,                  |<   | j                   j/                  |       | j(                  j/                  |       | j*                  j/                  |       | j0                  j/                  |       y7 # t        $ r#}t        j                  d|        Y d}~d}~ww xY w7 # t        $ r#}t        j                  d|        Y d}~yd}~ww xY w7 m# t        $ r#}t        j                  d|        Y d}~?d}~ww xY ww)	z>Aggregates prompts, resources, and tools from a given session.NzCould not fetch prompts: zCould not fetch resources: zCould not fetch tools: z  already exist in group prompts.ra   z" already exist in group resources.z already exist in group tools.)r1   list_promptsr-   _component_namerZ   addr   loggingwarninglist_resourcesr.   
list_toolsr/   anyr8   rU   r2   r
   rd   re   r3   r4   r5   updater6   )rB   rl   r^   ri   prompts_tempresources_temp
tools_temptool_to_session_tempr-   promptrZ   errr.   resourcer/   toolmatching_promptsmatching_resourcesmatching_toolss                      r!   ro   z(ClientSessionGroup._aggregate_components  sU     ..0 1346,.
=?	?$1133<<G! 2++FKKE%+T"''++D12	A&5577BBI% 4++HMM;G'/t$))--d34	="--//66E 0++DII{C#'
4 -4$T*%%))$/	0 L.*=>))'2 (,,.1C1C1EE--/00PQ  ,002T__5I5I5KK--122TU  $*T[[-=-=-??---..LM  #2w\*~.:&$$%9:C 4
  	?OO7u=>>	?
 8
  	AOO9#?@@	A
 0  	=OO5cU;<<	=s   NL	 LAL	 NL; L8AL; (N*M- =M*>AM- F2NL	 		L5L0*N0L55N8L; ;	M'M"N"M''N*M- -	N6NNNNc                 B    | j                   r| j                  ||      S |S rE   )r:   )rB   rZ   rl   s      r!   r   z"ClientSessionGroup._component_namek  s#    $$,,T;??r    )NN).r   r   r   r   r   r1   r   r   r
   Promptr   ResourceToolrw   rz   r?   r@   r   Implementationr9   r   rC   r	   rF   typeBaseExceptionr   r'   rR   propertyrT   rV   r-   r.   r/   r   CallToolResultr]   rk   rp   r(   rt   tuplers   ro   r   r   r    r!   r*   r*   D   s	   " )   3$%%S%..())ejj!! C%%6773 1 1122***s00*2K2KKLL
 %-c53G3G-H#-M$N	N,t33 8<9=8--48 0$68 
	8,$ 1&-1  $&1 %	1
 
1" +$s001 + + c5<</0   4U^^ 34   tCO,  @C @tCH~ @%BVBV @#2C4E4E #2$ #2J //:=:K:K			E'E 
		E,-,	u##S%6%66	7,\R;u7K7K R;VYVgVg R;lp R;hC e6J6J s r    r*   )r   r?   r   collections.abcr   datetimer   r
   r   typingr   r   rM   pydanticr   typing_extensionsr	   rw   mcp.client.sser   mcp.client.stdior   mcp.client.streamable_httpr   mcp.shared.exceptionsr   r   r#   r(   r   r*   r   r    r!   <module>r      sv      $   !   " 
  % 2 < *%) % $y $& 46IILdd ) dj jr    