Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Build an MCP server in Python with FastMCP

Build a small MCP server in Python with FastMCP, test its tools in MCP Inspector without a model, then connect it to Claude Code, Cursor or another MCP host.

By Updated Intermediate1 h hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

An MCP server is a program that exposes tools, and optionally resources and prompts, over the Model Context Protocol, so any MCP host can use them without a custom integration. If the roles are new to you, MCP explained covers hosts, clients, servers and transports first.

In this tutorial you build an MCP server that lets any compatible agent search and read a folder of Markdown notes. You will write it with FastMCP, a Python framework that turns decorated functions into MCP tools, test it without a model in MCP Inspector, and then connect it to Claude Code. The same server works in Cursor, Codex and other MCP hosts.

The example is deliberately small so the MCP parts stand out. The workflow Build an MCP server for an internal API applies the same steps to a real service.

1. Create the project

Using uv, which manages the virtual environment for you:

uv init notes-server
cd notes-server
uv add fastmcp
mkdir notes
printf "# Deploy checklist\nRun migrations before the release. Rollback with git revert.\n" > notes/deploy.md
printf "# Onboarding\nNew starters get laptop access on day one.\n" > notes/onboarding.md

For the other uv commands you will meet (uv sync, uv lock, uvx), see the uv commands cheat sheet. If you prefer pip: create a virtual environment, activate it, and run pip install fastmcp. Everywhere this tutorial says uv run fastmcp, use fastmcp.

2. Write the server

Create server.py next to the files uv generated (you can delete the sample main.py):

# server.py
import os
from pathlib import Path

from fastmcp import FastMCP

NOTES_DIR = Path(os.environ.get("NOTES_DIR", "notes")).resolve()

mcp = FastMCP("notes")


def safe_path(name: str) -> Path:
    path = (NOTES_DIR / name).resolve()
    if path.parent != NOTES_DIR or path.suffix != ".md":
        raise ValueError(f"{name!r} is not a note in {NOTES_DIR}")
    return path


@mcp.tool(annotations={"readOnlyHint": True})
def search_notes(query: str) -> list[str]:
    """Find Markdown notes whose text contains a word or phrase (case-insensitive). Returns file names."""
    q = query.lower()
    return [p.name for p in sorted(NOTES_DIR.glob("*.md")) if q in p.read_text(encoding="utf-8").lower()]


@mcp.tool(annotations={"readOnlyHint": True})
def read_note(name: str) -> str:
    """Return the full Markdown text of one note, by file name (for example deploy.md)."""
    return safe_path(name).read_text(encoding="utf-8")


@mcp.resource("notes://index")
def index() -> str:
    """A newline-separated list of every note file."""
    return "\n".join(p.name for p in sorted(NOTES_DIR.glob("*.md")))


if __name__ == "__main__":
    mcp.run()

That is a complete MCP server. What FastMCP does with it:

  • FastMCP("notes") creates a server named notes. Hosts show this name next to its tools.
  • @mcp.tool registers a function as a tool. The function name becomes the tool name, the type hints become the input JSON Schema, and the docstring becomes the description the model reads. Return values are converted to MCP content, and typed returns such as list[str] are also sent as structured content.
  • annotations={"readOnlyHint": True} tells hosts the tool does not change anything. Some hosts use annotations to decide whether to ask for permission. They are hints, not enforcement.
  • @mcp.resource exposes data at a URI that the host can read, rather than a function for the model to call.
  • mcp.run() defaults to the stdio transport, which is what local hosts expect.

NOTES_DIR comes from an environment variable so the same server can point at any folder, and safe_path stops the model from reading files outside it. If a tool raises an exception, FastMCP returns it to the client as a tool error rather than crashing the server.

3. Test it from the command line

FastMCP’s CLI can list and call tools on a server file directly, which is the fastest check that it starts and does what you expect:

uv run fastmcp list server.py
uv run fastmcp call server.py search_notes query=rollback

The second command should print a result containing deploy.md.

You can also test in Python with FastMCP’s in-memory client, which makes a good unit test:

# test_server.py
import asyncio

from fastmcp import Client

from server import mcp


async def main() -> None:
    async with Client(mcp) as client:
        print([t.name for t in await client.list_tools()])
        result = await client.call_tool("search_notes", {"query": "rollback"})
        print(result.data)  # ['deploy.md']
        bad = await client.call_tool("read_note", {"name": "../server.py"}, raise_on_error=False)
        print(bad.is_error)  # True: the path guard worked


asyncio.run(main())
uv run python test_server.py

Passing the server object to Client runs it in the same process, with no subprocess or network. Wrap the same calls in pytest and you have regression tests that run without a model or an API key.

4. Inspect it in MCP Inspector

MCP Inspector shows what a host will see. FastMCP can launch it with your server attached:

uv run fastmcp dev inspector server.py

Or start Inspector on its own and point it at the server:

npx @modelcontextprotocol/inspector uv run fastmcp run server.py

In the browser UI, open the Tools tab, select search_notes, enter a query and run it. Check three things:

  1. The descriptions read well to someone who cannot see your code. That person is the model.
  2. The input schema has the parameter names and types you expect.
  3. Errors are readable. Call read_note with ../server.py and confirm you get a clear error, not a stack trace or, worse, the file.

5. Connect it to Claude Code

Register the server with Claude Code. Everything after -- is the command Claude Code runs to start the server, so use absolute paths:

claude mcp add notes \
  -e NOTES_DIR=/absolute/path/to/notes-server/notes \
  -- uv run --directory /absolute/path/to/notes-server fastmcp run server.py

Start claude in any directory, run /mcp to confirm the server is connected, then ask:

Using the notes server, what do I need to do before a release?

Claude Code asks your permission the first time it calls each tool. Approve it and watch it call search_notes and then read_note.

claude mcp add stores the server in your local scope by default (this project, only you). Add --scope project to write it to a .mcp.json file that you can commit for the team, or --scope user to make it available in every project.

FastMCP can also write the configuration for you: uv run fastmcp install claude-code server.py and uv run fastmcp install cursor server.py are available. For other hosts, uv run fastmcp install mcp-json server.py prints a JSON block you can paste into the host’s MCP configuration.

6. Run it over HTTP (optional)

To share the server with a team or call it from a remote agent, run it on Streamable HTTP:

uv run fastmcp run server.py --transport http --port 8000

Clients connect to http://localhost:8000/mcp. Before exposing an HTTP server beyond your machine, add authentication (FastMCP supports OAuth providers and bearer tokens) and run it behind TLS. An unauthenticated MCP server on a network is a remote file reader for anyone who finds it.

Pitfalls

Tool descriptions written for humans. “Searches notes” tells the model nothing about what comes back. Say what the tool returns and when to use it.

Too many tools. Every tool’s description is in the model’s context on every call. Five well-chosen tools beat thirty thin wrappers around API endpoints.

Returning huge payloads. Return the lines that match, or the first page, and offer paging parameters. A tool that dumps 50,000 tokens slows and confuses every later step.

Relying on annotations for safety. readOnlyHint is information for the host. Enforce read-only behaviour in your code and in the credentials you give the server.

Relative paths in host config. Hosts start servers from their own working directory. Use absolute paths in claude mcp add and in JSON configs.

Next steps

Covers

Check your understanding

Build an MCP server in Python quiz

FastMCP tools and resources, stdio rules, testing with the CLI and Inspector, and connecting the server to Claude Code.

7 questions · pass mark 70%

Question 1 of 70 answered
  1. With FastMCP's @mcp.tool decorator, where does the tool description the model reads come from?
  • MCP explained: hosts, clients, servers and transports

    What MCP is and how the Model Context Protocol connects AI apps to tools and data: hosts, clients, servers, transports and what the 2026-07-28 spec changed.

    TutorialBeginner20 min

  • Build an MCP server in TypeScript

    Build a small MCP server with the official TypeScript SDK v2, test it from the command line and in MCP Inspector, then connect it to Claude Code or Cursor.

    TutorialIntermediate1 h

  • Build an MCP server for an internal API

    Two read-only tools, tested in MCP Inspector and called from Claude Code, Codex or Cursor.

    WorkflowIntermediate2 h6 steps

  • MCP server

    A program that exposes tools, resources or prompts to MCP clients, running locally over stdio or remotely over HTTP, so any MCP host can use them.

    Glossary

  • What changed in MCP 2026-07-28: a stateless protocol

    The July 2026 MCP specification removes the handshake and sessions, adds server discovery and deprecates roots and sampling. What it means for you.

    Article

Back to top