
    nϞ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 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      Z2d%dZ3d&dZ4 G d de5      Z6dd	 	 	 	 	 d'dZ7dd	 	 	 	 	 d(dZ8dd	 	 	 	 	 d)dZ9dd	 	 	 	 	 d*dZ:	 	 	 	 d+d Z;d,d!Z<ddddddd"	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d-d#Z=ddddddd"	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d.d$Z>y# e$ rZ ed	      edZ[ww xY w)/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y)_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__     Y/var/www/html/jploft-chatbot/venv/lib/python3.12/site-packages/anthropic/lib/tools/mcp.pyr.   r.   J   s    r5   r.   c                      e Zd ZdZy)_TaggedTuplezBA tuple subclass that can carry a ``_stainless_helper`` attribute.Nr/   r4   r5   r6   r8   r8   R   s    Lr5   r8   c                    | t         v S N)_SUPPORTED_IMAGE_TYPES	mime_types    r6   _is_supported_image_typer>   V   s    ...r5   c                X    | d u xs% | j                  d      xs | dk(  xs t        |       S )Ntext/application/pdf)
startswithr>   r<   s    r6    _is_supported_resource_mime_typerC   Z   s?    T 	/(	/))	/ $I.	r5   c                      e Zd ZdZy)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_controlc               &   t        | t              r-t        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)typerH   rF   r$   zUnsupported image MIME type: imagebase64rI   data
media_typerI   sourcerE   rI   zUnsupported MCP content type: )
isinstancer	   r.   rH   r    r   r>   mimeTyper(   r   rM   r   _resource_contents_to_blockresourcegetattrrI   r0   )contentrF   blockimage_blockcontent_types        r6   r$   r$   q   s    ';'VW\\BC$%2E/"5-('<('(8(89*-J7K[K[J\+]^^!4! &//	
 $+8K(;.'+,*7+;+;=YY 7FDM,B,BCL
"%CL>#R
SSr5   c                  | j                   }|lt        |      rat        | t              st	        d| j
                         t        dt        d| j                  |      d      }|||d<   t        |d       |S |dk(  rat        | t              st	        d	| j
                         t        d
t        d| j                  d      d      }|||d<   t        |d       |S ||j                  d      rzt        | t              r| j                  }n.t        j                  | 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.z3Image resource must have blob data, not text. URI: rJ   rK   rL   rO   rF   r&   rA   z1PDF resource must have blob data, not text. URI: documentr@   utf-8rH   z
text/plainzUnsupported MIME type "z" for resource: )rR   r>   rQ   r   r(   urir.   r   blobr    r   rB   r   rH   rK   	b64decodedecoder   )rT   rF   r=   rX   	pdf_blockrM   
text_blocks          r6   rS   rS      s    !!I !9)!D($89*-`aiamam`n+opp!4!!(	
 $+8K(; 9: %%($89*-^_g_k_k^l+mnn"2!!0	
	 $)6Io&978 I009h 45==D##HMM299'BD "2+	

 $*7J':89
"%<YKGWX`XdXdWe#f
ggr5   c               z    t        | j                  t        | j                  |      gd      }t	        |d       |S )zCConvert an MCP prompt message to an Anthropic ``BetaMessageParam``.rE   )rolerV   r%   )r.   rd   r$   rV   r    )messagerF   results      r6   r%   r%      s<     LL#GOO=QR	
F v}%Mr5   c               ,   | j                   st        d      t        d | j                   D        d      }|M| j                   D cg c]  }|j                  |j                   }}t        ddj	                  |             t        ||      S c c}w )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  L   K   | ]  }t        |j                        s|  y wr:   )rC   rR   ).0cs     r6   	<genexpr>z*mcp_resource_to_content.<locals>.<genexpr>
  s     Tq'G

'STs   $$Nz>No supported MIME type found in resource contents. Available: z, rE   )contentsr(   nextrR   joinrS   )rf   rF   	supportedrk   
mime_typess        r6   r&   r&      s     ??&'_``TFOOTI *0//TQQZZ=SajjT
T&LTYYWaMbLcd
 	
 'yNN Us   BBc                   | j                   st        d      | j                   d   }t        |j                        }t	        |      j
                  }|r|j                  dd      d   nd}t        |t              r t        j                  |j                        }n|j                  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``.
    rh   r   /r   Nr\   r'   )rm   r(   strr]   r   pathrsplitrQ   r   rK   r_   r^   rH   encoder8   rR   r    )rf   rT   uri_strrv   namecontent_bytes
file_tuples          r6   r'   r'     s     ??&'_``q!H(,,G G!!D&*4;;sAr"D (01((7 ,,W5t]H4E4EFGJz12r5   c                :   | j                   r,t        | j                  D cg c]  }t        |       c}      | j                  s+| j                  t        j                  | j                        S | j                  D cg c]  }t        |       c}S c c}w c c}w )zQConvert MCP ``CallToolResult`` to a value suitable for returning from ``call()``.)isErrorr   rV   r$   structuredContentjsondumps)rf   items     r6   _convert_tool_resultr   8  sv    ~~v~~FtT*FGG >>f66Bzz&2233*0..9$K99 G :s   B>B)rF   defer_loadingallowed_callerseager_input_streaminginput_examplesstrictc                  
 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   Nc                 h    j                   j                  j                  |       }t        |      S r:   )from_threadrun	call_toolr   )kwargsrf   anyioclient	tool_names     r6   call_mcpzmcp_tool.<locals>.call_mcpp  s.    ""&&v'7'7FK#F++r5   	rz   descriptioninput_schemarF   r   r   r   r   r   r"   r   r   returnr   )anyio.from_threadrz   r   r   inputSchemar    )toolr   rF   r   r   r   r   r   r   rf   r   r   s    `        @@r6   r"   r"   I  s^    F 		I, $$%%##'3%F vz"Mr5   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.
    c                 \   K   j                  |        d {   }t        |      S 7 w)N)rz   	arguments)r   r   )r   rf   r   r   s     r6   r   z async_mcp_tool.<locals>.call_mcp  s0     ''Y&'II#F++ Js   ,*,r   r"   r   )rz   r   r   r   r    )r   r   rF   r   r   r   r   r   r   rf   r   s    `        @r6   r#   r#     s[    F 		I, $$%%##'3%F vz"Mr5   )r=   ru   r   bool)r=   z
str | Noner   r   )rV   r
   rF   %BetaCacheControlEphemeralParam | Noner   BetaContent)rT   z+TextResourceContents | BlobResourceContentsrF   r   r   r   )re   r   rF   r   r   zdict[str, Any])rf   r   rF   r   r   r   )rf   r   r   z$tuple[str | None, bytes, str | None])rf   r   r   r   )r   r   r   r   rF   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   rF   r   r   r   r   r   r   r   r   r   r   r   r   zBetaAsyncFunctionTool[Any])?r3   
__future__r   r   rK   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.   tupler8   r>   rC   	Exceptionr(   r$   rS   r%   r&   r'   r   r"   r#   r4   r5   r6   <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-	D((D-