
    iU=                       d Z ddlmZ ddlZddl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 ddlmZ n# e$ rZ ed	          edZ[ww xY wd
dlmZmZmZ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+ g dZ, e-h d          Z. G d de/          Z0 G d de1          Z2dGdZ3dHdZ4 G d de5          Z6dd dId&Z7dd dJd)Z8dd dKd-Z9dd dLd0Z:dMd2Z;dNd5Z<ddddddd6dOdDZ=ddddddd6dPdFZ>dS )QaG  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                      e Zd ZdZdS )_TaggedDictzA 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____doc__     T/root/projects/qq-shell/venv/lib/python3.11/site-packages/anthropic/lib/tools/mcp.pyr.   r.   J   s           r5   r.   c                      e Zd ZdZdS )_TaggedTuplezBA tuple subclass that can carry a ``_stainless_helper`` attribute.Nr/   r4   r5   r6   r8   r8   R   s        LLLLr5   r8   	mime_typestrreturnboolc                    | t           v S N)_SUPPORTED_IMAGE_TYPESr9   s    r6   _is_supported_image_typerA   V   s    ...r5   
str | Nonec                ^    | d u p)|                      d          p| dk    pt          |           S )Ntext/application/pdf)
startswithrA   r@   s    r6    _is_supported_resource_mime_typerG   Z   sE    T 	/((	/))	/ $I..	r5   c                      e Zd ZdZdS )r(   zURaised when an MCP value cannot be converted to a format supported by the Claude API.Nr/   r4   r5   r6   r(   r(   h   s        ____r5   r(   cache_controlcontentr
   rJ   %BetaCacheControlEphemeralParam | NoneBetaContentc               V   t          | t                    r0t          d| j        d          }|||d<   t	          |d           |S t          | t
                    rpt          | j                  st          d| j                   t          dt          d| j
        | j        	          d
          }|||d<   t	          |d           |S t          | t                    rt          | j        |          S t          | dt          |           j                  }t          d|           )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)typerO   NrJ   r$   zUnsupported image MIME type: imagebase64rP   data
media_typerP   sourcerI   rP   zUnsupported MCP content type: )
isinstancer	   r.   rO   r    r   rA   mimeTyper(   r   rT   r   _resource_contents_to_blockresourcegetattrrP   r0   )rK   rJ   blockimage_blockcontent_types        r6   r$   r$   q   sS    ';'' VW\BBCC$%2E/"5-((('<(( '(899 	_*+]7K[+]+]^^^!4! &/   	
 	
 $+8K(;...'+,, Z*7+;=YYYY 7FDMM,BCCL
"#RL#R#R
S
SSr5   r[   +TextResourceContents | BlobResourceContentsc               X   | j         }|{t          |          rlt          | t                    st	          d| j                   t          dt          d| j        |          d          }|||d<   t          |d           |S |d	k    rlt          | t                    st	          d
| j                   t          dt          d| j        d	          d          }|||d<   t          |d           |S ||                    d          rt          | t                    r| j        }n,t          j        | j                                      d          }t          dt#          d|d          d          }|||d<   t          |d           |S t	          d| d| j                   )z<Convert MCP resource contents to an Anthropic content block.Nz3Image resource must have blob data, not text. URI: rQ   rR   rS   rV   rJ   r&   rE   z1PDF resource must have blob data, not text. URI: documentrD   utf-8rO   z
text/plainzUnsupported MIME type "z" for resource: )rY   rA   rX   r   r(   urir.   r   blobr    r   rF   r   rO   rR   	b64decodedecoder   )r[   rJ   r9   r^   	pdf_blockrT   
text_blocks          r6   rZ   rZ      s-    !I !9)!D!D($899 	q*+oaiam+o+oppp!4!!(   	
 	
 $+8K(; 9::: %%%($899 	o*+m_g_k+m+mnnn"2!!0   	
 	
	 $)6Io&97888 I0099h 455 	C=DD#HM2299'BBD "2+   	
 	

 $*7J':8999
"#fY#f#fX`Xd#f#f
g
ggr5   messager   dict[str, Any]c               ~    t          | j        t          | j        |          gd          }t	          |d           |S )zCConvert an MCP prompt message to an Anthropic ``BetaMessageParam``.rI   )rolerK   r%   )r.   rm   r$   rK   r    )rj   rJ   results      r6   r%   r%      sN     L#GO=QQQR	
 	
 F v}%%%Mr5   rn   r   c                   | j         st          d          t          d | j         D             d          }|6d | j         D             }t          dd                    |                     t	          ||          S )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  B   K   | ]}t          |j                  |V  d S r>   )rG   rY   .0cs     r6   	<genexpr>z*mcp_resource_to_content.<locals>.<genexpr>
  s2      TTq'G
'S'STTTTTTTr5   Nc                *    g | ]}|j         	|j         S r>   )rY   rr   s     r6   
<listcomp>z+mcp_resource_to_content.<locals>.<listcomp>  s!    TTTQQZ=Saj=S=S=Sr5   z>No supported MIME type found in resource contents. Available: z, rI   )contentsr(   nextjoinrZ   )rn   rJ   	supported
mime_typess       r6   r&   r&      s     ? a&'_```TTFOTTT I TT&/TTT
&dTYYWaMbMbdd
 
 	
 'yNNNNr5   $tuple[str | None, bytes, str | None]c                   | j         st          d          | j         d         }t          |j                  }t	          |          j        }|r|                    dd          d         nd}t          |t                    rt          j
        |j                  }n|j                            d          }t          |||j        f          }t!          |d           |S )	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``.
    rp   r   /r   Nrc   r'   )rx   r(   r:   rd   r   pathrsplitrX   r   rR   rf   re   rO   encoder8   rY   r    )rn   r[   uri_strr   namecontent_bytes
file_tuples          r6   r'   r'     s     ? a&'_```q!H(,G G!D&*44;;sAr""D (011 6(77 ,,W55t]H4EFGGJz1222r5   r   r   c                    | j         rt          d | j        D                       | j        s | j        t	          j        | j                  S d | j        D             S )zQConvert MCP ``CallToolResult`` to a value suitable for returning from ``call()``.c                ,    g | ]}t          |          S r4   r$   rs   items     r6   rw   z(_convert_tool_result.<locals>.<listcomp>;  s     FFFtT**FFFr5   Nc                ,    g | ]}t          |          S r4   r   r   s     r6   rw   z(_convert_tool_result.<locals>.<listcomp>A  s     999$K999r5   )isErrorr   rK   structuredContentjsondumps)rn   s    r6   _convert_tool_resultr   8  si    ~ HFFv~FFFGGG > 4f6Bz&233399&.9999r5   )rJ   defer_loadingallowed_callerseager_input_streaminginput_examplesstricttoolr   clientr   r   bool | Noner   Tlist[Literal['direct', 'code_execution_20250825', 'code_execution_20260120']] | Noner   r   "Iterable[dict[str, object]] | Noner   BetaFunctionTool[Any]c                  
 ddl 
| j        d

fd}t          || j        | j        ||||||
  
        }	t          |	d	           |	S )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   Nkwargsr   r;   r   c                 d    j                             j        |           }t          |          S r>   )from_threadrun	call_toolr   )r   rn   anyior   	tool_names     r6   call_mcpzmcp_tool.<locals>.call_mcpp  s.    "&&v'7FKK#F+++r5   	r   descriptioninput_schemarJ   r   r   r   r   r   r"   r   r   r;   r   )anyio.from_threadr   r   r   inputSchemar    )r   r   rJ   r   r   r   r   r   r   rn   r   r   s    `        @@r6   r"   r"   I  s    F 	I, , , , , , , , $%##'3%  F vz"""Mr5   BetaAsyncFunctionTool[Any]c                  
 | j         
d
fd}t          |
| j        | j        ||||||
  
        }	t	          |	d           |	S )	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.
    r   r   r;   r   c                 `   K                        |            d {V }t          |          S )N)r   	arguments)r   r   )r   rn   r   r   s     r6   r   z async_mcp_tool.<locals>.call_mcp  s?      ''Y&'IIIIIIII#F+++r5   r   r"   r   )r   r   r   r   r    )r   r   rJ   r   r   r   r   r   r   rn   r   s    `        @r6   r#   r#     s    F 	I, , , , , , , $%##'3%  F vz"""Mr5   )r9   r:   r;   r<   )r9   rB   r;   r<   )rK   r
   rJ   rL   r;   rM   )r[   r`   rJ   rL   r;   rM   )rj   r   rJ   rL   r;   rk   )rn   r   rJ   rL   r;   rM   )rn   r   r;   r}   )rn   r   r;   r   )r   r   r   r   rJ   rL   r   r   r   r   r   r   r   r   r   r   r;   r   )r   r   r   r   rJ   rL   r   r   r   r   r   r   r   r   r   r   r;   r   )?r3   
__future__r   r   rR   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!   rM   __all__	frozensetr?   dictr.   tupler8   rA   rG   	Exceptionr(   r$   rZ   r%   r&   r'   r   r"   r#   r4   r5   r6   <module>r      s  	 	 # " " " " "                   ! ! ! ! ! ! % % % % % %                        1000000   
+ 	I 
                           , + + + + + M M M M M M   ##Y#Y#YZZ     $   M M M M M5 M M M/ / / /   ` ` ` ` `y ` ` ` <@(T (T (T (T (T (T\ <@Ch Ch Ch Ch Ch Ch\ <@     0 <@O O O O O O4   D	: 	: 	: 	:* <@!%lp)-9=8 8 8 8 8 8~ <@!%lp)-9=6 6 6 6 6 6 6 6s   A A
AA