
    ^sj(              
          d Z ddlmZ ddl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  G d	 d
e      Z G d deej(                  ej*                  ej,                  ej.                  ej0                  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": True})
        ):
            # 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)AnyN)MemoryObjectReceiveStreamMemoryObjectSendStream)AnyUrl)InitializationOptions)BaseSessionRequestResponderc                       e Zd ZdZdZdZy)InitializationState         N)__name__
__module____qualname__NotInitializedInitializingInitialized     E/root/.hermes/venv/lib/python3.12/site-packages/mcp/server/session.pyr   r   8   s    NLKr   r   c                       e Zd ZU ej                  Zeed<   dZej                  dz  ed<   de
ej                  ez     deej                     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deej,                  ej.                  f   fdZdej2                  ddfdZ	 d)dej6                  dededz  ddfdZdeddfdZ dddddddde!ejD                     de#dedz  dejH                  dz  de%dz  de!e   dz  de&eef   dz  dejN                  dz  dejP                  fdZ)dejT                  fd Z+dejX                  fd!Z-	 d)d"ee#z  d#e%d$e%dz  ddfd%Z.d*d&Z/d*d'Z0d*d(Z1 xZ2S )+ServerSession_initializedN_client_paramsread_streamwrite_streaminit_optionsreturnc                     t         |   ||t        j                  t        j                         t
        j                  | _        || _        y N)	super__init__typesClientRequestClientNotificationr   r   _initialization_state_init_options)selfr   r   r   	__class__s       r   r$   zServerSession.__init__J   s?     	u':':E<T<T	
 &9%G%G")r   c                     | j                   S r"   )r   r*   s    r   client_paramszServerSession.client_paramsV   s    """r   
capabilityc                    | j                   y| j                   j                  }|j                  :|j                  y|j                  j                  r|j                  j                  s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experimentalitems)r*   r/   client_capsexp_key	exp_values        r   check_client_capabilityz%ServerSession.check_client_capabilityZ   s    & ))66 '  (++K4E4E4Q4Q*##+"".''/&0&=&=&C&C&E !";#;#;;"//8IE ! r   	responderc                 6  K   |j                   j                  t        j                  d x\  }t        j
                  | _        || _        |j                  t        j                  t        j                  t        j                  | j                  j                  t        j                  | j                  j                  | j                  j                                            d {    y  	 | j                  t        j"                  k7  rt%        d      y 7 0w)N)params)nameversion)protocolVersionr1   
serverInfoz3Received request before initialization was complete)requestrootr%   InitializeRequestr   r   r(   r   respondServerResultInitializeResultLATEST_PROTOCOL_VERSIONr)   r1   Implementationserver_nameserver_versionr   RuntimeError)r*   r;   r=   s      r   _received_requestzServerSession._received_requestz   s      $$((7-@-M-M*&,#''&&..,1,I,I)-););)H)H',';';%)%7%7%C%C(,(:(:(I(I(	   8 --1D1P1PP&M  Qs   C$D&D'1D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)
anyiolowlevel
checkpointrC   r%   InitializedNotificationr   r   r(   rL   )r*   rN   s     r   _received_notificationz$ServerSession._received_notification   sy      nn'')))..0-@-L-L* 1--1D1P1PP&R  Q 	*s   "BB
A&Bleveldataloggerc                    K   | j                  t        j                  t        j                  dt        j                  |||                         d{    y7 w)z Send a log message notification.znotifications/message)rU   rV   rW   methodr=   N)send_notificationr%   ServerNotificationLoggingMessageNotification LoggingMessageNotificationParams)r*   rU   rV   rW   s       r   send_log_messagezServerSession.send_log_message   sV      $$$$002 AA#!%	
 	
 	
   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)ra   rY   N)r[   r%   r\   ResourceUpdatedNotification!ResourceUpdatedNotificationParams)r*   ra   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_preferencesmessages
max_tokensrf   rg   rh   ri   rj   rk   c                   K   | j                  t        j                  t        j                  dt        j                  ||||||||                  t        j
                         d{   S 7 w)z'Send a sampling/create_message request.zsampling/createMessage)rl   systemPromptincludeContextrh   	maxTokensstopSequencesrj   modelPreferencesrY   N)send_requestr%   ServerRequestCreateMessageRequestCreateMessageRequestParamsCreateMessageResult)	r*   rl   rm   rf   rg   rh   ri   rj   rk   s	            r   create_messagezServerSession.create_message   su      &&**3 ;;!)%2'6$/",&4!)):	 %%!
 
 	
 
s   A'A0)A.*A0c                    K   | j                  t        j                  t        j                  d            t        j                         d{   S 7 w)zSend a roots/list request.z
roots/listrZ   N)rt   r%   ru   ListRootsRequestListRootsResultr-   s    r   
list_rootszServerSession.list_roots   sM     &&&&'
 !!
 
 	
 
   AAAAc                    K   | j                  t        j                  t        j                  d            t        j                         d{   S 7 w)zSend a ping request.pingr{   N)rt   r%   ru   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   rY   N)r[   r%   r\   ProgressNotificationProgressNotificationParams)r*   r   r   r   s       r   send_progress_notificationz(ServerSession.send_progress_notification   sV      $$$$**3 ;;&4!)#	
 	
 	
r`   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)r[   r%   r\   ResourceListChangedNotificationr-   s    r   send_resource_list_changedz(ServerSession.send_resource_list_changed  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)r[   r%   r\   ToolListChangedNotificationr-   s    r   send_tool_list_changedz$ServerSession.send_tool_list_changed  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)r[   r%   r\   PromptListChangedNotificationr-   s    r   send_prompt_list_changedz&ServerSession.send_prompt_list_changed  s=     $$$$33?
 	
 	
r   r"   )r    N)3r   r   r   r   r   r   __annotations__r   r%   InitializeRequestParamsr   JSONRPCMessage	Exceptionr   r   r$   propertyr.   ClientCapabilitiesboolr:   r
   r&   rF   rM   r'   rT   LoggingLevelr   strr_   r   re   listSamplingMessageintIncludeContextfloatdictModelPreferencesrx   ry   r}   r~   r   r   r   r   r   r   __classcell__)r+   s   @r   r   r   >   sV    )<(J(JL%J;?NE11D8?
*.u/C/Ci/OP
* -U-A-AB
* ,	
*
 

* #u<<tC # #%2J2J t @)%*=*=u?Q?Q*QR2!44	 JN
''
/2
<?$J
	
"	
v 	
$ 	
  %)7;$(+/*.;?
u,,-
 	

 Tz
 --4
 T\
 S	D(
 sCx.4'
 !11D8
 
	"	"
@	
%"7"7 	
	
!2!2 	
 QU
!Ci
38
AF
	
"


r   r   )__doc__enumr   typingr   rP   anyio.lowlevelanyio.streams.memoryr   r   pydanticr   	mcp.typesr%   mcp.server.modelsr   mcp.shared.sessionr	   r
   r   ru   r\   rF   r&   r'   r   r   r   r   <module>r      s|   %N     R   3$ b
    		"b
r   