
    {h3              
          d Z ddlmZ ddlmZm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mZ ddlmZmZ dd	lmZmZ dd
lmZ  G d de      Z edd      Zeej6                  ej8                  f   ej:                  z  ez  Z G d deej@                  ejB                  ej8                  ej6                  ej:                  f         Z"y)a  
ServerSession Module

This module provides the ServerSession class, which manages communication between the
server and client in the MCP (Model Context Protocol) framework. It is most commonly
used in MCP servers to interact with the client.

Common usage pattern:
```
    server = Server(name)

    @server.call_tool()
    async def handle_tool_call(ctx: RequestContext, arguments: dict[str, Any]) -> Any:
        # Check client capabilities before proceeding
        if ctx.session.check_client_capability(
            types.ClientCapabilities(experimental={"advanced_tools": dict()})
        ):
            # Perform advanced tool operations
            result = await perform_advanced_tool_operation(arguments)
        else:
            # Fall back to basic tool operations
            result = await perform_basic_tool_operation(arguments)

        return result

    @server.list_prompts()
    async def handle_list_prompts(ctx: RequestContext) -> list[types.Prompt]:
        # Access session for any necessary checks or operations
        if ctx.session.client_params:
            # Customize prompts based on client initialization parameters
            return generate_custom_prompts(ctx.session.client_params)
        else:
            return default_prompts
```

The ServerSession class is typically used internally by the Server class and should not
be instantiated directly by users of the MCP framework.
    )Enum)AnyTypeVarN)MemoryObjectReceiveStreamMemoryObjectSendStream)AnyUrl)InitializationOptions)ServerMessageMetadataSessionMessage)BaseSessionRequestResponder)SUPPORTED_PROTOCOL_VERSIONSc                       e Zd ZdZdZdZy)InitializationState         N)__name__
__module____qualname__NotInitializedInitializingInitialized     S/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/mcp/server/session.pyr   r   :   s    NLKr   r   ServerSessionTServerSession)boundc                       e Zd ZU ej                  Zeed<   dZej                  dz  ed<   	 d2de
eez     dee   dededdf
 fd	Zedej                  dz  fd
       Zdej&                  defdZd3 fdZdeej.                  ej0                  f   fdZdej4                  ddfdZ	 	 d4dej8                  dededz  dej>                  dz  ddf
dZ de!ddfdZ"ddddddddde#ejH                     de%dedz  dejL                  dz  de'dz  de#e   dz  d e(eef   dz  d!ejR                  dz  dej>                  dz  dejT                  fd"Z+dejX                  fd#Z-	 d5d$ed%ej\                  dej>                  dz  dej^                  fd&Z0dejb                  fd'Z2	 	 	 d6d(ee%z  d)e'd*e'dz  d$edz  dedz  ddfd+Z3d3d,Z4d3d-Z5d3d.Z6d/e7ddfd0Z8ede
e7   fd1       Z9 xZ:S )7r   _initializedN_client_paramsread_streamwrite_streaminit_options	statelessreturnc                 N    t            ||t        j                  t        j                         |rt
        j                  nt
        j                   _        | _	        t        j                  t           d      \   _         _         j                  j!                   fd       y )Nr   c                  8     j                   j                         S N)_incoming_message_stream_readeracloseselfs   r   <lambda>z(ServerSession.__init__.<locals>.<lambda>c   s    T5Y5Y5`5`5b r   )super__init__typesClientRequestClientNotificationr   r   r   _initialization_state_init_optionsanyiocreate_memory_object_streamServerRequestResponder_incoming_message_stream_writerr+   _exit_stackpush_async_callback)r.   r#   r$   r%   r&   	__class__s   `    r   r1   zServerSession.__init__S   s     	lE4G4GIaIab/8++>Q>`>` 	" *UZUvUv"V

VR,d.R 	,,-bcr   c                     | j                   S r*   )r"   r-   s    r   client_paramszServerSession.client_paramse   s    """r   
capabilityc                    | j                   y| j                   j                  }|j                  :|j                  y|j                  j                  r|j                  j                  sy|j                  |j                  y|j
                  |j
                  y|j                  Q|j                  y|j                  j                         D ]'  \  }}||j                  vs|j                  |   |k7  s' y y)z3Check if the client supports a specific capability.FT)r"   capabilitiesrootslistChangedsamplingelicitationexperimentalitems)r.   r@   client_capsexp_key	exp_values        r   check_client_capabilityz%ServerSession.check_client_capabilityi   s    & ))66 '  (++K4E4E4Q4Q*##+!!-&&."".''/&0&=&=&C&C&E !"+":"::k>V>VW^>_cl>l ! r   c                    K   | j                   4 d {    t        | 	          d {    d d d       d {    y 7 +7 7 	# 1 d {  7  sw Y   y xY wwr*   )r:   r0   _receive_loop)r.   r=   s    r   rN   zServerSession._receive_loop   sT     77 	* 	*'')))	* 	* 	*)	* 	* 	* 	*sQ   AA AAAAAAAAAAAAA	responderc                   K   |j                   j                  t        j                  d x\  }|j                  }t
        j                  | _        || _        |5  |j                  t        j                  t        j                  |t        v r|nt        j                  | j                  j                  t        j                   | j                  j"                  | j                  j$                        | j                  j&                                     d {    d d d        y  	 | j                  t
        j(                  k7  rt+        d      y 7 8# 1 sw Y   y xY ww)N)params)nameversion)protocolVersionrB   
serverInfoinstructionsz3Received request before initialization was complete)requestrootr2   InitializeRequestrT   r   r   r5   r"   respondServerResultInitializeResultr   LATEST_PROTOCOL_VERSIONr6   rB   Implementationserver_nameserver_versionrV   r   RuntimeError)r.   rO   rQ   requested_versions       r   _received_requestzServerSession._received_request   s.    $$((7$*$:$:!-@-M-M*&,# #++**!22#48S#S 1B%*%B%B-1-?-?-L-L+0+?+?)-););)G)G,0,>,>,M,M," .2-?-?-L-L
   	 8( --1D1P1PP&'\]] Q! s1   AEB<EEE4EEEEnotificationc                   K   t         j                  j                          d {    |j                  t        j
                  d x\   t        j                  | _        y  	 | j                  t        j                  k7  rt        d      y 7 ew)Nr   z8Received notification before initialization was complete)
r7   lowlevel
checkpointrX   r2   InitializedNotificationr   r   r5   ra   )r.   rd   s     r   _received_notificationz$ServerSession._received_notification   ss     nn'')))..0-@-L-L* 1--1D1P1PP&'abb Q 	*s   "BB
A&Bleveldataloggerrelated_request_idc                    K   | j                  t        j                  t        j                  dt        j                  |||                  |       d{    y7 w)z Send a log message notification.znotifications/message)rj   rk   rl   methodrQ   N)send_notificationr2   ServerNotificationLoggingMessageNotification LoggingMessageNotificationParams)r.   rj   rk   rl   rm   s        r   send_log_messagezServerSession.send_log_message   s[      $$$$002 AA#!%	 
 	
 	
s   AAAAuric           
         K   | j                  t        j                  t        j                  dt        j                  |                         d{    y7 w)z%Send a resource updated notification.znotifications/resources/updated)rv   ro   N)rq   r2   rr   ResourceUpdatedNotification!ResourceUpdatedNotificationParams)r.   rv   s     r   send_resource_updatedz#ServerSession.send_resource_updated   sK     $$$$11< BBsK
 	
 	
s   AAAA)system_promptinclude_contexttemperaturestop_sequencesmetadatamodel_preferencesrm   messages
max_tokensr{   r|   r}   r~   r   r   c                   K   | j                  t        j                  t        j                  dt        j                  ||||||||                  t        j
                  t        |	             d{   S 7 w)z'Send a sampling/create_message request.zsampling/createMessage)r   systemPromptincludeContextr}   	maxTokensstopSequencesr   modelPreferencesro   rm   )rW   result_typer   N)send_requestr2   ServerRequestCreateMessageRequestCreateMessageRequestParamsCreateMessageResultr
   )
r.   r   r   r{   r|   r}   r~   r   r   rm   s
             r   create_messagezServerSession.create_message   s      &&''**3 ;;!)%2'6$/",&4!)):	 11*#5# ' 
 
 	
 
s   A3A<5A:6A<c                    K   | j                  t        j                  t        j                  d            t        j                         d{   S 7 w)zSend a roots/list request.z
roots/listrp   N)r   r2   r   ListRootsRequestListRootsResultr-   s    r   
list_rootszServerSession.list_roots   sM     &&&&'
 !!
 
 	
 
   AAAAmessagerequestedSchemac                    K   | j                  t        j                  t        j                  dt        j                  ||                  t        j
                  t        |             d{   S 7 w)zSend an elicitation/create request.

        Args:
            message: The message to present to the user
            requestedSchema: Schema defining the expected response structure

        Returns:
            The client's response
        zelicitation/create)r   r   ro   r   )r   N)r   r2   r   ElicitRequestElicitRequestParamsElicitResultr
   )r.   r   r   rm   s       r   elicitzServerSession.elicit  sq      &&##/ 44 '(7 *>PQ ' 
 
 	
 
s   A-A6/A40A6c                    K   | j                  t        j                  t        j                  d            t        j                         d{   S 7 w)zSend a ping request.pingr   N)r   r2   r   PingRequestEmptyResultr-   s    r   	send_pingzServerSession.send_ping  sM     &&!!!
 
 
 	
 
r   progress_tokenprogresstotalc                    K   | j                  t        j                  t        j                  dt        j                  ||||                  |       d{    y7 w)zSend a progress notification.znotifications/progress)progressTokenr   r   r   ro   N)rq   r2   rr   ProgressNotificationProgressNotificationParams)r.   r   r   r   r   rm   s         r   send_progress_notificationz(ServerSession.send_progress_notification*  s^      $$$$**3 ;;&4!)# '	
 
 	
 	
s   AAAAc                    K   | j                  t        j                  t        j                  d                   d{    y7 w)z*Send a resource list changed notification.z$notifications/resources/list_changedr   N)rq   r2   rr   ResourceListChangedNotificationr-   s    r   send_resource_list_changedz(ServerSession.send_resource_list_changedB  s=     $$$$55A
 	
 	
   <AAAc                    K   | j                  t        j                  t        j                  d                   d{    y7 w)z&Send a tool list changed notification.z notifications/tools/list_changedr   N)rq   r2   rr   ToolListChangedNotificationr-   s    r   send_tool_list_changedz$ServerSession.send_tool_list_changedL  s=     $$$$11=
 	
 	
r   c                    K   | j                  t        j                  t        j                  d                   d{    y7 w)z(Send a prompt list changed notification.z"notifications/prompts/list_changedr   N)rq   r2   rr   PromptListChangedNotificationr-   s    r   send_prompt_list_changedz&ServerSession.send_prompt_list_changedV  s=     $$$$33?
 	
 	
r   reqc                 V   K   | j                   j                  |       d {    y 7 wr*   )r:   send)r.   r   s     r   _handle_incomingzServerSession._handle_incoming`  s      2277<<<s   )')c                     | j                   S r*   )r+   r-   s    r   incoming_messageszServerSession.incoming_messagesc  s     333r   )F)r'   N)NNr*   )NNN);r   r   r   r   r   r!   __annotations__r"   r2   InitializeRequestParamsr   r   	Exceptionr   r	   boolr1   propertyr?   ClientCapabilitiesrL   rN   r   r3   r[   rc   r4   ri   LoggingLevelr   str	RequestIdru   r   rz   listSamplingMessageintIncludeContextfloatdictModelPreferencesr   r   r   r   ElicitRequestedSchemar   r   r   r   r   r   r   r   r9   r   r   __classcell__)r=   s   @r   r   r   G   s:    )<(J(JL%J;?NE11D8?  d.~	/IJd -^<d ,	d
 d 
d$ #u<<tC # #%2J2J t B*^1A%BUBUW\WiWiBi1j ^4c9Q9Q cVZ c "59
!!
 
 d
	

 "OOd2
 

,	
v 	
$ 	
  %)7;$(+/*.;?59"
u,,-"
 	"

 Tz"
 --4"
 T\"
 S	D("
 sCx.4'"
 !11D8"
 "OOd2"
 
	"	""
H	
%"7"7 	
 6:	

 44
 "OOd2	

 
		
:	
!2!2 	
 #")-
c	
 
 t|	

 t
  $J
 

0


=*@ =T = 4	"#9	:4 4r   )#__doc__enumr   typingr   r   r7   anyio.lowlevelanyio.streams.memoryr   r   pydanticr   	mcp.typesr2   mcp.server.modelsr	   mcp.shared.messager
   r   mcp.shared.sessionr   r   mcp.shared.versionr   r   r   r3   r[   r4   r   r9   r   rr   r   r   r   r   <module>r      s   %N     R   3 D ;$  )A U((%*<*<<=@X@XX[dd 
`4    		"`4r   