o
    î6Wj¯=  ã                
   @  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 )Ú_TaggedDictzçA 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   úf/home/esfera/Documents/content_generation/venv/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|› �ƒ‚)zÕConvert 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¡r—t| 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 )
z£Convert 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 )	zµConvert 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‡   úolist[Literal['direct', 'code_execution_20250825', 'code_execution_20260120', 'code_execution_20260521']] | 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_mcps  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ýý

"ôBô