
    )`i                        d 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 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 d
ZdZdedefdZdededefdZdefdZ 	 ddededz  defdZ!edededee         fd            Z"dS )z
Helper functions for pure task management.

These helpers work with pure TaskContext and don't require server dependencies.
For server-integrated task helpers, use mcp.server.experimental.
    )AsyncIterator)asynccontextmanager)datetimetimezone)uuid4)McpError)TaskContext)	TaskStore)
INVALID_PARAMSTASK_STATUS_CANCELLEDTASK_STATUS_COMPLETEDTASK_STATUS_FAILEDTASK_STATUS_WORKINGCancelTaskResult	ErrorDataTaskTaskMetadata
TaskStatusz0io.modelcontextprotocol/model-immediate-responsez$io.modelcontextprotocol/related-taskstatusreturnc                 .    | t           t          t          fv S )a  
    Check if a task status represents a terminal state.

    Terminal states are those where the task has finished and will not change.

    Args:
        status: The task status to check

    Returns:
        True if the status is terminal (completed, failed, or cancelled)
    )r   r   r   r   s    y/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/mcp/shared/experimental/tasks/helpers.pyis_terminalr   &   s     +-?AVWWW    storetask_idc                   K   |                      |           d{V }|&t          t          t          d|                     t	          |j                  r,t          t          t          d|j         d                    |                     |t                     d{V }t          di |	                                S )a7  
    Cancel a task with spec-compliant validation.

    Per spec: "Receivers MUST reject cancellation of terminal status tasks
    with -32602 (Invalid params)"

    This helper validates that the task exists and is not in a terminal state
    before setting it to "cancelled".

    Args:
        store: The task store
        task_id: The task identifier to cancel

    Returns:
        CancelTaskResult with the cancelled task state

    Raises:
        McpError: With INVALID_PARAMS (-32602) if:
            - Task does not exist
            - Task is already in a terminal state (completed, failed, cancelled)

    Example:
        @server.experimental.cancel_task()
        async def handle_cancel(request: CancelTaskRequest) -> CancelTaskResult:
            return await cancel_task(store, request.params.taskId)
    NzTask not found: )codemessagez&Cannot cancel task in terminal state ''r    )
get_taskr   r   r   r   r   update_taskr   r   
model_dump)r   r   taskcancelled_tasks       r   cancel_taskr(   5   s      < ((((((((D|#4744  
 
 	
 4; 
#OOOO  
 
 	
 !,,W=R,SSSSSSSSN::n7799:::r   c                  8    t          t                                S )zGenerate a unique task ID.)strr   r"   r   r   generate_task_idr+   i   s    uww<<r   Nmetadatac                     t          j        t          j                  }t	          |pt                      t          ||| j        d          S )a  
    Create a Task object with initial state.

    This is a helper for TaskStore implementations.

    Args:
        metadata: Task metadata
        task_id: Optional task ID (generated if not provided)

    Returns:
        A new Task in "working" status
    i  )taskIdr   	createdAtlastUpdatedAtttlpollInterval)r   nowr   utcr   r+   r   r1   )r,   r   r3   s      r   create_task_stater5   n   sL      ,x|
$
$C,*,,"L   r   c                T  K   |                     |            d{V }|t          d|  d          t          ||          }	 |W V  dS # t          $ rR}t	          |j        j                  s.|                    t          |                     d{V  Y d}~dS Y d}~dS d}~ww xY w)a  
    Context manager for safe task execution (pure, no server dependencies).

    Loads a task from the store and provides a TaskContext for the work.
    If an unhandled exception occurs, the task is automatically marked as failed
    and the exception is suppressed (since the failure is captured in task state).

    This is useful for distributed workers that don't have a server session.

    Args:
        task_id: The task identifier to execute
        store: The task store (must be accessible by the worker)

    Yields:
        TaskContext for updating status and completing/failing the task

    Raises:
        ValueError: If the task is not found in the store

    Example (distributed worker):
        async def worker_process(task_id: str):
            store = RedisTaskStore(redis_url)
            async with task_execution(task_id, store) as ctx:
                await ctx.update_status("Working...")
                result = await do_work()
                await ctx.complete(result)
    NzTask z
 not found)	r#   
ValueErrorr	   	Exceptionr   r&   r   failr*   )r   r   r&   ctxes        r   task_executionr<      s      @ ((((((((D|4444555
dE
"
"C#						 # # # 38?++ 	#((3q66"""""""""""""""	# 	# 	# 	# 	# 	##s   A 
B'AB""B')N)#__doc__collections.abcr   
contextlibr   r   r   uuidr   mcp.shared.exceptionsr   %mcp.shared.experimental.tasks.contextr	   #mcp.shared.experimental.tasks.storer
   	mcp.typesr   r   r   r   r   r   r   r   r   r   MODEL_IMMEDIATE_RESPONSE_KEYRELATED_TASK_METADATA_KEYboolr   r*   r(   r+   r5   r<   r"   r   r   <module>rH      s    * ) ) ) ) ) * * * * * * ' ' ' ' ' ' ' '       * * * * * * = = = = = = 9 9 9 9 9 9                          R  C X
 Xt X X X X1;1;1; 1; 1; 1; 1;h#      4Z 
   6 *#*#*# ;*# *# *# *# *# *#r   