
    )`iY                        d Z ddlmZ ddl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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mZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0  G d d          Z1dS )z
ServerTaskContext - Server-integrated task context with elicitation and sampling.

This wraps the pure TaskContext and adds server-specific functionality:
- Elicitation (task.elicit())
- Sampling (task.create_message())
- Status notifications
    )AnyN)TaskResultHandler)ServerSession)validate_sampling_tools!validate_tool_use_result_messages)McpError)"require_task_augmented_elicitationrequire_task_augmented_sampling)TaskContext)QueuedMessageTaskMessageQueue)Resolver)	TaskStore)INVALID_REQUESTTASK_STATUS_INPUT_REQUIREDTASK_STATUS_WORKINGClientCapabilitiesCreateMessageResultCreateTaskResultElicitationCapabilityElicitRequestedSchemaElicitResult	ErrorDataIncludeContextModelPreferences	RequestIdResultSamplingCapabilitySamplingMessageServerNotificationTaskTaskMetadataTaskStatusNotificationTaskStatusNotificationParamsTool
ToolChoicec                      e Zd ZdZdddedededededz  f
d	Z	e
d
efd            Ze
d
efd            Ze
d
efd            Zd2dZdddeded
dfdZdddeded
dfdZdddeded
dfdZd2dZd2dZd2dZdeded
efdZdededed
efdZddddddddd d!ee         d"ed#edz  d$edz  d%e dz  d&ee         dz  d'e!ee"f         dz  d(e#dz  d)ee$         dz  d*e%dz  d
e&fd+Z'd,d-deded.ed
efd/Z(d,ddddddddd0	d!ee         d"ed.ed#edz  d$edz  d%e dz  d&ee         dz  d'e!ee"f         dz  d(e#dz  d)ee$         dz  d*e%dz  d
e&fd1Z)dS )3ServerTaskContextaE  
    Server-integrated task context with elicitation and sampling.

    This wraps a pure TaskContext and adds server-specific functionality:
    - elicit() for sending elicitation requests to the client
    - create_message() for sampling requests
    - Status notifications via the session

    Example:
        async def my_task_work(task: ServerTaskContext) -> CallToolResult:
            await task.update_status("Starting...")

            result = await task.elicit(
                message="Continue?",
                requestedSchema={"type": "object", "properties": {"ok": {"type": "boolean"}}}
            )

            if result.content.get("ok"):
                return CallToolResult(content=[TextContent(text="Done!")])
            else:
                return CallToolResult(content=[TextContent(text="Cancelled")])
    N)handlertaskstoresessionqueuer)   c                j    t          ||          | _        || _        || _        || _        || _        dS )aH  
        Create a ServerTaskContext.

        Args:
            task: The Task object
            store: The task store
            session: The server session
            queue: The message queue for elicitation/sampling
            handler: The result handler for response routing (required for elicit/create_message)
        )r*   r+   N)r   _ctx_session_queue_handler_store)selfr*   r+   r,   r-   r)   s         x/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/mcp/server/experimental/task_context.py__init__zServerTaskContext.__init__M   s8    &  T777	    returnc                     | j         j        S )zThe task identifier.)r/   task_idr4   s    r5   r:   zServerTaskContext.task_idh   s     y  r7   c                     | j         j        S )zThe current task state.)r/   r*   r;   s    r5   r*   zServerTaskContext.taskm   s     y~r7   c                     | j         j        S )z(Whether cancellation has been requested.)r/   is_cancelledr;   s    r5   r>   zServerTaskContext.is_cancelledr   s     y%%r7   c                 8    | j                                          dS )z"Request cancellation of this task.N)r/   request_cancellationr;   s    r5   r@   z&ServerTaskContext.request_cancellationw   s    	&&(((((r7   T)notifymessagerA   c                   K   | j                             |           d{V  |r|                                  d{V  dS dS )z
        Update the task's status message.

        Args:
            message: The new status message
            notify: Whether to send a notification to the client
        N)r/   update_status_send_notification)r4   rB   rA   s      r5   rD   zServerTaskContext.update_status}   sl       i%%g......... 	,))+++++++++++	, 	,r7   resultc                   K   | j                             |           d{V  |r|                                  d{V  dS dS )z
        Mark the task as completed with the given result.

        Args:
            result: The task result
            notify: Whether to send a notification to the client
        N)r/   completerE   )r4   rF   rA   s      r5   rH   zServerTaskContext.complete   sl       i  ((((((((( 	,))+++++++++++	, 	,r7   errorc                   K   | j                             |           d{V  |r|                                  d{V  dS dS )z
        Mark the task as failed with an error message.

        Args:
            error: The error message
            notify: Whether to send a notification to the client
        N)r/   failrE   )r4   rI   rA   s      r5   rK   zServerTaskContext.fail   sj       innU######### 	,))+++++++++++	, 	,r7   c                   K   | j         j        }| j                            t	          t          t          |j        |j        |j	        |j
        |j        |j        |j                                                 d{V  dS )z.Send a task status notification to the client.)taskIdstatusstatusMessage	createdAtlastUpdatedAtttlpollInterval)paramsN)r/   r*   r0   send_notificationr    r#   r$   rM   rN   rO   rP   rQ   rR   rS   )r4   r*   s     r5   rE   z$ServerTaskContext._send_notification   s      y~m--&7#{#{&*&8"&.&*&8 H%)%6  
 
 
 
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
r7   c                     | j                             t          t                                          s#t	          t          t          d                    dS )z)Check if the client supports elicitation.)elicitationz.Client does not support elicitation capabilitycoderB   N)r0   check_client_capabilityr   r   r   r   r   r;   s    r5   _check_elicitation_capabilityz/ServerTaskContext._check_elicitation_capability   sa    }445GTiTkTk5l5l5lmm 	(L    	 	r7   c                     | j                             t          t                                          s#t	          t          t          d                    dS )z&Check if the client supports sampling.)samplingz+Client does not support sampling capabilityrX   N)r0   rZ   r   r   r   r   r   r;   s    r5   _check_sampling_capabilityz,ServerTaskContext._check_sampling_capability   sa    }445GQcQeQe5f5f5fgg 	(I    	 	r7   requestedSchemac                   K   |                                   | j        t          d          | j                            | j        t                     d{V  | j                            ||| j                  }|j	        }t                      }|| j        j        |<   t          d|||          }| j                            | j        |           d{V  	 |                                 d{V }| j                            | j        t                      d{V  t#          j        |          S # t'          j                    $ r. | j                            | j        t                      d{V   w xY w)a  
        Send an elicitation request via the task message queue.

        This method:
        1. Checks client capability
        2. Updates task status to "input_required"
        3. Queues the elicitation request
        4. Waits for the response (delivered via tasks/result round-trip)
        5. Updates task status back to "working"
        6. Returns the result

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

        Returns:
            The client's response

        Raises:
            McpError: If client doesn't support elicitation capability
        NzEhandler is required for elicit(). Pass handler= to ServerTaskContext.rN   )rB   r_   related_task_idrequesttyperB   resolveroriginal_request_id)r[   r2   RuntimeErrorr3   update_taskr:   r   r0   _build_elicit_form_requestidr   _pending_requestsr   r1   enqueuewaitr   r   model_validateanyioget_cancelled_exc_class)r4   rB   r_   rc   
request_idrf   queuedresponse_datas           r5   elicitzServerTaskContext.elicit   s     4 	**,,,= fggg k%%dl;U%VVVVVVVVV -::+ L ; 
 

 !(

-5ZZ6>'
3 *	
 
 
 k!!$,777777777
	"*--//111111M+))$,?R)SSSSSSSSS.}===,.. 	 	 	 +))$,?R)SSSSSSSSS	s   AD3 3AE7urlelicitation_idc                   K   |                                   | j        t          d          | j                            | j        t                     d{V  | j                            |||| j                  }|j	        }t                      }|| j        j        |<   t          d|||          }| j                            | j        |           d{V  	 |                                 d{V }| j                            | j        t                      d{V  t#          j        |          S # t'          j                    $ r. | j                            | j        t                      d{V   w xY w)a  
        Send a URL mode elicitation request via the task message queue.

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

        This method:
        1. Checks client capability
        2. Updates task status to "input_required"
        3. Queues the elicitation request
        4. Waits for the response (delivered via tasks/result round-trip)
        5. Updates task status back to "working"
        6. Returns the result

        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

        Returns:
            The client's response indicating acceptance, decline, or cancellation

        Raises:
            McpError: If client doesn't support elicitation capability
            RuntimeError: If handler is not configured
        NzIhandler is required for elicit_url(). Pass handler= to ServerTaskContext.ra   )rB   rv   rw   rb   rc   rd   )r[   r2   rh   r3   ri   r:   r   r0   _build_elicit_url_requestrk   r   rl   r   r1   rm   rn   r   r   ro   rp   rq   )	r4   rB   rv   rw   rc   rr   rf   rs   rt   s	            r5   
elicit_urlzServerTaskContext.elicit_url  s     @ 	**,,,= jkkk k%%dl;U%VVVVVVVVV -99) L	 : 
 
 !(

-5ZZ6>'
3 *	
 
 
 k!!$,777777777	"*--//111111M+))$,?R)SSSSSSSSS.}===,.. 	 	 	+))$,?R)SSSSSSSSS	s   AD4 4AE8)system_promptinclude_contexttemperaturestop_sequencesmetadatamodel_preferencestoolstool_choicemessages
max_tokensr{   r|   r}   r~   r   r   r   r   c       	           K   |                                   | j        j        r| j        j        j        nd}t	          ||	|
           t          |           | j        t          d          | j        	                    | j
        t                     d{V  | j                            |||||||||	|
| j
                  }|j        }t                      }|| j        j        |<   t!          d|||          }| j                            | j
        |           d{V  	 |                                 d{V }| j        	                    | j
        t(                     d{V  t+          j        |          S # t/          j                    $ r. | j        	                    | j
        t(                     d{V   w xY w)a  
        Send a sampling request via the task message queue.

        This method:
        1. Checks client capability
        2. Updates task status to "input_required"
        3. Queues the sampling request
        4. Waits for the response (delivered via tasks/result round-trip)
        5. Updates task status back to "working"
        6. Returns the result

        Args:
            messages: The conversation messages for sampling
            max_tokens: Maximum tokens in the response
            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 sampling capability or tools
            ValueError: If tool_use or tool_result message structure is invalid
        NzMhandler is required for create_message(). Pass handler= to ServerTaskContext.ra   )r   r   r{   r|   r}   r~   r   r   r   r   rb   rc   rd   )r^   r0   client_paramscapabilitiesr   r   r2   rh   r3   ri   r:   r   _build_create_message_requestrk   r   rl   r   r1   rm   rn   r   r   ro   rp   rq   )r4   r   r   r{   r|   r}   r~   r   r   r   r   client_capsrc   rr   rf   rs   rt   s                    r5   create_messagez ServerTaskContext.create_messageP  s     X 	'')))BF-B]gdm1>>cgUK@@@)(333= nooo k%%dl;U%VVVVVVVVV -==!'+#)/# L > 
 
 !(

-5ZZ6>'
3 *	
 
 
 k!!$,777777777
	"*--//111111M+))$,?R)SSSSSSSSS&5mDDD,.. 	 	 	 +))$,?R)SSSSSSSSS	s    AE: :AF>i`  rR   rR   c                  K   | j         j        r| j         j        j        nd}t          |           | j        t          d          | j                            | j        t                     d{V  | j         
                    ||| j        t          |                    }|j        }t                      }|| j        j        |<   t          d|||          }| j                            | j        |           d{V  	 |                                 d{V }	t'          j        |	          }
|
j        j        }| j         j                            |          2 3 d{V }6 | j         j                            |t4                     d{V }| j                            | j        t6                     d{V  |S # t9          j                    $ r. | j                            | j        t6                     d{V   w xY w)aJ  
        Send a task-augmented elicitation via the queue, then poll client.

        This is for use inside a task-augmented tool call when you want the client
        to handle the elicitation as its own task. The elicitation request is queued
        and delivered when the client calls tasks/result. After the client responds
        with CreateTaskResult, we poll the client's task until complete.

        Args:
            message: The message to present to the user
            requestedSchema: Schema defining the expected response structure
            ttl: Task time-to-live in milliseconds for the client's task

        Returns:
            The client's elicitation response

        Raises:
            McpError: If client doesn't support task-augmented elicitation
            RuntimeError: If handler is not configured
        Nz(handler is required for elicit_as_task()ra   r   )rB   r_   rb   r*   rc   rd   )r0   r   r   r	   r2   rh   r3   ri   r:   r   rj   r"   rk   r   rl   r   r1   rm   rn   r   ro   r*   rM   experimental	poll_taskget_task_resultr   r   rp   rq   )r4   rB   r_   rR   r   rc   rr   rf   rs   rt   create_resultclient_task_id_rF   s                 r5   elicit_as_taskz ServerTaskContext.elicit_as_task  su     6 CG-B]gdm1>>cg*;777= IJJJ k%%dl;U%VVVVVVVVV-::+ L#&&&	 ; 
 
 !(

-5ZZ6>'
3 *	
 
 
 k!!$,777777777	"*--//111111M,;MJJM*/6N  =5??OO       a P  =5EE       F
 +))$,?R)SSSSSSSSSM,.. 	 	 	+))$,?R)SSSSSSSSS	s   AF= E#!AF= =AH)	rR   r{   r|   r}   r~   r   r   r   r   c       
         X  K   | j         j        r| j         j        j        nd}t          |           t	          ||
|           t          |           | j        t          d          | j        	                    | j
        t                     d{V  | j                             ||||||||	|
|| j
        t          |                    }|j        }t                      }|| j        j        |<   t#          d|||          }| j                            | j
        |           d{V  	 |                                 d{V }t+          j        |          }|j        j        }| j         j                            |          2 3 d{V }6 | j         j                            |t8                     d{V }| j        	                    | j
        t:                     d{V  |S # t=          j                    $ r. | j        	                    | j
        t:                     d{V   w xY w)a<  
        Send a task-augmented sampling request via the queue, then poll client.

        This is for use inside a task-augmented tool call when you want the client
        to handle the sampling as its own task. The request is queued and delivered
        when the client calls tasks/result. After the client responds with
        CreateTaskResult, we poll the client's task until complete.

        Args:
            messages: The conversation messages for sampling
            max_tokens: Maximum tokens in the response
            ttl: Task time-to-live in milliseconds for the client's task
            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
            RuntimeError: If handler is not configured
        Nz0handler is required for create_message_as_task()ra   r   )r   r   r{   r|   r}   r~   r   r   r   r   rb   r*   rc   rd   ) r0   r   r   r
   r   r   r2   rh   r3   ri   r:   r   r   r"   rk   r   rl   r   r1   rm   rn   r   ro   r*   rM   r   r   r   r   r   rp   rq   )r4   r   r   rR   r{   r|   r}   r~   r   r   r   r   r   rc   rr   rf   rs   rt   r   r   r   rF   s                         r5   create_message_as_taskz(ServerTaskContext.create_message_as_task  s     X CG-B]gdm1>>cg'444UK@@@)(333= QRRR k%%dl;U%VVVVVVVVV -==!'+#)/# L#&&& > 
 
 !(

-5ZZ6>'
3 *	
 
 
 k!!$,777777777	"*--//111111M,;MJJM*/6N  =5??OO       a P  =5EE#       F
 +))$,?R)SSSSSSSSSM,.. 	 	 	+))$,?R)SSSSSSSSS	s   *AG% F	AG% %AH))r8   N)*__name__
__module____qualname____doc__r!   r   r   r   r   r6   propertystrr:   r*   boolr>   r@   rD   r   rH   rK   rE   r[   r^   r   r   ru   rz   listr   intr   floatdictr   r   r%   r&   r   r   r   r    r7   r5   r(   r(   5   s        < -1    	
    #T)   6 ! ! ! ! X! d    X &d & & & X&) ) ) ) CG 
, 
, 
,3 
,4 
,4 
, 
, 
, 
, @D 
, 
, 
,V 
, 
, 
, 
, 
, 
, 8< 
, 
, 
, 
, 
, 
, 
, 
, 
,
 
 
 
*      ?? /? 
	? ? ? ?BCC C 	C
 
C C C CT %)15$(+/*.59#')-\ \ \'\ 	\
 Tz\ ($.\ T\\ S	D(\ sCx.4'\ ,d2\ DzD \  $&\ 
\ \ \ \F L L LL /L
 L 
L L L Lf $(15$(+/*.59#')-h h h'h 	h
 h Tzh ($.h T\h S	D(h sCx.4'h ,d2h DzD h  $&h 
h h h h h hr7   r(   )2r   typingr   rp   +mcp.server.experimental.task_result_handlerr   mcp.server.sessionr   mcp.server.validationr   r   mcp.shared.exceptionsr   *mcp.shared.experimental.tasks.capabilitiesr	   r
   %mcp.shared.experimental.tasks.contextr   +mcp.shared.experimental.tasks.message_queuer   r   &mcp.shared.experimental.tasks.resolverr   #mcp.shared.experimental.tasks.storer   	mcp.typesr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r(   r   r7   r5   <module>r      s(           I I I I I I , , , , , , \ \ \ \ \ \ \ \ * * * * * *        > = = = = = W W W W W W W W ; ; ; ; ; ; 9 9 9 9 9 9                                                 6o o o o o o o o o or7   