
    ie7                       d Z ddlmZ ddlZddlmZ ddlmZm	Z	m
Z
mZmZ ddlZddlZerddlmZ ddlmZ ddlmZ ddlZdd	lmZ dd
lmZmZ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) ddl*m+Z+ ddl,m-Z-  e+e.      Z/ G d dej`                        Z1 G d de-      Z G d dej`                        Z2 G d de)      Zg dZ3ddZ4y)z!Base classes for FastMCP prompts.    )annotationsN)Callable)TYPE_CHECKINGAnyClassVarLiteraloverload)Docket)	ExecutionFunctionPrompt)GetPromptResult)EmbeddedResourceIconPromptMessageTextContent)Prompt)PromptArgument)Field)SkipJsonSchema)	AuthCheck)
TaskConfigTaskMeta)FastMCPComponent)
get_logger)FastMCPBaseModelc                  L     e Zd ZU dZded<   ded<   	 d	 	 	 d	 fdZd
dZ xZS )Messagea  Wrapper for prompt message with auto-serialization.

    Accepts any content - strings pass through, other types
    (dict, list, BaseModel) are JSON-serialized to text.

    Example:
        ```python
        from fastmcp.prompts import Message

        # String content (user role by default)
        Message("Hello, world!")

        # Explicit role
        Message("I can help with that.", role="assistant")

        # Auto-serialized to JSON
        Message({"key": "value"})
        Message(["item1", "item2"])
        ```
    Literal['user', 'assistant']rolezTextContent | EmbeddedResourcecontentc                   t        |t        t        f      r|}nTt        |t              rt        d|      }n6t	        j
                  |t              j                         }t        d|      }t        | !  ||       y)a_  Create Message with automatic serialization.

        Args:
            content: The message content. str passes through directly.
                     TextContent and EmbeddedResource pass through.
                     Other types (dict, list, BaseModel) are JSON-serialized.
            role: The message role, either "user" or "assistant".
        text)typer#   )fallbackr    r!   N)	
isinstancer   r   strpydantic_coreto_jsondecodesuper__init__)selfr!   r    normalized_content
serialized	__class__s        f/Users/bowang/.openclaw/workspace/ChatDev/.venv/lib/python3.12/site-packages/fastmcp/prompts/prompt.pyr-   zMessage.__init__B   so     g-=>?AH%!,&w!G '..wELLNJ!,&z!Jd,>?    c                D    t        | j                  | j                        S )zConvert to MCP PromptMessage.r&   )r   r    r!   )r.   s    r2   to_mcp_prompt_messagezMessage.to_mcp_prompt_message[   s    $))T\\BBr3   )user)r!   r   r    r   )returnr   )__name__
__module____qualname____doc____annotations__r-   r5   __classcell__r1   s   @r2   r   r   )   s;    * '&++
 .4@@ +@2Cr3   r   c                  j    e Zd ZU dZ ed      Zded<    edd      Zd	ed
<    edd      Zded<   y)r   z+An argument that can be passed to a prompt.zName of the argument)descriptionr(   nameNz%Description of what the argument doesdefaultr@   
str | Noner@   Fz Whether the argument is requiredboolrequired)	r8   r9   r:   r;   r   rA   r<   r@   rF    r3   r2   r   r   `   sE    5"89D#9#"IK  #EHd r3   r   c                  ~     e Zd ZU dZded<   dZded<   dZded<   	 	 d	 	 	 	 	 d fd	Ze	 	 	 	 dd
       Z	ddZ
 xZS )PromptResultaw  Canonical result type for prompt rendering.

    Provides explicit control over prompt responses: multiple messages,
    roles, and metadata at both the message and result level.

    Accepts:
        - str: Wrapped as single Message (user role)
        - list[Message]: Used directly for multiple messages or custom roles

    Example:
        ```python
        from fastmcp import FastMCP
        from fastmcp.prompts import PromptResult, Message

        mcp = FastMCP()

        # Simple string content
        @mcp.prompt
        def greet() -> PromptResult:
            return PromptResult("Hello!")

        # Multiple messages with roles
        @mcp.prompt
        def conversation() -> PromptResult:
            return PromptResult([
                Message("What's the weather?"),
                Message("It's sunny today.", role="assistant"),
            ])
        ```
    list[Message]messagesNrD   r@   dict[str, Any] | Nonemetac                L    | j                  |      }t        | 	  |||       y)zCreate PromptResult.

        Args:
            messages: String or list of Message objects.
            description: Optional description of the prompt result.
            meta: Optional metadata about the prompt result.
        )rK   r@   rM   N)_normalize_messagesr,   r-   )r.   rK   r@   rM   
normalizedr1   s        r2   r-   zPromptResult.__init__   s)     --h7
*+DQr3   c           
     6   t        | t              rt        |       gS t        | t              rMt	        |       D ]=  \  }}t        |t              rt        d| dt        |      j                   d|d       | S t        dt        |       j                         )z!Normalize input to list[Message].	messages[z] must be Message, got . Use Message() to wrap the value.z+messages must be str or list[Message], got )r'   r(   r   list	enumerate	TypeErrorr$   r8   )rK   iitems      r2   rO   z PromptResult._normalize_messages   s    
 h$H%&&h%$X.4!$0##A3&=d4j>Q>Q=R S''+h.BD  / O9$x.:Q:Q9RS
 	
r3   c                    | j                   D cg c]  }|j                          }}t        | j                  || j                        S c c}w )zConvert to MCP GetPromptResult.)r@   rK   _meta)rK   r5   r   r@   rM   )r.   mmcp_messagess      r2   to_mcp_prompt_resultz!PromptResult.to_mcp_prompt_result   sI    ;?==I=a//1=I((!))
 	
 Js   A
NN)rK   str | list[Message]r@   rD   rM   rL   )rK   r`   r7   rJ   )r7   r   )r8   r9   r:   r;   r<   r@   rM   r-   staticmethodrO   r^   r=   r>   s   @r2   rI   rI   l   s{    > "K""&D
&
 #'&*	R%R  R $	R  
%
	
 
&
r3   rI   c                  t    e Zd ZU dZdZded<    edd      Zded	<    edd
d      Zded<   	 	 	 	 ddZ	e
dddddddddd		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z	 d	 	 	 ddZddZe	 	 d 	 	 	 	 	 d!d       Ze	 	 	 	 	 	 d"d       Z	 	 d 	 	 	 	 	 d#dZd$dZddd	 	 	 	 	 	 	 	 	 	 	 d%dZd& fdZ xZS )'r   z7A prompt template that can be rendered with parameters.promptzClassVar[str]
KEY_PREFIXNz*Arguments that can be passed to the promptrB   zlist[PromptArgument] | None	argumentsz$Authorization checks for this promptT)rC   r@   excludez2SkipJsonSchema[AuthCheck | list[AuthCheck] | None]authc                   | j                   xs g D cg c].  }t        |j                  |j                  |j                        0 }}t        |j                  d| j                        |j                  d| j                        ||j                  d| j                        |j                  d| j                        |j                  d| j                                     S c c}w )z$Convert the prompt to an MCP prompt.)rA   r@   rF   rA   r@   titleiconsr[   )rA   r@   re   ri   rj   r[   )
re   SDKPromptArgumentrA   r@   rF   	SDKPromptgetri   rj   get_meta)r.   	overridesargre   s       r2   to_mcp_promptzPrompt.to_mcp_prompt   s     ~~++
 , XXOO
 , 	 
 vtyy1!mT5E5EF--4--4--	
 		

s   3C)	rA   versionri   r@   rj   tagsrM   taskrg   c       	        F    ddl m}  |j                  |||||||||	|

      S )zCreate a Prompt from a function.

        The function can return:
        - str: wrapped as single user Message
        - list[Message | str]: converted to list[Message]
        - PromptResult: used directly
        r   r   )
fnrA   rr   ri   r@   rj   rs   rM   rt   rg   )fastmcp.prompts.function_promptr   from_function)clsrv   rA   rr   ri   r@   rj   rs   rM   rt   rg   r   s               r2   rx   zPrompt.from_function   s;    , 	C+~++#
 	
r3   c                    K   t        d      w)zRender the prompt with arguments.

        Subclasses must implement this method. Return one of:
        - str: Wrapped as single user Message
        - list[Message | str]: Converted to list[Message]
        - PromptResult: Used directly
        z"Subclasses must implement render())NotImplementedError)r.   re   s     r2   renderzPrompt.render  s      ""FGGs   c           
     P   t        |t              r|S t        |t              r"t        || j                  | j                        S t        |t
        t        z        rg }t        |      D ]y  \  }}t        |t              r|j                  |       (t        |t              r|j                  t        |             St        d| dt        |      j                   d|d       t        || j                  | j                        S t        dt        |      j                         )a  Convert a raw return value to PromptResult.

        Accepts:
            - PromptResult: passed through
            - str: wrapped as single Message
            - list[Message | str]: converted to list[Message]

        Raises:
            TypeError: for unsupported types
        )r@   rM   rR   z] must be Message or str, got rS   rT   z<Prompt must return str, list[Message], or PromptResult, got )r'   rI   r(   r@   rM   rU   tuplerV   r   appendrW   r$   r8   )r.   	raw_valuerK   rX   rY   s        r2   convert_resultzPrompt.convert_result  s	    i.i%	t7G7GdiiXXi.&(H$Y/4dG,OOD)c*OOGDM2##A3&DT$ZEXEXDY Z''+h.BD  0  d6F6FTYYWW	?++,.
 	
r3   c                   K   y wNrG   r.   re   	task_metas      r2   _renderzPrompt._render9  s     
    c                   K   y wr   rG   r   s      r2   r   zPrompt._render@  s     
 &)r   c                   K   ddl m}  || d||       d{   }|r|S | j                  |       d{   }| j                  |      S 7 27 w)a:  Server entry point that handles task routing.

        This allows ANY Prompt subclass to support background execution by setting
        task_config.mode to "supported" or "required". The server calls this
        method instead of render() directly.

        Args:
            arguments: Prompt arguments
            task_meta: If provided, execute as background task and return
                CreateTaskResult. If None (default), execute synchronously and
                return PromptResult.

        Returns:
            PromptResult when task_meta is None.
            CreateTaskResult when task_meta is provided.

        Subclasses can override this to customize task routing behavior.
        For example, FastMCPProviderPrompt overrides to delegate to child
        middleware without submitting to Docket.
        r   )check_background_taskrc   )	component	task_typere   r   N)fastmcp.server.tasks.routingr   r|   r   )r.   re   r   r   task_resultresults         r2   r   zPrompt._renderG  sa     2 	G1	
 
  {{9--""6**
 .s   AAAAAAc                    | j                   j                         sy|j                  | j                  | j                  g       y)z:Register this prompt with docket for background execution.N)names)task_configsupports_tasksregisterr|   key)r.   dockets     r2   register_with_docketzPrompt.register_with_docketo  s1    ..0DHH:6r3   )fn_keytask_keyc               ~   K   |xs | j                   }|r||d<     |j                  |fi ||       d{   S 7 w)ai  Schedule this prompt for background execution via docket.

        Args:
            docket: The Docket instance
            arguments: Prompt arguments
            fn_key: Function lookup key in Docket registry (defaults to self.key)
            task_key: Redis storage key for the result
            **kwargs: Additional kwargs passed to docket.add()
        r   N)r   add)r.   r   re   r   r   kwargs
lookup_keys          r2   add_to_docketzPrompt.add_to_docketu  sE     $ 'txx
$F5M5ZVZZ
5f5i@@@@s   4=;=c                ,    t         |          dddz  S )Nrc   LocalProvider)zfastmcp.component.typezfastmcp.provider.type)r,   get_span_attributes)r.   r1   s    r2   r   zPrompt.get_span_attributes  s#    w*,&.%40
 
 	
r3   )ro   r   r7   rl   )rv   zCallable[..., Any]rA   rD   rr   zstr | int | Noneri   rD   r@   rD   rj   zlist[Icon] | Noners   zset[str] | NonerM   rL   rt   zbool | TaskConfig | Nonerg   z"AuthCheck | list[AuthCheck] | Noner7   r   r   )re   rL   r7   z(str | list[Message | str] | PromptResult)r   r   r7   rI   r_   )re   rL   r   Noner7   rI   )re   rL   r   r   r7   zmcp.types.CreateTaskResult)re   rL   r   zTaskMeta | Noner7   z)PromptResult | mcp.types.CreateTaskResult)r   r
   r7   r   )r   r
   re   rL   r   rD   r   rD   r   r   r7   r   )r7   zdict[str, Any])r8   r9   r:   r;   rd   r<   r   re   rg   rq   classmethodrx   r|   r   r	   r   r   r   r   r=   r>   s   @r2   r   r      s   A (J(-2"N.I*  @E"HRV@D
< 

 

2 
  $( "&#' $&*)-37"
"
 	"

 ""
 "
  "
 !"
 "
 $"
 '"
 1"
 
"
 "
L ,0H(H 
2H"
H  ,0(  
	  )() ) 
$	) ) ,0%)&+(&+ #&+ 
3	&+P7 "#AA )A
 A A A 
A.
 
r3   r   )r   r   r   rI   c                    ddd}| |v rLddl }|j                  j                  r t        j                  d|  dt
        d	       dd
lm} t        ||       S t        dt        d|       )z2Deprecated re-exports for backwards compatibility.r   rc   )r   rc   r   Nz
Importing z` from fastmcp.prompts.prompt is deprecated. Import from fastmcp.prompts.function_prompt instead.   )
stacklevel)function_promptzmodule z has no attribute )fastmcpsettingsdeprecation_warningswarningswarnDeprecationWarningfastmcp.promptsr   getattrAttributeErrorr8   )rA   deprecated_exportsr   r   s       r2   __getattr__r     s     +
 !!00MMTF #G H"	 	4--
78,.@I
JJr3   )rA   r(   r7   r   )5r;   
__future__r   _annotationsr   collections.abcr   typingr   r   r   r   r	   pydanticr)   r   r
   docket.executionr   rw   r   	mcp.typesmcpr   r   r   r   r   r   rl   r   rk   r   pydantic.json_schemar   !fastmcp.server.auth.authorizationr   fastmcp.server.tasks.configr   r   fastmcp.utilities.componentsr   fastmcp.utilities.loggingr   fastmcp.utilities.typesr   r8   logger	BaseModelr   rI   __all__r   rG   r3   r2   <module>r      s    ' 2  $ B B  *>    * 9  / 7 < 9 0 
H	4Ch   4Cn	% 	O
8%% O
dR
 R
jKr3   