Securing FastMCP Servers with Authentication
Protect remote servers with JWT verification, token introspection or OAuth, and adopt habits that keep secrets safe.
Read articleConnect to local or remote servers from Python, call tools, read resources and handle results and errors.

Client connects to a URL, a script path, a config dictionary or a server object.result.data for Python values and result.content for raw blocks.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.
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 memoryThe 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())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.
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.
async with client:
result = await client.call_tool("multiply", {"a": 5, "b": 3})
print(result.data) # 15
print(result.content) # the raw MCP content blocksArguments 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.
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.
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.
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.
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.
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.
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())Client(mcp), in tests: no ports, no subprocesses and no flaky timing.tool.input_schema when a call is rejected; it shows exactly what the server expects.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.
Protect remote servers with JWT verification, token introspection or OAuth, and adopt habits that keep secrets safe.
Read articleRun your server over HTTP, add health checks, scale with stateless mode and put it behind systemd and nginx.
Read articleWrite quick, reliable tests with an in-memory client, pytest fixtures, parametrised cases and snapshots.
Read article