
    KiY                        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      Z1y)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)y)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                `    t        ||      | _        || _        || _        || _        || _        y)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         p/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/mcp/server/experimental/task_context.py__init__zServerTaskContext.__init__M   s.    &  T7	    returnc                 .    | j                   j                  S )zThe task identifier.)r/   task_idr4   s    r5   r:   zServerTaskContext.task_idh   s     yy   r7   c                 .    | j                   j                  S )zThe current task state.)r/   r*   r;   s    r5   r*   zServerTaskContext.taskm   s     yy~~r7   c                 .    | j                   j                  S )z(Whether cancellation has been requested.)r/   is_cancelledr;   s    r5   r>   zServerTaskContext.is_cancelledr   s     yy%%%r7   c                 8    | j                   j                          y)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                   j                  |       d{    |r| j                          d{    yy7  7 w)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}   sC      ii%%g...))+++  	/+   AAAAAAresultc                   K   | j                   j                  |       d{    |r| j                          d{    yy7  7 w)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   rG   rA   s      r5   rI   zServerTaskContext.complete   sC      ii  ((())+++  	)+rF   errorc                   K   | j                   j                  |       d{    |r| j                          d{    yy7  7 w)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   rJ   rA   s      r5   rL   zServerTaskContext.fail   sA      iinnU###))+++  	$+rF   c                 T  K   | j                   j                  }| j                  j                  t	        t        t        |j                  |j                  |j                  |j                  |j                  |j                  |j                                           d{    y7 w)z.Send a task status notification to the client.)taskIdstatusstatusMessage	createdAtlastUpdatedAtttlpollInterval)paramsN)r/   r*   r0   send_notificationr    r#   r$   rN   rO   rP   rQ   rR   rS   rT   )r4   r*   s     r5   rE   z$ServerTaskContext._send_notification   s~     yy~~mm--&7#{{#{{&*&8&8"&..&*&8&8 HH%)%6%6

 	
 	
s   BB( B&!B(c                     | j                   j                  t        t                           st	        t        t        d            y)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   s?    }}445GTiTk5lm(L  nr7   c                     | j                   j                  t        t                           st	        t        t        d            y)z&Check if the client supports sampling.)samplingz+Client does not support sampling capabilityrY   N)r0   r[   r   r   r   r   r   r;   s    r5   _check_sampling_capabilityz,ServerTaskContext._check_sampling_capability   s?    }}445GQcQe5fg(I  hr7   requestedSchemac                 X  K   | j                          | j                  t        d      | j                  j	                  | j
                  t               d{    | j                  j                  ||| j
                        }|j                  }t               }|| j                  j                  |<   t        d|||      }| j                  j                  | j
                  |       d{    	 |j                          d{   }| j                  j	                  | j
                  t                d{    t#        j$                  |      S 7 7 g7 P7 # t'        j(                         $ r6 | j                  j	                  | j
                  t                d{  7    w xY w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.rO   )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`   rd   
request_idrg   queuedresponse_datas           r5   elicitzServerTaskContext.elicit   sl    4 	**,== fgg kk%%dll;U%VVV --::+ LL ; 

 !(


-5Z6>''
3 *	
 kk!!$,,777
	"*--/1M++))$,,?R)SSS..}==3 	W& 	8 2S,,. 	 ++))$,,?R)SSS	sn   AF*EBF*,E-F*2E E2E 8E9E F*F*E E AF'F" F''F*urlelicitation_idc                 Z  K   | j                          | j                  t        d      | j                  j	                  | j
                  t               d{    | j                  j                  |||| j
                        }|j                  }t               }|| j                  j                  |<   t        d|||      }| j                  j                  | j
                  |       d{    	 |j                          d{   }| j                  j	                  | j
                  t                d{    t#        j$                  |      S 7 7 g7 P7 # t'        j(                         $ r6 | j                  j	                  | j
                  t                d{  7    w xY w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.rb   )rB   rw   rx   rc   rd   re   )r\   r2   ri   r3   rj   r:   r   r0   _build_elicit_url_requestrl   r   rm   r   r1   rn   ro   r   r   rp   rq   rr   )	r4   rB   rw   rx   rd   rs   rg   rt   ru   s	            r5   
elicit_urlzServerTaskContext.elicit_url  sn    @ 	**,== jkk kk%%dll;U%VVV --99) LL	 : 
 !(


-5Z6>''
3 *	
 kk!!$,,777	"*--/1M++))$,,?R)SSS..}==5 	W( 	8 2S,,. 	++))$,,?R)SSS	sn   AF+EBF+-E.F+3E E2E 9E:E F+F+E E AF( F#!F((F+)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                  j                  r | j                  j                  j                  nd}t	        ||	|
       t        |       | j                  t        d      | j                  j                  | j                  t               d{    | j                  j                  |||||||||	|
| j                        }|j                  }t               }|| j                  j                  |<   t!        d|||      }| j"                  j%                  | j                  |       d{    	 |j'                          d{   }| j                  j                  | j                  t(               d{    t+        j,                  |      S 7 7 h7 Q7  # t/        j0                         $ r6 | j                  j                  | j                  t(               d{  7    w xY w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.rb   )r   r   r|   r}   r~   r   r   r   r   r   rc   rd   re   )r_   r0   client_paramscapabilitiesr   r   r2   ri   r3   rj   r:   r   _build_create_message_requestrl   r   rm   r   r1   rn   ro   r   r   rp   rq   rr   )r4   r   r   r|   r}   r~   r   r   r   r   r   client_capsrd   rs   rg   rt   ru   s                    r5   create_messagez ServerTaskContext.create_messageP  s    X 	'')BF--B]B]dmm11>>cgUK@)(3== noo kk%%dll;U%VVV --==!'+#)/# LL > 
 !(


-5Z6>''
3 *	
 kk!!$,,777
	"*--/1M++))$,,?R)SSS&55mDDC 	W6 	8 2S,,. 	 ++))$,,?R)SSS	sn   B&H(F*)BHF-H
F3 F/2F3 F1F3 )H-H/F3 1F3 3AH 8G;9H  Hi`  rS   rS   c                  K   | j                   j                  r | j                   j                  j                  nd}t        |       | j                  t        d      | j                  j                  | j                  t               d{    | j                   j                  ||| j                  t        |            }|j                  }t               }|| j                  j                  |<   t        d|||      }| j                   j#                  | j                  |       d{    	 |j%                          d{   }	t'        j(                  |	      }
|
j*                  j,                  }| j                   j.                  j1                  |      2 3 d{   }
7 7 z7 c7 6 | j                   j.                  j3                  |t4               d{  7  }| j                  j                  | j                  t6               d{  7   |S # t9        j:                         $ r6 | j                  j                  | j                  t6               d{  7    w xY w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()rb   r   )rB   r`   rc   r*   rd   re   )r0   r   r   r	   r2   ri   r3   rj   r:   r   rk   r"   rl   r   rm   r   r1   rn   ro   r   rp   r*   rN   experimental	poll_taskget_task_resultr   r   rq   rr   )r4   rB   r`   rS   r   rd   rs   rg   rt   ru   create_resultclient_task_id_rG   s                 r5   elicit_as_taskz ServerTaskContext.elicit_as_task  s    6 CG--B]B]dmm11>>cg*;7== IJJ kk%%dll;U%VVV--::+ LL#&	 ; 
 !(


-5Z6>''
3 *	
 kk!!$,,777	"*--/1M,;;MJM*//66N  ==55??O  a; 	W& 	8 2
O  ==55EE  F
 ++))$,,?R)SSSM,,. 	++))$,,?R)SSS	s   B	I%F"BI%*F%+I%0H F'AH F+F)F+ H "I%%I%'H )F++.H G3H HH I%AI"II""I%)	rS   r|   r}   r~   r   r   r   r   r   c       
           K   | j                   j                  r | j                   j                  j                  nd}t        |       t	        ||
|       t        |       | j                  t        d      | j                  j                  | j                  t               d{    | j                   j                  ||||||||	|
|| j                  t        |            }|j                  }t               }|| j                  j                   |<   t#        d|||      }| j$                  j'                  | j                  |       d{    	 |j)                          d{   }t+        j,                  |      }|j.                  j0                  }| j                   j2                  j5                  |      2 3 d{   }
7 7 z7 c7 6 | j                   j2                  j7                  |t8               d{  7  }| j                  j                  | j                  t:               d{  7   |S # t=        j>                         $ r6 | j                  j                  | j                  t:               d{  7    w xY w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()rb   r   )r   r   r|   r}   r~   r   r   r   r   r   rc   r*   rd   re   ) r0   r   r   r
   r   r   r2   ri   r3   rj   r:   r   r   r"   rl   r   rm   r   r1   rn   ro   r   rp   r*   rN   r   r   r   r   r   rq   rr   )r4   r   r   rS   r|   r}   r~   r   r   r   r   r   r   rd   rs   rg   rt   ru   r   r   r   rG   s                         r5   create_message_as_taskz(ServerTaskContext.create_message_as_task  s4    X CG--B]B]dmm11>>cg'4UK@)(3== QRR kk%%dll;U%VVV --==!'+#)/# LL#& > 
 !(


-5Z6>''
3 *	
 kk!!$,,777	"*--/1M,;;MJM*//66N  ==55??O  aM 	W8 	8 2
O  ==55EE#  F
 ++))$,,?R)SSSM,,. 	++))$,,?R)SSS	s   B!J#G$B&J
GJH5 #G$AH5 8G<G	=G H5 JJH5 	G.H5 9G<:3H5 -H0.H5 4J5AJ:I=;JJ)r8   N)*__name__
__module____qualname____doc__r!   r   r   r   r   r6   propertystrr:   r*   boolr>   r@   rD   r   rI   rL   rE   r\   r_   r   r   rv   r{   listr   intr   floatdictr   r   r%   r&   r   r   r   r    r7   r5   r(   r(   5   sJ   < -1  	
    #T)6 ! ! ! d   &d & &) CG 
,3 
,4 
,4 
, @D 
,V 
, 
, 
, 8< 
, 
, 
, 
,
*?? /? 
	?BCC C 	C
 
CT %)15$(+/*.59#')-\'\ 	\
 Tz\ ($.\ T\\ S	D(\ sCx.4'\ ,d2\ DzD \  $&\ 
\F LL /L
 L 
Lf $(15$(+/*.59#')-h'h 	h
 h Tzh ($.h T\h S	D(h sCx.4'h ,d2h DzD h  $&h 
hr7   r(   )2r   typingr   rq   +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 , \ * > W ; 9      6o or7   