o
    ^۷iU=                  
   @  s  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 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 W n eyU Z zed	edZ[w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 de/Z0G dd de1Z2dQddZ3dRddZ4G d d! d!e5Z6dd"dSd(d)Z7dd"dTd,d-Z8dd"dUd1d2Z9dd"dVd5d6Z:dWd8d9Z;dXd<d=Z<ddddddd>dYdLdMZ=ddddddd>dZdOdPZ>dS )[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                   @     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__ r3   r3   M/home/ubuntu/vllm_env/lib/python3.10/site-packages/anthropic/lib/tools/mcp.pyr-   J       r-   c                   @  r,   )_TaggedTuplezBA tuple subclass that can carry a ``_stainless_helper`` attribute.Nr.   r3   r3   r3   r4   r6   R   r5   r6   	mime_typestrreturnboolc                 C  s   | t v S N)_SUPPORTED_IMAGE_TYPESr7   r3   r3   r4   _is_supported_image_typeV   s   r>   
str | Nonec                 C  s"   | d u p|  dp| dkpt| S )Ntext/application/pdf)
startswithr>   r=   r3   r3   r4    _is_supported_resource_mime_typeZ   s   rC   c                   @  r,   )r'   zURaised when an MCP value cannot be converted to a format supported by the Claude API.Nr.   r3   r3   r3   r4   r'   h   r5   r'   cache_controlcontentr	   rE   %BetaCacheControlEphemeralParam | NoneBetaContentc                C  s   t | trtd| jd}|dur||d< t|d |S t | trKt| js.td| j tdt	d| j
| jd	d
}|durD||d< t|d |S t | trWt| j|d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)typerI   NrE   r#   zUnsupported image MIME type: imagebase64rJ   data
media_typerJ   sourcerD   rJ   zUnsupported MCP content type: )
isinstancer   r-   rI   r   r
   r>   mimeTyper'   r   rN   r   _resource_contents_to_blockresourcegetattrrJ   r/   )rF   rE   blockimage_blockcontent_typer3   r3   r4   r#   q   s4   







r#   rU   +TextResourceContents | BlobResourceContentsc                C  sD  | j }|dur4t|r4t| tstd| j tdtd| j|dd}|dur-||d< t	|d |S |d	krat| tsEtd
| j tdt
d| jd	dd}|durZ||d< t	|d |S |du sj|drt| trs| j}n	t| jd}tdtd|ddd}|dur||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: rK   rL   rM   rP   rE   r%   rA   z1PDF resource must have blob data, not text. URI: documentr@   utf-8rI   z
text/plainzUnsupported MIME type "z" for resource: )rS   r>   rR   r   r'   urir-   r   blobr   r   rB   r   rI   rL   	b64decodedecoder   )rU   rE   r7   rX   	pdf_blockrN   
text_blockr3   r3   r4   rT      sf   








rT   messager   dict[str, Any]c                C  s*   t | jt| j|dgd}t|d |S )zCConvert an MCP prompt message to an Anthropic ``BetaMessageParam``.rD   )rolerF   r$   )r-   re   r#   rF   r   )rc   rE   resultr3   r3   r4   r$      s   
r$   rf   r   c                C  s\   | j stdtdd | j D d}|du r(dd | j D }tdd| t||d	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                 s  s    | ]
}t |jr|V  qd S r;   )rC   rS   .0cr3   r3   r4   	<genexpr>
  s    z*mcp_resource_to_content.<locals>.<genexpr>Nc                 S  s   g | ]
}|j d ur|j qS r;   )rS   rh   r3   r3   r4   
<listcomp>  s    z+mcp_resource_to_content.<locals>.<listcomp>z>No supported MIME type found in resource contents. Available: z, rD   )contentsr'   nextjoinrT   )rf   rE   	supported
mime_typesr3   r3   r4   r%      s   
r%   $tuple[str | None, bytes, str | None]c                 C  s   | j std| j d }t|j}t|j}|r |ddd nd}t|tr.t	
|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``.
    rg   r   /r   Nr\   r&   )rm   r'   r8   r]   r   pathrsplitrR   r   rL   r_   r^   rI   encoder6   rS   r   )rf   rU   uri_strru   namecontent_bytes
file_tupler3   r3   r4   r&     s   




r&   r   r   c                 C  sF   | j rtdd | jD | js| jdurt| jS dd | jD S )zQConvert MCP ``CallToolResult`` to a value suitable for returning from ``call()``.c                 S     g | ]}t |qS r3   r#   ri   itemr3   r3   r4   rl   ;      z(_convert_tool_result.<locals>.<listcomp>Nc                 S  r|   r3   r}   r~   r3   r3   r4   rl   A  r   )isErrorr   rF   structuredContentjsondumps)rf   r3   r3   r4   _convert_tool_result8  s
   r   )rE   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          
        sN   ddl  | jd fdd}t|| j| j||||||d	
}	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   r9   r   c                    s    j j| }t|S r;   )from_threadrun	call_toolr   r   rf   anyior   	tool_namer3   r4   call_mcpp  s   zmcp_tool.<locals>.call_mcp	ry   descriptioninput_schemarE   r   r   r   r   r   r!   r   r   r9   r   )anyio.from_threadry   r   r   inputSchemar   
r   r   rE   r   r   r   r   r   r   rf   r3   r   r4   r!   I  s"   #
r!   BetaAsyncFunctionTool[Any]c          
        sD   | j d
 fdd}t|| j| j||||||d
}	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   r9   r   c                    s    j | dI d H }t|S )N)ry   	arguments)r   r   r   r   r   r3   r4   r     s   z async_mcp_tool.<locals>.call_mcpr   r!   Nr   )ry   r   r   r   r   r   r3   r   r4   r"     s    #
r"   )r7   r8   r9   r:   )r7   r?   r9   r:   )rF   r	   rE   rG   r9   rH   )rU   rZ   rE   rG   r9   rH   )rc   r   rE   rG   r9   rd   )rf   r   rE   rG   r9   rH   )rf   r   r9   rr   )rf   r   r9   r   )r   r   r   r   rE   rG   r   r   r   r   r   r   r   r   r   r   r9   r   )r   r   r   r   rE   rG   r   r   r   r   r   r   r   r   r   r   r9   r   )?r2   
__future__r   r   rL   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    rH   __all__	frozensetr<   dictr-   tupler6   r>   rC   	Exceptionr'   r#   rT   r$   r%   r&   r   r!   r"   r3   r3   r3   r4   <module>   sj    0 

.N

"?