fastmcp.client.client
Classes
ClientSessionState
Holds 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).
CallToolResult
Parsed result from a tool call.
Client
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.
session
initialize_result
set_roots
send_roots_list_changed.
set_sampling_callback
set_elicitation_callback
is_connected
new
- A new Client instance with the same configuration but disconnected state.
initialize
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.
- The server’s initialization response containing server info, capabilities, protocol version, and optional instructions.
RuntimeError: If the client is not connected or initialization times out.
close
ping
cancel
progress
set_logging_level
send_roots_list_changed
list_resources_mcp
- mcp.types.ListResourcesResult: The complete response object from the protocol, containing the list of resources and any additional metadata.
RuntimeError: If called while the client is not connected.
list_resources
- list[mcp.types.Resource]: A list of Resource objects.
RuntimeError: If called while the client is not connected.
list_resource_templates_mcp
- mcp.types.ListResourceTemplatesResult: The complete response object from the protocol, containing the list of resource templates and any additional metadata.
RuntimeError: If called while the client is not connected.
list_resource_templates
- list[mcp.types.ResourceTemplate]: A list of ResourceTemplate objects.
RuntimeError: If called while the client is not connected.
read_resource_mcp
uri: The URI of the resource to read. Can be a string or an AnyUrl object.meta: Request metadata (e.g., for SEP-1686 tasks). Defaults to None.
- mcp.types.ReadResourceResult: The complete response object from the protocol, containing the resource contents and any additional metadata.
RuntimeError: If called while the client is not connected.
read_resource
read_resource
read_resource
uri: The URI of the resource to read. Can be a string or an AnyUrl object.task: If True, execute as background task (SEP-1686). Defaults to False.task_id: Optional client-provided task ID (auto-generated if not provided).ttl: Time to keep results available in milliseconds (default 60s).
- list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents] | ResourceTask: A list of content objects if task=False, or a ResourceTask object if task=True.
RuntimeError: If called while the client is not connected.
list_prompts_mcp
- mcp.types.ListPromptsResult: The complete response object from the protocol, containing the list of prompts and any additional metadata.
RuntimeError: If called while the client is not connected.
list_prompts
- list[mcp.types.Prompt]: A list of Prompt objects.
RuntimeError: If called while the client is not connected.
get_prompt_mcp
name: The name of the prompt to retrieve.arguments: Arguments to pass to the prompt. Defaults to None.meta: Request metadata (e.g., for SEP-1686 tasks). Defaults to None.
- mcp.types.GetPromptResult: The complete response object from the protocol, containing the prompt messages and any additional metadata.
RuntimeError: If called while the client is not connected.
get_prompt
get_prompt
get_prompt
name: The name of the prompt to retrieve.arguments: Arguments to pass to the prompt. Defaults to None.task: If True, execute as background task (SEP-1686). Defaults to False.task_id: Optional client-provided task ID (auto-generated if not provided).ttl: Time to keep results available in milliseconds (default 60s).
- mcp.types.GetPromptResult | PromptTask: The complete response object if task=False, or a PromptTask object if task=True.
RuntimeError: If called while the client is not connected.
complete_mcp
ref: The reference to complete.argument: Arguments to pass to the completion request.context_arguments: Optional context arguments to include with the completion request. Defaults to None.
- mcp.types.CompleteResult: The complete response object from the protocol, containing the completion and any additional metadata.
RuntimeError: If called while the client is not connected.
complete
ref: The reference to complete.argument: Arguments to pass to the completion request.context_arguments: Optional context arguments to include with the completion request. Defaults to None.
- mcp.types.Completion: The completion object.
RuntimeError: If called while the client is not connected.
list_tools_mcp
- mcp.types.ListToolsResult: The complete response object from the protocol, containing the list of tools and any additional metadata.
RuntimeError: If called while the client is not connected.
list_tools
- list[mcp.types.Tool]: A list of Tool objects.
RuntimeError: If called while the client is not connected.
call_tool_mcp
name: The name of the tool to call.arguments: Arguments to pass to the tool.timeout: The timeout for the tool call. Defaults to None.progress_handler: The progress handler to use for the tool call. Defaults to None.meta: 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 viacontext.request_context.meta. Defaults to None.
- mcp.types.CallToolResult: The complete response object from the protocol, containing the tool result and any additional metadata.
RuntimeError: If called while the client is not connected.
call_tool
call_tool
call_tool
name: The name of the tool to call.arguments: Arguments to pass to the tool. Defaults to None.timeout: The timeout for the tool call. Defaults to None.progress_handler: The progress handler to use for the tool call. Defaults to None.raise_on_error: Whether to raise an exception if the tool call results in an error. Defaults to True.meta: 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 viacontext.request_context.meta. Defaults to None.task: If True, execute as background task (SEP-1686). Defaults to False.task_id: Optional client-provided task ID (auto-generated if not provided).ttl: Time to keep results available in milliseconds (default 60s).
- CallToolResult | ToolTask: The content returned by the tool if task=False, or a ToolTask object if task=True. 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.
ToolError: If the tool call results in an error.RuntimeError: If called while the client is not connected.
get_task_status
task_id: The task ID returned from call_tool_as_task
- Status information including taskId, status, pollInterval, etc.
RuntimeError: If client not connected
get_task_result
task_id: The task ID returned from call_tool_as_task
- The raw result (could be tool, prompt, or resource result)
RuntimeError: If client not connected, task not found, or task failed
list_tasks
cursor: Optional pagination cursorlimit: Maximum number of tasks to return (default 50)
- Response with structure:
- tasks: List of task status dicts with taskId, status, etc.
- nextCursor: Optional cursor for next page
RuntimeError: If client not connected
cancel_task
task_id: The task ID to cancel
- The task status showing cancelled state
RuntimeError: If task doesn’t exist

