I copied the first example from a tutorial on building an MCP server in Python, ran it, and got this:
ModuleNotFoundError: No module named 'mcp.server.fastmcp'. This is mcp 2.x, where FastMCP was renamed to MCPServer (from mcp.server.mcpserver import MCPServer) and other APIs changed
If you are trying to build an MCP server in Python and have seen that error too, you are not doing anything wrong. Version 2 of the official MCP Python SDK renamed FastMCP to MCPServer, and most of the tutorials online were written for version 1.
So I rebuilt a small MCP server in Python from scratch on the new SDK, tested every line, and wrote down what changed. This post walks through all of it: a working server, how to test it, and how to plug it into Claude Code.
What our MCP server in Python will do
An MCP server is a small program that gives an AI assistant new abilities. It can offer tools (functions the model can call), resources (data the app can read) and prompts (ready-made instructions). If the idea is new to you, I explained how it differs from a normal web API in MCP vs API.
Ours will be a notes server. Point it at a folder of Markdown files, and your assistant can search them and read them. It is deliberately read-only. That is a good habit for a first server, and for most servers.
Three files sit in the folder for this walkthrough: a note about Postgres connection pooling, a release checklist and some stand-up notes.
Setting up
You need Python 3.10 or newer. I use uv, but plain pip works the same way.
uv init notes-mcp cd notes-mcp uv add "mcp[cli]" mkdir notes # put a few .md files in here
The [cli] extra gives you the mcp command, which opens your server in the MCP Inspector, a browser UI for poking at it by hand. I tested everything here with version 2.3.0 of the SDK.
The whole MCP server in Python, in one file
Here is server.py. Read it once, then we will look at the parts that matter.
import logging
import os
from pathlib import Path
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
# Never print() in a stdio server: stdout carries the protocol messages.
# Logging writes to stderr, which is safe.
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("notes")
NOTES_DIR = Path(os.environ.get("NOTES_DIR", "notes")).resolve()
mcp = MCPServer("Notes")
def note_path(name: str) -> Path:
"""Turn a note name into a path, refusing anything outside NOTES_DIR."""
path = (NOTES_DIR / name).with_suffix(".md").resolve()
if not path.is_relative_to(NOTES_DIR):
raise ToolError(f"Note name not allowed: {name}")
return path
@mcp.tool()
def search_notes(query: str, limit: int = 5) -> list[dict]:
"""Search the Markdown notes for a word or phrase (case-insensitive).
Returns the note name and each matching line.
"""
log.info("search_notes %r", query)
needle = query.lower()
results = []
for path in sorted(NOTES_DIR.glob("*.md")):
lines = [line.strip() for line in path.read_text().splitlines()
if needle in line.lower()]
if lines:
results.append({"note": path.stem, "matches": lines})
return results[:limit]
@mcp.tool()
def read_note(name: str) -> str:
"""Return the full text of one note, by name (without .md)."""
path = note_path(name)
if not path.exists():
raise ToolError(f"No note called {name}")
return path.read_text()
@mcp.resource("notes://index")
def note_index() -> str:
"""A list of every note name."""
return "\n".join(p.stem for p in sorted(NOTES_DIR.glob("*.md")))
@mcp.prompt()
def summarise_note(name: str) -> str:
"""Ask the model to summarise one note."""
return (f"Read the note '{name}' with the read_note tool and summarise it "
"in three bullet points. List any action items separately.")
if __name__ == "__main__":
mcp.run() # stdio by default
That is a complete MCP server. There is no JSON Schema to write, no request parsing and no protocol code. You write typed Python functions, and the SDK handles everything else.
Three lines in that file do more work than they appear to.
1. Your type hints are the contract
The model never sees your Python. It sees a schema the SDK builds from your function signature and docstring. For search_notes, that schema looks like this:
{'type': 'object',
'properties': {'query': {'title': 'Query', 'type': 'string'},
'limit': {'default': 5, 'title': 'Limit', 'type': 'integer'}},
'required': ['query'],
'title': 'search_notesArguments'}
The default value tells the model limit is optional. The docstring becomes the tool’s description, and that description is how the model decides when to call it. A vague docstring gives you a tool the model either ignores or calls at the wrong moment.
The function signature is the contract. Write it as carefully as you would write a public API.
2. Use ToolError for errors the model should see
My first version raised a plain ValueError when someone asked for a note outside the folder. The call failed, but the model only received “Error executing tool read_note”. My helpful message had disappeared.
That is deliberate in version 2. An unexpected exception might contain a file path or a secret, so the SDK keeps its text on the server. When you want the model to read the message, raise ToolError instead:
Error executing tool read_note: Note name not allowed: ../server
Now the model knows what went wrong and can try again with a better name.
3. Never print to stdout
A local MCP server talks to its client over standard input and output. Every byte on stdout must be a protocol message. One stray print() for debugging, and the client sees broken JSON and drops the connection.
Use logging, which writes to stderr by default. It is the most common reason a new server “connects and then immediately fails”.
Trying it out
Before connecting the server to any assistant, I like to talk to it from a short script. The same SDK includes a client that can start the server as a subprocess:
import asyncio
import sys
from mcp import Client, StdioServerParameters
server = StdioServerParameters(command=sys.executable, args=["server.py"])
async def main() -> None:
async with Client(server) as client:
tools = await client.list_tools()
print("tools:", [t.name for t in tools.tools])
result = await client.call_tool("search_notes", {"query": "pooling"})
print("search:", result.structured_content)
result = await client.call_tool("read_note", {"name": "../server"})
print("traversal blocked:", result.is_error, result.content[0].text)
index = await client.read_resource("notes://index")
print("index:", index.contents[0].text.splitlines())
asyncio.run(main())
tools: ['search_notes', 'read_note']
search: {'result': [{'note': 'postgres-pooling', 'matches': ['# Postgres connection pooling']}, {'note': 'standup-2026-11-20', 'matches': ['- Ben: investigating slow login; suspects connection pooling.']}]}
traversal blocked: True Error executing tool read_note: Note name not allowed: ../server
index: ['postgres-pooling', 'release-checklist', 'standup-2026-11-20']
Search finds both notes that mention pooling. The attempt to read ../server, a file outside the notes folder, is refused with a clear message. The resource lists every note.
If you would rather click than code, uv run mcp dev server.py opens the same server in the MCP Inspector.
Testing your MCP server
This is my favourite change in version 2. You can pass the server object straight to Client, and it connects in-process. There is no subprocess and no network, so tests are fast and simple:
import pytest
from mcp import Client
from server import mcp
@pytest.mark.anyio
async def test_search_finds_matching_lines():
async with Client(mcp) as client:
result = await client.call_tool("search_notes", {"query": "pgbouncer"})
notes = [hit["note"] for hit in result.structured_content["result"]]
assert notes == ["postgres-pooling"]
@pytest.mark.anyio
async def test_read_note_refuses_paths_outside_the_folder():
async with Client(mcp) as client:
result = await client.call_tool("read_note", {"name": "../server"})
assert result.is_error
assert "not allowed" in result.content[0].text
@pytest.fixture
def anyio_backend():
return "asyncio"
.. [100%] 2 passed in 0.36s
Install the test tools with uv add --dev pytest anyio. The second test matters most. Your server is a door into your machine, so the check that keeps the door narrow deserves a test of its own.
Connecting the MCP server to Claude Code
One command registers the server. Everything after -- is the command Claude Code runs to start it:
claude mcp add notes -e NOTES_DIR=/path/to/notes-mcp/notes \ -- /path/to/notes-mcp/.venv/bin/python /path/to/notes-mcp/server.py
Use absolute paths. Claude Code starts the server from its own working directory, not from yours, so a relative path that worked in your terminal will point somewhere else.
By default the server is only available to you, in the current project. Add --scope project to write it to a .mcp.json file you can commit for your team. Claude Code asks each person to approve a project server before it runs, and claude mcp get notes shows “Pending approval” until they do. That is a sensible safety net, since a shared config file could otherwise run any command on a teammate’s machine.
Once it is connected, ask something like “what do my notes say about connection pooling?” and Claude calls search_notes for you. The tools appear as mcp__notes__search_notes and mcp__notes__read_note, which are the names to use if you want to pre-approve them in your permission settings.
Coming from version 1?
For a simple server, the change is usually one import:
# Version 1
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Notes")
# Version 2
from mcp.server import MCPServer
mcp = MCPServer("Notes")
The decorators work as before. Check the official migration guide for the rest, and especially look at how you raise errors. A ValueError that used to reach the model now gets hidden. If you are not ready to move, pin mcp<2 in your dependencies.
What I would build next
The notes server is small on purpose, but the shape is the same for anything you want your assistant to reach: a database, an internal API, your issue tracker. Keep tools narrow, keep them read-only until you have a reason not to, and write the docstrings for the model, not for yourself.
And if your notes folder grows into thousands of files, plain substring search will stop being enough. That is the point where hybrid search in PostgreSQL or a proper vector index starts to earn its place, though, as I argued in Claude Code uses grep, simple search goes further than most people expect.
Further reading
- MCP Python SDK documentation, including the version 2 migration guide
- Model Context Protocol specification
- Claude Code documentation: connecting MCP servers
- On this site: MCP vs API and LangChain MCP Adapter 2.0
