
    kKj8                       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* ddl+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1  e,e2      Z3 G d dejh                        Z5 G d de1      Z  G d dejh                        Z6 G d de*      Zg dZ7ddZ8y) 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)FastMCPComponent)
get_logger)
TaskConfigTaskMeta)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 | ImageContent | AudioContent | EmbeddedResourcecontentc                   t        |t        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, 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        e/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/prompts/base.pyr0   zMessage.__init__E   s|     k<?OP

   %!,&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$   )r1   s    r5   to_mcp_prompt_messagezMessage.to_mcp_prompt_messagec   s    $))T\\BBr6   )user)r$   r   r#   r"   )returnr   )__name__
__module____qualname____doc____annotations__r0   r8   __classcell__r4   s   @r5   r!   r!   ,   s;    * '&II
 .4@@ +@<Cr6   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defaultrC   
str | NonerC   Fz Whether the argument is requiredboolrequired)	r;   r<   r=   r>   r   rD   r?   rC   rI    r6   r5   r   r   h   sE    5"89D#9#"IK  #EHd r6   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]messagesNrG   rC   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.
        )rN   rC   rP   N)_normalize_messagesr/   r0   )r1   rN   rC   rP   
normalizedr4   s        r5   r0   zPromptResult.__init__   s)     --h7
*+DQr6   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'   r;   )rN   iitems      r5   rR   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
 	
r6   c                    | j                   D cg c]  }|j                          }}t        | j                  || j                        S c c}w )zConvert to MCP GetPromptResult.)rC   rN   _meta)rN   r8   r   rC   rP   )r1   mmcp_messagess      r5   to_mcp_prompt_resultz!PromptResult.to_mcp_prompt_result   sI    ;?==I=a//1=I((!))
 	
 Js   A
NN)rN   str | list[Message]rC   rG   rP   rO   )rN   rc   r:   rM   )r:   r   )r;   r<   r=   r>   r?   rC   rP   r0   staticmethodrR   ra   r@   rA   s   @r5   rL   rL   t   s{    > "K""&D
&
 #'&*	R%R  R $	R  
%
	
 
&
r6   rL   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 promptrE   zlist[PromptArgument] | None	argumentsz$Authorization checks for this promptT)rF   rC   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.)rD   rC   rI   rD   rC   titleiconsr^   )rD   rC   rh   rl   rm   r^   )
rh   SDKPromptArgumentrD   rC   rI   	SDKPromptgetrl   rm   get_meta)r1   	overridesargrh   s       r5   to_mcp_promptzPrompt.to_mcp_prompt   s     ~~++
 , XXOO
 , 	 
 vtyy1!mT5E5EF--4--4--	
 		

s   3C)	rD   versionrl   rC   rm   tagsrP   taskrj   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   )
fnrD   ru   rl   rC   rm   rv   rP   rw   rj   )fastmcp.prompts.function_promptr   from_function)clsry   rD   ru   rl   rC   rm   rv   rP   rw   rj   r   s               r5   r{   zPrompt.from_function   s;    , 	C+~++#
 	
r6   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)r1   rh   s     r5   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
        )rC   rP   rU   z] must be Message or str, got rV   rW   z<Prompt must return str, list[Message], or PromptResult, got )r*   rL   r+   rC   rP   rX   tuplerY   r!   appendrZ   r'   r;   )r1   	raw_valuerN   r[   r\   s        r5   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	?++,.
 	
r6   c                   K   y wNrJ   r1   rh   	task_metas      r5   _renderzPrompt._renderA  s     
    c                   K   y wr   rJ   r   s      r5   r   zPrompt._renderH  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_taskrf   )	component	task_typerh   r   N)fastmcp.server.tasks.routingr   r   r   )r1   rh   r   r   task_resultresults         r5   r   zPrompt._renderO  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)r1   dockets     r5   register_with_docketzPrompt.register_with_docketw  s1    ..0DHH:6r6   )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)r1   r   rh   r   r   kwargs
lookup_keys          r5   add_to_docketzPrompt.add_to_docket}  sE     $ 'txx
$F5M5ZVZZ
5f5i@@@@s   4=;=c                ,    t         |          dddz  S )Nrf   LocalProvider)zfastmcp.component.typezfastmcp.provider.type)r/   get_span_attributes)r1   r4   s    r5   r   zPrompt.get_span_attributes  s#    w*,&.%40
 
 	
r6   )rr   r   r:   ro   )ry   zCallable[..., Any]rD   rG   ru   zstr | int | Nonerl   rG   rC   rG   rm   zlist[Icon] | Nonerv   zset[str] | NonerP   rO   rw   zbool | TaskConfig | Nonerj   z"AuthCheck | list[AuthCheck] | Noner:   r   r   )rh   rO   r:   z(str | list[Message | str] | PromptResult)r   r   r:   rL   rb   )rh   rO   r   Noner:   rL   )rh   rO   r   r   r:   zmcp.types.CreateTaskResult)rh   rO   r   zTaskMeta | Noner:   z)PromptResult | mcp.types.CreateTaskResult)r   r
   r:   r   )r   r
   rh   rO   r   rG   r   rG   r   r   r:   r   )r:   zdict[str, Any])r;   r<   r=   r>   rg   r?   r   rh   rj   rt   classmethodr{   r   r   r	   r   r   r   r   r@   rA   s   @r5   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.
 
r6   r   )r!   r   r   rL   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   rf   )r   rf   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       r5   __getattr__r     s     +
 !!00MMTF #G H)	 	4--
78,.@I
JJr6   )rD   r+   r:   r   )9r>   
__future__r   _annotationsr   collections.abcr   typingr   r   r   r   r	   pydanticr,   r   r
   docket.executionr   rz   r   	mcp.typesmcpr   r   r   r   r   r   r   r   ro   r   rn   r   pydantic.json_schemar   fastmcp.exceptionsr   fastmcp.utilities.authorizationr   fastmcp.utilities.componentsr   fastmcp.utilities.loggingr   fastmcp.utilities.tasksr   r   fastmcp.utilities.typesr   r;   logger	BaseModelr!   rL   __all__r   rJ   r6   r5   <module>r      s    ' 2  $ B B  *>    * 9  / 8 5 9 0 8 
H	9Ch   9Cx	% 	O
8%% O
dR
 R
jKr6   