o
    c۷i                     @   s   d Z ddlmZ ddlmZmZ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 er6ddlmZ ed	ejd
ZG dd dZdS )u8  
Experimental server session features for server→client task operations.

This module provides the server-side equivalent of ExperimentalClientFeatures,
allowing the server to send task-augmented requests to the client and poll for results.

WARNING: These APIs are experimental and may change without notice.
    )AsyncIterator)TYPE_CHECKINGAnyTypeVarN)validate_sampling_tools!validate_tool_use_result_messages)"require_task_augmented_elicitationrequire_task_augmented_sampling)poll_until_terminal)ServerSessionResultT)boundc                   @   s  e Zd ZdZd$ddZdedejfd	d
Zdede	e
 de
fddZdedeej fddZdddedejdedejfddZdddddddddd	deej de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ej dB d!ejdB dejfd"d#ZdS )%!ExperimentalServerSessionFeaturesu  
    Experimental server session features for server→client task operations.

    This provides the server-side equivalent of ExperimentalClientFeatures,
    allowing the server to send task-augmented requests to the client and
    poll for results.

    WARNING: These APIs are experimental and may change without notice.

    Access via session.experimental:
        result = await session.experimental.elicit_as_task(...)
    sessionr   returnNc                 C   s
   || _ d S )N)_session)selfr    r   ^/home/ubuntu/vllm_env/lib/python3.10/site-packages/mcp/server/experimental/session_features.py__init__)   s   
z*ExperimentalServerSessionFeatures.__init__task_idc                    s.   | j ttjtj|ddtjI dH S )z
        Send tasks/get to the client to get task status.

        Args:
            task_id: The task identifier

        Returns:
            GetTaskResult containing the task status
        taskIdparamsN)r   send_requesttypesServerRequestGetTaskRequestGetTaskRequestParamsGetTaskResult)r   r   r   r   r   get_task,   s
   

z*ExperimentalServerSessionFeatures.get_taskresult_typec                    s,   | j ttjtj|dd|I dH S )a  
        Send tasks/result to the client to retrieve the final result.

        Args:
            task_id: The task identifier
            result_type: The expected result type

        Returns:
            The task result, validated against result_type
        r   r   N)r   r   r   r   GetTaskPayloadRequestGetTaskPayloadRequestParams)r   r   r"   r   r   r   get_task_result;   s
   
z1ExperimentalServerSessionFeatures.get_task_resultc                 C  s(   t | j|2 z	3 dH W }|V  q6 dS )a  
        Poll a client task until it reaches terminal status.

        Yields GetTaskResult for each poll, allowing the caller to react to
        status changes. Exits when task reaches a terminal status.

        Respects the pollInterval hint from the client.

        Args:
            task_id: The task identifier

        Yields:
            GetTaskResult for each poll
        N)r
   r!   )r   r   statusr   r   r   	poll_taskO   s   z+ExperimentalServerSessionFeatures.poll_taski`  ttlmessagerequestedSchemar)   c                   s   | j jr
| j jjnd}t| | j ttjtj||tj	|dddtj
I dH }|jj}| |2 z3 dH W }q56 | |tjI dH S )a  
        Send a task-augmented elicitation to the client and poll until complete.

        The client will create a local task, process the elicitation asynchronously,
        and return the result when ready. This method handles the full flow:
        1. Send elicitation with task field
        2. Receive CreateTaskResult from client
        3. Poll client's task until terminal
        4. Retrieve and return the final ElicitResult

        Args:
            message: The message to present to the user
            requestedSchema: Schema defining the expected response
            ttl: Task time-to-live in milliseconds

        Returns:
            The client's elicitation response

        Raises:
            McpError: If client doesn't support task-augmented elicitation
        Nr(   )r*   r+   taskr   )r   client_paramscapabilitiesr   r   r   r   ElicitRequestElicitRequestFormParamsTaskMetadataCreateTaskResultr,   r   r'   r%   ElicitResult)r   r*   r+   r)   client_capscreate_resultr   _r   r   r   elicit_as_taska   s(   
	
z0ExperimentalServerSessionFeatures.elicit_as_task)	r)   system_promptinclude_contexttemperaturestop_sequencesmetadatamodel_preferencestoolstool_choicemessages
max_tokensr8   r9   r:   r;   r<   r=   r>   r?   c       
            s   | j jr
| j jjnd}t| t||
| t| | j ttj	tj
||||||||	|
|tj|dddtjI dH }|jj}| |2 z3 dH W }qG6 | |tjI dH S )a5  
        Send a task-augmented sampling request and poll until complete.

        The client will create a local task, process the sampling request
        asynchronously, and return the result when ready.

        Args:
            messages: The conversation messages for sampling
            max_tokens: Maximum tokens in the response
            ttl: Task time-to-live in milliseconds
            system_prompt: Optional system prompt
            include_context: Context inclusion strategy
            temperature: Sampling temperature
            stop_sequences: Stop sequences
            metadata: Additional metadata
            model_preferences: Model selection preferences
            tools: Optional list of tools the LLM can use during sampling
            tool_choice: Optional control over tool usage behavior

        Returns:
            The sampling result from the client

        Raises:
            McpError: If client doesn't support task-augmented sampling or tools
            ValueError: If tool_use or tool_result message structure is invalid
        Nr(   )r@   	maxTokenssystemPromptincludeContextr:   stopSequencesr<   modelPreferencesr>   
toolChoicer,   r   )r   r-   r.   r	   r   r   r   r   r   CreateMessageRequestCreateMessageRequestParamsr1   r2   r,   r   r'   r%   CreateMessageResult)r   r@   rA   r)   r8   r9   r:   r;   r<   r=   r>   r?   r4   r5   r   r6   r   r   r   create_message_as_task   s<   )

z8ExperimentalServerSessionFeatures.create_message_as_task)r   r   r   N)__name__
__module____qualname____doc__r   strr   r    r!   typer   r%   r   r'   ElicitRequestedSchemaintr3   r7   listSamplingMessageIncludeContextfloatdictr   ModelPreferencesTool
ToolChoicerJ   rK   r   r   r   r   r      sp    


8
	
r   )rO   collections.abcr   typingr   r   r   	mcp.typesr   mcp.server.validationr   r   *mcp.shared.experimental.tasks.capabilitiesr   r	   %mcp.shared.experimental.tasks.pollingr
   mcp.server.sessionr   Resultr   r   r   r   r   r   <module>   s    	