
    ̺iU=                       S r SSKJr  SSKrSSKrSSKJrJr  SSKJ	r	  SSK
Jr   SSKJrJrJrJrJrJrJrJrJrJr  SSKJr  S
SKJrJrJrJr  SSK J!r!J"r"J#r#J$r$J%r%J&r&  SSK'J(r(  S
SK)J*r+  / SQr,\-" 1 Sk5      r. " S S\/5      r0 " S S\15      r2S%S jr3S&S jr4 " S S\55      r6SS.     S'S jjr7SS.     S(S jjr8SS.     S)S jjr9SS.     S*S jjr:    S+S  jr;S,S! jr<SSSSSSS".                 S-S# jjr=SSSSSSS".                 S.S$ jjr>g! \ a  r\" S	5      \eSrCff = f)/aG  Helpers for integrating MCP (Model Context Protocol) SDK types with the Anthropic SDK.

These helpers reduce boilerplate when converting between MCP types and Anthropic API types.

Usage::

    from anthropic.lib.tools.mcp import mcp_tool, async_mcp_tool, mcp_message

This module requires the ``mcp`` package to be installed.
    )annotationsN)AnyIterable)urlparse)Literal)
ToolTextContentContentBlockImageContentPromptMessageCallToolResultEmbeddedResourceReadResourceResultBlobResourceContentsTextResourceContents)ClientSessionz~The `mcp` package is required to use MCP helpers. Install it with: pip install anthropic[mcp]. Requires Python 3.10 or higher.   )BetaBase64PDFSourceParamBetaPlainTextSourceParamBetaBase64ImageSourceParamBetaCacheControlEphemeralParam   )	ToolErrorBetaFunctionToolBetaAsyncFunctionToolBetaFunctionToolResultType	beta_toolbeta_async_tool   )
tag_helper)Content)mcp_toolasync_mcp_toolmcp_contentmcp_messagemcp_resource_to_contentmcp_resource_to_fileUnsupportedMCPValueError>   	image/gif	image/png
image/jpeg
image/webpc                      \ rS rSrSrSrg)_TaggedDictJ   zA dict subclass that can carry a ``_stainless_helper`` attribute.

Behaves identically to a regular dict for serialization and isinstance checks,
but allows attaching tracking metadata that won't appear in JSON output.
 N__name__
__module____qualname____firstlineno____doc____static_attributes__r0       V/var/www/piano.thomer.com/venv/lib/python3.13/site-packages/anthropic/lib/tools/mcp.pyr.   r.   J   s    r8   r.   c                      \ rS rSrSrSrg)_TaggedTupleR   zBA tuple subclass that can carry a ``_stainless_helper`` attribute.r0   Nr1   r0   r8   r9   r;   r;   R   s    Lr8   r;   c                    U [         ;   $ N)_SUPPORTED_IMAGE_TYPES	mime_types    r9   _is_supported_image_typerB   V   s    ...r8   c                v    U S L =(       d/    U R                  S5      =(       d    U S:H  =(       d    [        U 5      $ )Ntext/application/pdf)
startswithrB   r@   s    r9    _is_supported_resource_mime_typerG   Z   s?    T 	/(	/))	/ $I.	r8   c                      \ rS rSrSrSrg)r(   h   zURaised when an MCP value cannot be converted to a format supported by the Claude API.r0   Nr1   r0   r8   r9   r(   r(   h   s    _r8   r(   cache_controlc          	     B   [        U [        5      (       a-  [        SU R                  S.5      nUb  XS'   [	        US5        U$ [        U [
        5      (       ar  [        U R                  5      (       d  [        SU R                   35      e[        S[        SU R                  U R                  S9S	.5      nUb  XS'   [	        US5        U$ [        U [        5      (       a  [        U R                  US
9$ [        U S[        U 5      R                   5      n[        SU 35      e)zConvert a single MCP content block to an Anthropic content block.

Handles text, image, and embedded resource content types.
Raises :class:`UnsupportedMCPValueError` for audio and resource_link types.
text)typerM   rK   r$   zUnsupported image MIME type: imagebase64rN   data
media_typerN   sourcerJ   rN   zUnsupported MCP content type: )
isinstancer	   r.   rM   r    r   rB   mimeTyper(   r   rR   r   _resource_contents_to_blockresourcegetattrrN   r2   )contentrK   blockimage_blockcontent_types        r9   r$   r$   q   s    ';''VW\\BC$%2/"5-('<(('(8(899*-J7K[K[J\+]^^!4! &//	
 $+8(;.'+,,*7+;+;=YY 7FDM,B,BCL
"%CL>#R
SSr8   c          	     :   U R                   nUbs  [        U5      (       ac  [        U [        5      (       d  [	        SU R
                   35      e[        S[        SU R                  US9S.5      nUb  XS'   [        US5        U$ US:X  ac  [        U [        5      (       d  [	        S	U R
                   35      e[        S
[        SU R                  SS9S.5      nUb  XS'   [        US5        U$ Ub  UR                  S5      (       a}  [        U [        5      (       a  U R                  nO/[        R                  " U R                  5      R!                  S5      n[        S
[#        SUSS9S.5      nUb  XS'   [        US5        U$ [	        SU SU R
                   35      e)z<Convert MCP resource contents to an Anthropic content block.z3Image resource must have blob data, not text. URI: rO   rP   rQ   rT   rK   r&   rE   z1PDF resource must have blob data, not text. URI: documentrD   utf-8rM   z
text/plainzUnsupported MIME type "z" for resource: )rW   rB   rV   r   r(   urir.   r   blobr    r   rF   r   rM   rP   	b64decodedecoder   )rY   rK   rA   r]   	pdf_blockrR   
text_blocks          r9   rX   rX      s    !!I !9)!D!D($899*-`aiamam`n+opp!4!!(	
 $+8(; 9: %%($899*-^_g_k_k^l+mnn"2!!0	
	 $)6o&978 I0099h 455==D##HMM299'BD "2+	

 $*7':89
"%<YKGWX`XdXdWe#f
ggr8   c               t    [        U R                  [        U R                  US9/S.5      n[	        US5        U$ )zCConvert an MCP prompt message to an Anthropic ``BetaMessageParam``.rJ   )roler[   r%   )r.   ri   r$   r[   r    )messagerK   results      r9   r%   r%      s<     LL#GOO=QR	
F v}%Mr8   c               8   U R                   (       d  [        S5      e[        S U R                    5       S5      nUcQ  U R                    Vs/ s H  o3R                  c  M  UR                  PM     nn[        SSR	                  U5       35      e[        X!S9$ s  snf )zConvert MCP resource contents to an Anthropic content block.

Finds the first resource with a supported MIME type from the result's
``contents`` list.
6Resource contents array must contain at least one itemc              3  ^   #    U  H#  n[        UR                  5      (       d  M  Uv   M%     g 7fr>   )rG   rW   ).0cs     r9   	<genexpr>*mcp_resource_to_content.<locals>.<genexpr>
  s     TOq'G

'SOs   -	-Nz>No supported MIME type found in resource contents. Available: z, rJ   )contentsr(   nextrW   joinrX   )rk   rK   	supportedrp   
mime_typess        r9   r&   r&      s     ??&'_``TFOOTI *0//T/QZZjajj/
T&LTYYWaMbLcd
 	
 'yNN Us   BBc                   U R                   (       d  [        S5      eU R                   S   n[        UR                  5      n[	        U5      R
                  nU(       a  UR                  SS5      S   OSn[        U[        5      (       a!  [        R                  " UR                  5      nOUR                  R                  S5      n[        XEUR                  45      n[!        US5        U$ )	zConvert MCP resource contents to a file tuple for ``files.upload()``.

Returns a ``(filename, content_bytes, mime_type)`` tuple compatible with
the SDK's ``FileTypes``.
rm   r   /r   Nra   r'   )rs   r(   strrb   r   pathrsplitrV   r   rP   rd   rc   rM   encoder;   rW   r    )rk   rY   uri_strr|   namecontent_bytes
file_tuples          r9   r'   r'     s     ??&'_``q!H(,,G G!!D&*4;;sAr"D (011((7 ,,W5tH4E4EFGJz12r8   c                ^   U R                   (       a/  [        U R                   Vs/ s H  n[        U5      PM     sn5      eU R                  (       d-  U R                  b   [
        R                  " U R                  5      $ U R                   Vs/ s H  n[        U5      PM     sn$ s  snf s  snf )zQConvert MCP ``CallToolResult`` to a value suitable for returning from ``call()``.)isErrorr   r[   r$   structuredContentjsondumps)rk   items     r9   _convert_tool_resultr   8  s~    ~~v~~F~tT*~FGG >>f66Bzz&2233*0..9.$K.99 G :s   B%B*)rK   defer_loadingallowed_callerseager_input_streaminginput_examplesstrictc                  ^^
^ SSK m
U R                  mSU
UU4S jjn[        UTU R                  U R                  UUUUUUS9
n	[        U	S5        U	$ )a  Convert an MCP tool to a sync runnable tool for ``tool_runner()``.

Example::

    from anthropic.lib.tools.mcp import mcp_tool

    tools_result = await mcp_client.list_tools()
    runner = client.beta.messages.tool_runner(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        tools=[mcp_tool(t, mcp_client) for t in tools_result.tools],
        messages=[{"role": "user", "content": "Use the available tools"}],
    )

Args:
    tool: An MCP tool definition from ``client.list_tools()``.
    client: The MCP ``ClientSession`` used to call the tool.
    cache_control: Cache control configuration.
    defer_loading: If true, tool will not be included in initial system prompt.
    allowed_callers: Which callers may use this tool.
    eager_input_streaming: Enable eager input streaming for this tool.
    input_examples: Example inputs for the tool.
    strict: When true, guarantees schema validation on tool names and inputs.
r   Nc                 h   > TR                   R                  TR                  TU 5      n[        U5      $ r>   )from_threadrun	call_toolr   )kwargsrk   anyioclient	tool_names     r9   call_mcpmcp_tool.<locals>.call_mcpp  s.    ""&&v'7'7FK#F++r8   	r   descriptioninput_schemarK   r   r   r   r   r   r"   r   r   returnr   )anyio.from_threadr   r   r   inputSchemar    )toolr   rK   r   r   r   r   r   r   rk   r   r   s    `        @@r9   r"   r"   I  sc    F 		I, , $$%%##'3%F vz"Mr8   c                  ^^
 U R                   m
SUU
4S jjn[        UT
U R                  U R                  UUUUUUS9
n	[	        U	S5        U	$ )a  Convert an MCP tool to an async runnable tool for ``tool_runner()``.

Example::

    from anthropic.lib.tools.mcp import async_mcp_tool

    tools_result = await mcp_client.list_tools()
    runner = await client.beta.messages.tool_runner(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        tools=[async_mcp_tool(t, mcp_client) for t in tools_result.tools],
        messages=[{"role": "user", "content": "Use the available tools"}],
    )

Args:
    tool: An MCP tool definition from ``client.list_tools()``.
    client: The MCP ``ClientSession`` used to call the tool.
    cache_control: Cache control configuration.
    defer_loading: If true, tool will not be included in initial system prompt.
    allowed_callers: Which callers may use this tool.
    eager_input_streaming: Enable eager input streaming for this tool.
    input_examples: Example inputs for the tool.
    strict: When true, guarantees schema validation on tool names and inputs.
c                 V   >#    TR                  TU S9I S h  vN n[        U5      $  N7f)N)r   	arguments)r   r   )r   rk   r   r   s     r9   r    async_mcp_tool.<locals>.call_mcp  s/     ''Y&'II#F++ Js   )')r   r"   r   )r   r   r   r   r    )r   r   rK   r   r   r   r   r   r   rk   r   s    `        @r9   r#   r#     s`    F 		I, , $$%%##'3%F vz"Mr8   )rA   r{   r   bool)rA   z
str | Noner   r   )r[   r
   rK   %BetaCacheControlEphemeralParam | Noner   BetaContent)rY   z+TextResourceContents | BlobResourceContentsrK   r   r   r   )rj   r   rK   r   r   zdict[str, Any])rk   r   rK   r   r   r   )rk   r   r   z$tuple[str | None, bytes, str | None])rk   r   r   r   )r   r   r   r   rK   r   r   bool | Noner   Tlist[Literal['direct', 'code_execution_20250825', 'code_execution_20260120']] | Noner   r   r   "Iterable[dict[str, object]] | Noner   r   r   zBetaFunctionTool[Any])r   r   r   r   rK   r   r   r   r   r   r   r   r   r   r   r   r   zBetaAsyncFunctionTool[Any])?r6   
__future__r   r   rP   typingr   r   urllib.parser   typing_extensionsr   	mcp.typesr   r	   r
   r   r   r   r   r   r   r   mcp.client.sessionr   ImportError_err
types.betar   r   r   r   _beta_functionsr   r   r   r   r   r   _stainless_helpersr    'types.beta.beta_tool_result_block_paramr!   r   __all__	frozensetr?   dictr.   tupler;   rB   rG   	Exceptionr(   r$   rX   r%   r&   r'   r   r"   r#   r0   r8   r9   <module>r      so  	 #     ! %   1   , M ##YZ $ M5 M/`y ` <@(T(T 9(T 	(T\ <@Ch9Ch 9Ch 	Ch\ <@ 9 	0 <@OO 9O 	O4)D	:* <@!%lp)-9=8
88 9	8
 8 j8 '8 78 8 8~ <@!%lp)-9=6
66 9	6
 6 j6 '6 76 6  6C  
 	Is   D* *D>0	D99D>