
    k7i#                    >   S SK Jr  S SKrS SKrS SKrS SKrS SKJrJr  S SK	J
r
Jr  S SKJr  S SKJrJrJrJrJrJr  S SKrS SKrS SKrS SKrS SKJr  S SKJr  S S	KJr  S SKrS S
K J!r!J"r"  S SK#J$r$J%r%J&r&  S SK'J(r(J)r)  S SK*J+r+J,r,  S SK-J.r.J/r/J0r0  S SK1J2r2J3r3J4r4  S SK5J6r6  S SK7J8r8  S SK9J:r:  S SK;J<r<  S SK=J>r>  S SK?J@r@  S SKAJBrB  SSKCJDrDJErEJFrFJGrGJHrHJIrIJJrJJKrKJLrLJMrMJNrNJOrO  / SQrP\@" \Q5      rR\" SSS9rS\
 " S S5      5       rT " S S \\E   5      rU\
 " S! S"5      5       rVg)#    )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   r0   Tr)   )boundc                      \ rS rSr% SrSrS\S'   SrS\S'   \" \	R                  S	9rS
\S'   SrS\S'   \" \	R                  S	9rS\S'   \" \	R                  S	9rS\S'   SrS\S'   Srg)ClientSessionStateP   zHolds 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_eventz!mcp.types.InitializeResult | Noneinitialize_result )__name__
__module____qualname____firstlineno____doc__r;   __annotations__r=   r   anyioLockr?   r@   EventrA   rB   rC   __static_attributes__rD       O/home/james-whalen/.local/lib/python3.13/site-packages/fastmcp/client/client.pyr9   r9   P   sn     %)G!(OSUZZ8D*8(,L%,$U[[AKA#EKK@J@;?8?rO   r9   c                     \ rS rSrSr\S0S j5       r\          S1S j5       r\          S2S j5       r\          S3S j5       r\          S4S j5       r\          S5S j5       r           S6                         S7S
 jjr\S8S j5       r\S9S j5       r	S:S jr
S;S jr    S<S jrS=S jrS>S jr\S 5       rS rS rS rS?S@S jjrS rS rS=S jr SA     SBS jjr  SC         SDS jjrSES jrSFS jrSGS jrSHS jr  SIS  jr  SJS! jr    SKS" jr     SLS# jr!SMS$ jr"SNS% jr# SA     SOS& jjr$ SA     SOS' jjr% SA       SPS( jjr& SA       SQS) jjr'SRS* jr(SSS+ jr)  SC         STS, jjr*    SU           SVS- jjr+\,SASWS. jj5       r-S/r.g	)Xr5   a   a	  
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"})
    ```
c                    g NrD   self	transportargskwargss       rP   __init__Client.__init__   s    TWrO   c                    g rT   rD   rU   s       rP   rZ   r[           rO   c                    g rT   rD   rU   s       rP   rZ   r[      r]   rO   c                    g rT   rD   rU   s       rP   rZ   r[      r]   rO   c                    g rT   rD   rU   s       rP   rZ   r[      r]   rO   c                    g rT   rD   rU   s       rP   rZ   r[      s     rO   Nc                
   U=(       d    U R                  5       U l        [        [        [	        U5      5      U l        Ub  U R
                  R                  U5        Uc  [        nUc  [        nXl	        [        U	[        [        -  5      (       a  [        R                  " [        U	5      S9n	U
c  [        R                   R"                  n
[        U
[        R                  5      (       a  U
R%                  5       n
OU
(       d  S n
O[        U
5      n
Xl        S S [)        U5      UU	US.U l        Ub  U R-                  U5        Ub  [/        U5      U R*                  S'   Ub  [1        U5      U R*                  S'   [3        5       U l        g )Nseconds)sampling_callbacklist_roots_callbacklogging_callbackmessage_handlerread_timeout_secondsclient_infore   elicitation_callback)generate_namenamer   r*   r4   rW   	_set_authr   r   _progress_handler
isinstancer<   floatdatetime	timedeltafastmcpsettingsclient_init_timeouttotal_seconds_init_timeoutr   _session_kwargs	set_rootsr    r   r9   _session_state)rV   rW   rm   rootssampling_handlerelicitation_handlerlog_handlerrh   progress_handlertimeoutinit_timeoutrj   auths                rP   rZ   r[      s]   0 0D..0	.	0JKNN$$T*-K#7!1gsU{++((w@G "++??LlH$6$677'557LL .L) "&#' 3K @.$+&/
 NN5!'8P 9D  !45 *;V#<D  !78
 12rO   c                r    U R                   R                  c  [        S5      eU R                   R                  $ )zEGet the current active session. Raises RuntimeError if not connected.LClient is not connected. Use the 'async with client:' context manager first.)r{   r;   RuntimeErrorrV   s    rP   r;   Client.session  s:     &&.^  ""***rO   c                r    U R                   R                  c  [        S5      eU R                   R                  $ )z-Get the result of the initialization request.r   )r{   rC   r   r   s    rP   rC   Client.initialize_result$  s:     008^  ""444rO   c                4    [        U5      U R                  S'   g)zYSet the roots for the client. This does not automatically call `send_roots_list_changed`.rf   N)r   ry   )rV   r|   s     rP   rz   Client.set_roots-  s    6KE6R23rO   c                4    [        U5      U R                  S'   g)z)Set the sampling callback for the client.re   N)r    ry   )rV   re   s     rP   set_sampling_callbackClient.set_sampling_callback1  s    4L5
01rO   c                4    [        U5      U R                  S'   g)z,Set the elicitation callback for the client.rk   N)r   ry   )rV   rk   s     rP   set_elicitation_callbackClient.set_elicitation_callback7  s     8S 8
34rO   c                2    U R                   R                  SL$ )z+Check if the client is currently connected.N)r{   r;   r   s    rP   is_connectedClient.is_connected?  s    ""**$66rO   c                    [         R                   " U 5      n[        U R                  [        5      (       d  [	        5       Ul        U=R                  S[        R                  " S5       3-  sl        U$ )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", {})
    ```
:   )	copyrp   rW   r2   r9   r{   rm   secrets	token_hex)rV   
new_clients     rP   new
Client.newC  sT    $ YYt_
$...99(:(<J%Qw003455rO   c               P  #    [        [        5       5         U R                  R                  " S0 U R                  D6 IS h  vN nXR
                  l         [        R                  " U R                  5         U R
                  R                  R                  5       I S h  vN U R
                  l        S S S 5        S 7v    S U R
                  l        S U R
                  l        S S S 5      IS h  vN   S S S 5        g  N N^! , (       d  f       NS= f! [        R                   a  n[        S5      UeS nAf[         a  n[        S5      UeS nAff = f! S U R
                  l        S U R
                  l        f = f N! , IS h  vN  (       d  f       N= f! , (       d  f       g = f7f)Nz&Server session was closed unexpectedlyz#Failed to initialize server sessionrD   )r   r$   rW   connect_sessionry   r{   r;   rK   
fail_afterrx   
initializerC   ClosedResourceErrorr   TimeoutError)rV   r;   es      rP   _context_managerClient._context_manager_  sS    %'(~~55 && .5##+A))$*<*<="&"5"5"="="H"H"JJ ++= >  37D''/<@D''9#  )( K >=
 00 X&'OPVWW# U&'LMSTTU 37D''/<@D''9#    )(s   F&+FC<FE; D7(D C>
 D 3D"E;#F.E9/F3	F&<F>D  
D
DE%D11E>E

EE$E66E;9F;F	FF	F
F#F&c                >   #    U R                  5       I S h  vN $  N7frT   )_connectr   s    rP   
__aenter__Client.__aenter__u  s     ]]_$$$s   c                @   #    U R                  5       I S h  vN   g  N7frT   )_disconnect)rV   exc_typeexc_valexc_tbs       rP   	__aexit__Client.__aexit__x  s        s   c                `  #    U R                   R                   ISh  vN   U R                   R                  SL =(       d$    U R                   R                  R                  5       nU(       Gan  U R                   R                  S:w  a"  [        SU R                   R                   35      e[        R                  " 5       U R                   l        [        R                  " 5       U R                   l	        [        R                  " U R                  5       5      U R                   l        U R                   R                  R                  5       I Sh  vN   U R                   R                  R                  5       (       ab  U R                   R                  R                  5       nUc  [        S5      e[        U[         R"                  5      (       a  Ue[        SU 35      UeU R                   =R                  S-  sl        SSS5      ISh  vN   U $  GN N N! , ISh  vN  (       d  f       U $ = f7f)a  
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{   r?   r@   doner=   r   rK   rM   rB   rA   asynciocreate_task_session_runnerwait	exceptionrp   httpxHTTPStatusError)rV   need_to_startr   s      rP   r   Client._connect{  s     &&+++##00D8 ;&&3388: 
 &&66!;&efjfyfy  gJ  gJ  fK  L  27##.27++-##/3:3F3F((*4##0 ))55::<<<&&3388:: $ 3 3 @ @ J J LI (*\  ")U-B-BCC'&4YK@$% //14/= ,+@ A ,  =! ,++@ sX   H.HH.D*HHB.H:H.HH.HH.H+HH+&H.c                  #    U R                   R                   ISh  vN   U(       a  SU R                   l        O2[        SU R                   R                  S-
  5      U R                   l        U R                   R                  S:  a   SSS5      ISh  vN   gU R                   R                  c   SSS5      ISh  vN   gU R                   R
                  R                  5         U R                   R                  I Sh  vN   SU R                   l        SSS5      ISh  vN   g GN	 N Nn N- N! , ISh  vN  (       d  f       g= f7f)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{   r?   r=   maxr@   rB   set)rV   forces     rP   r   Client._disconnect  s      &&+++67##3 7:t**::Q>7##3
 ""22Q6 ,++  ""//7# ,++$ **..0%%2222/3D,+ ,++( 3) ,+++s   ED&EA'D1ED)ED11E<D+=E=D1?D- D1E D/!E)E+E-D1/E1E7D:8EEc                   #     [        5        ISh  vN nUR                  U R                  5       5      I Sh  vN   U R                  R                  R                  5         U R                  R                  R                  5       I Sh  vN   SSS5      ISh  vN   U R                  R                  R                  5         g N N N= N/! , ISh  vN  (       d  f       ND= f! U R                  R                  R                  5         f = f7f)a  
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{   rA   r   rB   r   )rV   stacks     rP   r   Client._session_runner  s     		2%''5//0E0E0GHHH##//335))4499;;; (' ++//1 (H < (''' ++//1s   DC% CC% #CCAC	C
CC% C	C% %DC% CC	C% C"CC"C% %&DDc                   #    U R                  SS9I S h  vN   U R                  R                  5       I S h  vN   g  N' N7f)NT)r   )r   rW   closer   s    rP   r   Client.close  s:     T***nn""$$$ 	+$s   A=!A?AAc                   #    U R                   R                  5       I Sh  vN n[        U[        R                  R
                  5      $  N(7f)zSend a ping request.N)r;   	send_pingrp   mcptypesEmptyResultrV   results     rP   pingClient.ping  s6     ||--//&#))"7"788 0s   AA	)Ac           
        #    [         R                  R                  [         R                  R                  S[         R                  R	                  UUS9S9S9nU R
                  R                  U5      I Sh  vN   g N7f)z<Send a cancellation notification for an in-progress request.znotifications/cancelled)	requestIdreason)methodparams)rootN)r   r   ClientNotificationCancelledNotificationCancelledNotificationParamsr;   send_notification)rV   
request_idr   notifications       rP   cancelClient.cancel  sq      yy33000yy<<(! =  1  4 
 ll,,\:::s   A4A>6A<7A>c                X   #    U R                   R                  XX45      I Sh  vN   g N7f)zSend a progress notification.N)r;   send_progress_notification)rV   progress_tokenprogresstotalmessages        rP   r   Client.progress  s(      ll55e
 	
 	
s    *(*c                V   #    U R                   R                  U5      I Sh  vN   g N7f)z Send a logging/setLevel request.N)r;   set_logging_level)rV   levels     rP   r   Client.set_logging_level  s     ll,,U333s   )')c                T   #    U R                   R                  5       I Sh  vN   g N7f)z'Send a roots/list_changed notification.N)r;   send_roots_list_changedr   s    rP   r   Client.send_roots_list_changed  s     ll22444s   (&(c                   #    [         R                  SU R                   S35        U R                  R	                  5       I Sh  vN nU$  N7f)a6  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debugrm   r;   list_resourcesr   s     rP   list_resources_mcpClient.list_resources_mcp  s@      	q#:;<||2244 5   AAA
Ac                V   #    U R                  5       I Sh  vN nUR                  $  N7f)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   s     rP   r   Client.list_resources+  s)      ..00 1   )')c                   #    [         R                  SU R                   S35        U R                  R	                  5       I Sh  vN nU$  N7f)aX  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   rm   r;   list_resource_templatesr   s     rP   list_resource_templates_mcp"Client.list_resource_templates_mcp7  s@      	q#CDE||;;== >r   c                V   #    U R                  5       I Sh  vN nUR                  $  N7f)zRetrieve 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   s     rP   r   Client.list_resource_templatesH  s)      7799''' :r   c                   #    [         R                  SU R                   SU 35        [        U[        5      (       a  [        U5      nU R                  R                  U5      I Sh  vN nU$  N7f)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   rm   rp   strr   r;   read_resource)rV   urir   s      rP   read_resource_mcpClient.read_resource_mcpV  s\      	q#;C5ABc3+C||11#66 7s   A$A/&A-'A/c                   #    [        U[        5      (       a   [        U5      nU R                  U5      I Sh  vN nUR                  $ ! [         a  n[	        S[        U5      < 35      UeSnAff = f N;7f)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)rp   r  r   	Exception
ValueErrorr  contents)rV   r  r   r   s       rP   r  Client.read_resourcel  sv      c3Sk
 --c22   8SE 3s1   A6A	 A6A4A6	
A1A,,A11A6c                   #    [         R                  SU R                   S35        U R                  R	                  5       I Sh  vN nU$  N7f)a0  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   rm   r;   list_promptsr   s     rP   list_prompts_mcpClient.list_prompts_mcp  s@      	q#89:||0022 3r   c                V   #    U R                  5       I Sh  vN nUR                  $  N7f)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   s     rP   r  Client.list_prompts  s'      ,,..~~ /r   c                j  #    [         R                  SU R                   SU 35        SnU(       a]  0 nUR                  5        HG  u  pE[	        U[
        5      (       a  XSU'   M   [        R                  " U5      R                  S5      X4'   MI     U R                  R                  XS9I Sh  vN nU$  N7f)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rm   	arguments)r   r   rm   itemsrp   r  pydantic_coreto_jsondecoder;   
get_prompt)rV   rm   r  serialized_argumentskeyvaluer   s          rP   get_prompt_mcpClient.get_prompt_mcp  s       	q#8?@ 7;#% 'oo/
eS))05- 1>0E0Ee0L0S0S1(- 0 ||.. / 
 
 
s   B(B3*B1+B3c                @   #    U R                  XS9I Sh  vN nU$  N7f)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  )rV   rm   r  r   s       rP   r  Client.get_prompt  s(       ***JJ Ks   c                   #    [         R                  SU R                   SU 35        U R                  R	                  XUS9I Sh  vN nU$  N7f)au  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: refargumentcontext_argumentsN)r   r   rm   r;   completerV   r%  r&  r'  r   s        rP   complete_mcpClient.complete_mcp  sU     * 	q#6se<=||,,:K - 
 
 
s   AAAAc                V   #    U R                  XUS9I Sh  vN nUR                  $  N7f)a  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)  s        rP   r(  Client.complete  s:     ( ((:K ) 
 
    
r   c                   #    [         R                  SU R                   S35        U R                  R	                  5       I Sh  vN nU$  N7f)a*  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   rm   r;   
list_toolsr   s     rP   list_tools_mcpClient.list_tools_mcp  s@      	q#678||..00 1r   c                V   #    U R                  5       I Sh  vN nUR                  $  N7f)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)r1  toolsr   s     rP   r0  Client.list_tools.  s'      **,,|| -r   c                <  #    [         R                  SU R                   SU 35        [        U[        [
        -  5      (       a  [        R                  " [        U5      S9nU R                  R                  UUUU=(       d    U R                  S9I Sh  vN nU$  N7f)a3  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.

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: rc   )rm   r  ri   progress_callbackN)r   r   rm   rp   r<   rq   rr   rs   r;   	call_toolro   )rV   rm   r  r   r   r   s         rP   call_tool_mcpClient.call_tool_mcp<  s     2 	q#7v>?gsU{++((w@G||--!(.H$2H2H	 . 
 
 
s   BBBBc                4  #    U R                  UU=(       d    0 UUS9I Sh  vN nSnUR                  (       aM  U(       aF  [        [        R                  R
                  UR                  S   5      R                  n[        U5      eUR                  (       Ga   XR                  R                  ;  a"  U R                  R                  5       I Sh  vN   XR                  R                  ;   a  U R                  R                  R                  U5      n	U	(       a  U	R                  S5      (       a=  U	R                  S0 5      R                  S5      n	UR                  R                  S5      n
OUR                  n
[        U	5      n[        U5      nUR!                  U
5      nOUR                  n[+        UR                  UR                  UUR                  S	9$  GN GN
! ["         a/  n[$        R'                  SU R(                   SU 35         SnANdSnAff = f7f)
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.

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.
)rm   r  r   r   Nr   zx-fastmcp-wrap-result
propertiesr   r   z$] Error parsing structured content: )contentstructured_contentdatais_error)r9  isErrorr   r   r   TextContentr=  textr!   structuredContentr;   _tool_output_schemasr0  getr%   r'   validate_pythonr	  r   errorrm   CallToolResult)rV   rm   r  r   r   raise_on_errorr   r?  msgoutput_schemar>  output_typetype_adapterr   s                 rP   r8  Client.call_toola  s    > ))o2-	 * 
 
 >>nsyy,,fnnQ.?@EECC. %%%U||@@@,,11333<<<<<$(LL$E$E$I$I$$OM$(,,-DEE,9,=,=lB,O,S,S (-M 281I1I1M1Mh1W.171I1I.&9-&H'=k'J+;;<NO%77 NN%77^^	
 	
A
 4   Uq+OPQsSTTUsY   HGA6H6G GCG H G ,+HG 
H&%HHHHc                    U R                   nUc  U S[        R                  " S5       3$ U SU S[        R                  " S5       3$ )N-r   )rE   r   r   )clsrm   
class_names      rP   rl   Client.generate_name  sP    \\
< \7#4#4Q#7"899 \4&'*;*;A*>)?@@rO   )rx   ro   ry   r{   rm   rW   )
rV   z	Client[T]rW   r6   rX   r	   rY   r	   returnNone)
rV   z.Client[SSETransport | StreamableHttpTransport]rW   r   rX   r	   rY   r	   rU  rV  )
rV   zClient[FastMCPTransport]rW   zFastMCP | FastMCP1ServerrX   r	   rY   r	   rU  rV  )
rV   z1Client[PythonStdioTransport | NodeStdioTransport]rW   r   rX   r	   rY   r	   rU  rV  )
rV   zClient[MCPConfigTransport]rW   zMCPConfig | dict[str, Any]rX   r	   rY   r	   rU  rV  )
rV   zZClient[PythonStdioTransport | NodeStdioTransport | SSETransport | StreamableHttpTransport]rW   r  rX   r	   rY   r	   rU  rV  )NNNNNNNNNNN)rW   z^ClientTransportT | FastMCP | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | strrm   
str | Noner|   zRootsList | RootsHandler | Noner}   zClientSamplingHandler | Noner~   zElicitationHandler | Noner   zLogHandler | Nonerh   z'MessageHandlerT | MessageHandler | Noner   ProgressHandler | Noner   'datetime.timedelta | float | int | Noner   rY  rj   zmcp.types.Implementation | Noner   z*httpx.Auth | Literal['oauth'] | str | NonerU  rV  )rU  r   )rU  zmcp.types.InitializeResult)r|   zRootsList | RootsHandlerrU  rV  )re   r   rU  rV  )rk   r   rU  rV  )rU  bool)rU  zClient[ClientTransportT])F)r   rZ  rT   )r   	str | intr   rW  rU  rV  )NN)
r   r[  r   rq   r   zfloat | Noner   rW  rU  rV  )r   zmcp.types.LoggingLevelrU  rV  )rU  rV  )rU  zmcp.types.ListResourcesResult)rU  zlist[mcp.types.Resource])rU  z%mcp.types.ListResourceTemplatesResult)rU  z list[mcp.types.ResourceTemplate])r  AnyUrl | strrU  zmcp.types.ReadResourceResult)r  r\  rU  zElist[mcp.types.TextResourceContents | mcp.types.BlobResourceContents])rU  zmcp.types.ListPromptsResult)rU  zlist[mcp.types.Prompt])rm   r  r  dict[str, Any] | NonerU  zmcp.types.GetPromptResult)r%  ?mcp.types.ResourceTemplateReference | mcp.types.PromptReferencer&  dict[str, str]r'  r]  rU  zmcp.types.CompleteResult)r%  r^  r&  r_  r'  r]  rU  zmcp.types.Completion)rU  zmcp.types.ListToolsResult)rU  zlist[mcp.types.Tool])
rm   r  r  zdict[str, Any]r   rX  r   rY  rU  zmcp.types.CallToolResult)NNNT)rm   r  r  r]  r   rY  r   rX  rJ  rZ  rU  rI  )rm   rW  rU  r  )/rE   rF   rG   rH   rI   r   rZ   propertyr;   rC   rz   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(  r1  r0  r9  r8  classmethodrl   rN   rD   rO   rP   r5   r5   a   s   9v W W<  	
 
  &+  	
 
  ?  	
 
  (-  	
 
  


 
 
 
 

 
0  159=9=)-CG37;?@D7;;?-K3K3 K3 /K3 7K3 7K3  '!K3" A#K3$ 1%K3& 9'K3( >)K3* 5+K3, 9-K3. 
/K3Z + + 5 5S

$6
	
78 A A*%!.`$4L22%9 ";; ; 
	;* #"

!

 

 	


 

 


45
 	."(	)(	%,	NN
 =A""$9"	""J =A$9	"2 48	L ! 1	
 
"@ 48	!L! !! 1	!
 
!6
$ 48;?## "# 1	#
 9# 
"#P ,0;?37#D
D
 )D
 9	D

 1D
 D
 
D
L A ArO   r5   c                  F    \ rS rSr% S\S'   S\S'   SrS\S'   S	rS
\S'   Srg)rI  i  zlist[mcp.types.ContentBlock]r=  r]  r>  Nr	   r?  FrZ  r@  rD   )rE   rF   rG   rH   rJ   r?  r@  rN   rD   rO   rP   rI  rI    s"    ))--D#HdrO   rI  )W
__future__r   r   r   rr   r   
contextlibr   r   dataclassesr   r   pathlibr   typingr	   r
   r   r   r   r   rK   r   	mcp.typesr   r  exceptiongroupr   r   pydanticr   rt   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/   r0   r1   r2   r3   r4   __all__rE   r   r6   r9   r5   rI  rD   rO   rP   <module>rz     s    "     : (  A A          V 
 D M 
 
 ) ( " ; B 0 :    
H	C() @ @ @ LAW%& LA^   rO   