FastMCP Tutorial: Build an MCP Server in Python, Step by Step

Andreas Nigg
Andreas Nigg · Co-Founder, Pondhouse Data
Published Updated 12 min read
FastMCP Tutorial: Build an MCP Server in Python, Step by Step
On this page

An MCP server exposes your data and tools to LLM applications through the Model Context Protocol (MCP), a standard for connecting LLMs to external resources. FastMCP is a Python framework that turns ordinary functions into MCP resources and tools with a few decorators, so any MCP-compatible client (like Claude Desktop) can use them right away.

This guide explains what an MCP server is and how it differs from a regular API. Then we build one with FastMCP: a resource, a resource template, a tool with parameter metadata, progress reporting and a small test client.

Think of MCP as a USB-C port for AI applications: one connector that lets your language models plug into different data sources and tools with minimal friction.

Update (November 2026): This guide was written for FastMCP 2.x. pip install fastmcp now installs FastMCP 4, which has breaking changes, so pin fastmcp<3 to run the code as written or follow the upgrade guides. The HTTP+SSE transport used below was deprecated in the MCP specification of 2025-03-26 in favour of Streamable HTTP. FastMCP now lists SSE as legacy and recommends mcp.run(transport="http"), which serves the server at /mcp (see Running your server).

What is an MCP server?

An MCP server is a lightweight program that exposes your data and functionality to language models through the standardized Model Context Protocol. It sits between AI applications (like Claude Desktop or other LLM-powered tools) and your local data sources or remote services.

The main thing to understand: MCP Servers are basically just a standardized API for accessing your internal tools or data.

MCP has six main building blocks:

  1. Resources: Read-only endpoints that provide data to LLMs (similar to GET requests in web APIs)
  2. Tools: Functional endpoints that execute actions when called by an LLM (like POST/PUT endpoints)
  3. Prompts: Reusable templates that guide how LLMs interact with your server
  4. Sampling: The ability to request completions from the connected LLM. If the server needs an LLM to complete its own action (for example, creating a summary), it can ask the client to run the LLM completion. The client then pays for the completion and controls which LLM is used, which matters for data privacy. We cover this in detail in LLM sampling with FastMCP.
  5. Transports: Communication mechanisms that enable clients and servers to exchange messages, such as stdio (Standard Input/Output) for local tools and SSE (Server-Sent Events) for web-based applications
  6. Roots: URI-based boundaries that define where servers can operate, allowing clients to inform servers about relevant resource locations (like file paths or API endpoints)

MCP servers operate within a client-server architecture where:

  • Your MCP server runs locally or on your infrastructure
  • MCP clients (like Claude Desktop) connect to your server
  • Your server provides secure access to your files, databases, APIs, or custom functionality

Unlike traditional web APIs, MCP servers are designed for LLM interactions, with context management and other LLM-specific features built in.

With an MCP server, AI assistants can work with your data and services while your information stays secure and under your control. You don't need to upload sensitive documents to third-party services or rebuild integrations for each new AI tool.

Added benefit: Since everyone and their mum currently wants MCP server tools, offering an MCP interface gives your software a marketing advantage.

LLM app with an MCP client connecting to an MCP server

MCP server example: the GitHub MCP server

If that sounds abstract, here's a simple example. GitHub offers an MCP server, which provides tools to interact with GitHub: for example, tools to get repository information or to create pull requests.

Many AI chat tools already ship an MCP client, so all of them can now connect to GitHub and build AI-powered workflows. Both sides win. These tools don't need to integrate the GitHub API (or, for that matter, many other APIs); they only implement the MCP client. Because MCP lets LLMs read the list of available tools, the LLMs automatically know about every tool ("API endpoint", if you will).

What's the difference between an MCP server and an API?

MCP servers, at their core, are standardized APIs. So why not use the millions of existing APIs? Because MCP servers make it easy for LLMs to discover which tools and resources an API offers. They also standardize authentication and transport. If enough companies agree on MCP as the way forward (and many already do, like Microsoft, Anthropic, Google and OpenAI), we get one single interface optimized for LLM discoverability. Client-side tools only need to implement the MCP client; the protocol and the LLMs using the client handle the rest. Note that MCP only really makes sense when an LLM "reads" the provided resources and tools and then acts on them.

If you simply need to call APIs, ordinary REST endpoints are still the way to go.

MCP servers have one more advantage. Because AI client tools have widely adopted the protocol, you can also run a local MCP server to give controlled, secure access to resources on your system. For example, you can allow file-system access, but only on a certain file mount.

What is FastMCP?

FastMCP is a high-level Python framework for building MCP servers. The raw MCP protocol requires you to implement server setup, protocol handlers, content types and error management. FastMCP handles all of these details for you.

At its heart, FastMCP provides a decorator-based API that turns regular Python functions into MCP-compatible tools, resources and prompts. Its main advantages:

  1. Minimal boilerplate: a working MCP server takes only a few lines of code.
  2. The decorator pattern will feel familiar if you've used Flask or FastAPI.
  3. Automatic schema generation: FastMCP uses type hints and docstrings to generate the MCP schemas, without manual configuration.
  4. Pydantic integration: use Pydantic models for complex inputs and outputs, with automatic validation.
  5. Built-in support for both synchronous and asynchronous function handlers.
  6. Transport abstraction: switch between communication protocols (stdio, Streamable HTTP and the legacy SSE transport) without changing your application code.
  7. A context object to access server capabilities, log information, report progress and even request LLM sampling.
  8. A full client implementation for testing your servers programmatically.

FastMCP aims to make MCP development accessible to Python developers of all skill levels while still exposing the full protocol. You focus on your business logic instead of the details of the MCP specification.

With FastMCP, you can go from concept to working MCP server in minutes rather than hours. That makes it our pick for prototyping AI-powered tools as well as for building production MCP services.

Great detail: FastMCP 1.0 was so successful that it got integrated directly into the official MCP Python SDK. The standalone fastmcp package we use here is the separately maintained successor.

Hands-on: building an MCP server using FastMCP

Let's build a simple MCP server that can:

  • Fetch a user's profile (Resource)
  • Update a document on the server (Tool)
  • Add progress reporting (Context)

Prerequisites: basic MCP server setup

First, create a virtual environment and install fastmcp (it includes the mcp dependencies).

1uv venv
2source .venv/bin/activate
3uv pip install fastmcp

Then, create the basic server instance:

1from fastmcp import FastMCP
2
3mcp = FastMCP(
4 name="Document Assistant",
5 instructions="This server allows to fetch and update documents related to PONDHOUSE DATA DOCS."
6)
7
8if __name__ == "__main__":
9 mcp.run()

This snippet runs an MCP server (without any resources yet) in STDIO transport mode. That means:

  • The client starts a new server process for each session
  • Communication happens through standard input/output streams
  • The server process terminates when the client disconnects
  • This is ideal for integrations with local tools like Claude Desktop, where each conversation gets its own server instance

FastMCP transports explained

The server above uses the STDIO transport, so it mainly gives access to resources on your local system. There are many use cases for that, but we think the main advantage of MCP servers is remote access: controlled, secure access to your internal systems. For this, FastMCP offers a second transport: SSE Transport (Server Sent Events).

To use this transport, run:

1mcp.run(transport="sse", host="0.0.0.0", port=8000)

This starts a server listening on all interfaces on port 8000.

Interesting to know: FastMCP in SSE transport mode uses Starlette for providing the ASGI interface and uvicorn to wrap it in a server.

We'll use this transport from here on.

Creating an MCP resource using FastMCP

MCP resources offer read-only access to internal data. A client requests a resource by its URI (which is often AI-generated on the client side). FastMCP uses the URI to find the requested resource, fetches the data from its environment and returns it to the client.

Defining a Resource is simple:

  1. Create a Python function that returns the data you want your resource to return.

  2. Add a fastmcp resource decorator with the unique URI of this resource as parameter.

  3. Optionally add metadata, like a description or tags.

    Note: Clients can use this metadata for filtering or to decide which resource to call. As with any LLM-based application, the metadata is important so the (client) AI knows what to do. We recommend always filling in all of it.

    These metadata fields are available:

    • uri: The unique identifier for the resource (required).
    • name: A human-readable name (defaults to function name).
    • description: Explanation of the resource (defaults to docstring).
    • mime_type: Specifies the content type (FastMCP often infers a default like text/plain or application/json, but explicit is better for non-text types).
    • tags: A set of strings for categorization, potentially used by clients for filtering.

Important: Make your functions async when they do disk or remote operations, so they don't block the server.

1from fastmcp import FastMCP
2
3mcp = FastMCP(
4 name="Document Assistant",
5 instructions="This server allows to fetch and update documents related to PONDHOUSE DATA DOCS."
6)
7
8@mcp.resource(
9 uri="data://application-information",
10 name="ApplicationInfo",
11 description="Provides general runtime-information about the application",
12 mime_type="application/json",
13 tags={"status", "observability"}
14)
15async def get_application_status() -> dict:
16 """Function description - ignored if set via decorator description parameter"""
17
18 # TODO: Implement any logic here. Eg. database call or request status
19 # information from your monitoring system.
20
21 return {
22 "app_id": 123,
23 "status": "running",
24 "started_at": "2025-04-27 10:23:00"
25 }

Important: MCP uses the docstrings of your functions to generate a description for the LLM, so write good, descriptive ones. If you set the description in the decorator, the docstring isn't needed (and is actually ignored).

So far, a client that requests the URI data://application-information gets the application status report. Next, we want to return a user profile. The problem: we can't pass a user ID to the MCP server yet, because the URI is the only thing we exchange.

This is where resource templates come into play.

MCP resource templates

Resource templates tell the MCP server that parts of the URI path in the resource definition are dynamic. For example, we can define the URI data://user-profile/{user_id} for our user profile resource. The resource function then takes an additional parameter for the dynamic value.

1@mcp.resource(
2 uri="data://user-profile/{user_id}",
3 name="UserProfile",
4 description="Gets the user profile information for user_id",
5 mime_type="application/json",
6 tags={"user"}
7)
8async def get_user_profile(user_id: str) -> dict:
9 """Gets the user profile information for user_id"""
10
11 # TODO: Implement any logic here. Eg. database call or request profile
12 # information from your user auth system.
13
14 return {
15 "user_id": 1234,
16 "user_name": "Hans Maier",
17 "email": "hans@maier.com"
18 }

Now clients request the resource with a dynamic user_id parameter.

Creating an MCP tool using FastMCP

Tools are the most important part of any AI agent system. Tools are functions that let the AI interact with the outside world. Say you have a function that makes a database call. Turn this function into a tool, and the AI can call it and therefore access your database. Our post on running an MCP server for BigQuery shows that pattern with a real data warehouse.

Note: When we talk about AI "calling" a function, technically, they don't call anything (as an AI model itself can't run code etc.). The AI model simply returns (via text), that it wants to call a specific tool (which are just python functions), and you execute this function on behalf of the AI.

For an in-depth introduction to tools, we recommend our AI Agents from scratch article.

As with resources, FastMCP takes care of the underlying protocol and of who calls what. Write a function that does something, add a decorator and optionally some metadata.

FastMCP:

  • Uses the function's name as tool name. Make it descriptive.
  • Uses the docstring (or the decorator description param) as tool description.
  • Uses type-annotations for schema generation.
  • Validates the incoming data based on this type schema.

Again, make your tools async if they wait on I/O.

1@mcp.tool()
2async def edit_file(filename: str, line: str) -> None:
3 """
4 Asynchronously appends a line of text to the end of a file.
5 """
6 try:
7 async with aiofiles.open(filename, mode='a') as file:
8 if not line.endswith('\n'):
9 line += '\n'
10 await file.write(line)
11 except Exception as e:
12 print(f"Error appending to file: {str(e)}")
13 raise

Adding parameter metadata

Anyone who has built AI agents (or clients) knows that the tool description matters most, and the parameter descriptions even more. They tell the AI which parameters to provide.

FastMCP lets you add this information to parameters with pydantic's Field inside Annotated.

Parameters with default values are communicated as optional.

1@mcp.tool()
2async def edit_file(
3 filename: Annotated[ str, Field( description="Path to the target file", min_length=1, max_length=255) ],
4 line: Annotated[ str, Field( description="Text content to append to the file", min_length=1) ],
5 second_line: Annotated[ str, Field( description="Optional second line to append to the file", min_length=1), ] = ""
6 ):
7 """
8 Asynchronously appends a line of text to the end of a file.
9 """
10 try:
11 async with aiofiles.open(filename, mode='a') as file:
12 if not line.endswith('\n'):
13 line += '\n'
14 await file.write(line)
15
16 if second_line:
17 if not second_line.endswith('\n'):
18 second_line += '\n'
19 await file.write(second_line)
20 except Exception as e:
21 print(f"Error appending to file: {str(e)}")
22 raise

Error handling with FastMCP tools

The final piece: how do we tell the AI about errors? Usually you want the AI to know that a tool failed, so it can run the tool differently or use another one.

In FastMCP this is easy: raise a standard Python exception, as we did above.

FastMCP converts the exception into an MCP error response and sends it back to the client. The client decides what to do with the error, but usually it passes it on to the LLM to act on.

Supported types with FastMCP tools

For tool input parameters, FastMCP supports most types that Pydantic supports. This includes all built-in types, dates, literals, enums, collections (dicts, lists), UUIDs, complex Pydantic models and many more. For a complete list, see the FastMCP docu

Output types are more limited. These are the supported return types:

  • str: Sent as TextContent.
  • dict, list, Pydantic BaseModel: Serialized to a JSON string and sent as TextContent.
  • bytes: Base64 encoded and sent as BlobResourceContents (often within an EmbeddedResource).
  • fastmcp.Image: A helper class for easily returning image data. Sent as ImageContent.
  • None: Results in an empty response (no content is sent back to the client).

Implement MCP server progress reporting using FastMCP Context

The FastMCP Context gives you access to the underlying MCP session and to your MCP server's capabilities. For example:

  • Logging: Send log messages from your MCP server back to the client.
  • Accessing resources: Your MCP server tools might need resources you already defined, e.g. to get a file path from a resource.
  • Progress reporting: Send progress updates to the client for long-running operations.

More advanced context options are out of scope for this article. You can read up on them here, and our follow-up on LLM sampling with FastMCP covers one of them.

For our small project, we implement progress reporting to show how the Context works.

It takes two steps:

  1. In the function (resource or tool) where you want to access the context, add a parameter ctx of type Context. The name doesn't matter, but the type hint Context is required.

  2. Call ctx.report_progress(progress, total) to send progress back to the client.

Note: Context methods are mostly async, so make sure to await them.

1from typing import Annotated
2
3import aiofiles
4from fastmcp import FastMCP, Context
5from pydantic import Field
6
7mcp = FastMCP(
8 name="Document Assistant",
9 instructions="This server allows to fetch and update documents related to PONDHOUSE DATA DOCS."
10)
11
12@mcp.tool()
13async def edit_file(
14 filename: Annotated[ str, Field( description="Path to the target file", min_length=1, max_length=255) ],
15 ctx: Context,
16 line: Annotated[ str, Field( description="Text content to append to the file", min_length=1) ],
17 second_line: Annotated[ str, Field( description="Optional second line to append to the file", min_length=1), ] = ""
18 ):
19 """
20 Asynchronously appends a line of text to the end of a file.
21 """
22 await ctx.info(f"Appending to {filename}")
23 try:
24 async with aiofiles.open(filename, mode='a') as file:
25 if not line.endswith('\n'):
26 line += '\n'
27 await file.write(line)
28 if second_line:
29 await ctx.report_progress(progress=50, total=100)
30 if not second_line.endswith('\n'):
31 second_line += '\n'
32 await file.write(second_line)
33
34 await ctx.report_progress(progress=100, total=100)
35 except Exception as e:
36 print(f"Error appending to file: {str(e)}")
37 raise

That's it.

Testing your MCP server

To test the MCP server, run it first. FastMCP already includes uvicorn, so just run your Python file. If you followed this guide, the server uses the SSE transport and listens on port 8000.

Then use a tool like Claude Desktop or write a simple MCP client to test the capabilities.

1from fastmcp.client import Client
2import asyncio
3
4# Note the `sse` path post-fix for sse servers
5# For all transports, see https://gofastmcp.com/clients/client#transports
6sse_url = "http://localhost:8000/sse"
7
8client = Client(sse_url)
9
10
11async def main():
12 # Connection is established here
13 async with client:
14 print(f"Client connected: {client.is_connected()}")
15
16 tools = await client.list_tools()
17 print(f"Available tools: {tools}")
18
19 if any(tool.name == "edit_file" for tool in tools):
20 result = await client.call_tool(
21 "edit_file",
22 {
23 "filename": "hello-world.txt",
24 "line": "This text will be added to the file.",
25 },
26 )
27 print(f"Greet result: {result}")
28
29 # Connection is closed automatically here
30 print(f"Client connected: {client.is_connected()}")
31
32
33if __name__ == "__main__":
34 asyncio.run(main())

For a full reference of the FastMCP client's methods, see their documentation

Wrapping up

We built an MCP server with FastMCP that offers a resource, a resource template and a tool with progress reporting, served over SSE on port 8000. Any client that implements MCP can now connect to it and use these capabilities. If you already have a REST API, you don't have to write every tool by hand: we show how to generate an MCP server from OpenAPI and FastAPI.

Further reading

Interested in building high-quality AI agent systems?

We prepared a comprehensive guide based on cutting-edge research for how to build robust, reliable AI agent systems that actually work in production. This guide covers:

  • Understanding the 14 systematic failure modes in multi-agent systems
  • Evidence-based best practices for agent design
  • Structured communication protocols and verification mechanisms
Andreas Nigg

About the author

Andreas Nigg

Co-Founder, Pondhouse Data

Andreas has spent more than eight years building data applications. At Pondhouse Data he designs and ships AI systems and integrates them into complex, real-world environments.