How to Build an MCP Server in Python in 30 Minutes
Why build your own MCP server?
Most AI agents are only as useful as the tools they can reach. If every new capability needs custom glue code for every app, integration work grows with each combination of model and data source. The Model Context Protocol (MCP) gives models one standard way to discover tools, read resources, and use prompts. Instead of wiring your notes into each host separately, you build one server and let any MCP-compatible host talk to it.
In this tutorial you will build a small, local notes server with the official Python SDK. It exposes two tools and one resource, you will test it with the MCP Inspector, and you will prove it works over HTTP with a tiny client. Everything stays on your machine: no deployment, no public endpoint, and no credentials to manage. It pairs with our guide to giving a local LLM tools with Ollama.
Source: Microsoft Learn — MCP server architecture overview.
What an MCP server actually exposes
An MCP server offers three primitives, and choosing the right one is most of the design work. Tools are functions the model can call, with user approval, to do something: search files or query a database. Resources are read-only data the model pulls in as context, addressed by a URI like notes://ideas.md. Prompts are reusable templates for a recurring task.
For a first server, keep the surface small and read-only. A server that only lists and reads notes is easy to test and impossible to misuse destructively. Add a write tool later, once you have decided which writes are allowed and how they will be confirmed.
Two transports matter. Stdio is the local default: the host launches your server as a subprocess and talks to it over standard input and output, with no network port involved. Streamable HTTP is the network transport, used in the client test below. Start with stdio, and only move to HTTP when you need remote access.
Prerequisites
- Python 3.11 or newer, as required by the current official Python SDK.
uv, the fast Python package manager, for project setup and running commands.- A text editor and a terminal. No API key, cloud account, or GPU is needed.
Step 1: Create the project
Create a project folder and install the SDK with its command-line extra, which adds the mcp command used for testing:
uv init notes-mcp
cd notes-mcp
uv add "mcp[cli]"
mkdir notes
Add one sample note so the server has something real to serve:
echo "# Ideas" > notes/ideas.md
echo "- Build a notes MCP server" >> notes/ideas.md
Step 2: Write the server
Create server.py. The SDK turns type hints into tool input schemas and docstrings into tool descriptions, so write both carefully: the model reads them when deciding whether and how to call your tool.
from pathlib import Path
from mcp.server import MCPServer
NOTES_DIR = Path("notes")
mcp = MCPServer("Notes")
def _note_path(name: str) -> Path:
path = (NOTES_DIR / name).resolve()
if path.parent != NOTES_DIR.resolve():
raise ValueError("Notes must stay directly inside the notes folder.")
return path
@mcp.tool()
def list_notes() -> list[str]:
"""List the note files available in the notes folder."""
return sorted(p.name for p in NOTES_DIR.glob("*.md"))
@mcp.tool()
def read_note(name: str) -> str:
"""Read one note file by name, for example 'ideas.md'."""
return _note_path(name).read_text(encoding="utf-8")
@mcp.resource("notes://{name}")
def note_resource(name: str) -> str:
"""Expose a note as a readable MCP resource."""
return _note_path(name).read_text(encoding="utf-8")
if __name__ == "__main__":
mcp.run()
Notice the guard in _note_path: a tool that takes a filename must never let a caller escape its folder with a path like ../secrets.txt. Copy this check into any file-serving tool you build next.
Step 3: Test it with the MCP Inspector
The MCP Inspector is a browser-based debugger for MCP servers. It lists your tools and resources and lets you call them without wiring up a full host first. Launch it against your server:
uv run mcp dev server.py
In the Inspector, call list_notes and confirm it returns ideas.md. Then call read_note with ideas.md and confirm the note text comes back. If a tool does not appear, the usual cause is a missing type hint or a syntax error in server.py; the Inspector surfaces both faster than a chat host will.
Step 4: Prove it over HTTP with a small client
Next, serve the same server over Streamable HTTP and check it from a separate client process. In one terminal, run:
uv run mcp run server.py --transport streamable-http
In another terminal, create client.py:
import asyncio
from mcp import Client
async def main() -> None:
async with Client("http://localhost:8000/mcp") as client:
notes = await client.call_tool("list_notes", {})
print(notes)
asyncio.run(main())
Run it with uv run client.py. You should see the tool result for list_notes, which proves the server answers real MCP clients, not just the Inspector. This client pattern is also the seed of something bigger: the same Client can drive your server from an agent loop, which is how a server like this plugs into building an AI agent with LangGraph or any other agent framework.
Step 5: Connect it to a host
Once the Inspector and client tests pass, connect the server to a host such as Claude Desktop. Following the official tutorial's pattern, the configuration looks like this, with the path replaced by your own absolute project path:
{
"mcpServers": {
"notes": {
"command": "uv",
"args": ["--directory", "/ABSOLUTE/PATH/TO/notes-mcp", "run", "server.py"]
}
}
}
Save the configuration and restart the host. Then ask it to list your notes. If the server does not show up, check three things: the path is absolute, not relative; the host was fully restarted; and the project contains server.py and the notes folder. Relative paths are the most common cause of a silently missing server.
Troubleshooting
- Never print to stdout in a stdio server. Stdout carries protocol messages, so a stray
print()corrupts them. Log to stderr or a file instead. - Bind HTTP to localhost only. An unauthenticated HTTP server is an open door to your files. Keep it on
127.0.0.1locally, and add authentication before exposing it elsewhere. - Keep tool descriptions specific. Vague descriptions produce vague tool calls. Name the expected input format, as in "by name, for example 'ideas.md'".
- Start read-only, then add writes deliberately. A write tool needs confirmation, backups, or both. Ship the read-only version first and let real usage tell you which write is worth the risk.
Where to go next
You now have a working pattern, not just a demo: a guarded file tool, a resource, an Inspector test, and a client check. Natural next steps are a search tool that greps note contents or a write tool with an explicit confirmation step. If you want the server to sit alongside a chat interface and retrieval, assembling a local AI stack with Docker, Ollama, Open WebUI, and Qdrant shows how the pieces fit together on one machine.
The deeper lesson is that MCP servers are ordinary programs with a standard contract. Build them small, guard their inputs, and test them outside any chat host, and they become reusable building blocks for every agent you run.

Comments
Post a Comment