Client Overview
Learn how to use the FastMCP Client to interact with MCP servers.
The fastmcp.Client
provides a high-level, asynchronous interface for interacting with any Model Context Protocol (MCP) server, whether it’s built with FastMCP or another implementation. It simplifies communication by handling protocol details and connection management.
FastMCP Client
The FastMCP Client architecture separates the protocol logic (Client
) from the connection mechanism (Transport
).
Client
: Handles sending MCP requests (liketools/call
,resources/read
), receiving responses, and managing callbacks.Transport
: Responsible for establishing and maintaining the connection to the server (e.g., via WebSockets, SSE, Stdio, or in-memory).
Transports
Clients must be initialized with a transport
. You can either provide an already instantiated transport object, or provide a transport source and let FastMCP attempt to infer the correct transport to use.
The following inference rules are used to determine the appropriate ClientTransport
based on the input type:
ClientTransport
Instance: If you provide an already instantiated transport object, it’s used directly.FastMCP
Instance: Creates aFastMCPTransport
for efficient in-memory communication (ideal for testing).Path
orstr
pointing to an existing file:- If it ends with
.py
: Creates aPythonStdioTransport
to run the script usingpython
. - If it ends with
.js
: Creates aNodeStdioTransport
to run the script usingnode
.
- If it ends with
AnyUrl
orstr
pointing to a URL:- If it starts with
http://
orhttps://
: Creates anSSETransport
. - If it starts with
ws://
orwss://
: Creates aWSTransport
.
- If it starts with
- Other: Raises a
ValueError
if the type cannot be inferred.
For more control over connection details (like headers for SSE, environment variables for Stdio), you can instantiate the specific ClientTransport
class yourself and pass it to the Client
. See the Transports page for details.
Client Usage
Connection Lifecycle
The client operates asynchronously and must be used within an async with
block. This context manager handles establishing the connection, initializing the MCP session, and cleaning up resources upon exit.
You can make multiple calls to the server within the same async with
block using the established session.
Client Methods
The Client
provides methods corresponding to standard MCP requests:
Tool Operations
list_tools()
: Retrieves a list of tools available on the server.call_tool(name: str, arguments: dict[str, Any] | None = None)
: Executes a tool on the server.- Arguments are passed as a dictionary. FastMCP servers automatically handle JSON string parsing for complex types if needed.
- Returns a list of content objects (usually
TextContent
orImageContent
).
Resource Operations
list_resources()
: Retrieves a list of static resources.list_resource_templates()
: Retrieves a list of resource templates.read_resource(uri: str | AnyUrl)
: Reads the content of a resource or a resolved template.
Prompt Operations
list_prompts()
: Retrieves available prompt templates.get_prompt(name: str, arguments: dict[str, Any] | None = None)
: Retrieves a rendered prompt message list.
Callbacks
MCP allows servers to make requests back to the client for certain capabilities. The Client
constructor accepts callback functions to handle these server requests:
Roots
roots: RootsList | RootsHandler | None
: Provides the server with a list of root directories the client grants access to. This can be a static list or a function that dynamically determines roots.Seefastmcp.client.roots
for helpers.
LLM Sampling
sampling_handler: SamplingHandler | None
: Handlessampling/createMessage
requests from the server. This callback receives messages from the server and should return an LLM completion.Seefastmcp.client.sampling
for helpers.
Logging
log_handler: LoggingFnT | None
: Receives log messages sent from the server (ctx.info
,ctx.error
, etc.).
Error Handling
When a call_tool
request results in an error on the server (e.g., the tool function raised an exception), the client.call_tool()
method will raise a fastmcp.client.ClientError
.
Other errors, like connection failures, will raise standard Python exceptions (e.g., ConnectionError
, TimeoutError
).
The client transport often has its own error-handling mechanisms, so you can not always trap errors like those raised by call_tool
outside of the async with
block. Instead, you can call call_tool(..., _return_raw_result=True)
to get the raw mcp.types.CallToolResult
object and handle errors yourself by checking its isError
attribute.