
    )`ik              
          d Z ddlmZ ddlmZ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 dd	lmZ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j%        ej&        f         ej'        z  e(z  Z) G 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TypeVaroverloadN)MemoryObjectReceiveStreamMemoryObjectSendStream)AnyUrl)!ExperimentalServerSessionFeatures)InitializationOptions)validate_sampling_tools!validate_tool_use_result_messages)check_tasks_capability)RELATED_TASK_METADATA_KEY)ServerMessageMetadataSessionMessage)BaseSessionRequestResponder)SUPPORTED_PROTOCOL_VERSIONSc                       e Zd ZdZdZdZdS )InitializationState         N)__name__
__module____qualname__NotInitializedInitializingInitialized     f/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/mcp/server/session.pyr   r   >   s        NLKKKr!   r   ServerSessionTServerSession)boundc                       e Zd ZU ej        Zeed<   dZej	        dz  ed<   dZ
edz  ed<   	 dFd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ed
efd            Zdej        d
efdZdG fdZdeej        ej        f         fdZdej        d
dfdZ	 	 dHdej        de de!dz  dej"        dz  d
df
dZ#de$d
dfdZ%e&dddddddddd	de'ej(                 de)de!dz  d ej*        dz  d!e+dz  d"e'e!         dz  d#e,e!e f         dz  d$ej-        dz  d%dd&ej.        dz  dej"        dz  d
ej/        fd'            Z0e&ddddddddd(de'ej(                 de)de!dz  d ej*        dz  d!e+dz  d"e'e!         dz  d#e,e!e f         dz  d$ej-        dz  d%e'ej1                 d&ej.        dz  dej"        dz  d
ej2        fd)            Z0dddddddddd	de'ej(                 de)de!dz  d ej*        dz  d!e+dz  d"e'e!         dz  d#e,e!e f         dz  d$ej-        dz  d%e'ej1                 dz  d&ej.        dz  dej"        dz  d
ej/        ej2        z  fd*Z0d
ej3        fd+Z4	 dId,e!d-ej5        dej"        dz  d
ej6        fd.Z7	 dId,e!d-ej5        dej"        dz  d
ej6        fd/Z8	 dId,e!d0e!d1e!dej"        dz  d
ej6        f
d2Z9d
ej:        fd3Z;	 	 	 dJd4e!e)z  d5e+d6e+dz  d,e!dz  de!dz  d
dfd7Z<dGd8Z=dGd9Z>dGd:Z?	 dId1e!dej"        dz  d
dfd;Z@	 	 dHd,e!d-ej5        d<e!dz  d=ejA        dz  d
ejB        f
d>ZC	 dId,e!d0e!d1e!d<e!dz  d
ejB        f
d?ZDddddddddddd@
de'ej(                 de)de!dz  d ej*        dz  d!e+dz  d"e'e!         dz  d#e,e!e f         dz  d$ej-        dz  d%e'ej1                 dz  d&ej.        dz  d<e!dz  d=ejA        dz  d
ejB        fdAZEd,ed
dfdBZFdCeGd
dfdDZHed
eeG         fdE            ZI xZJS )Kr$   _initializedN_client_params_experimental_featuresFread_streamwrite_streaminit_options	statelessreturnc                 X    t                                          ||t          j        t          j                   |rt
          j        nt
          j         _        | _	        t          j        t                   d          \   _         _         j                             fd           d S )Nr   c                  6     j                                         S N)_incoming_message_stream_readeracloseselfs   r"   <lambda>z(ServerSession.__init__.<locals>.<lambda>h   s    T5Y5`5`5b5b r!   )super__init__typesClientRequestClientNotificationr   r   r   _initialization_state_init_optionsanyiocreate_memory_object_streamServerRequestResponder_incoming_message_stream_writerr2   _exit_stackpush_async_callback)r5   r*   r+   r,   r-   	__class__s   `    r"   r8   zServerSession.__init__X   s     	lE4GIabbb/8`++>Q>` 	" *UZUv"V

V VR,d.R 	,,-b-b-b-bcccccr!   c                     | j         S r1   )r(   r4   s    r"   client_paramszServerSession.client_paramsj   s    ""r!   c                 F    | j         t          |           | _         | j         S )u   Experimental APIs for server→client task operations.

        WARNING: These APIs are experimental and may change without notice.
        )r)   r
   r4   s    r"   experimentalzServerSession.experimentaln   s&     &.*KD*Q*QD'**r!   
capabilityc                    | j         dS | j         j        }|j        #|j        dS |j        j        r|j        j        sdS |j        =|j        dS |j        j        |j        j        dS |j        j        |j        j        dS |j        	|j        dS |j        E|j        dS |j        	                                D ]"\  }}||j        vs|j        |         |k    r dS #|j
        %|j
        dS t          |j
        |j
                  sdS dS )z3Check if the client supports a specific capability.NFT)r(   capabilitiesrootslistChangedsamplingcontexttoolselicitationrH   itemstasksr   )r5   rI   client_capsexp_key	exp_values        r"   check_client_capabilityz%ServerSession.check_client_capabilityx   s[   &5)6' (u+ K4E4Q u*#+u"*6;;O;W;_u"(49M9S9[u!-+2I2Q5".'/u&0&=&C&C&E&E ! !"+":::k>VW^>_cl>l>l 55 ?m ' (u)**:K<MNN utr!   c                    K   | j         4 d {V  t                                                       d {V  d d d           d {V  d S # 1 d {V swxY w Y   d S r1   )rA   r7   _receive_loop)r5   rD   s    r"   rY   zServerSession._receive_loop   s      7 	* 	* 	* 	* 	* 	* 	* 	*'''')))))))))	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	*s   'A
AA	responderc                   K   |j         j        xt          j        d x\  } |j        }t
          j        | _        || _        |5  |	                    t          j
        t          j        |t          v r|nt          j        | j        j        t          j        | j        j        | j        j        | j        j        | j        j                  | j        j                                       d {V  d d d            n# 1 swxY w Y   t
          j        | _        d S  t          j        d x\   d S  	 | j        t
          j        k    rt1          d          d S )Nparams)nameversion
websiteUrlicons)protocolVersionrK   
serverInfoinstructionsr    z3Received request before initialization was complete)requestrootr9   InitializeRequestrb   r   r   r<   r(   respondServerResultInitializeResultr   LATEST_PROTOCOL_VERSIONr=   rK   Implementationserver_nameserver_versionwebsite_urlra   rd   r   PingRequestRuntimeError)r5   rZ   r]   requested_versions       r"   _received_requestzServerSession._received_request   s     $7(77777$*$:!-@-M*&,#  #++*!2#48S#S#S 1B0A%*%B-1-?-L+0+?)-);)G,0,>,M/3/A/M*.*<*B	," ," ," .2-?-L                         $ .A-L***- 8. "$$$$$ % -1D1PPP&'\]]] QPs   B+C::C>C>notificationc                    K   t           j                                         d {V  |j        t          j        d x\   t          j        | _        d S  	 | j        t          j        k    rt          d          d S )Nr    z8Received notification before initialization was complete)
r>   lowlevel
checkpointrf   r9   InitializedNotificationr   r   r<   rq   )r5   rt   s     r"   _received_notificationz$ServerSession._received_notification   s      n''))))))))).00000-@-L*** 1-1D1PPP&'abbb QPr!   leveldataloggerrelated_request_idc                    K   |                      t          j        t          j        t          j        |||                              |           d{V  dS )z Send a log message notification.)rz   r{   r|   r\   N)send_notificationr9   ServerNotificationLoggingMessageNotification LoggingMessageNotificationParams)r5   rz   r{   r|   r}   s        r"   send_log_messagezServerSession.send_log_message   s       $$$0 A#!%      
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
r!   uric           	         K   |                      t          j        t          j        t          j        |                                         d{V  dS )z%Send a resource updated notification.)r   r\   N)r   r9   r   ResourceUpdatedNotification!ResourceUpdatedNotificationParams)r5   r   s     r"   send_resource_updatedz#ServerSession.send_resource_updated   s|      $$$1 BsKKK   
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
r!   )	system_promptinclude_contexttemperaturestop_sequencesmetadatamodel_preferencesrP   tool_choicer}   messages
max_tokensr   r   r   r   r   r   rP   r   c       
         
   K   dS )z0Overload: Without tools, returns single content.Nr    r5   r   r   r   r   r   r   r   r   rP   r   r}   s               r"   create_messagezServerSession.create_message         " 	r!   )r   r   r   r   r   r   r   r}   c       
         
   K   dS )z4Overload: With tools, returns array-capable content.Nr    r   s               r"   r   zServerSession.create_message   r   r!   c       
           K   | j         r| j         j        nd}t          ||	|
           t          |           t	          j        t	          j        t	          j        |||||||||	|

  
                            }t          |          }|	(| 	                    |t          j
        |           d{V S | 	                    |t          j        |           d{V S )a  Send a sampling/create_message request.

        Args:
            messages: The conversation messages to send.
            max_tokens: Maximum number of tokens to generate.
            system_prompt: Optional system prompt.
            include_context: Optional context inclusion setting.
                Should only be set to "thisServer" or "allServers"
                if the client has sampling.context capability.
            temperature: Optional sampling temperature.
            stop_sequences: Optional stop sequences.
            metadata: Optional metadata to pass through to the LLM provider.
            model_preferences: Optional model selection preferences.
            tools: Optional list of tools the LLM can use during sampling.
                Requires client to have sampling.tools capability.
            tool_choice: Optional control over tool usage behavior.
                Requires client to have sampling.tools capability.
            related_request_id: Optional ID of a related request.

        Returns:
            The sampling result from the client.

        Raises:
            McpError: If tools are provided but client doesn't support them.
            ValueError: If tool_use or tool_result message structure is invalid.
        N)
r   systemPromptincludeContextr   	maxTokensstopSequencesr   modelPreferencesrP   
toolChoicer\   r}   )re   result_typer   )r(   rK   r   r   r9   ServerRequestCreateMessageRequestCreateMessageRequestParamsr   send_requestCreateMessageResultWithToolsCreateMessageResult)r5   r   r   r   r   r   r   r   r   rP   r   r}   rT   re   metadata_objs                  r"   r   zServerSession.create_message  sG     R ;?:MWd)66SWUK@@@)(333%&7%!.#2 +("0%%6*    
 
  -@RSSS **!>% +         
 &&1! ' 
 
 
 
 
 
 
 
 	
r!   c                    K   |                      t          j        t          j                              t          j                   d{V S )zSend a roots/list request.N)r   r9   r   ListRootsRequestListRootsResultr4   s    r"   
list_rootszServerSession.list_roots^  sY      && 6 8 899!
 
 
 
 
 
 
 
 	
r!   messagerequestedSchemac                 @   K   |                      |||           d{V S )a  Send a form mode elicitation/create request.

        Args:
            message: The message to present to the user
            requestedSchema: Schema defining the expected response structure
            related_request_id: Optional ID of the request that triggered this elicitation

        Returns:
            The client's response

        Note:
            This method is deprecated in favor of elicit_form(). It remains for
            backward compatibility but new code should use elicit_form().
        N)elicit_formr5   r   r   r}   s       r"   elicitzServerSession.elicite  s3      ( %%g@RSSSSSSSSSr!   c           
         K   |                      t          j        t          j        t          j        ||                              t          j        t          |                     d{V S )ag  Send a form mode elicitation/create request.

        Args:
            message: The message to present to the user
            requestedSchema: Schema defining the expected response structure
            related_request_id: Optional ID of the request that triggered this elicitation

        Returns:
            The client's response with form data
        )r   r   r\   r   r   N)r   r9   r   ElicitRequestElicitRequestFormParamsElicitResultr   r   s       r"   r   zServerSession.elicit_form{  s        &&# 8 '(7      *>PQQQ ' 
 
 
 
 
 
 
 
 	
r!   urlelicitation_idc                    K   |                      t          j        t          j        t          j        |||                              t          j        t          |                     d{V S )ak  Send a URL mode elicitation/create request.

        This directs the user to an external URL for out-of-band interactions
        like OAuth flows, credential collection, or payment processing.

        Args:
            message: Human-readable explanation of why the interaction is needed
            url: The URL the user should navigate to
            elicitation_id: Unique identifier for tracking this elicitation
            related_request_id: Optional ID of the request that triggered this elicitation

        Returns:
            The client's response indicating acceptance, decline, or cancellation
        r   r   elicitationIdr\   r   r   N)r   r9   r   r   ElicitRequestURLParamsr   r   )r5   r   r   r   r}   s        r"   
elicit_urlzServerSession.elicit_url  s      * &&# 7 '&4      *>PQQQ ' 
 
 
 
 
 
 
 
 	
r!   c                    K   |                      t          j        t          j                              t          j                   d{V S )zSend a ping request.N)r   r9   r   rp   EmptyResultr4   s    r"   	send_pingzServerSession.send_ping  sY      && 1 3 344
 
 
 
 
 
 
 
 	
r!   progress_tokenprogresstotalc                    K   |                      t          j        t          j        t          j        ||||                              |           d{V  dS )zSend a progress notification.)progressTokenr   r   r   r\   N)r   r9   r   ProgressNotificationProgressNotificationParams)r5   r   r   r   r   r}   s         r"   send_progress_notificationz(ServerSession.send_progress_notification  s       $$$* ;&4!)# '	    	 	 
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
r!   c                    K   |                      t          j        t          j                                         d{V  dS )z*Send a resource list changed notification.N)r   r9   r   ResourceListChangedNotificationr4   s    r"   send_resource_list_changedz(ServerSession.send_resource_list_changed  sF      $$U%=e>c>e>e%f%fgggggggggggr!   c                    K   |                      t          j        t          j                                         d{V  dS )z&Send a tool list changed notification.N)r   r9   r   ToolListChangedNotificationr4   s    r"   send_tool_list_changedz$ServerSession.send_tool_list_changed  sF      $$U%=e>_>a>a%b%bcccccccccccr!   c                    K   |                      t          j        t          j                                         d{V  dS )z(Send a prompt list changed notification.N)r   r9   r   PromptListChangedNotificationr4   s    r"   send_prompt_list_changedz&ServerSession.send_prompt_list_changed  sF      $$U%=e>a>c>c%d%deeeeeeeeeeer!   c           	         K   |                      t          j        t          j        t          j        |                              |           d{V  dS )a  Send an elicitation completion notification.

        This should be sent when a URL mode elicitation has been completed
        out-of-band to inform the client that it may retry any requests
        that were waiting for this elicitation.

        Args:
            elicitation_id: The unique identifier of the completed elicitation
            related_request_id: Optional ID of the request that triggered this
        )r   r\   N)r   r9   r   ElicitCompleteNotification ElicitCompleteNotificationParams)r5   r   r}   s      r"   send_elicit_completez"ServerSession.send_elicit_complete  s       $$$0 AP^___   
 
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
r!   related_task_idtaskc                 t   t          j        |||          }|                    ddd          }|@d|vri |d<   t          j        |                              d          |d         t          <   |rd	| d
t          |           n| j        }|| xj        dz  c_        t          j        d|d|          S )a  Build a form mode elicitation request without sending it.

        Args:
            message: The message to present to the user
            requestedSchema: Schema defining the expected response structure
            related_task_id: If provided, adds io.modelcontextprotocol/related-task metadata
            task: If provided, makes this a task-augmented request

        Returns:
            A JSONRPCRequest ready to be sent or queued
        )r   r   r   Tjsonby_aliasmodeexclude_noneN_metataskIdr   task--r   2.0elicitation/createjsonrpcidmethodr]   )r9   r   
model_dumpRelatedTaskMetadatar   r   _request_idJSONRPCRequest)r5   r   r   r   r   r]   params_data
request_ids           r"   _build_elicit_form_requestz(ServerSession._build_elicit_form_request  s   $ .+
 
 

 ''FQU'VV &k))')G$>C>W&? ? ?j$j''  !:; @Od;_;;r&zz;;;TXTd
"!#'	
 
 
 	
r!   c                 t   t          j        |||          }|                    ddd          }|@d|vri |d<   t          j        |                              d          |d         t          <   |rd	| d
t          |           n| j        }|| xj        dz  c_        t          j        d|d|          S )a  Build a URL mode elicitation request without sending it.

        Args:
            message: Human-readable explanation of why the interaction is needed
            url: The URL the user should navigate to
            elicitation_id: Unique identifier for tracking this elicitation
            related_task_id: If provided, adds io.modelcontextprotocol/related-task metadata

        Returns:
            A JSONRPCRequest ready to be sent or queued
        r   Tr   r   Nr   r   r   r   r   r   r   r   r   )r9   r   r   r   r   r   r   r   )r5   r   r   r   r   r]   r   r   s           r"   _build_elicit_url_requestz'ServerSession._build_elicit_url_request*  s   $ -(
 
 

 ''FQU'VV &k))')G$>C>W&? ? ?j$j''  !:; @Od;_;;r&zz;;;TXTd
"!#'	
 
 
 	
r!   )
r   r   r   r   r   r   rP   r   r   r   c                   t          j        |||||||||	|
|          }|                    ddd          }|@d|vri |d<   t          j        |                              d          |d         t          <   |rd	| d
t          |           n| j        }|| xj        dz  c_        t          j        d|d|          S )a  Build a sampling/createMessage request without sending it.

        Args:
            messages: The conversation messages to send
            max_tokens: Maximum number of tokens to generate
            system_prompt: Optional system prompt
            include_context: Optional context inclusion setting
            temperature: Optional sampling temperature
            stop_sequences: Optional stop sequences
            metadata: Optional metadata to pass through to the LLM provider
            model_preferences: Optional model selection preferences
            tools: Optional list of tools the LLM can use during sampling
            tool_choice: Optional control over tool usage behavior
            related_task_id: If provided, adds io.modelcontextprotocol/related-task metadata
            task: If provided, makes this a task-augmented request

        Returns:
            A JSONRPCRequest ready to be sent or queued
        )r   r   r   r   r   r   r   r   rP   r   r   Tr   r   Nr   r   r   r   r   r   r   zsampling/createMessager   )r9   r   r   r   r   r   r   r   )r5   r   r   r   r   r   r   r   r   rP   r   r   r   r]   r   r   s                   r"   _build_create_message_requestz+ServerSession._build_create_message_requestW  s   F 1&*# (."
 
 
 ''FQU'VV &k))')G$>C>W&? ? ?j$j''  !:; @Od;_;;r&zz;;;TXTd
"!#+	
 
 
 	
r!   c                 J   K   | j                             |           d{V  dS )a  Send a raw session message.

        This is primarily used by TaskResultHandler to deliver queued messages
        (elicitation/sampling requests) to the client during task execution.

        WARNING: This is a low-level experimental method that may change without
        notice. Prefer using higher-level methods like send_notification() or
        send_request() for normal operations.

        Args:
            message: The session message to send
        N)_write_streamsend)r5   r   s     r"   send_messagezServerSession.send_message  s7        %%g...........r!   reqc                 J   K   | j                             |           d {V  d S r1   )rA   r   )r5   r   s     r"   _handle_incomingzServerSession._handle_incoming  s5      277<<<<<<<<<<<r!   c                     | j         S r1   )r2   r4   s    r"   incoming_messageszServerSession.incoming_messages  s     33r!   )F)r.   N)NNr1   )NNN)Kr   r   r   r   r   r'   __annotations__r(   r9   InitializeRequestParamsr)   r
   r   r   	Exceptionr   r   boolr8   propertyrF   rH   ClientCapabilitiesrW   rY   r   r:   ri   rs   r;   ry   LoggingLevelr   str	RequestIdr   r	   r   r   listSamplingMessageintIncludeContextfloatdictModelPreferences
ToolChoicer   r   Toolr   r   r   ElicitRequestedSchemar   r   r   r   r   r   r   r   r   r   r   TaskMetadatar   r   r   r   r   r@   r   r   __classcell__)rD   s   @r"   r$   r$   K   s
         )<(JL%JJJ;?NE1D8???GK=DKKK  d d.~	/IJd -^<d ,	d
 d 
d d d d d d$ #u<tC # # # X# +? + + + X+%%2J %t % % % %N* * * * * *^1A%BUW\WiBi1j ^ ^ ^ ^@c9Q cVZ c c c c "59
 
!
 
 d
	

 "Od2
 

 
 
 
*
v 
$ 
 
 
 
  %)7;$(+/*.;?/359  u,- 	
 Tz -4 T\ S	D( sCx.4' !1D8  %, "Od2 
	"   X$  %)7;$(+/*.;?/359  u,- 	
 Tz -4 T\ S	D( sCx.4' !1D8 EJ %, "Od2 
	+   X. %)7;$(+/*.;?)-/359J
 J
 J
u,-J
 	J

 TzJ
 -4J
 T\J
 S	D(J
 sCx.4'J
 !1D8J
 EJ$&J
 %,J
 "Od2J
 
	"U%G	GJ
 J
 J
 J
X
%"7 
 
 
 
 6:	T TT 4T "Od2	T
 
	T T T T4 6:	
 

 4
 "Od2	

 
	
 
 
 
D 6:!
 !
!
 !
 	!

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

 t
  $J
 

 
 
 
.h h h hd d d df f f f 6:
 

 "Od2
 
	
 
 
 
8 '+*.+
 +
+
 4+
 t	+

  4'+
 
	+
 +
 +
 +
d '++
 +
+
 +
 	+

 t+
 
	+
 +
 +
 +
d %)7;$(+/*.;?)-/3&**.D
 D
 D
u,-D
 	D

 TzD
 -4D
 T\D
 S	D(D
 sCx.4'D
 !1D8D
 EJ$&D
 %,D
 tD
  4'D
 
	D
 D
 D
 D
L/. /T / / / /=*@ =T = = = = 4	"#9	:4 4 4 X4 4 4 4 4r!   )-__doc__enumr   typingr   r   r   r>   anyio.lowlevelanyio.streams.memoryr   r   pydanticr	   	mcp.typesr9   (mcp.server.experimental.session_featuresr
   mcp.server.modelsr   mcp.server.validationr   r   *mcp.shared.experimental.tasks.capabilitiesr   %mcp.shared.experimental.tasks.helpersr   mcp.shared.messager   r   mcp.shared.sessionr   r   mcp.shared.versionr   r   r#   r:   ri   r;   r   r@   r   r   r$   r    r!   r"   <module>r!     s  % %N       ) ) ) ) ) ) ) ) ) )      R R R R R R R R             V V V V V V 3 3 3 3 3 3 \ \ \ \ \ \ \ \ M M M M M M K K K K K K D D D D D D D D        ; : : : : :    $    )AAA U(%*<<=@XX[dd 
h	4 h	4 h	4 h	4 h	4  		"h	4 h	4 h	4 h	4 h	4r!   