
    Ki !                         d Z ddlmZ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 dd	lmZ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 e G d d             Zy)a	  
Experimental request context features.

This module provides the Experimental class which gives access to experimental
features within a request context, such as task-augmented request handling.

WARNING: These APIs are experimental and may change without notice.
    )	AwaitableCallable)	dataclassfield)Any)ServerTaskContext)TaskSupport)ServerSession)McpError)MODEL_IMMEDIATE_RESPONSE_KEYis_terminal)
METHOD_NOT_FOUNDTASK_FORBIDDENTASK_REQUIREDClientCapabilitiesCreateTaskResult	ErrorDataResultTaskExecutionModeTaskMetadataToolc            	       X   e Zd ZU dZdZedz  ed<    edd      Ze	dz  ed<    edd      Z
edz  ed<    edd      Zedz  ed<   ed	efd
       Zed	efd       Zdddedz  ded	edz  fdZdddeded	edz  fdZdedz  d	efdZddddeegee   f   dedz  dedz  d	efdZy)Experimentala  
    Experimental features context for task-augmented requests.

    Provides helpers for validating task execution compatibility and
    running tasks with automatic lifecycle management.

    WARNING: This API is experimental and may change without notice.
    Ntask_metadataF)defaultrepr_client_capabilities_session_task_supportreturnc                     | j                   duS )z(Check if this request is task-augmented.N)r   selfs    s/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/mcp/server/experimental/request_context.pyis_taskzExperimental.is_task1   s     !!--    c                 L    | j                   y| j                   j                  duS )z*Check if the client declared task support.NF)r   tasksr"   s    r$   client_supports_tasksz"Experimental.client_supports_tasks6   s*     $$,((..d::r&   Traise_errortool_task_moder+   c                    |xs t         }d}|t        k(  r| j                  st        t        d      }n&|t         k(  r| j                  rt        t        d      }||rt        |      |S )a  
        Validate that the request is compatible with the tool's task execution mode.

        Per MCP spec:
        - "required": Clients MUST invoke as task. Server returns -32601 if not.
        - "forbidden" (or None): Clients MUST NOT invoke as task. Server returns -32601 if they do.
        - "optional": Either is acceptable.

        Args:
            tool_task_mode: The tool's execution.taskSupport value
                ("forbidden", "optional", "required", or None)
            raise_error: If True, raises McpError on validation failure. If False, returns ErrorData.

        Returns:
            None if valid, ErrorData if invalid and raise_error=False

        Raises:
            McpError: If invalid and raise_error=True
        Nz,This tool requires task-augmented invocation)codemessagez4This tool does not support task-augmented invocation)r   r   r%   r   r   r   )r#   r,   r+   modeerrors        r$   validate_task_modezExperimental.validate_task_mode=   sj    4 /"&= %FE ^#%NE
 5/!r&   toolc                p    |j                   r|j                   j                  nd}| j                  ||      S )a  
        Validate that the request is compatible with the given tool.

        Convenience wrapper around validate_task_mode that extracts the mode from a Tool.

        Args:
            tool: The Tool definition
            raise_error: If True, raises McpError on validation failure.

        Returns:
            None if valid, ErrorData if invalid and raise_error=False
        Nr*   )	executiontaskSupportr2   )r#   r3   r+   r0   s       r$   validate_for_toolzExperimental.validate_for_toolk   s1    $ .2^^t~~))&&t&EEr&   c                 D    |xs t         }|t        k(  r| j                  syy)a  
        Check if this client can use a tool with the given task mode.

        Useful for filtering tool lists or providing warnings.
        Returns False if tool requires "required" but client doesn't support tasks.

        Args:
            tool_task_mode: The tool's execution.taskSupport value

        Returns:
            True if the client can use this tool, False otherwise
        FT)r   r   r)   )r#   r,   r0   s      r$   can_use_toolzExperimental.can_use_tool   s$     /= )C)Cr&   )task_idmodel_immediate_responseworkr:   r;   c                
  	K   | j                   t        d      | j                  t        d      | j                  t        d      | j                   }|j                  }|j
                  j                  | j                  |       d{   }t        ||j
                  | j                  |j                  |j                        	d		fd}|j                  |       d}|t        |i}t        d
d|i|rd|iS i S 7 uw)as  
        Create a task, spawn background work, and return CreateTaskResult immediately.

        This is the recommended way to handle task-augmented tool calls. It:
        1. Creates a task in the store
        2. Spawns the work function in a background task
        3. Returns CreateTaskResult immediately

        The work function receives a ServerTaskContext with:
        - elicit() for sending elicitation requests
        - create_message() for sampling requests
        - update_status() for progress updates
        - complete()/fail() for finishing the task

        When work() returns a Result, the task is auto-completed with that result.
        If work() raises an exception, the task is auto-failed.

        Args:
            work: Async function that does the actual work
            task_id: Optional task ID (generated if not provided)
            model_immediate_response: Optional string to include in _meta as
                io.modelcontextprotocol/model-immediate-response

        Returns:
            CreateTaskResult to return to the client

        Raises:
            RuntimeError: If task support is not enabled or task_metadata is missing

        Example:
            @server.call_tool()
            async def handle_tool(name: str, args: dict):
                ctx = server.request_context

                async def work(task: ServerTaskContext) -> CallToolResult:
                    result = await task.elicit(
                        message="Are you sure?",
                        requestedSchema={"type": "object", ...}
                    )
                    confirmed = result.content.get("confirm", False)
                    return CallToolResult(content=[TextContent(text="Done" if confirmed else "Cancelled")])

                return await ctx.experimental.run_task(work)

        WARNING: This API is experimental and may change without notice.
        NzHTask support not enabled. Call server.experimental.enable_tasks() first.zSession not available.zgRequest is not task-augmented (no task field in params). The client must send a task-augmented request.)taskstoresessionqueuehandlerc                  d  K   	         d {   } t        j                  j                        sj                  |        d {    y y 7 >7 # t        $ rQ}t        j                  j                        s(j                  t        |             d {  7   Y d }~y Y d }~y d }~ww xY ww)N)r   r>   statuscomplete	Exceptionfailstr)resultetask_ctxr<   s     r$   executez&Experimental.run_task.<locals>.execute   s     0#H~-"8==#7#78"++F333 9 .3 0"8==#7#78"--A/// 90s\   B0A A7A A	A B0A A 	B-<B(BB(
B0(B--B0r>   _meta)r    N )r   RuntimeErrorr   r   
task_groupr?   create_taskr   rA   rB   
start_soonr   r   )
r#   r<   r:   r;   supportrP   r>   rL   metarK   s
    `       @r$   run_taskzExperimental.run_task   s	    j %ijj== 788%A 
 $$''
]]..t/A/A7KK$--MM--OO
	0 	g&&*#/02JKDMTMgt_MM"MM3 Ls   BDDA6D)__name__
__module____qualname____doc__r   r   __annotations__r   r   r   r   r
   r   r	   propertyboolr%   r)   r   r   r2   r   r7   r9   r   r   r   r   rH   r   rU   rN   r&   r$   r   r   !   sa    *.M<$&-6;Du6U,t3U%*4e%DHmd"D(-d(GM;%G. . . ;t ; ; !	,)D0, 	,
 
T	,d !	FF 	F
 
T	F*+<t+C  , #/3\N)*If,==>\N t	\N
 #&*\N 
\Nr&   r   N) rY   collections.abcr   r   dataclassesr   r   typingr   $mcp.server.experimental.task_contextr   $mcp.server.experimental.task_supportr	   mcp.server.sessionr
   mcp.shared.exceptionsr   %mcp.shared.experimental.tasks.helpersr   r   	mcp.typesr   r   r   r   r   r   r   r   r   r   r   rN   r&   r$   <module>rf      sR    0 (  B < , * [   LN LN LNr&   