
    $j8                       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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( ddl)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1  e/e2          Z3 G d dej4                  Z5 G d de1          Z  G d dej4                  Z6 G d de-          Zg dZ7d#d"Z8dS )$z!Base classes for FastMCP prompts.    )annotationsN)Callable)TYPE_CHECKINGAnyClassVarLiteraloverload)Docket)	ExecutionFunctionPrompt)GetPromptResult)AudioContentEmbeddedResourceIconImageContentPromptMessageTextContent)Prompt)PromptArgument)Field)SkipJsonSchema)FastMCPDeprecationWarning)	AuthCheck)
TaskConfigTaskMeta)FastMCPComponent)
get_logger)FastMCPBaseModelc                  F     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 | ImageContent | AudioContent | EmbeddedResourcecontentuserr   c                n   t          |t          t          t          t          f          r|}net          |t
                    rt          d|          }n>t          j        |t
                                                    }t          d|          }t                      
                    ||           dS )a  Create Message with automatic serialization.

        Args:
            content: The message content. str passes through directly.
                     TextContent, ImageContent, AudioContent, 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   r   r   strpydantic_coreto_jsondecodesuper__init__)selfr$   r#   normalized_content
serialized	__class__s        \/home/rurouni/.hermes/hermes-agent/venv/lib/python3.11/site-packages/fastmcp/prompts/base.pyr1   zMessage.__init__E   s     k<?OP
 
 	K
   %% 	K!,&w!G!G!G '.wEEELLNNJ!,&z!J!J!Jd,>?????    returnr   c                8    t          | j        | j                  S )zConvert to MCP PromptMessage.r*   )r   r#   r$   )r2   s    r6   to_mcp_prompt_messagezMessage.to_mcp_prompt_messagec   s    $)T\BBBBr7   )r%   )r$   r   r#   r"   )r8   r   )__name__
__module____qualname____doc____annotations__r1   r:   __classcell__r5   s   @r6   r!   r!   ,   s          * '&&&IIII
 .4@ @ @ @ @ @ @<C C C C C C C Cr7   r!   c                  ~    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<   dS )r   z+An argument that can be passed to a prompt.zName of the argument)descriptionr,   nameNz%Description of what the argument doesdefaultrC   
str | NonerC   Fz Whether the argument is requiredboolrequired)	r;   r<   r=   r>   r   rD   r?   rC   rI    r7   r6   r   r   h   s         55"8999D9999#e"I  K     U#E  H      r7   r   c                  r     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]messagesNrG   rC   dict[str, Any] | Nonemetastr | list[Message]c                z    |                      |          }t                                          |||           dS )zCreate PromptResult.

        Args:
            messages: String or list of Message objects.
            description: Optional description of the prompt result.
            meta: Optional metadata about the prompt result.
        )rN   rC   rP   N)_normalize_messagesr0   r1   )r2   rN   rC   rP   
normalizedr5   s        r6   r1   zPromptResult.__init__   s=     --h77
*+DQQQQQr7   r8   c           
     l   t          | t                    rt          |           gS t          | t                    rWt	          |           D ]E\  }}t          |t                    s+t          d| dt          |          j         d|d          F| 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(   r;   )rN   iitems      r6   rS   z PromptResult._normalize_messages   s    
 h$$ 	'H%%&&h%% 	$X..  4!$00 #DA D Dd4jj>Q D D'+D D D  
 OS$x..:QSS
 
 	
r7   r   c                \    d | j         D             }t          | j        || j                  S )zConvert to MCP GetPromptResult.c                6    g | ]}|                                 S rJ   )r:   ).0ms     r6   
<listcomp>z5PromptResult.to_mcp_prompt_result.<locals>.<listcomp>   s$    IIIa//11IIIr7   )rC   rN   _meta)rN   r   rC   rP   )r2   mcp_messagess     r6   to_mcp_prompt_resultz!PromptResult.to_mcp_prompt_result   s<    II4=III(!)
 
 
 	
r7   NN)rN   rQ   rC   rG   rP   rO   )rN   rQ   r8   rM   )r8   r   )r;   r<   r=   r>   r?   rC   rP   r1   staticmethodrS   re   r@   rA   s   @r6   rL   rL   t   s          > "K"""""&D&&&&
 #'&*	R R R R R R R  
 
 
 \
&
 
 
 
 
 
 
 
r7   rL   c                  $    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<   dAdZ	e
dddddddddd	dBd'            Z	 dCdDd)ZdEd,Ze	 	 dFdGd/            ZedHd2            Z	 	 dFdId5ZdJd8Zddd9dKd>ZdL fd@Z xZS )Mr   z7A prompt template that can be rendered with parameters.promptzClassVar[str]
KEY_PREFIXNz*Arguments that can be passed to the promptrE   zlist[PromptArgument] | None	argumentsz$Authorization checks for this promptT)rF   rC   excludez2SkipJsonSchema[AuthCheck | list[AuthCheck] | None]auth	overridesr   r8   	SDKPromptc                f   d | j         pg D             }t          |                    d| j                  |                    d| j                  ||                    d| j                  |                    d| j                  |                    d|                                                     S )z$Convert the prompt to an MCP prompt.c                P    g | ]#}t          |j        |j        |j                   $S ))rD   rC   rI   )SDKPromptArgumentrD   rC   rI   )r`   args     r6   rb   z(Prompt.to_mcp_prompt.<locals>.<listcomp>   sH     
 
 
  XO  
 
 
r7   rD   rC   titleiconsrc   )rD   rC   rk   rt   ru   rc   )rk   ro   getrD   rC   rt   ru   get_meta)r2   rn   rk   s      r6   to_mcp_promptzPrompt.to_mcp_prompt   s    

 
 ~+
 
 
	 vty11!mT5EFF--44--44-- 	
 	
 	
 		
r7   )	rD   versionrt   rC   ru   tagsrP   taskrm   fnCallable[..., Any]rD   rG   ry   str | int | Nonert   rC   ru   list[Icon] | Nonerz   set[str] | NonerP   rO   r{   bool | TaskConfig | None"AuthCheck | list[AuthCheck] | Noner   c       	        B    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   )
r|   rD   ry   rt   rC   ru   rz   rP   r{   rm   )fastmcp.prompts.function_promptr   from_function)clsr|   rD   ry   rt   rC   ru   rz   rP   r{   rm   r   s               r6   r   zPrompt.from_function   sQ    , 	CBBBBB+~+#
 
 
 	
r7   (str | list[Message | str] | PromptResultc                $   K   t          d          )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)r2   rk   s     r6   renderzPrompt.render  s       ""FGGGr7   	raw_valuerL   c           
        t          |t                    r|S t          |t                    rt          || j        | j                  S t          |t
          t          z            rg }t          |          D ]\  }}t          |t                    r|	                    |           0t          |t                    r#|	                    t          |                     ht          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
        )rC   rP   rV   z] must be Message or str, got rW   rX   z<Prompt must return str, list[Message], or PromptResult, got )r+   rL   r,   rC   rP   rY   tuplerZ   r!   appendr[   r(   r;   )r2   r   rN   r\   r]   s        r6   convert_resultzPrompt.convert_result  so    i.. 	i%% 	Y	t7GdiXXXXi.. 	X&(H$Y// 	 	4dG,, OOD))))c** OOGDMM2222#DA D DT$ZZEX D D'+D D D    d6FTYWWWW.	??+. .
 
 	
r7   	task_metaNonec                
   K   d S NrJ   r2   rk   r   s      r6   _renderzPrompt._renderA  s      
 sr7   r   mcp.types.CreateTaskResultc                
   K   d S r   rJ   r   s      r6   r   zPrompt._renderH  s      
 &)Sr7   TaskMeta | None)PromptResult | mcp.types.CreateTaskResultc                   K   ddl m}  || d||           d{V }|r|S |                     |           d{V }|                     |          S )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_taskri   )	component	task_typerk   r   N)fastmcp.server.tasks.routingr   r   r   )r2   rk   r   r   task_resultresults         r6   r   zPrompt._renderO  s      2 	GFFFFF11	
 
 
 
 
 
 
 
 
  	 {{9--------""6***r7   docketr
   c                    | j                                         sdS |                    | j        | j        g           dS )z:Register this prompt with docket for background execution.N)names)task_configsupports_tasksregisterr   key)r2   r   s     r6   register_with_docketzPrompt.register_with_docketw  s@    ..00 	FDH:66666r7   )fn_keytask_keyr   r   kwargsr   c               `   K   |p| j         }|r||d<     |j        |fi ||           d{V S )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)r2   r   rk   r   r   r   
lookup_keys          r6   add_to_docketzPrompt.add_to_docket}  s[      $ 'tx
 	%$F5M5ZVZ
55f55i@@@@@@@@@r7   dict[str, Any]c                P    t                                                      dddz  S )Nri   LocalProvider)zfastmcp.component.typezfastmcp.provider.type)r0   get_span_attributes)r2   r5   s    r6   r   zPrompt.get_span_attributes  s0    ww**,,&.%40
 0
 
 	
r7   )rn   r   r8   ro   )r|   r}   rD   rG   ry   r~   rt   rG   rC   rG   ru   r   rz   r   rP   rO   r{   r   rm   r   r8   r   r   )rk   rO   r8   r   )r   r   r8   rL   rf   )rk   rO   r   r   r8   rL   )rk   rO   r   r   r8   r   )rk   rO   r   r   r8   r   )r   r
   r8   r   )r   r
   rk   rO   r   rG   r   rG   r   r   r8   r   )r8   r   )r;   r<   r=   r>   rj   r?   r   rk   rm   rx   classmethodr   r   r   r	   r   r   r   r   r@   rA   s   @r6   r   r      s        AA (J((((-2U"N. . .I     @Eu"HRV@ @ @D    
 
 
 
2 
  $( "&#' $&*)-37"
 "
 "
 "
 "
 ["
L ,0H H H H H"
 "
 "
 "
H  ,0    X ) ) ) X) ,0%)&+ &+ &+ &+ &+P7 7 7 7 "#A A A A A A.
 
 
 
 
 
 
 
 
 
r7   r   )r!   r   r   rL   rD   r,   r8   r   c                    ddd}| |v rFd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   ri   )r   ri   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warnr   fastmcp.promptsr   getattrAttributeErrorr;   )rD   deprecated_exportsr   r   s       r6   __getattr__r     s     + 
 !!!0 	MHT H H H)	    	433333---
I8IIII
J
JJr7   )rD   r,   r8   r   )9r>   
__future__r   _annotationsr   collections.abcr   typingr   r   r   r   r	   pydanticr-   r   r
   docket.executionr   r   r   	mcp.typesmcpr   r   r   r   r   r   r   r   ro   r   rr   r   pydantic.json_schemar   fastmcp.exceptionsr   !fastmcp.server.auth.authorizationr   fastmcp.server.tasks.configr   r   fastmcp.utilities.componentsr   fastmcp.utilities.loggingr   fastmcp.utilities.typesr   r;   logger	BaseModelr!   rL   __all__r   rJ   r7   r6   <module>r      s   ' ' 2 2 2 2 2 2  $ $ $ $ $ $ B B B B B B B B B B B B B B      ?******>>>>>>                          * ) ) ) ) ) 9 9 9 9 9 9       / / / / / / 8 8 8 8 8 8 7 7 7 7 7 7 < < < < < < < < 9 9 9 9 9 9 0 0 0 0 0 0      
H		9C 9C 9C 9C 9Ch  9C 9C 9Cx	 	 	 	 	% 	 	 	O
 O
 O
 O
 O
8% O
 O
 O
dR
 R
 R
 R
 R
 R
 R
 R
j  K K K K K Kr7   