o
    hw1                  	   @   s   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 deZedddZeejejf ejB eB ZG dd deej ej!ejejejf Z"dS )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                   @   s   e Zd ZdZdZdZdS )InitializationState         N)__name__
__module____qualname__NotInitializedInitializingInitialized r   r   S/var/www/html/openai_agents/venv/lib/python3.10/site-packages/mcp/server/session.pyr   :   s    r   ServerSessionTServerSession)boundc                       sP  e Zd ZU ejZeed< dZej	dB ed< 	dEde
eeB  dee deded	df
 fd
dZed	ej	dB fddZdejd	efddZdF fddZdeejejf fddZdejd	dfddZ		dGdejdededB dejdB d	df
ddZ de!d	dfd d!Z"dddddddd"d#e#ej$ d$e%d%edB d&ej&dB d'e'dB d(e#e dB d)e(eef dB d*ej)dB dejdB d	ej*fd+d,Z+d	ej,fd-d.Z-	dHd/ed0ej.dejdB d	ej/fd1d2Z0d	ej1fd3d4Z2			dId5ee%B d6e'd7e'dB d/edB dedB d	dfd8d9Z3dFd:d;Z4dFd<d=Z5dFd>d?Z6d@e7d	dfdAdBZ8ed	e
e7 fdCdDZ9  Z:S )Jr   _initializedN_client_paramsFread_streamwrite_streaminit_options	statelessreturnc                    s\   t  ||tjtj |rtjntj _| _	t
jt d\ _ _ j fdd d S )Nr   c                      s
    j  S N)_incoming_message_stream_readeracloser   selfr   r   <lambda>c   s   
 z(ServerSession.__init__.<locals>.<lambda>)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__r'   r   r+   S   s   zServerSession.__init__c                 C      | j S r$   )r   r'   r   r   r   client_paramse   s   zServerSession.client_params
capabilityc                 C   s   | j du rdS | j j}|jdur!|jdu rdS |jjr!|jjs!dS |jdur-|jdu r-dS |jdur9|jdu r9dS |jdur^|jdu rEdS |j D ]\}}||jvsZ|j| |kr] dS qJdS )z3Check if the client supports a specific capability.NFT)r   capabilitiesrootslistChangedsamplingelicitationexperimentalitems)r(   r;   client_capsexp_key	exp_valuer   r   r   check_client_capabilityi   s,   








z%ServerSession.check_client_capabilityc              	      sR   | j 4 I d H  t  I d H  W d   I d H  d S 1 I d H s"w   Y  d S r$   )r4   r*   _receive_loopr'   r7   r   r   rG      s   .zServerSession._receive_loop	responderc                    s   |j j tjd r\ d  } |j}tj| _|| _|5 |	t
tj|tv r*|ntj| jjtj| jj| jj| jj| jjd| jjdI d H  W d    d S 1 sUw   Y  d S  tjd re d S  	 | jtjkrqtdd S )Nparamsr   )nameversion
websiteUrlicons)protocolVersionr<   
serverInfoinstructionsr   z3Received request before initialization was complete)requestrootr,   InitializeRequestrO   r   r   r/   r   respondServerResultInitializeResultr   LATEST_PROTOCOL_VERSIONr0   r<   Implementationserver_nameserver_versionwebsite_urlrN   rQ   PingRequestr   RuntimeError)r(   rH   rJ   requested_versionr   r   r   _received_request   sB   "zServerSession._received_requestnotificationc                    sJ   t j I d H  |jtjd r tj| _d S  	 | jtjkr#t	dd S )Nr   z8Received notification before initialization was complete)
r1   lowlevel
checkpointrS   r,   InitializedNotificationr   r   r/   r^   )r(   ra   r   r   r   _received_notification   s   z$ServerSession._received_notificationleveldataloggerrelated_request_idc              
      s2   |  ttjtj|||dd|I dH  dS )z Send a log message notification.)rf   rg   rh   rI   N)send_notificationr,   ServerNotificationLoggingMessageNotification LoggingMessageNotificationParams)r(   rf   rg   rh   ri   r   r   r   send_log_message   s   	zServerSession.send_log_messageuric                    s,   |  ttjtj|ddI dH  dS )z%Send a resource updated notification.)ro   rI   N)rj   r,   rk   ResourceUpdatedNotification!ResourceUpdatedNotificationParams)r(   ro   r   r   r   send_resource_updated   s   
z#ServerSession.send_resource_updated)system_promptinclude_contexttemperaturestop_sequencesmetadatamodel_preferencesri   messages
max_tokensrs   rt   ru   rv   rw   rx   c          
         sD   | j ttjtj||||||||ddtjt|	ddI dH S )z'Send a sampling/create_message request.)ry   systemPromptincludeContextru   	maxTokensstopSequencesrw   modelPreferencesrI   ri   )rR   result_typerw   N)send_requestr,   ServerRequestCreateMessageRequestCreateMessageRequestParamsCreateMessageResultr	   )
r(   ry   rz   rs   rt   ru   rv   rw   rx   ri   r   r   r   create_message   s*   zServerSession.create_messagec                        |  tt tjI dH S )zSend a roots/list request.N)r   r,   r   ListRootsRequestListRootsResultr'   r   r   r   
list_roots   
   
zServerSession.list_rootsmessagerequestedSchemac                    s8   | j ttjtj||ddtjt|ddI dH S )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
        )r   r   rI   r   )rw   N)r   r,   r   ElicitRequestElicitRequestParamsElicitResultr	   )r(   r   r   ri   r   r   r   elicit   s   zServerSession.elicitc                    r   )zSend a ping request.N)r   r,   r   r]   EmptyResultr'   r   r   r   	send_ping  r   zServerSession.send_pingprogress_tokenprogresstotalc                    s4   |  ttjtj||||dd|I dH  dS )zSend a progress notification.)progressTokenr   r   r   rI   N)rj   r,   rk   ProgressNotificationProgressNotificationParams)r(   r   r   r   r   ri   r   r   r   send_progress_notification#  s   	
z(ServerSession.send_progress_notificationc                        |  tt I dH  dS )z*Send a resource list changed notification.N)rj   r,   rk   ResourceListChangedNotificationr'   r   r   r   send_resource_list_changed:     z(ServerSession.send_resource_list_changedc                    r   )z&Send a tool list changed notification.N)rj   r,   rk   ToolListChangedNotificationr'   r   r   r   send_tool_list_changed>  r   z$ServerSession.send_tool_list_changedc                    r   )z(Send a prompt list changed notification.N)rj   r,   rk   PromptListChangedNotificationr'   r   r   r   send_prompt_list_changedB  r   z&ServerSession.send_prompt_list_changedreqc                    s   | j |I d H  d S r$   )r4   send)r(   r   r   r   r   _handle_incomingF  s   zServerSession._handle_incomingc                 C   r9   r$   )r%   r'   r   r   r   incoming_messagesI  s   zServerSession.incoming_messages)F)r#   N)NNr$   )NNN);r   r   r   r   r   r   __annotations__r   r,   InitializeRequestParamsr   r
   	Exceptionr   r   boolr+   propertyr:   ClientCapabilitiesrF   rG   r   r-   rV   r`   r.   re   LoggingLevelr   str	RequestIdrn   r   rr   listSamplingMessageintIncludeContextfloatdictModelPreferencesr   r   r   r   ElicitRequestedSchemar   r   r   r   r   r   r   r   r3   r   r   __classcell__r   r   r7   r   r   G   s   
 	
!

	

#




)#__doc__enumr   typingr   r   r1   anyio.lowlevelanyio.streams.memoryr   r   pydanticr   	mcp.typesr,   mcp.server.modelsr   mcp.shared.messager	   r
   mcp.shared.sessionr   r   mcp.shared.versionr   r   r   r-   rV   r.   r   r3   r   rk   r   r   r   r   r   <module>   s4    '
