MCP Servers & Security

Build an MCP Server in Python: The Smallest Useful One, With MCPServer

14 November 2026 · Updated 28 November 2026 · 12 min read · by Yang Kai

Build a minimal, useful MCP server in Python with the SDK v2 MCPServer decorator API: one read-only tool, validated input, real error handling, and a safe config you can copy.

Starter code inside: Minimal Python (MCPServer) MCP Server Skeleton

Contents
  1. What you need before you start
  2. Step 1: Pick a job that cannot hurt anything
  3. Step 2: Set up the project
  4. Step 3: Write the server skeleton
  5. Step 4: Test in the Inspector before connecting anything
  6. Step 5: Connect it to your client
  7. Step 6: Test the same boring cases
  8. Troubleshooting: the Python-specific failures
  9. Growing it without growing the risk
  10. How we researched this
  11. What to do next

Most Python MCP tutorials you will find are quietly out of date. They import a class called FastMCP — and on the current Python SDK, that import fails, because SDK v2 renamed the class to MCPServer and removed the old module entirely. Follow an older tutorial and your first server errors before it starts.

This tutorial is built on the v2 API from the start. You will build one read-only tool, word_count, that counts words in Markdown drafts inside a single allowed folder: validated input, errors the model can act on, and a client config that survives restarts.

It is the Python counterpart to the TypeScript starter server, and it follows the official Python SDK documentation as checked in November 2026. Same job, same safety habits, different language — so you can compare the two shapes directly.

The whole build, in five lines:

  1. Create a virtual environment and install the SDK with pip install "mcp[cli]" — that now gives you v2.
  2. Create an MCPServer, and register one typed function with @mcp.tool().
  3. Validate the file name and keep every read inside one allowed folder.
  4. Raise ToolError for failures, so the client marks the call as an error instead of data.
  5. Test in the MCP Inspector, then point your client’s config at the venv’s Python.

What you need before you start

No API key, no account, no network service. Everything in this build runs on your own machine.

Step 1: Pick a job that cannot hurt anything

Your first tool should be read-only, deterministic, and something you need weekly. Counting words in a draft qualifies. So does checking frontmatter, listing files older than a date, or summarising a CSV’s shape.

Anything that sends, deletes, pays, or publishes does not. Not because Python makes it dangerous, but because a first server is where you learn the failure modes, and you want those lessons to be cheap.

If you are still deciding whether a server is even the right shape for your problem, what MCP actually does for builders covers that judgement call before you write a line.

Step 2: Set up the project

Create a folder and a virtual environment, then install the SDK. The [cli] extra adds the mcp command, which Step 5 uses to open the Inspector:

mkdir draft-tools-py && cd draft-tools-py
python -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install "mcp[cli]"
pip freeze > requirements.txt

Two version facts matter here, both checked November 2026:

If you already work with uv, the SDK documentation’s preferred flow works too: uv init, then uv add "mcp[cli]", and run the server with uv run. The venv-and-pip route above is shown because it makes the interpreter path — the thing your client config needs — explicit.

The official Python SDK documentation carries a v1-to-v2 migration guide that lists every rename; for a new server, you only need the one in the next step.

Step 3: Write the server skeleton

Save this as server.py. It is the complete file — a working skeleton, not a fragment:

import os
from pathlib import Path

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

ALLOWED_DIR = Path(os.environ.get("DRAFTS_DIR", "./drafts")).resolve()

mcp = MCPServer("draft-tools-py")

@mcp.tool()
def word_count(filename: str) -> str:
    """Count words in a Markdown draft inside the drafts folder.

    Pass a file name only, e.g. 'my-post.md' — not a path.
    """
    safe_name = Path(filename).name  # strips any ../ tricks
    path = (ALLOWED_DIR / safe_name).resolve()
    if path != ALLOWED_DIR and ALLOWED_DIR not in path.parents:
        raise ToolError(f"'{safe_name}' is outside the allowed folder.")
    if path.suffix != ".md" or not path.is_file():
        raise ToolError(f"No Markdown draft named '{safe_name}' in the drafts folder.")
    words = len(path.read_text(encoding="utf-8").split())
    return f"{safe_name}: {words} words"

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

Five details carry the whole design:

Sync functions are fine. The skeleton uses a plain def, and that is a supported shape — the SDK accepts ordinary functions as well as async def ones. Reach for async when a tool spends its time waiting on network calls or a database; for local file work like this, a plain function is simpler and behaves identically from the client’s side.

One Python-specific trap: do not print() debugging output to stdout. Over stdio transport, stdout is the protocol channel, and a stray print corrupts it. Log to stderr, or use the logging module configured to write there.

Step 4: Test in the Inspector before connecting anything

Do not debug a server through a chat window — that mixes your server’s errors with the model’s behaviour, and you cannot tell which one failed. The SDK’s CLI opens the MCP Inspector against your file directly:

mcp dev server.py

In the Inspector you should see word_count listed with a single required filename argument. Call it with a real draft name and check the count. Call it with a missing name and confirm the result comes back marked as an error, with your message attached.

You should now have: a server that starts, lists one tool, answers a good call, and refuses a bad one — before any client is involved. If the Inspector cannot start the server, the client will not either; fix it here, where the error messages are yours.

Step 5: Connect it to your client

Point your client’s MCP configuration at the virtual environment’s Python, so the server runs with its dependencies available:

{
  "mcpServers": {
    "draft-tools-py": {
      "command": "/absolute/path/to/draft-tools-py/.venv/bin/python",
      "args": ["/absolute/path/to/draft-tools-py/server.py"],
      "env": { "DRAFTS_DIR": "/absolute/path/to/drafts" }
    }
  }
}

Using the venv interpreter directly — rather than activating the environment first — is the detail that makes this reliable across restarts. The client launches the command exactly as written; there is no shell session to activate anything.

For Claude Desktop specifically, the SDK CLI offers a shortcut — mcp install server.py writes the entry into the desktop app’s config for you. It is convenient, but read what it wrote before relying on it: the manual config above teaches you the two things that actually break in practice, the absolute interpreter path and the env block, and you will need both the first time you move the project.

Configuration belongs in the environment, as this config shows: the drafts folder arrives through env, not hard-coded in the source file you will eventually commit. If your setup involves wiring servers into a coding agent specifically, the Claude Code plus MCP setup walkthrough covers the client side of that pairing in depth.

Step 6: Test the same boring cases

Run the five tests from the checklist for exercising a server’s error paths:

  1. A real draft returns a count you can verify by hand.
  2. A missing file returns a clean, flagged error — not a crash, not a fake count.
  3. ../../secret.txt is refused.
  4. A .png name is rejected.
  5. A very large Markdown file completes.

Then restart the client and confirm the tool reappears. Boring tests, run every time you change the server, are what separate a tool you trust from a demo you once saw work.

Re-run the same five after every SDK upgrade, even a minor one. The v1-to-v2 rename is the recent proof of why: nothing about your tool’s logic changed, yet every server written against the old import stopped starting. A two-minute test pass after an upgrade is cheaper than discovering the breakage mid-task, with the client reporting a server that simply never appears.

Troubleshooting: the Python-specific failures

Growing it without growing the risk

Add tools one at a time, inside the same theme. A natural second tool here is missing_frontmatter, which lists drafts lacking a title or description — still read-only, still one folder. That one-tool-at-a-time rhythm is exactly the path taken in growing from a first server to a second one, and it applies identically in Python.

As the tool count grows, the docstrings start doing real work. With one tool, the model has nothing to confuse it with; with five, it picks between them using exactly the descriptions you wrote. Keep each docstring to what the tool does, what input it expects, and what it returns — and when two tools sound alike, rewrite the descriptions before you rewrite the code. Most “the model called the wrong tool” bugs are description bugs.

When the server needs to answer questions about data rather than files, resist bolting a database query onto this skeleton. Database access deserves its own rails — read-only credentials, query limits, allow-listed tables — which is the subject of connecting MCP to databases safely.

And when a capability is really reference data or a repeatable workflow rather than an action, Python’s decorators cover the other primitives too — @mcp.resource() and @mcp.prompt() sit next to @mcp.tool(). Resources, prompts, and sampling explained helps you decide which primitive a job actually is.

How we researched this

This tutorial follows the official Python SDK documentation and its v1-to-v2 migration guide, checked November 2026: the MCPServer rename, the run() transport change, and the ToolError behaviour are all stated there. meetBlogging is a desk-research site — the code above is the smallest server that demonstrates the documented API and the safety habits, and the five tests in Step 6 are how you verify it on your own machine.

What to do next

Build the skeleton, point it at a harmless drafts folder, and pass the five tests. The mcp-builder skill is worth a look once you start a second Python server and want the scaffolding steps packaged, and if you later need this server reachable when your laptop is closed, hosting options from local to remote maps that next step.

FAQ

Why build an MCP server in Python instead of TypeScript? Because your data, scripts, or team already live in Python. The protocol does not care which language the server uses; the client sees the same tools either way, so the right choice is the ecosystem you can debug at midnight.

What happened to FastMCP in the Python SDK? It was renamed. SDK v2 replaced the FastMCP class with MCPServer and removed the mcp.server.fastmcp module rather than deprecating it, so v1 code fails at import time until the import is updated. The decorator API — @mcp.tool(), @mcp.resource(), @mcp.prompt() — carried over unchanged.

What does the Python MCP SDK give me? A decorator-based way to declare tools: write a typed function, decorate it, and the SDK generates the schema the agent reads and handles the protocol. You still own validation, error messages, and configuration — the parts this article spends its time on.

Where should a Python MCP server keep its tokens? In environment variables, read at startup — never hard-coded in the source file you will eventually commit. The skeleton in this article loads its one configuration value from the environment for exactly that reason.

How do I test a Python MCP server before connecting it? Open it in the MCP Inspector with mcp dev server.py and call each tool with good input, bad input, and empty input. Then run the five boring cases from Step 6 through the real client, including a restart, before you trust the server with daily work.

Category: MCP Servers & Security · Tags: #mcp #tutorial #ai-agents #ai-api

Next step: this article is part of MCP guides, which covers the full topic from first setup to advanced use.

Related guides