Skip to content
devtoolbox.cc

FastMCP · Chapter 1 of 6

FastMCP tutorial: what MCP is and your first server

10 min study · Examples checked with FastMCP 4.2 and MCP Python SDK 2.3 on Python 3.14 ·

A learning website already knows which lessons exist, how long they take, and where readers should begin. An AI application cannot reliably infer that live catalog from its training data. Model Context Protocol, or MCP, gives the application a standard way to discover and call capabilities you expose. In this chapter, you will make a tiny catalog available through FastMCP and call it without an API key or a language model.

Identify the participants

The host is the application a person uses, such as an assistant or an editor. An MCP client inside that application communicates with a server. The server advertises capabilities and executes operations against its data or services. A language model may help the host choose an operation, but it is not required to exercise the protocol: an ordinary Python client can make the same call.

Your FastMCP server therefore does not automatically become an autonomous agent. It supplies a controlled interface. The host still decides how to incorporate results, present them, and handle user approval. The underlying business service still owns rules such as which lessons are published and who may change them.

MCP defines protocol messages and transport behavior; FastMCP is a Python framework that implements those details around your functions. FastAPI is a separate framework for HTTP APIs. A service can expose both interfaces, and the last chapter shows how to share its underlying logic.

Learn the three server primitives

A tool performs a named operation with arguments and a result. It might search lessons, calculate a study plan, or publish an approved revision. Tools can be read-only or state-changing.

A resource provides readable content identified by a URI, such as catalog://overview or lesson://12. A resource template describes a family of parameterized URIs. Reading a resource should not secretly publish or delete a lesson.

A prompt returns a reusable message template, such as instructions for explaining a chosen topic. Retrieving a prompt does not run a model or guarantee a particular answer. These primitives give a host different ways to discover capabilities and assemble context; the host’s actual interface determines how users see them.

Install the standalone framework

This track was checked with FastMCP 4.2.0 and the MCP Python SDK 2.3.0 on Python 3.14. Use an isolated environment and install the pinned package:

python -m pip install "fastmcp==4.2.0"
fastmcp version

In a uv project, use uv add "fastmcp==4.2.0" and run commands through uv run. Commit the dependency metadata and lockfile. The standalone package uses from fastmcp import FastMCP. Older examples using from mcp.server.fastmcp import FastMCP target a different high-level implementation bundled with an older SDK; their APIs should not be mixed casually. See the installation guide.

Expose a small catalog

Create a new directory and save this complete file as server.py:

from fastmcp import FastMCP

mcp = FastMCP("Learning catalog")

@mcp.tool(annotations={"readOnlyHint": True})
def list_lessons() -> dict:
    """List the published introductory lessons and their durations in minutes."""
    return {
        "lessons": [
            {"id": 1, "title": "Python functions", "minutes": 12},
            {"id": 2, "title": "FastAPI requests", "minutes": 15},
        ]
    }

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

The name identifies the server. The decorator registers a tool, the function name supplies its identifier, and the docstring describes what callers should expect. The returned dictionary becomes structured output. The read-only annotation describes intended behavior; it does not prevent Python code from performing writes.

The guard matters because importing this module should register definitions without starting a blocking server. mcp.run() defaults to stdio: a client launches the program and exchanges protocol messages through its standard streams. Running python server.py can appear to wait silently because it expects a protocol peer, not keyboard commands.

Call it in process

Save this as client.py beside the server:

import asyncio

from fastmcp import Client
from server import mcp

async def main():
    async with Client(mcp) as client:
        tools = await client.list_tools()
        print([tool.name for tool in tools])
        result = await client.call_tool("list_lessons", {})
        print(result.data["lessons"][0]["title"])

if __name__ == "__main__":
    asyncio.run(main())

Run python client.py. It prints the available tool name and Python functions. Passing the server object selects an in-memory transport, so this example does not open a network port or start another interpreter. It still exercises discovery, schema handling, and result conversion through the client API. Later chapters test subprocess and HTTP boundaries separately.

The async context manager owns the client’s connection lifecycle. Use it even for a short test. An async Python context is not a promise that every MCP revision uses a persistent server-side session; protocol compatibility is the library’s responsibility.

Separate protocol behavior from host behavior

The current MCP revision uses self-contained requests with per-request metadata. Older revisions used an initialization handshake and connection-scoped sessions. FastMCP handles compatible peers, so application examples should not manually copy an old handshake sequence or invent required HTTP headers. The transport specification explains the version boundary.

Discovering a tool does not mean a host will call it, and registering a resource does not mean every host will display a resource picker. Test the required capabilities in the target host after the Python-level contract works. This keeps integration questions separate from errors in the server itself.

For stdio, reserve stdout for protocol traffic. Send server diagnostics to stderr through logging, and avoid top-level print() calls in imported modules. Printing from the client is fine because its stdout is not the server’s protocol stream.

Practice

Add a read-only catalog_status tool returning the number of published lessons and the catalog language. Discover it with the client and assert its structured result. Then import server in a Python shell and confirm that importing alone does not start the server.

Answer check: discovery shows both tools, the result is a dictionary with deliberate fields, and no model account is required. A silent stdio server is not evidence that its tools are broken; the client must speak the protocol.

Summary

MCP connects a host to defined capabilities. FastMCP turns Python declarations into that interface. Begin with a tiny, testable contract and add transports, persistence, and authorization as separate layers.

All FastMCP chapters