FastMCP Tools, Resources and Prompts Explained
The three MCP building blocks compared: what each one does, how to declare it and which to choose for a given job.
Read articleWrite a single-file server with a tool, a resource and a prompt, run it locally or over HTTP and call it from Python.

FastMCP object plus decorated functions.mcp.run() uses STDIO; pass transport="http" for network access.--reload and the MCP Inspector while developing.A FastMCP server can be as small as five lines of Python. In this guide you will build one step by step, describe its inputs precisely, handle errors properly, run it in two different ways and call it from a client to prove that it works.
The finished server is a small “notes” service. It exposes three kinds of component:
Together they cover the three building blocks of the Model Context Protocol. You need FastMCP installed and Python 3.11 or later; if you have not installed it yet, follow the installation guide first.
A single file is enough to begin with. Create a folder and an empty server file:
uv init notes-server
cd notes-server
uv add fastmcp
touch my_server.pyAs the server grows, you can split tools into modules and combine them later; the composition section at the end shows how.
Open my_server.py and add:
from fastmcp import FastMCP
mcp = FastMCP("My MCP Server")The FastMCP object is your server. The name you pass is shown to clients when they connect, so choose something descriptive. Every component you define will be registered on this object.
Tools are functions that a language model can decide to call. Decorate an ordinary function with @mcp.tool:
@mcp.tool
def greet(name: str) -> str:
"""Return a friendly greeting for the given name."""
return f"Hello, {name}!"FastMCP reads the type hints and the docstring to build the JSON schema that clients see. The model learns that greet takes one string argument called name, and the docstring tells it when the tool is useful. Clear names and docstrings therefore matter: they are the instructions the model reads.
Synchronous functions like this one are run in a thread pool, so a slow function does not block the server. For network calls and other I/O, you can write async def instead.
When a parameter needs more explanation than its name, add a description with Annotated. A Field can also enforce limits, which FastMCP validates before your code runs:
from typing import Annotated
from pydantic import Field
@mcp.tool
def shout(
text: Annotated[str, "The text to repeat in capitals"],
times: Annotated[int, Field(description="How many repetitions", ge=1, le=5)] = 1,
) -> str:
"""Repeat text in capital letters."""
return " ".join([text.upper()] * times)Google-style Args: sections in the docstring also work. If both are present, the explicit Annotated description takes precedence.
When a tool receives input it cannot work with, raise ToolError with a message that tells the model how to correct the call:
from datetime import date
from fastmcp.exceptions import ToolError
@mcp.tool
def count_days(start_date: date, end_date: date) -> int:
"""Count the days between two dates."""
if start_date >= end_date:
raise ToolError("start_date must be before end_date. Please correct the date range.")
return (end_date - start_date).daysMessages from ToolError are always passed to the client. If you create the server with FastMCP("My MCP Server", mask_error_details=True), details of other, unexpected exceptions are hidden, which avoids leaking internal information.
Resources provide read-only data at a URI. Prompts are reusable message templates.
@mcp.resource("config://app")
def app_config() -> dict:
"""Current application settings."""
return {"theme": "dark", "version": "1.0"}
@mcp.prompt
def review_code(code: str) -> str:
"""Ask for a careful review of a code snippet."""
return f"Please review this code and point out any bugs:\n\n{code}"The application decides when to read a resource, while prompts are usually offered to the user as commands. The guide on tools, resources and prompts explores the difference in depth.
Add an entry point at the bottom of the file:
if __name__ == "__main__":
mcp.run()Called without arguments, mcp.run() uses the STDIO transport. That is the right choice when a desktop AI application launches your server as a local process. To make the server reachable over the network instead, switch to HTTP:
if __name__ == "__main__":
mcp.run(transport="http", port=8000)python my_server.pyThe server now listens at http://localhost:8000/mcp.
The CLI imports your server object directly and ignores the __main__ block. If your object is named mcp, server or app, you do not even need to name it:
fastmcp run my_server.py
fastmcp run my_server.py:mcp --transport http --port 8000During development, --reload restarts the server whenever you save a file, so you never test stale code:
fastmcp run my_server.py --reload --transport http --port 8000The MCP Inspector is a browser tool for listing and calling components by hand. FastMCP can launch it for you, with auto-reload switched on:
fastmcp dev inspector my_server.pyIt is a convenient way to check that schemas and descriptions read as you intended before any model sees them.
With the HTTP server running, create client.py in another terminal:
import asyncio
from fastmcp import Client
client = Client("http://localhost:8000/mcp")
async def main():
async with client:
tools = await client.list_tools()
print([t.name for t in tools])
result = await client.call_tool("greet", {"name": "Ada"})
print(result.data)
asyncio.run(main())Running it prints the list of tool names, then Hello, Ada!. The async with block opens the connection and keeps it open for as many calls as you need.
from datetime import date
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
mcp = FastMCP("My MCP Server")
@mcp.tool
def greet(name: str) -> str:
"""Return a friendly greeting for the given name."""
return f"Hello, {name}!"
@mcp.tool
def count_days(start_date: date, end_date: date) -> int:
"""Count the days between two dates."""
if start_date >= end_date:
raise ToolError("start_date must be before end_date.")
return (end_date - start_date).days
@mcp.resource("config://app")
def app_config() -> dict:
"""Current application settings."""
return {"theme": "dark", "version": "1.0"}
@mcp.prompt
def review_code(code: str) -> str:
"""Ask for a careful review of a code snippet."""
return f"Please review this code and point out any bugs:\n\n{code}"
if __name__ == "__main__":
mcp.run()Larger projects can be split into several servers and combined with mount(). A namespace keeps names apart, so two modules can each define a tool called get_data:
weather = FastMCP("Weather")
calendar = FastMCP("Calendar")
main = FastMCP("Main")
main.mount(weather, namespace="weather") # tools become weather_*
main.mount(calendar, namespace="calendar") # tools become calendar_*Mounting creates a live link: components added to a child server later still appear through the parent.
There is no fixed limit, but smaller, focused servers are easier for models to use. If a server grows large, split it into modules and combine them with mount() and namespaces.
Either works. Synchronous tools run in a thread pool, so they do not block the server. Choose async def when the tool spends most of its time waiting on network calls or other I/O.
Usually the name or docstring does not make its purpose clear. Describe what the tool does, when to use it and what it returns, and give parameters precise descriptions.
No, but the CLI looks for an object called mcp, server or app automatically. With any other name, pass it explicitly, for example fastmcp run my_server.py:my_object.
The three MCP building blocks compared: what each one does, how to declare it and which to choose for a given job.
Read articleHow the STDIO and HTTP transports differ, when to use each and how to switch between them with a single argument.
Read articleConnect to local or remote servers from Python, call tools, read resources and handle results and errors.
Read article