
    Ki7                         d Z ddlmZ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mZ 	 ddlmZ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! dd	l"m#Z# dd
l$m%Z% ddl&m'Z' ddl(m)Z) dgZ, G d d      Z-y# e*$ rZ+ e*d      e+dZ+[+ww xY w)z'Anthropic sampling handler for FastMCP.    )IteratorSequence)Any)CreateMessageRequestParams)CreateMessageResultCreateMessageResultWithToolsModelPreferencesSamplingMessageSamplingMessageContentBlock
StopReasonTextContentTool
ToolChoiceToolResultContentToolUseContent)AsyncAnthropicNotGiven)	NOT_GIVEN)MessageMessageParam	TextBlockTextBlockParam	ToolParamToolResultBlockParamToolUseBlockToolUseBlockParam)
ModelParam)ToolChoiceAnyParam)ToolChoiceAutoParam)ToolChoiceParamzThe `anthropic` package is not installed. Install it with `pip install fastmcp[anthropic]` or add `anthropic` to your dependencies.NAnthropicSamplingHandlerc            	       R   e Zd ZdZ	 ddededz  ddfdZdee   de	d	e
deez  fd
Zedeez  ee   z  dz  dee   fd       Zedee   dee   fd       Zededefd       Zdeez  ee   z  dz  defdZedee   dee   fd       Zedededz  fd       Zededefd       Zy)r!   a  Sampling handler that uses the Anthropic API.

    Example:
        ```python
        from anthropic import AsyncAnthropic
        from fastmcp import FastMCP
        from fastmcp.client.sampling.handlers.anthropic import AnthropicSamplingHandler

        handler = AnthropicSamplingHandler(
            default_model="claude-sonnet-4-5",
            client=AsyncAnthropic(),
        )

        server = FastMCP(sampling_handler=handler)
        ```
    Ndefault_modelclientreturnc                 8    |xs
 t               | _        || _        y N)r   r$   r#   )selfr#   r$   s      v/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/fastmcp/client/sampling/handlers/anthropic.py__init__z!AnthropicSamplingHandler.__init__A   s     '-&@0@)6    messagesparamscontextc           
        K   | j                  |      }| j                  |j                        }t        }|j                  r| j                  |j                        }t        }|j                  r&| j                  |j                        }|t        }n|}| j                  j                  j                  |||j                  |j                  nt        |j                  |j                  nt        |j                  |j                  |j                  nt        ||       d {   }	|j                  r| j                  |	      S | j!                  |	      S 7 2w)N)r,   )modelr,   systemtemperature
max_tokensstop_sequencestoolstool_choice)_convert_to_anthropic_messages_select_model_from_preferencesmodelPreferencesr   r5   _convert_tools_to_anthropic
toolChoice!_convert_tool_choice_to_anthropicr$   r,   createsystemPromptr2   	maxTokensstopSequences_message_to_result_with_tools!_message_to_create_message_result)
r(   r,   r-   r.   anthropic_messagesr0   anthropic_toolsanthropic_tool_choice	convertedresponses
             r)   __call__z!AnthropicSamplingHandler.__call__G   sC     261T1T 2U 2
 !??@W@WX 7@<<">>v||LO =F>>v?P?PQI "+(1%--44''-':':'F##I '-&8&8&D"")''(.(<(<(H$$i!- 5 
 
$ <<55h??55h??)
s   D!E#E$3Emodel_preferencesc              #      K   | y t        | t              r|  y t        | t              r| E d {    y t        | t              r*| j                  x}sy |D ]  }|j
                  x}s|  y y 7 @wr'   )
isinstancestrlistr	   hintsname)rI   rN   hintrO   s       r)   _iter_models_from_preferencesz6AnthropicSamplingHandler._iter_models_from_preferencesy   s      $'-##)40((()+;<.444E4  $		))
		 = )s   .A3A1AA3c                 T   g }| D ]  }|j                   }t        |t              r}g }|D ]K  }t        |t              r=|j	                  t        d|j                  |j                  |j                               Qt        |t              r'|j	                  t        d|j                               t        |t              sd}|j                   reg }|j                   D ]9  }t        |t              s|j	                  t        d|j                               ; t        |      dk(  r	|d   d   }n|r|}|j	                  t        d|j                  ||j                   r|j                   nd	
             N |r&|j	                  t#        |j$                  |             t        |t              rJ|j	                  t#        dt        d|j                  |j                  |j                        g             t        |t              rd}	|j                   reg }
|j                   D ]9  }t        |t              s|
j	                  t        d|j                               ; t        |
      dk(  r	|
d   d   }	n|
r|
}	|j	                  t#        dt        d|j                  |	|j                   r|j                   nd	
      g             t        |t              r2|j	                  t#        |j$                  |j                               t'        dt)        |              |S )Ntool_usetypeidrO   inputtextrU   rX       r   tool_resultF)rU   tool_use_idcontentis_error)roler^   	assistantuserzUnsupported content type: )r^   rK   rM   r   appendr   rV   rO   rW   r   r   rX   r   lenr   	toolUseIdisErrorr   r`   
ValueErrorrU   )r,   rC   messager^   content_blocksitemresult_contenttext_blockssub_itemresult_content_str
text_partss              r)   r7   z7AnthropicSamplingHandler._convert_to_anthropic_messages   s    24 q	KGooG '4(   $ $D!$7&---%/#'77%)YY&*jj	 $D+6&--*TYYG $D*;<EG<<@BK,0LL &#-h#D$/$6$6(6F(W%&&
  #;/141<Q1G!,1<&--0%2,0NN(69=5	;$L "&--$!($2  '>2")) (-%/#*::%,\\&-mm	!
  '#45AC"??79J ' %dK8&-- .F K
 :!+-7]6-B*#-7*")) #0%2,3,=,=(:<COOQV	!
  ';/")) $\\ ' 9$w-IJJcq	Kf "!r+   rh   c           	      R   t        | j                        dk(  rt        d      dj                  d | j                  D              }|r#t	        t        d|      d| j                        S t        d	| j                  D cg c]  }t        |      j                   c}       c c}w )
Nr   %No content in response from AnthropicrZ   c              3   V   K   | ]!  }t        |t              s|j                   # y wr'   )rK   r   rX   ).0blocks     r)   	<genexpr>zMAnthropicSamplingHandler._message_to_create_message_result.<locals>.<genexpr>  s"      
 z%7SEJJ
s   ))rX   rY   ra   )r^   r`   r0   z,No text content in response from Anthropic: )	rd   r^   rg   joinr   r   r0   rU   __name__)rh   rX   bs      r)   rB   z:AnthropicSamplingHandler._message_to_create_message_result  s     w1$DEE ww 
$+OO
 
 &#d; mm  :V]VeVe;fQRDG<L<L;f:gh
 	
;fs   ?B$
c                 p    | j                  |      D ]  }|j                  d      s|c S  | j                  S )Nclaude)rQ   
startswithr#   )r(   rI   model_options      r)   r8   z7AnthropicSamplingHandler._select_model_from_preferences!  sA     !>>?PQ 	$L&&x0##	$
 !!!r+   r5   c                     g }| D ]U  }t        |j                        }d|vrd|d<   |j                  t        |j                  |j
                  xs d|             W |S )z+Convert MCP tools to Anthropic tool format.rU   objectrZ   )rO   descriptioninput_schema)dictinputSchemarc   r   rO   r   )r5   rD   toolr   s       r)   r:   z4AnthropicSamplingHandler._convert_tools_to_anthropic+  sp     ,. 	D+/0@0@+AL\)'/V$"" $ 0 0 6B!-	 r+   r6   c                     | j                   dk(  rt        d      S | j                   dk(  rt        d      S | j                   dk(  ryt        d| j                         )zConvert MCP tool_choice to Anthropic format.

        Returns None for "none" mode, signaling that tools should be omitted
        from the request entirely (Anthropic doesn't have an explicit "none" option).
        auto)rU   requiredanynoneNzUnsupported tool_choice mode: )moder   r   rg   )r6   s    r)   r<   z:AnthropicSamplingHandler._convert_tool_choice_to_anthropic>  sc     v%&F33+%511' =k>N>N=QRSSr+   c           	         t        | j                        dk(  rt        d      | j                  dk(  rd}n8| j                  dk(  rd}n&| j                  dk(  rd}n| j                  d	k(  rd}nd}g }| j                  D ]  }t	        |t
              r'|j                  t        d
|j                               :t	        |t              sKt	        |j                  t              r|j                  ni }|j                  t        d|j                  |j                  |              |st        d      t        |d| j                   |      S )z;Convert Anthropic response to CreateMessageResultWithTools.r   rq   rS   toolUseend_turnendTurnr3   r?   stop_sequencerX   rY   rT   ra   )r^   r`   r0   
stopReason)rd   r^   rg   stop_reasonrK   r   rc   r   rX   r   rW   r   r   rV   rO   r   r0   )rh   r   r^   rt   	argumentss        r)   rA   z6AnthropicSamplingHandler._message_to_result_with_toolsR  s'   
 w1$DEE *,#K  J.#K  L0%K  O3#K#K 68__ 	E%+{UZZHIE<0+5ekk4+HEKKb	"' 88"ZZ'		" DEE+--"	
 	
r+   r'   ) rw   
__module____qualname____doc__r   r   r*   rM   r
   SamplingParamsr   r   r   rH   staticmethodr	   rL   r   rQ   r   r   r7   r   rB   r8   r   r   r:   r   r    r<   rA    r+   r)   r!   r!   /   s   $ JN7'71?$1F7	70@'0@ 0@ 	0@
 
;	;0@d +c1DI=D	# , x"?+x"	l	x" x"t 

	
 
*"!1C!7$s)!Cd!J"	" 4: $y/  $ TT	4	T T& 0
0
	%0
 0
r+   ).r   collections.abcr   r   typingr   	mcp.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   	anthropicr   r   anthropic._typesr   anthropic.typesr   r   r   r   r   r   r   r   anthropic.types.model_paramr   %anthropic.types.tool_choice_any_paramr   &anthropic.types.tool_choice_auto_paramr   !anthropic.types.tool_choice_paramr    ImportErrore__all__r!   r   r+   r)   <module>r      s    - .  B   2*	 	 	 7HJA &
&T
 T
  
	d s   :A: :B?	BB