What You'll Build in This MCP Server Tutorial
This MCP server tutorial in Python builds a Study Helper server with the official Model Context Protocol SDK. It gives any MCP client two tools (days_until to count days to an exam and split_topics to spread a syllabus across study days), a resource that returns a subject's topic list, and a reusable prompt for a revision plan. In our AI agent tutorial you wrote tools inside one agent. MCP turns tools into a separate server that Claude Desktop, Claude Code, Cursor and VS Code can all plug into, the idea explained in MCP explained.
Prerequisites
- Basic Python: functions, type hints, lists and dictionaries.
- Python 3.11 or newer (the SDK docs target 3.11+) and a terminal.
- No API key: the server never calls a model itself.
- Optional:
uv(the docs' recommended installer) and Node.js, which the MCP Inspector needs fornpx.
Build the MCP Server Step by Step
1 Set up the project
Install the SDK with the cli extra, which adds the mcp command used to run, test and install servers. Use either uv or pip:
# with uv (recommended by the SDK docs)
uv init study-helper && cd study-helper
uv add "mcp[cli]"
# or with pip
mkdir study-helper && cd study-helper
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "mcp[cli]"
This tutorial was tested with mcp 2.3.0, the latest release on PyPI when we checked. Many older blog posts use from mcp.server.fastmcp import FastMCP: that is version 1. In version 2 the class is called MCPServer and the old import path is gone, so copy the imports below exactly.
2 Write the server
Create study_server.py. Each decorator turns a normal Python function into something an MCP client can discover:
from datetime import date
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
mcp = MCPServer("Study Helper")
SYLLABUS = {
"physics": ["Kinematics", "Laws of Motion", "Work and Energy", "Rotation", "Gravitation"],
"chemistry": ["Mole Concept", "Atomic Structure", "Chemical Bonding", "Thermodynamics"],
}
@mcp.tool()
def days_until(exam_date: str) -> int:
"""Return how many days are left until an exam date given as YYYY-MM-DD."""
target = date.fromisoformat(exam_date)
return (target - date.today()).days
@mcp.tool()
def split_topics(subject: str, days: int) -> list[str]:
"""Spread a subject's syllabus topics across a number of study days."""
topics = SYLLABUS.get(subject.lower())
if topics is None:
raise ToolError(f"Unknown subject: {subject}")
if days < 1:
raise ToolError("days must be at least 1")
plan = [[] for _ in range(days)]
for i, topic in enumerate(topics):
plan[i % days].append(topic)
return [f"Day {n + 1}: {', '.join(day)}" for n, day in enumerate(plan) if day]
@mcp.resource("syllabus://{subject}")
def syllabus(subject: str) -> str:
"""The topic list for one subject, one topic per line."""
topics = SYLLABUS.get(subject.lower(), [])
return "\n".join(topics) or f"No syllabus saved for {subject}."
@mcp.prompt()
def revision_plan(subject: str, exam_date: str) -> str:
"""Ask the model to build a revision plan using the server's tools."""
return (
f"I have a {subject} exam on {exam_date}. Use days_until to count the days left, "
f"then split_topics to spread the {subject} syllabus over those days, "
"and give me a short daily plan."
)
if __name__ == "__main__":
mcp.run()
@mcp.tool()exposes a function the model can call. The SDK builds the input schema from the type hints (str,int,list[str]) and uses the docstring as the description the model reads, so write docstrings as instructions.@mcp.resource("syllabus://{subject}")is a read-only resource template. The{subject}part of the URI becomes the function argument.@mcp.prompt()is a reusable prompt a user can pick from the client's menu.ToolErrorsends a clear message back to the model. In v2, any other exception is logged on the server and the model only sees a generic "Error executing tool" message.
3 Test it with the Python client
You do not need a chat app to check your server. The SDK's Client can connect to the server object directly, in memory. Save this as test_server.py in the same folder:
import asyncio
from mcp import Client
from study_server import mcp
async def main():
async with Client(mcp) as client:
tools = await client.list_tools()
print("Tools:", [tool.name for tool in tools.tools])
result = await client.call_tool("split_topics", {"subject": "physics", "days": 3})
print("Plan:", result.structured_content["result"])
res = await client.read_resource("syllabus://chemistry")
print("Chemistry:", res.contents[0].text.splitlines())
bad = await client.call_tool("split_topics", {"subject": "biology", "days": 3})
print("Error?", bad.is_error, "-", bad.content[0].text)
asyncio.run(main())
Run python test_server.py (or uv run test_server.py). You should see:
Tools: ['days_until', 'split_topics']
Plan: ['Day 1: Kinematics, Rotation', 'Day 2: Laws of Motion, Gravitation', 'Day 3: Work and Energy']
Chemistry: ['Mole Concept', 'Atomic Structure', 'Chemical Bonding', 'Thermodynamics']
Error? True - Error executing tool split_topics: Unknown subject: biology
The last line is the point of ToolError: the tool call fails safely and the model gets a message it can act on, such as asking which subject you meant.
4 Explore it in the MCP Inspector
The MCP Inspector is a browser UI for poking at a server by hand. Start it with:
uv run mcp dev study_server.py
# without uv, the Inspector can launch your server directly:
npx @modelcontextprotocol/inspector python study_server.py
Open the Tools tab, run days_until with a date such as 2027-01-22, then read syllabus://physics in the Resources tab. If the Inspector will not start, check that Node.js is installed and npx is on your PATH.
5 Connect it to Claude Desktop or Claude Code
Because mcp.run() with no arguments starts a stdio server, a desktop client can launch it as a subprocess. For Claude Desktop, the quickest way is:
uv run mcp install study_server.py
That writes an entry to claude_desktop_config.json (on macOS in ~/Library/Application Support/Claude/, on Windows in %APPDATA%\Claude\). You can also add it by hand; always use absolute paths:
{
"mcpServers": {
"study-helper": {
"command": "uv",
"args": ["run", "--with", "mcp[cli]", "mcp", "run", "/absolute/path/to/study_server.py"]
}
}
}
Fully quit and reopen Claude Desktop after editing the file. For Claude Code, one command does it:
claude mcp add study-helper -- uv run --with "mcp[cli]" mcp run /absolute/path/to/study_server.py
Now ask: "I have a physics exam on 22 January 2027. Make me a revision plan." The model should call days_until, then split_topics, and answer with a plan. If you would rather run the server over the network, the SDK also supports Streamable HTTP: uv run mcp run study_server.py --transport streamable-http.
6 Keep your MCP server safe
An MCP server runs on your machine with your permissions, and the model decides when to call it. The same rules from the agent tutorial apply:
- Narrow, read-only tools first. Our tools only compute and read a dictionary. Think hard before adding tools that delete files, send messages or run shell commands.
- Validate every input.
split_topicsrejects unknown subjects and zero days. Never pass model input toeval()or a shell. - Only install servers you trust. A third-party MCP server is code you run. Read it, or use servers from sources you trust.
- Treat text from resources as untrusted. Web pages and files can contain instructions aimed at the model; see our prompt injection guide.
Practice Task
Extend the server on your own, then check yourself with the quiz below.
- Add a
"maths"subject toSYLLABUSand confirm it appears throughsyllabus://maths. - Make
days_untilraise aToolErrorwith a friendly message when the date is in the past or not in YYYY-MM-DD format. - Add a
pomodoro_count(hours: float) -> inttool that returns how many 25-minute sessions fit, and test it withClient. - Load
SYLLABUSfrom asyllabus.jsonfile so you can edit topics without touching code.
MCP Server Tutorial Quiz
Five quick questions on this tutorial.
Frequently Asked Questions
What is an MCP server?
An MCP server is a small program that exposes tools, resources and prompts through the Model Context Protocol, so any MCP client such as Claude Desktop, Claude Code, Cursor or VS Code can use them.
Is FastMCP the same as MCPServer?
In version 1 of the official Python SDK the class was FastMCP, imported from mcp.server.fastmcp. Version 2 renamed it to MCPServer, imported from mcp.server, and removed the old import path.
Do I need an API key to build an MCP server?
No. The server itself calls no model, so it needs no API key. The client app you connect it to handles the model.
What is the difference between a tool and a resource in MCP?
A tool is a function the model can call to do something or compute something. A resource is read-only data the client can load into context, addressed by a URI.
How do I test an MCP server without Claude Desktop?
Run uv run mcp dev server.py to open the MCP Inspector, or write a short Python test with the SDK's Client class, as this tutorial shows.
Sources
- MCP Python SDK documentation (v2)
- MCP Python SDK: what's new in v2 (FastMCP renamed to MCPServer)
- MCP Python SDK: connect a server to a real host
- The mcp package on PyPI
- Model Context Protocol official site
Code run and checked against mcp 2.3.0 on Python 3.13 on November 21, 2026. If you are on SDK version 1, upgrade rather than mixing v1 and v2 imports.