Building MCP Servers

In this final lesson on MCP, we’ll build an MCP server with Python using FastMCP.

This Lesson Will Cover
  • 🏗️ Spinning up a FastMCP server with uv
  • 🔧 Adding tools, resources, and prompt templates
  • 🧪 Testing & debugging via CLI self-tests and MCP Inspector
  • 📦 Packaging MCP servers for PyPI

FastMCP

FastMCP is a Python framework for building MCP clients and servers. It handles the most complicated parts, like protocol details and server management, and abstracts them into a nice, clean API (whose design is clearly inspired by FastAPI and Flask).

Not only does it abstract away a lot of boilerplate code, but it guides us towards best practices.[1]

FastMCP VS the Official MCP Python SDK

It is recommend to use the latest version of FastMCP on PyPI as opposed to the official MCP Python SDK (which is an older version of FastMCP).[2]

Installation

We can add FastMCP to our project the same way as any other python library.

e.g.

pip install fastmcp # install with pip
uv add fastmcp # or, install with uv

FastMCP Tutorial

Like the previous lesson, this one is going to be hands-on! (again, this is optional but highly recommended)

We’re going to work from a reference MCP server that I’ve prepared[2:1] for demonstration purposes.

Go ahead and open it up on GitHub here:

https://github.com/zazencodes/zazencodes-season-2/tree/main/src/fastmcp-tutorial

Cloning & Installing

To get started, we’ll clone and install the server.

We’re going to use the uv package manager, so the first step is ensuring that it’s installed:

uv --version

It can be installed on MacOS and Linux as follows:

curl -LsSf https://astral.sh/uv/install.sh | sh

Then clone and navigate to the source code:

git clone https://github.com/zazencodes/zazencodes-season-2.git
cd zazencodes-season-2/src/fastmcp-tutorial

Listing the files in the project, we can see:

ls -a

# Output:
#  .python-version
#  LICENSE
#  main.py
#  PACKAGE_SUMMARY.md
#  PUBLISHING.md
#  pyproject.toml
# 󰂺 README.md
#  src
#  test_server.py
#  uv.lock

The dependencies are listed in pyproject.toml:

[project]
...
requires-python = ">=3.12"
dependencies = [
    "fastmcp>=2.5.1",
]

Let’s go ahead and install it using uv:

uv sync

We can now see that a .venv virtual environment has been added to the project.

Running the Server with uv

Now we’re ready to start the server:

uv run fastmcp-tutorial

# Output:
# Starting FastMCP Tutorial Server...
# Tools: 3 | Resources: 4 | Prompts: 4
# Press Ctrl+C to stop the server
# [06/07/25 06:02:10] INFO     Starting MCP server 'Tutorial MCP Server' with transport 'stdio'

This executes the fastmcp-tutorial command specified in the pyproject.toml file:

[project.scripts]
fastmcp-tutorial = "fastmcp_tutorial.cli:main"
fastmcp-tutorial-test = "fastmcp_tutorial.test:run_tests"

Now let’s stop the server (Ctrl+C) and run the test script.

Running the Tests

The repo ships with a self-test harness (src/test.py)

Let’s run it with the following command:

uv run fastmcp-tutorial-test

Output (abridged):

============================================================
TESTING FASTMCP TUTORIAL SERVER
============================================================

🔧 TESTING TOOLS:
--------------------
✓ Greet tool: [TextContent(type='text', text='Hello, World! Welcome to FastMCP 2.0!'...
✓ Add numbers tool: [TextContent(type='text', text='8', annotations=None)]
✓ Server info tool: [TextContent(type='text', text='This is a tutorial MCP server ...

📚 TESTING RESOURCES:
--------------------
✓ Server status resource: [TextResourceContents(uri=AnyUrl('resource://server-status'), ...
✓ Greeting resource: [TextResourceContents(uri=AnyUrl('resource://greeting'), ...
✓ Config server resource: [TextResourceContents(uri=AnyUrl('config://server'), ...
✓ Config features resource: [TextResourceContents(uri=AnyUrl('config://features'), ...
✓ User profile resource: [TextResourceContents(uri=AnyUrl('data://user/123/profile'), ...

💬 TESTING PROMPTS:
--------------------
✓ Code review prompt: meta=None description='Generate a code review prompt for the ...
✓ Documentation prompt: meta=None description='Generate a documentation writing ...
✓ Explain concept prompt: meta=None description='Generate a prompt to explain a ...
✓ Debugging assistant prompt: meta=None description='Generate a debugging assistance ...

============================================================
✅ ALL TESTS COMPLETED!
============================================================

Exploring the Server with MCP Inspector

Now we’ll run this server with the MCP Inspector and play around with the resources, prompts and tools.

npx @modelcontextprotocol/inspector uv run fastmcp-tutorial

# Output:
# Starting MCP inspector...
# ⚙️  Proxy server listening on port 6277
# New connection
# Query parameters: [Object: null prototype] {
#   command: 'npx',
#   args: '-y @upstash/context7-mcp',
#   env: '{"HOME":"/Users/alex","PATH": ... },
#   transportType: 'stdio'
# }
# Stdio transport: command=/Users/alex/.nvm/versions/node/v23.9.0/bin/npx, args=-y,@upstash/context7-mcp
# Spawned stdio transport
# Connected MCP client to backing server transport
# Created client/server transports
# Set up MCP proxy
# 🔍 MCP Inspector is up and running at http://127.0.0.1:6274 🚀

Opening up the MCP Inspector at http://127.0.0.1:6274 and clicking “Connect” will spin up the server.

You should see more logging on the inspector process in the terminal, and a log like this in the inspector app itself:

[06/07/25 06:05:10] INFO     Starting MCP server 'Tutorial MCP Server' with transport 'stdio'

From here, we can do the following:

  • List Resources

    • Resources available on our server:
      • resource://server-status

        {
          "contents": [
            {
              "uri": "resource://server-status",
              "mimeType": "text/plain",
              "text": "{\n  \"status\": \"running\",\n  \"timestamp\": \"2025-06-07T06:14:38.961408\",\n  \"version\": \"2.5.1\",\n  \"features\": [\n    \"tools\",\n    \"resources\",\n    \"prompts\"\n  ]\n}"
            }
          ]
        }
        
      • resource://greeting

        {
          "contents": [
            {
              "uri": "resource://greeting",
              "mimeType": "text/plain",
              "text": "Hello from FastMCP Resources! This is a static resource that provides information."
            }
          ]
        }
        
  • List Templates

    • Resource templates available on our server:
      • get_config_section

        e.g. “omtose_phellack” (not valid)

        {
          "contents": [
            {
              "uri": "config://omtose_phellack",
              "mimeType": "text/plain",
              "text": "{\n  \"error\": \"Configuration section 'omtose_phellack' not found\"\n}"
            }
          ]
        }
        
      • get_user_profile

        e.g. “123”

        {
          "contents": [
            {
              "uri": "data://user/123/profile",
              "mimeType": "text/plain",
              "text": "{\n  \"id\": \"123\",\n  \"name\": \"Alice Smith\",\n  \"email\": \"alice@example.com\",\n  \"role\": \"developer\",\n  \"created_at\": \"2024-01-15T10:30:00Z\"\n}"
            }
          ]
        }
        
  • List Prompts

    • Prompts available on our server:
      • code_review_prompt
        Generate a code review prompt for the given language and code.

      • documentation_prompt
        Generate a documentation writing prompt.

      • explain_concept_prompt
        Generate a prompt to explain a technical concept to a specific audience.

        e.g. concept = “malazan lore”, audience = “my wife”

        {
            description: "Generate a prompt to explain a technical concept to a specific audience."
            messages: [
                0: {
                    role: "user"
                    content: {
                        type: "text"
                        text: "Explain the concept of 'malazan lore' to a my wife audience.
        
                        Guidelines: Use accessible language wi..."
                    }
                }
            ]
        }
        
      • debugging_assistant_prompt
        Generate a debugging assistance prompt.

  • List Tools

    • Tools available on our server:
      • greet
        Greet a person by name.

      • add_numbers
        Add two numbers together.

        e.g. a = 832819, b = 2

        Tool Result: Success
        "832821"
        
      • get_server_info
        Get information about this MCP server.

Having explored what the server does, let’s explain how it works.

Code Walkthrough

Let’s walk through the project and explain the key aspects.

Anatomy of main.py
from fastmcp import FastMCP
mcp = FastMCP("Tutorial MCP Server")

FastMCP exposes decorators for the three core capabilities of MCP servers:

Decorator What it creates Example
@mcp.tool() Callable tool (RPC) greet, add_numbers, get_server_info
@mcp.resource() Addressable data (URI) resource://server-status, config://{section}
@mcp.prompt() Prompt template code_review_prompt, debugging_assistant_prompt
Tools

For each Tool, @mcp.tool(), FastMCP will do the following (in order to make the tool available to MCP clients like Claude Desktop):

  1. Introspect the signature and build the JSON-Schema.
  2. Register the tool so clients can discover its name, description and input schema with tools/list.
  3. Handle invocation through a tools/call JSON-RPC request containing the tool name and arguments.

With stdio, those messages travel through standard input and output. With Streamable HTTP, MCP uses a single endpoint path for protocol messages. The tool name belongs in the JSON-RPC request; FastMCP does not require a REST route for each tool.

For example, here’s the tool for adding numbers:

@mcp.tool()
def add_numbers(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

Notice how the docstring matches the server description in the MCP Inspector. The typehints are also important aspects of the tool definition.

Resources

A Resource must be a valid URI, e.g.

@mcp.resource("config://{section}")
def get_config_section(section: str) -> dict:
    """Get configuration for a specific section."""
    configs = {
        "server": {
            "name": "Tutorial MCP Server",
            "version": "1.0.0",
            "max_connections": 100
        },
        "features": {
            "tools_enabled": True,
            "resources_enabled": True,
            "prompts_enabled": True
        },
        "logging": {
            "level": "INFO",
            "format": "json",
            "output": "stdout"
        }
    }
    return configs.get(section, {"error": f"Configuration section '{section}' not found"})

This resource enables the LLM to fetch config data based on a named section.

Prompt templates

LLMs can request ready-to-send Prompts.

For example, the code below exposes a prompt template for explaining concepts to different audiences:

@mcp.prompt()
def explain_concept_prompt(concept: str, audience: str = "general") -> str:
    """Generate a prompt to explain a technical concept to a specific audience."""
    audience_instructions = {
        "beginner": "Use simple language, avoid jargon, and provide relatable analogies",
        "intermediate": "Use technical terms but explain them, provide examples",
        "expert": "Use precise technical language and focus on nuances",
        "general": "Use accessible language with some technical detail"
    }

    instruction = audience_instructions.get(audience, audience_instructions["general"])

    return f"""Explain the concept of '{concept}' to a {audience} audience.

Packaging for PyPI

Everything related to packaging this project is specified in the pyproject.toml.

Below are the most important sections to understand:

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
  • build-system: Defines which tool is used to build the package. Here, we’re using Hatchling, so any python -m build (or uv build) command will invoke Hatchling under the hood.
[project]
name = "fastmcp-tutorial"
version = "1.0.0"
description = "A comprehensive FastMCP 2.0 tutorial server with tools, resources, and prompts"
readme = "README.md"
license = { text = "MIT" }
authors = [
    { name = "Your Name", email = "your.email@example.com" }
]
maintainers = [
    { name = "Your Name", email = "your.email@example.com" }
]
requires-python = ">=3.12"
dependencies = [
    "fastmcp>=2.5.1",
]
  • name & version: These define the package coordinates on PyPI (e.g., fastmcp-tutorial==1.0.0). Bumping the version here (and in __init__.py) is required before publishing a new release.
  • Metadata fields (description, readme, license, authors, etc.) populate PyPI’s package page automatically.
  • requires-python: Specifies the minimum Python version (3.12 in this case).
  • dependencies: Runtime requirements — anything listed here will be installed when someone does pip install fastmcp-tutorial.
[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "pytest-asyncio>=0.21.0",
    "black>=23.0",
    "ruff>=0.1.0",
]
  • optional-dependencies: Convenience groups for extras; here, a dev group installs testing and linting tools. Users can do pip install fastmcp-tutorial[dev] to get these.
[project.urls]
Homepage = "https://github.com/yourusername/fastmcp-tutorial"
Repository = "https://github.com/yourusername/fastmcp-tutorial"
Documentation = "https://github.com/yourusername/fastmcp-tutorial#readme"
"Bug Reports" = "https://github.com/yourusername/fastmcp-tutorial/issues"
  • project.urls: Links that appear on the PyPI page (e.g., source code, issue tracker, docs).
[project.scripts]
fastmcp-tutorial = "fastmcp_tutorial.cli:main"
fastmcp-tutorial-test = "fastmcp_tutorial.test:run_tests"
  • project.scripts: Defines console entry points. After installation, users can run:

    fastmcp-tutorial         # launches the CLI at fastmcp_tutorial/cli.py
    fastmcp-tutorial-test    # runs the test suite via fastmcp_tutorial/test.py
    
[tool.hatch.build.targets.wheel]
packages = ["src/fastmcp_tutorial"]

[tool.hatch.build.targets.sdist]
include = [
    "src/",
    "README.md",
    "LICENSE",
]
  • tool.hatch.build.targets: Controls what goes into the built distributions:

    • The wheel target ensures only the src/fastmcp_tutorial package is packaged into the .whl.
    • The sdist target includes source files (src/), plus documentation (README.md) and license.

A full explanation of distributing an MCP server over PyPI is out of scope for this course, but you can follow along with the instructions in PUBLISHING.md to see exactly how we would publish this code (building with Hatchling, uploading via Twine, etc.).

Conclusion

And that brings us to the end of the MCP section of the course!

When I first released the AI Engineer Roadmap at the start of 2025, this section was not included. But as the year went on, it quickly became obvious that MCP was something really big and important.

I have a vision of students learning about MCP in school, the same way that we learned about SSH or HTTP. How cool is it that we’re here at the start!

Key Takeaways

🏗️ FastMCP exposes tools, resources, and prompts with minimal boilerplate — no custom HTTP routes, just one JSON-RPC endpoint

🔄 A single JSON-RPC transport keeps client integration uniform and future-proof

🧪 A ready-made CLI test harness (plus optional pytest extras) simplifies validation before every deploy

📦 Clean Python packaging lets anyone install your server with pip install ... or uv add ...

🔍 MCP Inspector and Claude Desktop provide an interactive way to debug and iterate on your server

📊 Structured logs surface real-time insight into how your server is being used

Footnotes


  1. The FastMCP documentation is fantastic and a must-read for MCP developers. ↩︎

  2. I discuss the different between FastAPI 2.0 and the MCP Python SDK in my FastAPI tutorial on YouTube. In fact, in that video I actually built out the exact server that we’re looking at in this lesson (using Claude Code). ↩︎ ↩︎

Comments (0)

No comments yet.