Build Your First FastMCP Server in Python

Write a single-file server with a tool, a resource and a prompt, run it locally or over HTTP and call it from Python.

Code editor showing a FastMCP server file with a greet tool and a terminal below

Key takeaways

  • A server is a FastMCP object plus decorated functions.
  • Type hints and docstrings become the schema the model reads.
  • mcp.run() uses STDIO; pass transport="http" for network access.
  • Use --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.

What You Will Build

The finished server is a small “notes” service. It exposes three kinds of component:

  • a tool that greets a user and another that counts the days between two dates;
  • a resource that returns the server’s configuration;
  • a prompt that prepares a code-review request.

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.

Set Up the Project

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.py

As the server grows, you can split tools into modules and combine them later; the composition section at the end shows how.

Create the Server Object

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.

Add Your First Tool

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.

Describe Parameters Precisely

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.

Handle Errors Clearly

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).days

Messages 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.

Add a Resource and a Prompt

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.

Run the Server

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.py

The server now listens at http://localhost:8000/mcp.

Using the FastMCP CLI

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 8000

Reload on every change

During 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 8000

Inspect the Server Visually

The 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.py

It is a convenient way to check that schemas and descriptions read as you intended before any model sees them.

Call the Server from a Client

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.

The Complete Server

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()

Growing Beyond One File

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.

Next Steps

  • Read the explainer on tools, resources and prompts to choose the right component for each job.
  • Compare the STDIO and HTTP transports before you decide how to ship.
  • Add tests early: an in-memory client makes them fast and reliable.

Frequently Asked Questions

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.

Keep reading

Related Guides