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:
- Resources: Read-only endpoints that provide data to LLMs (similar to GET requests in web APIs)
- Tools: Functional endpoints that execute actions when called by an LLM (like POST/PUT endpoints)
- Prompts: Reusable templates that guide how LLMs interact with your server
- 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.
- 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
- 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:
- Minimal boilerplate: a working MCP server takes only a few lines of code.
- The decorator pattern will feel familiar if you've used Flask or FastAPI.
- Automatic schema generation: FastMCP uses type hints and docstrings to generate the MCP schemas, without manual configuration.
- Pydantic integration: use Pydantic models for complex inputs and outputs, with automatic validation.
- Built-in support for both synchronous and asynchronous function handlers.
- Transport abstraction: switch between communication protocols (stdio, Streamable HTTP and the legacy SSE transport) without changing your application code.
- A context object to access server capabilities, log information, report progress and even request LLM sampling.
- 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).
Then, create the basic server instance:
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:
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:
-
Create a Python function that returns the data you want your resource to return.
-
Add a fastmcp resource decorator with the unique URI of this resource as parameter.
-
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.
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.
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.
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.
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, PydanticBaseModel: 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:
-
In the function (resource or tool) where you want to access the context, add a parameter
ctxof typeContext. The name doesn't matter, but the type hintContextis required. -
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.
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.
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
- Smolagents: Minimal Agent Framework: Explore a lightweight approach to agent development
- Langfuse: The Open Source Observability Platform: Monitor and improve your LLM applications
- Evaluate RAG Performance Using RAGAS: Learn how to measure and optimize your retrieval systems
- High-Quality AI Agent Systems: Best practices for building robust AI agents
- Microsoft Agent Framework: Build enterprise agents that use MCP servers as tools
- LLM tools from any Python SDK: Generate LangChain tools from an existing SDK instead of writing them by hand
- Text-to-SQL with NVIDIA Auto Ontology: A semantic layer for databases that agents can query over MCP
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



