o
    i                     @  s  d dl mZ d dlZd dlZd dlZd dlZd dlmZmZ d dl	m
Z
mZ d dlmZ d dlmZmZmZmZmZmZ d dlZd dlZd dlZd dlZd dlmZ d dlmZ d d	lmZ d dlZd d
l m!Z!m"Z" d dl#m$Z$m%Z%m&Z& d dl'm(Z(m)Z) d dl*m+Z+m,Z, d dl-m.Z.m/Z/m0Z0 d dl1m2Z2m3Z3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z< d dl=m>Z> d dl?m@Z@ d dlAmBZB ddlCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZO g dZPe@eQZRedddZSd)d!d"ZTe
G d#d$ d$ZUG d%d& d&eeE ZVe
G d'd( d(ZWdS )*    )annotationsN)AsyncExitStackasynccontextmanager)	dataclassfield)Path)AnyGenericLiteralTypeVarcastoverload)catch)ClientSession)AnyUrl)ElicitationHandlercreate_elicitation_callback)
LogHandlercreate_log_callbackdefault_log_handler)MessageHandlerMessageHandlerT)ProgressHandlerdefault_progress_handler)RootsHandler	RootsListcreate_roots_callback)ClientSamplingHandlerSamplingHandlercreate_sampling_callback)	ToolError)	MCPConfig)FastMCP)get_catch_handlers)json_schema_to_type)
get_logger)get_cached_typeadapter   )ClientTransportClientTransportTFastMCP1ServerFastMCPTransportMCPConfigTransportNodeStdioTransportPythonStdioTransportSessionKwargsSSETransportStdioTransportStreamableHttpTransportinfer_transport)
Clientr   r   r   r   r   r   r   r   r/   Tr(   )boundtimeout'datetime.timedelta | float | int | Nonereturnfloat | Nonec                 C  s(   | d u rd S t | tjr|  S t| S N)
isinstancedatetime	timedeltatotal_secondsfloat)r7    rA   [/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/client/client.py_timeout_to_secondsP   s
   rC   c                   @  s~   e Zd ZU dZdZded< dZded< eej	dZ
d	ed
< dZded< eejdZded< eejdZded< dZded< dS )ClientSessionStatezHolds all session-related state for a Client instance.

    This allows clean separation of configuration (which is copied) from
    session state (which should be fresh for each new client instance).
    NzClientSession | Nonesessionr   intnesting_counter)default_factoryz
anyio.Locklockzasyncio.Task | Nonesession_taskzanyio.Eventready_event
stop_event!mcp.types.InitializeResult | Noneinitialize_result)__name__
__module____qualname____doc__rE   __annotations__rG   r   anyioLockrI   rJ   EventrK   rL   rN   rA   rA   rA   rB   rD   Z   s   
 rD   c                   @  s4  e Zd ZdZedddZedddZedddZedddZedddZedddZ												ddd6dZedd8d9Zedd;d<Zdd>d?Z	ddBdCZ
ddFdGZddHdIZddKdLZedMdN ZdOdP ZdQdR ZdSdT ZdddWdXZdYdZ Zd[d\ Z	ddd^d_Zdd`daZ	dddedfZ		dddmdnZddqdrZddsdtZddvdwZddydzZdd|d}ZdddZdddZ dddZ!dddZ"dddZ#	ddddZ$	ddddZ%	ddddZ&	ddddZ'dddZ(dddZ)			ddddZ*					ddddZ+e,ddddZ-dS )r4   al
  
    MCP client that delegates connection management to a Transport instance.

    The Client class is responsible for MCP protocol logic, while the Transport
    handles connection establishment and management. Client provides methods for
    working with resources, prompts, tools and other MCP capabilities.

    This client supports reentrant context managers (multiple concurrent
    `async with client:` blocks) using reference counting and background session
    management. This allows efficient session reuse in any scenario with
    nested or concurrent client usage.

    MCP SDK 1.10 introduced automatic list_tools() calls during call_tool()
    execution. This created a race condition where events could be reset while
    other tasks were waiting on them, causing deadlocks. The issue was exposed
    in proxy scenarios but affects any reentrant usage.

    The solution uses reference counting to track active context managers,
    a background task to manage the session lifecycle, events to coordinate
    between tasks, and ensures all session state changes happen within a lock.
    Events are only created when needed, never reset outside locks.

    This design prevents race conditions where tasks wait on events that get
    replaced by other tasks, ensuring reliable coordination in concurrent scenarios.

    Args:
        transport:
            Connection source specification, which can be:

                - ClientTransport: Direct transport instance
                - FastMCP: In-process FastMCP server
                - AnyUrl or str: URL to connect to
                - Path: File path for local socket
                - MCPConfig: MCP server configuration
                - dict: Transport configuration

        roots: Optional RootsList or RootsHandler for filesystem access
        sampling_handler: Optional handler for sampling requests
        log_handler: Optional handler for log messages
        message_handler: Optional handler for protocol messages
        progress_handler: Optional handler for progress notifications
        timeout: Optional timeout for requests (seconds or timedelta)
        init_timeout: Optional timeout for initial connection (seconds or timedelta).
            Set to 0 to disable. If None, uses the value in the FastMCP global settings.

    Examples:
        ```python
        # Connect to FastMCP server
        client = Client("http://localhost:8080")

        async with client:
            # List available resources
            resources = await client.list_resources()

            # Call a tool
            result = await client.call_tool("my_tool", {"param": "value"})
        ```
    self	Client[T]	transportr5   argsr   kwargsr9   Nonec                 O     d S r;   rA   rW   rY   rZ   r[   rA   rA   rB   __init__   s   zClient.__init__.Client[SSETransport | StreamableHttpTransport]r   c                 O  r]   r;   rA   r^   rA   rA   rB   r_         Client[FastMCPTransport]FastMCP | FastMCP1Serverc                 O  r]   r;   rA   r^   rA   rA   rB   r_      ra   1Client[PythonStdioTransport | NodeStdioTransport]r   c                 O  r]   r;   rA   r^   rA   rA   rB   r_      ra   Client[MCPConfigTransport]MCPConfig | dict[str, Any]c                 O  r]   r;   rA   r^   rA   rA   rB   r_      ra   ZClient[PythonStdioTransport | NodeStdioTransport | SSETransport | StreamableHttpTransport]strc                 O  r]   r;   rA   r^   rA   rA   rB   r_      s   NT^ClientTransportT | FastMCP | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | strname
str | NonerootsRootsList | RootsHandler | Nonesampling_handlerClientSamplingHandler | Noneelicitation_handlerElicitationHandler | Nonelog_handlerLogHandler | Nonemessage_handler'MessageHandlerT | MessageHandler | Noneprogress_handlerProgressHandler | Noner7   r8   auto_initializeboolinit_timeoutclient_infomcp.types.Implementation | Noneauth*httpx.Auth | Literal['oauth'] | str | Nonec                 C  s   |p|   | _ttt|| _|d ur| j| |d u rt}|d u r%t}|| _	t
|	ttB r7tjt|	d}	|d u r?tjj}t|| _|
| _d d t|||	|d| _|d ur\| | |d urgt|| jd< |d urrt|| jd< t | _d S )Nseconds)sampling_callbacklist_roots_callbacklogging_callbackrt   read_timeout_secondsr{   r   elicitation_callback)generate_namerj   r   r)   r3   rY   	_set_authr   r   _progress_handlerr<   rF   r@   r=   r>   fastmcpsettingsclient_init_timeoutrC   _init_timeoutrx   r   _session_kwargs	set_rootsr   r   rD   _session_state)rW   rY   rj   rl   rn   rp   rr   rt   rv   r7   rx   rz   r{   r}   rA   rA   rB   r_      sB   
	


r   c                 C  s   | j jdu r
td| j jS )zEGet the current active session. Raises RuntimeError if not connected.NzLClient is not connected. Use the 'async with client:' context manager first.)r   rE   RuntimeErrorrW   rA   rA   rB   rE   "  s
   zClient.sessionrM   c                 C  s   | j jS )z-Get the result of the initialization request.)r   rN   r   rA   rA   rB   rN   ,  s   zClient.initialize_resultRootsList | RootsHandlerc                 C     t || jd< dS )zYSet the roots for the client. This does not automatically call `send_roots_list_changed`.r   N)r   r   )rW   rl   rA   rA   rB   r   1  s   zClient.set_rootsr   r   c                 C  r   )z)Set the sampling callback for the client.r   N)r   r   )rW   r   rA   rA   rB   set_sampling_callback5  s   zClient.set_sampling_callbackr   r   c                 C  r   )z,Set the elicitation callback for the client.r   N)r   r   )rW   r   rA   rA   rB   set_elicitation_callback;  s   zClient.set_elicitation_callbackc                 C  s   | j jduS )z+Check if the client is currently connected.N)r   rE   r   rA   rA   rB   is_connectedC  s   zClient.is_connectedClient[ClientTransportT]c                 C  s<   t  | }t| jtst |_| jdtd 7  _|S )a  Create a new client instance with the same configuration but fresh session state.

        This creates a new client with the same transport, handlers, and configuration,
        but with no active session. Useful for creating independent sessions that don't
        share state with the original client.

        Returns:
            A new Client instance with the same configuration but disconnected state.

        Example:
            ```python
            # Create a fresh client for each concurrent operation
            fresh_client = client.new()
            async with fresh_client:
                await fresh_client.call_tool("some_tool", {})
            ```
        :   )	copyr<   rY   r1   rD   r   rj   secrets	token_hex)rW   
new_clientrA   rA   rB   newG  s
   
z
Client.newc                 C s   t t o | jjdi | j4 I d H E}|| j_z,z| jr&|  I d H  d V  W n t	j
y< } ztd|d }~ww W d | j_d | j_n	d | j_d | j_w W d   I d H  n1 I d H s`w   Y  W d    d S W d    d S 1 sxw   Y  d S )Nz&Server session was closed unexpectedlyrA   )r   r#   rY   connect_sessionr   r   rE   rx   
initializerT   ClosedResourceErrorr   rN   )rW   rE   erA   rA   rB   _context_managerc  s0   



*"zClient._context_managerc                   s   |   I d H S r;   )_connectr   rA   rA   rB   
__aenter__u  s   zClient.__aenter__c                   s   |   I d H  d S r;   )_disconnect)rW   exc_typeexc_valexc_tbrA   rA   rB   	__aexit__x  s   zClient.__aexit__c              	     s  | j j4 I dH s | j jdu p| j j }|ri| j jdkr'td| j j t | j _t | j _	t
|  | j _| j j	 I dH  | j j ri| j j }|du rYtdt|tjra|td| || j  jd7  _W d  I dH  | S 1 I dH sw   Y  | S )aT  
        Establish or reuse a session connection.

        This method implements the reentrant context manager pattern:
        - First call: Creates background session task and waits for it to be ready
        - Subsequent calls: Increments reference counter and reuses existing session
        - All operations protected by _context_lock to prevent race conditions

        The critical fix: Events are only created when starting a new session,
        never reset outside the lock, preventing the deadlock scenario where
        tasks wait on events that get replaced by other tasks.
        Nr   zKInternal error: nesting counter should be 0 when starting new session, got z>Session task completed without exception but connection failedzClient failed to connect: r'   )r   rI   rJ   donerG   r   rT   rV   rL   rK   asynciocreate_task_session_runnerwait	exceptionr<   httpxHTTPStatusError)rW   need_to_startr   rA   rA   rB   r   {  sD   
  zClient._connectFforcec              	     s   | j j4 I dH S |rd| j _ntd| j jd | j _| j jdkr.	 W d  I dH  dS | j jdu r@	 W d  I dH  dS | j j  | j jI dH  d| j _W d  I dH  dS 1 I dH sbw   Y  dS )a  
        Disconnect from session using reference counting.

        This method implements proper cleanup for reentrant context managers:
        - Decrements reference counter for normal exits
        - Only stops session when counter reaches 0 (no more active contexts)
        - Force flag bypasses reference counting for immediate shutdown
        - Session cleanup happens inside the lock to ensure atomicity

        Key fix: Removed the problematic "Reset for future reconnects" logic
        that was resetting events outside the lock, causing race conditions.
        Event recreation now happens only in _connect() when actually needed.
        Nr   r'   )r   rI   rG   maxrJ   rL   set)rW   r   rA   rA   rB   r     s"   

.zClient._disconnectc              	     s   zHt  4 I dH $}||  I dH  | jj  | jj I dH  W d  I dH  n1 I dH s3w   Y  W | jj  dS W | jj  dS | jj  w )aF  
        Background task that manages the actual session lifecycle.

        This task runs in the background and:
        1. Establishes the transport connection via _context_manager()
        2. Signals that the session is ready via _ready_event.set()
        3. Waits for disconnect signal via _stop_event.wait()
        4. Ensures _ready_event is always set, even on failures

        The simplified error handling (compared to the original) removes
        redundant exception re-raising while ensuring waiting tasks are
        always unblocked via the finally block.
        N)r   enter_async_contextr   r   rK   r   rL   r   )rW   stackrA   rA   rB   r     s   *zClient._session_runnerc                   s(   | j ddI d H  | j I d H  d S )NT)r   )r   rY   closer   rA   rA   rB   r     s   zClient.closemcp.types.InitializeResultc              
     s   | j dur	| j S |du r| j}z)tt| | j I dH }|| j_ |W  d   W S 1 s2w   Y  W dS  tyJ } zt	d|d}~ww )aX  Send an initialize request to the server.

        This method performs the MCP initialization handshake with the server,
        exchanging capabilities and server information. It is idempotent - calling
        it multiple times returns the cached result from the first call.

        The initialization happens automatically when entering the client context
        manager unless `auto_initialize=False` was set during client construction.
        Manual calls to this method are only needed when auto-initialization is disabled.

        Args:
            timeout: Optional timeout for the initialization request (seconds or timedelta).
                If None, uses the client's init_timeout setting.

        Returns:
            InitializeResult: The server's initialization response containing server info,
                capabilities, protocol version, and optional instructions.

        Raises:
            RuntimeError: If the client is not connected or initialization times out.

        Example:
            ```python
            # With auto-initialization disabled
            client = Client(server, auto_initialize=False)
            async with client:
                result = await client.initialize()
                print(f"Server: {result.serverInfo.name}")
                print(f"Instructions: {result.instructions}")
            ```
        Nz#Failed to initialize server session)
rN   r   rT   
fail_afterrC   rE   r   r   TimeoutErrorr   )rW   r7   rN   r   rA   rA   rB   r     s   
$(
zClient.initializec                   s    | j  I dH }t|tjjS )zSend a ping request.N)rE   	send_pingr<   mcptypesEmptyResultrW   resultrA   rA   rB   ping!  s   zClient.ping
request_id	str | intreasonc                   s>   t jjt jjdt jj||ddd}| j|I dH  dS )z<Send a cancellation notification for an in-progress request.znotifications/cancelled)	requestIdr   )methodparams)rootN)r   r   ClientNotificationCancelledNotificationCancelledNotificationParamsrE   send_notification)rW   r   r   notificationrA   rA   rB   cancel&  s   	zClient.cancelprogress_tokenprogressr@   totalr:   messagec                   s   | j ||||I dH  dS )zSend a progress notification.N)rE   send_progress_notification)rW   r   r   r   r   rA   rA   rB   r   7  s   zClient.progresslevelmcp.types.LoggingLevelc                   s   | j |I dH  dS )z Send a logging/setLevel request.N)rE   set_logging_level)rW   r   rA   rA   rB   r   C  s   zClient.set_logging_levelc                   s   | j  I dH  dS )z'Send a roots/list_changed notification.N)rE   send_roots_list_changedr   rA   rA   rB   r   G  s   zClient.send_roots_list_changedmcp.types.ListResourcesResultc                   *   t d| j d | j I dH }|S )af  Send a resources/list request and return the complete MCP protocol result.

        Returns:
            mcp.types.ListResourcesResult: The complete response object from the protocol,
                containing the list of resources and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
        [z] called list_resourcesN)loggerdebugrj   rE   list_resourcesr   rA   rA   rB   list_resources_mcpM     
zClient.list_resources_mcplist[mcp.types.Resource]c                      |   I dH }|jS )zRetrieve a list of resources available on the server.

        Returns:
            list[mcp.types.Resource]: A list of Resource objects.

        Raises:
            RuntimeError: If called while the client is not connected.
        N)r   	resourcesr   rA   rA   rB   r   \     	zClient.list_resources%mcp.types.ListResourceTemplatesResultc                   r   )a  Send a resources/listResourceTemplates request and return the complete MCP protocol result.

        Returns:
            mcp.types.ListResourceTemplatesResult: The complete response object from the protocol,
                containing the list of resource templates and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
        r   z ] called list_resource_templatesN)r   r   rj   rE   list_resource_templatesr   rA   rA   rB   list_resource_templates_mcph  s   z"Client.list_resource_templates_mcp list[mcp.types.ResourceTemplate]c                   r   )a  Retrieve a list of resource templates available on the server.

        Returns:
            list[mcp.types.ResourceTemplate]: A list of ResourceTemplate objects.

        Raises:
            RuntimeError: If called while the client is not connected.
        N)r   resourceTemplatesr   rA   rA   rB   r   y  s   zClient.list_resource_templatesuriAnyUrl | strmcp.types.ReadResourceResultc                   sB   t d| j d|  t|trt|}| j|I dH }|S )a  Send a resources/read request and return the complete MCP protocol result.

        Args:
            uri (AnyUrl | str): The URI of the resource to read. Can be a string or an AnyUrl object.

        Returns:
            mcp.types.ReadResourceResult: The complete response object from the protocol,
                containing the resource contents and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
        r   z] called read_resource: N)r   r   rj   r<   rh   r   rE   read_resource)rW   r   r   rA   rA   rB   read_resource_mcp  s   
zClient.read_resource_mcpElist[mcp.types.TextResourceContents | mcp.types.BlobResourceContents]c              
     s\   t |tr#zt|}W n ty" } z
tdt||d}~ww | |I dH }|jS )a  Read the contents of a resource or resolved template.

        Args:
            uri (AnyUrl | str): The URI of the resource to read. Can be a string or an AnyUrl object.

        Returns:
            list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents]: A list of content
                objects, typically containing either text or binary data.

        Raises:
            RuntimeError: If called while the client is not connected.
        z"Provided resource URI is invalid: N)r<   rh   r   	Exception
ValueErrorr   contents)rW   r   r   r   rA   rA   rB   r     s   
zClient.read_resourcemcp.types.ListPromptsResultc                   r   )a`  Send a prompts/list request and return the complete MCP protocol result.

        Returns:
            mcp.types.ListPromptsResult: The complete response object from the protocol,
                containing the list of prompts and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
        r   z] called list_promptsN)r   r   rj   rE   list_promptsr   rA   rA   rB   list_prompts_mcp  r   zClient.list_prompts_mcplist[mcp.types.Prompt]c                   r   )zRetrieve a list of prompts available on the server.

        Returns:
            list[mcp.types.Prompt]: A list of Prompt objects.

        Raises:
            RuntimeError: If called while the client is not connected.
        N)r   promptsr   rA   rA   rB   r     r   zClient.list_prompts	argumentsdict[str, Any] | Nonemcp.types.GetPromptResultc                   sz   t d| j d|  d}|r0i }| D ]\}}t|tr%|||< qt|d||< q| j	j
||dI dH }|S )a  Send a prompts/get request and return the complete MCP protocol result.

        Args:
            name (str): The name of the prompt to retrieve.
            arguments (dict[str, Any] | None, optional): Arguments to pass to the prompt. Defaults to None.

        Returns:
            mcp.types.GetPromptResult: The complete response object from the protocol,
                containing the prompt messages and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
        r   z] called get_prompt: Nzutf-8rj   r   )r   r   rj   itemsr<   rh   pydantic_coreto_jsondecoderE   
get_prompt)rW   rj   r   serialized_argumentskeyvaluer   rA   rA   rB   get_prompt_mcp  s   



zClient.get_prompt_mcpc                   s   | j ||dI dH }|S )a  Retrieve a rendered prompt message list from the server.

        Args:
            name (str): The name of the prompt to retrieve.
            arguments (dict[str, Any] | None, optional): Arguments to pass to the prompt. Defaults to None.

        Returns:
            mcp.types.GetPromptResult: The complete response object from the protocol,
                containing the prompt messages and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
        r   N)r  )rW   rj   r   r   rA   rA   rB   r    s   zClient.get_promptref?mcp.types.ResourceTemplateReference | mcp.types.PromptReferenceargumentdict[str, str]context_argumentsmcp.types.CompleteResultc                   s6   t d| j d|  | jj|||dI dH }|S )a  Send a completion request and return the complete MCP protocol result.

        Args:
            ref (mcp.types.ResourceTemplateReference | mcp.types.PromptReference): The reference to complete.
            argument (dict[str, str]): Arguments to pass to the completion request.
            context_arguments (dict[str, Any] | None, optional): Optional context arguments to
                include with the completion request. Defaults to None.

        Returns:
            mcp.types.CompleteResult: The complete response object from the protocol,
                containing the completion and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
        r   z] called complete: r  r  r
  N)r   r   rj   rE   completerW   r  r  r
  r   rA   rA   rB   complete_mcp  s   zClient.complete_mcpmcp.types.Completionc                   s   | j |||dI dH }|jS )aK  Send a completion request to the server.

        Args:
            ref (mcp.types.ResourceTemplateReference | mcp.types.PromptReference): The reference to complete.
            argument (dict[str, str]): Arguments to pass to the completion request.
            context_arguments (dict[str, Any] | None, optional): Optional context arguments to
                include with the completion request. Defaults to None.

        Returns:
            mcp.types.Completion: The completion object.

        Raises:
            RuntimeError: If called while the client is not connected.
        r  N)r  
completionr  rA   rA   rB   r  5  s
   zClient.completemcp.types.ListToolsResultc                   r   )aZ  Send a tools/list request and return the complete MCP protocol result.

        Returns:
            mcp.types.ListToolsResult: The complete response object from the protocol,
                containing the list of tools and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
        r   z] called list_toolsN)r   r   rj   rE   
list_toolsr   rA   rA   rB   list_tools_mcpP  r   zClient.list_tools_mcplist[mcp.types.Tool]c                   r   )zRetrieve a list of tools available on the server.

        Returns:
            list[mcp.types.Tool]: A list of Tool objects.

        Raises:
            RuntimeError: If called while the client is not connected.
        N)r  toolsr   rA   rA   rB   r  _  r   zClient.list_toolsdict[str, Any]metamcp.types.CallToolResultc                   s^   t d| j d|  t|ttB rtjt|d}| jj	||||p&| j
|dI dH }|S )a)  Send a tools/call request and return the complete MCP protocol result.

        This method returns the raw CallToolResult object, which includes an isError flag
        and other metadata. It does not raise an exception if the tool call results in an error.

        Args:
            name (str): The name of the tool to call.
            arguments (dict[str, Any]): Arguments to pass to the tool.
            timeout (datetime.timedelta | float | int | None, optional): The timeout for the tool call. Defaults to None.
            progress_handler (ProgressHandler | None, optional): The progress handler to use for the tool call. Defaults to None.
            meta (dict[str, Any] | None, optional): Additional metadata to include with the request.
                This is useful for passing contextual information (like user IDs, trace IDs, or preferences)
                that shouldn't be tool arguments but may influence server-side processing. The server
                can access this via `context.request_context.meta`. Defaults to None.

        Returns:
            mcp.types.CallToolResult: The complete response object from the protocol,
                containing the tool result and any additional metadata.

        Raises:
            RuntimeError: If called while the client is not connected.
        r   z] called call_tool: r   )rj   r   r   progress_callbackr  N)r   r   rj   r<   rF   r@   r=   r>   rE   	call_toolr   )rW   rj   r   rv   r7   r  r   rA   rA   rB   call_tool_mcpm  s   zClient.call_tool_mcpraise_on_errorCallToolResultc              
     s:  | j ||pi |||dI dH }d}|jr&|r&ttjj|jd j}	t|	|j	rzH|| j
jvr8| j
 I dH  || j
jv rp| j
j|}
|
rm|
dr\|
di d}
|j	d}n|j	}t|
}t|}||}n|j	}W n ty } ztd| j d|  W Y d}~nd}~ww t|j|j	|j||jd	S )
a  Call a tool on the server.

        Unlike call_tool_mcp, this method raises a ToolError if the tool call results in an error.

        Args:
            name (str): The name of the tool to call.
            arguments (dict[str, Any] | None, optional): Arguments to pass to the tool. Defaults to None.
            timeout (datetime.timedelta | float | int | None, optional): The timeout for the tool call. Defaults to None.
            progress_handler (ProgressHandler | None, optional): The progress handler to use for the tool call. Defaults to None.
            raise_on_error (bool, optional): Whether to raise a ToolError if the tool call results in an error. Defaults to True.
            meta (dict[str, Any] | None, optional): Additional metadata to include with the request.
                This is useful for passing contextual information (like user IDs, trace IDs, or preferences)
                that shouldn't be tool arguments but may influence server-side processing. The server
                can access this via `context.request_context.meta`. Defaults to None.

        Returns:
            CallToolResult:
                The content returned by the tool. If the tool returns structured
                outputs, they are returned as a dataclass (if an output schema
                is available) or a dictionary; otherwise, a list of content
                blocks is returned. Note: to receive both structured and
                unstructured outputs, use call_tool_mcp instead and access the
                raw result object.

        Raises:
            ToolError: If the tool call results in an error.
            RuntimeError: If called while the client is not connected.
        )rj   r   r7   rv   r  Nr   zx-fastmcp-wrap-result
propertiesr   r   z$] Error parsing structured content: )contentstructured_contentr  datais_error)r  isErrorr   r   r   TextContentr   textr    structuredContentrE   _tool_output_schemasr  getr$   r&   validate_pythonr   r   errorrj   r  r  )rW   rj   r   r7   rv   r  r  r   r"  msgoutput_schemar!  output_typetype_adapterr   rA   rA   rB   r    sR   %

$zClient.call_toolc                 C  s<   | j }|d u r| dtd S | d| dtd S )N-r   )rO   r   r   )clsrj   
class_namerA   rA   rB   r     s   zClient.generate_name)
rW   rX   rY   r5   rZ   r   r[   r   r9   r\   )
rW   r`   rY   r   rZ   r   r[   r   r9   r\   )
rW   rb   rY   rc   rZ   r   r[   r   r9   r\   )
rW   rd   rY   r   rZ   r   r[   r   r9   r\   )
rW   re   rY   rf   rZ   r   r[   r   r9   r\   )
rW   rg   rY   rh   rZ   r   r[   r   r9   r\   )NNNNNNNNTNNN)rY   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   r7   r8   rx   ry   rz   r8   r{   r|   r}   r~   r9   r\   )r9   r   )r9   rM   )rl   r   r9   r\   )r   r   r9   r\   )r   r   r9   r\   )r9   ry   )r9   r   )F)r   ry   r;   )r7   r8   r9   r   )r   r   r   rk   r9   r\   )NN)
r   r   r   r@   r   r:   r   rk   r9   r\   )r   r   r9   r\   )r9   r\   )r9   r   )r9   r   )r9   r   )r9   r   )r   r   r9   r   )r   r   r9   r   )r9   r   )r9   r   )rj   rh   r   r   r9   r   )r  r  r  r	  r
  r   r9   r  )r  r  r  r	  r
  r   r9   r  )r9   r  )r9   r  )NNN)rj   rh   r   r  rv   rw   r7   r8   r  r   r9   r  )NNNTN)rj   rh   r   r   r7   r8   rv   rw   r  ry   r  r   r9   r  )rj   rk   r9   rh   ).rO   rP   rQ   rR   r   r_   propertyrE   rN   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  classmethodr   rA   rA   rA   rB   r4   k   s    ;K	





0&
1








'
% 

0Nr4   c                   @  s>   e Zd ZU ded< ded< ded< dZded< d	Zd
ed< dS )r  zlist[mcp.types.ContentBlock]r   r   r!  r  Nr   r"  Fry   r#  )rO   rP   rQ   rS   r"  r#  rA   rA   rA   rB   r    s   
 r  )r7   r8   r9   r:   )X
__future__r   r   r   r=   r   
contextlibr   r   dataclassesr   r   pathlibr   typingr   r	   r
   r   r   r   rT   r   	mcp.typesr   r   exceptiongroupr   r   pydanticr   r   fastmcp.client.elicitationr   r   fastmcp.client.loggingr   r   r   fastmcp.client.messagesr   r   fastmcp.client.progressr   r   fastmcp.client.rootsr   r   r   fastmcp.client.samplingr   r   r   fastmcp.exceptionsr    fastmcp.mcp_configr!   fastmcp.serverr"   fastmcp.utilities.exceptionsr#   "fastmcp.utilities.json_schema_typer$   fastmcp.utilities.loggingr%   fastmcp.utilities.typesr&   
transportsr(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   __all__rO   r   r5   rC   rD   r4   r  rA   rA   rA   rB   <module>   s^     8

       