Using the FastMCP Client to Call MCP Servers

Connect to local or remote servers from Python, call tools, read resources and handle results and errors.

Python client code calling a FastMCP server with the result shown in a terminal

Key takeaways

  • Client connects to a URL, a script path, a config dictionary or a server object.
  • Use result.data for Python values and result.content for raw blocks.
  • Handlers receive server logs and progress updates.
  • Send bearer tokens through the auth argument.

FastMCP is not only for building servers. Its Client class connects to any MCP server, whether it was written with FastMCP or not, which makes it useful for scripts, automated tests, data pipelines and your own agent code.

When You Need a Client

  • Testing – call your own server’s tools from pytest without a model in the loop.
  • Automation – run a server’s tools from a scheduled job or a command-line script.
  • Agents – connect your own agent framework to existing MCP servers.
  • Aggregation – talk to several servers through one connection.

Connecting to a Server

Pass the client whatever identifies the server. FastMCP picks the transport for you:

from pathlib import Path
from fastmcp import Client

client = Client("https://api.example.com/mcp")   # remote, over HTTP
client = Client(Path("my_server.py"))            # local script, over STDIO
client = Client(mcp)                             # server object, in memory

The client is asynchronous. Open the connection with async with; it stays open for every call inside the block and closes cleanly afterwards.

import asyncio


async def main():
    async with Client("http://localhost:8000/mcp") as client:
        ...  # every call happens here


asyncio.run(main())

Connecting to Several Servers at Once

A configuration dictionary in the standard mcpServers format connects to several servers through one client:

config = {
    "mcpServers": {
        "weather": {"url": "https://weather-api.example.com/mcp"},
        "assistant": {"command": "python", "args": ["./assistant_server.py"]},
    }
}

client = Client(config)

Tool names are prefixed with the server name, so a get_forecast tool on the weather server becomes weather_get_forecast. Resource URIs receive a similar prefix. This keeps names unique even when two servers define components with the same name.

Discovering What a Server Offers

async with client:
    tools = await client.list_tools()
    resources = await client.list_resources()
    prompts = await client.list_prompts()

    for tool in tools:
        print(tool.name, "-", tool.description)

Each tool exposes its name, description and input_schema. Listing components is the quickest way to confirm that a server is reachable and exposes what you expect, and printing the schema shows exactly which arguments a tool requires.

Calling Tools

async with client:
    result = await client.call_tool("multiply", {"a": 5, "b": 3})
    print(result.data)     # 15
    print(result.content)  # the raw MCP content blocks

Arguments are passed as a dictionary whose keys match the tool’s parameter names. The result has two views:

  • result.data – the value converted back into a Python object, so an integer arrives as an int rather than as text;
  • result.content – the underlying MCP content blocks, including text, images and other media.

Use data in application code and content when you need to pass the result on to a model unchanged.

Reading Resources and Fetching Prompts

async with client:
    content = await client.read_resource("config://app")
    print(content[0].text)

    prompt = await client.get_prompt("analyze_data", {"data": [1, 2, 3]})
    print(prompt.messages)

Resource reads return a list of content items. Prompt requests return the rendered messages, ready to pass to a model.

Receiving Logs and Progress

Servers can send log messages and progress updates while a tool runs. Register handlers when you create the client to receive them:

from fastmcp.client.logging import LogMessage


async def log_handler(message: LogMessage):
    print(f"Server log: {message.data}")


async def progress_handler(progress: float, total: float | None, message: str | None):
    print(f"Progress: {progress}/{total} - {message}")


client = Client(
    Path("my_mcp_server.py"),
    log_handler=log_handler,
    progress_handler=progress_handler,
    timeout=30.0,
)

Progress handlers are particularly useful in command-line tools, where a long-running operation would otherwise look frozen.

Setting Timeouts

A client-wide timeout prevents a slow or unresponsive server from hanging your program:

client = Client(server, timeout=30.0)

Choose a value that comfortably exceeds your slowest legitimate tool. Very short timeouts cause spurious failures; very long ones hide real problems.

Handling Errors

If a tool fails on the server, the client raises an exception rather than returning a silent failure. Wrap calls that may fail in try and except, log the message and decide whether to retry or report the problem.

try:
    result = await client.call_tool("divide", {"a": 1, "b": 0})
except Exception as exc:
    print(f"Tool call failed: {exc}")

Distinguish between errors worth retrying, such as network interruptions, and errors that will never succeed, such as invalid arguments. Retrying the second kind only wastes time.

Authenticating

Protected servers expect a bearer token in the Authorization header. The client can send one for you:

import os

client = Client(
    "https://mcp.example.com/mcp",
    auth=os.environ["MCP_TOKEN"],
)

Read tokens from environment variables or a secrets manager; never commit them to source control. For servers that use OAuth, the client also supports a browser-based sign-in flow, described in the official client documentation.

A Complete Example

This short script connects to a server, lists its tools and calls one of them, reporting any failure clearly:

import asyncio
import os
from fastmcp import Client

SERVER_URL = os.environ.get("MCP_URL", "http://localhost:8000/mcp")


async def main():
    async with Client(SERVER_URL, timeout=30.0) as client:
        tools = await client.list_tools()
        print("Available:", ", ".join(t.name for t in tools))
        try:
            result = await client.call_tool("greet", {"name": "Ada"})
            print("Result:", result.data)
        except Exception as exc:
            print("Call failed:", exc)


asyncio.run(main())

Practical Tips

  • Reuse one open client for a batch of calls instead of reconnecting each time.
  • Use the in-memory form, Client(mcp), in tests: no ports, no subprocesses and no flaky timing.
  • Print tool.input_schema when a call is rejected; it shows exactly what the server expects.
  • Keep server URLs and tokens in configuration, so the same script works against development and production.

Frequently Asked Questions

Yes. The client speaks the standard Model Context Protocol, so it works with any compliant MCP server, whichever language or framework that server was written in.

With several servers in one client, names could collide. FastMCP prefixes each tool with its server's name, such as weather_get_forecast, so every name stays unique.

It is asynchronous. Open it with async with inside an async function, and run that function with asyncio.run() from ordinary scripts.

Set a timeout when creating the client, for example Client(url, timeout=30.0), and handle the resulting exception so the script can report the problem and exit cleanly.

Keep reading

Related Guides