FastMCP is the quickest way I know to put Python functions in front of an LLM through the Model Context Protocol. You decorate a function and it becomes a tool. That simplicity also hides a few sharp edges: tools the model calls wrongly, servers that hang, errors that never reach the user. This post starts with a small server that works and then goes through the pitfalls I see most often, each with broken and fixed code.
TL;DR
- Type hints and docstrings are your tool schema. Use
Annotated[..., Field(description=...)]andLiteralso the model knows exactly what to send. - Return dicts or Pydantic models, not ORM objects or arbitrary class instances.
- Never block the event loop inside an
async deftool. Use async clients orasyncio.to_thread. - Don't
print()in stdio mode. Log throughContextor to stderr, and raiseToolErrorfor messages the client should see. - Test in-process with
fastmcp.Client, and use absolute paths when installing into Claude Desktop or Claude Code.
A minimal server that works
Install FastMCP into your project (uv add fastmcp or pip install fastmcp) and create server.py:
from datetime import datetime, timezone
from uuid import uuid4
from fastmcp import FastMCP
mcp = FastMCP("Notes")
NOTES: dict[str, dict] = {}
@mcp.tool
def add_note(title: str, body: str) -> dict:
"""Save a note and return its id."""
note_id = uuid4().hex[:8]
NOTES[note_id] = {
"id": note_id,
"title": title,
"body": body,
"created_at": datetime.now(timezone.utc).isoformat(),
}
return {"id": note_id}
@mcp.tool
def list_notes() -> list[dict]:
"""List all saved notes, newest first."""
return sorted(NOTES.values(), key=lambda n: n["created_at"], reverse=True)
if __name__ == "__main__":
mcp.run()mcp.run() defaults to the stdio transport, which is what desktop clients expect. The notes live in memory, which keeps the examples short. Swap in a real database when you need persistence.
Note: Recent FastMCP versions accept both
@mcp.tooland@mcp.tool(). Very old releases required the parentheses. If the bare decorator fails, upgrade or add().
Pitfall 1: Weak schemas lead to wrong tool calls
The model never sees your code. It sees the tool name, the description (from the docstring) and a JSON Schema generated from your type hints. If those are vague, the model guesses.
Broken:
@mcp.tool
def search_notes(q, limit=10, sort="new"):
return [n for n in NOTES.values() if q in n["title"]][:limit]With no type hints, every parameter becomes "any". There's no description, and sort gives no hint that only two values are valid. The model may send limit="ten" or sort="latest".
Fixed:
from typing import Annotated, Literal
from pydantic import Field
@mcp.tool
def search_notes(
query: Annotated[str, Field(description="Case-insensitive text to find in note titles and bodies.")],
limit: Annotated[int, Field(ge=1, le=50, description="Maximum number of notes to return.")] = 10,
sort: Annotated[Literal["newest", "oldest"], Field(description="Sort order by creation time.")] = "newest",
) -> list[dict]:
"""Search saved notes by text. Use this before add_note to avoid creating duplicates."""
q = query.lower()
matches = [n for n in NOTES.values() if q in n["title"].lower() or q in n["body"].lower()]
matches.sort(key=lambda n: n["created_at"], reverse=(sort == "newest"))
return matches[:limit]Now the schema includes types, bounds, an enum for sort and a description for each field. FastMCP also validates incoming arguments against it, so a bad call fails with a clear validation error instead of crashing inside your function.
Tip: Write docstrings for the model, not for other developers. Say when to use the tool and how it relates to other tools. One sentence of guidance often does more than a long parameter list.
Pitfall 2: Returning objects that can't be serialized
Tool results have to become JSON. FastMCP uses Pydantic for serialization, so dicts, lists, primitives, Pydantic models and dataclasses all work, and so do common types like datetime and UUID. Arbitrary class instances, ORM rows, open file handles and database cursors don't.
Broken:
class NoteRecord:
def __init__(self, id: str, title: str, body: str):
self.id = id
self.title = title
self.body = body
@mcp.tool
def get_note(note_id: str):
"""Fetch a single note by id."""
n = NOTES[note_id]
return NoteRecord(n["id"], n["title"], n["body"])Depending on your FastMCP version, this either raises a serialization error or quietly sends the model something like <__main__.NoteRecord object at 0x10f3a2b90>. The second outcome is worse, because nothing fails and the model just gets useless output.
Fixed: return a Pydantic model (or a plain dict). You also get a typed output schema for free:
from datetime import datetime
from pydantic import BaseModel
class Note(BaseModel):
id: str
title: str
body: str
created_at: datetime
@mcp.tool
def get_note(note_id: str) -> Note:
"""Fetch a single note by id."""
return Note(**NOTES[note_id])If you're using SQLAlchemy or another ORM, convert at the boundary. With Pydantic v2, Note.model_validate(row, from_attributes=True) builds the model from an ORM object's attributes.
Pitfall 3: Blocking I/O inside async tools
FastMCP runs on an asyncio event loop. If an async def tool makes a blocking call (requests.get, time.sleep, a synchronous database driver), the whole server stops responding until it returns. That includes other tool calls and protocol messages.
Broken:
import requests
@mcp.tool
async def fetch_page_title(url: str) -> str:
"""Fetch a web page and return its <title>."""
html = requests.get(url, timeout=10).text # blocks the event loop
start = html.find("<title>") + len("<title>")
return html[start:html.find("</title>")].strip()Fixed, option A: use an async client.
import httpx
@mcp.tool
async def fetch_page_title(url: str) -> str:
"""Fetch a web page and return its <title>."""
async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client:
html = (await client.get(url)).text
start = html.find("<title>") + len("<title>")
return html[start:html.find("</title>")].strip()Fixed, option B: keep the sync library and move the blocking call to a worker thread.
import asyncio
import requests
def _download(url: str) -> str:
return requests.get(url, timeout=10).text
@mcp.tool
async def fetch_page_title(url: str) -> str:
"""Fetch a web page and return its <title>."""
html = await asyncio.to_thread(_download, url)
start = html.find("<title>") + len("<title>")
return html[start:html.find("</title>")].strip()You can also write the tool as a plain def. Whether FastMCP runs sync tools in a thread pool or on the event loop has varied between versions, so check the docs for yours. asyncio.to_thread is explicit and behaves the same everywhere.
Pitfall 4: Printing to stdout in stdio mode
With the stdio transport, stdout carries the JSON-RPC messages between client and server. A print() inside a tool adds a line the client can't parse, which can cause dropped connections or a server that shows as failed.
Broken:
@mcp.tool
def delete_note(note_id: str) -> dict:
"""Delete a note by id."""
print(f"Deleting {note_id}") # corrupts the stdio stream
NOTES.pop(note_id, None)
return {"deleted": note_id}Fixed: use the Context object. Add a parameter annotated as Context and FastMCP injects it. It isn't part of the tool's input schema. Its logging methods send MCP log notifications that the client can display:
import logging
import sys
from fastmcp import Context
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
log = logging.getLogger("notes")
@mcp.tool
async def delete_note(note_id: str, ctx: Context) -> dict:
"""Delete a note by id."""
await ctx.info(f"Deleting note {note_id}")
log.info("delete_note called with %s", note_id) # stderr, safe
NOTES.pop(note_id, None)
return {"deleted": note_id}Context also provides debug, warning and error, plus progress reporting. For quick debugging, print(..., file=sys.stderr) is fine too.
Pitfall 5: Errors the client never sees
If a tool raises an ordinary exception, FastMCP turns it into an error result, but what the client sees depends on configuration and may be a generic message. When you want the model to read the message and recover (for example, by retrying with a valid id), raise ToolError.
Broken:
@mcp.tool
def rename_note(note_id: str, title: str) -> dict:
"""Rename a note."""
note = NOTES[note_id] # KeyError: 'abc123'
note["title"] = title
return noteFixed:
from fastmcp.exceptions import ToolError
@mcp.tool
def rename_note(note_id: str, title: str) -> dict:
"""Rename a note."""
if note_id not in NOTES:
raise ToolError(f"No note with id '{note_id}'. Call list_notes to see valid ids.")
NOTES[note_id]["title"] = title
return NOTES[note_id]ToolError messages are always sent to the client. That makes them the right place for actionable guidance and the wrong place for stack traces or secrets. FastMCP can also hide the details of unexpected exceptions (look for the mask_error_details option in the docs), which is a sensible default for anything public.
Pitfall 6: Using tools for everything
Tools are actions the model decides to call. MCP also has two other primitives that are often a better fit:
- Resources are read-only data the client can load into context, addressed by URI. Resource templates take parameters from the URI.
- Prompts are reusable message templates that users pick from the client UI.
from fastmcp.exceptions import ResourceError
@mcp.resource("notes://{note_id}")
def note_resource(note_id: str) -> dict:
"""A single note, addressable by id."""
if note_id not in NOTES:
raise ResourceError(f"No note with id '{note_id}'.")
return NOTES[note_id]
@mcp.prompt
def summarize_notes(topic: str) -> str:
"""Ask the model to summarize notes about a topic."""
return (
f"Use the search_notes tool to find notes about '{topic}', "
"then write a short summary with the key points and any open questions."
)A good rule of thumb: if it changes something or needs the model's judgment about when to run it, make it a tool. If it's data that a user or client wants to attach as context, make it a resource. Client support for resources and prompts varies, so check what your target client exposes.
Testing in-process with the FastMCP client
You don't need a desktop client to test your server. fastmcp.Client can connect directly to a FastMCP instance in memory, without a subprocess or network, which makes tests fast and deterministic.
# test_server.py
import pytest
from fastmcp import Client
from fastmcp.exceptions import ToolError
from server import NOTES, mcp
@pytest.fixture(autouse=True)
def clear_notes():
NOTES.clear()
@pytest.mark.asyncio
async def test_tools_are_registered():
async with Client(mcp) as client:
tools = await client.list_tools()
names = {t.name for t in tools}
assert {"add_note", "list_notes"} <= names
@pytest.mark.asyncio
async def test_add_note_returns_id():
async with Client(mcp) as client:
result = await client.call_tool("add_note", {"title": "Groceries", "body": "Milk, eggs"})
note_id = result.data["id"]
assert note_id in NOTES
assert NOTES[note_id]["title"] == "Groceries"
@pytest.mark.asyncio
async def test_rename_missing_note_raises():
async with Client(mcp) as client:
with pytest.raises(ToolError):
await client.call_tool("rename_note", {"note_id": "nope", "title": "x"})Run it with pip install pytest pytest-asyncio and then pytest. The rename_note test assumes you've added that tool from Pitfall 5 to server.py.
Note: In recent FastMCP versions,
call_toolreturns a result object with a.dataattribute holding the deserialized output, and raisesToolErrorwhen the tool fails. Older versions returned a list of content blocks instead. If.datadoesn't exist in your version, check the client docs.
stdio vs HTTP
Use stdio when the client runs on the same machine and launches the server itself: Claude Desktop, Claude Code, Cursor. Use HTTP when the server runs somewhere else and several clients connect to it over the network.
if __name__ == "__main__":
mcp.run(transport="http", host="0.0.0.0", port=8000)The MCP endpoint is served at /mcp by default, so clients connect to http://localhost:8000/mcp. The in-process client works over HTTP too: Client("http://localhost:8000/mcp"). In Claude Code you can register it with:
claude mcp add --transport http notes http://localhost:8000/mcpWarning: Binding to
0.0.0.0exposes the server on every network interface. Put authentication in front of anything that isn't strictly local.
Older FastMCP releases named this transport "streamable-http", and some examples still use the legacy "sse" transport. If "http" is rejected, check which names your installed version supports.
Running and installing the server
The fastmcp CLI covers the common workflows:
# Run the server over stdio (what a client would do)
fastmcp run server.py
# Open the MCP Inspector against your server for manual testing
fastmcp dev server.pyfastmcp dev launches the MCP Inspector web UI, which needs Node.js available for npx. Recent versions also include fastmcp install, which writes the client config for you, with targets for clients such as Claude Desktop and Claude Code. Its subcommands and options have changed over time, so run fastmcp install --help to see what your version supports.
If you'd rather configure things by hand, this works in Claude Desktop's claude_desktop_config.json and similar mcpServers configs. uv provides FastMCP in an isolated environment, and the absolute path avoids working-directory problems:
{
"mcpServers": {
"notes": {
"command": "uv",
"args": ["run", "--with", "fastmcp", "fastmcp", "run", "/Users/you/projects/notes-mcp/server.py"]
}
}
}If your server needs other packages, add more --with flags (for example "--with", "httpx"), or use uv run --directory /abs/path/to/project so it picks up your project's own dependencies. If the client can't find uv itself, which happens often with GUI apps on macOS, replace "uv" with its absolute path from which uv.
The Claude Code equivalent is:
claude mcp add notes -- uv run --with fastmcp fastmcp run /Users/you/projects/notes-mcp/server.pyWrapping up
Most FastMCP problems come down to remembering what the model and the client can actually see:
- Schema: type hints,
Fielddescriptions,Literalenums and docstrings written for the model. - Output: dicts and Pydantic models, never ORM objects or arbitrary classes.
- Concurrency: no blocking calls in
async deftools. - Transport: nothing on stdout in stdio mode. Use
Contextlogging or stderr. - Errors:
ToolErrorfor anything the model should read and act on. - Shape: tools for actions, resources for data, prompts for reusable templates.
- Verification: in-process tests with
Client(mcp), then the Inspector, then the real client with absolute paths.
FastMCP is moving quickly, so when a snippet here doesn't match your installed version, check the changelog and docs first. The underlying ideas stay the same across versions.