Skip to content

Build Your First MCP Server (Python, Step by Step)

From “Claude can’t see that” to “Claude can use that”

Section titled “From “Claude can’t see that” to “Claude can use that””

An MCP server is a small program that gives Claude new abilities: read your notes, query your database, call your company’s API. The Model Context Protocol is the open standard that lets any compatible client (Claude Code, Claude Desktop and many others) discover those abilities and use them.

In this guide you will build a real one: a notes server that lets Claude save and search notes in a local file. It is small enough to understand in one sitting and shaped like the servers you will build later. Every snippet here was run and tested with the official Python SDK (version 2.3).

If you are not sure yet whether you need an MCP server, a skill or a hook, read Claude Code Extensions first.

CapabilityWhat it isExample in this guide
ToolsFunctions Claude can call (with your approval)add_note, search_notes
ResourcesRead-only data a client can load, like a filenotes://all
PromptsReusable prompt templates the user can pickNot used here

Most servers are mainly tools, so that is where we will spend our time.

You need Python 3.10 or newer and uv, a fast Python project manager.

Terminal window
# Install uv (macOS/Linux). On Windows, see docs.astral.sh/uv
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create the project and add the official SDK
uv init notes-server
cd notes-server
uv add "mcp[cli]"

Create notes_server.py:

import json
import logging
from datetime import datetime
from pathlib import Path
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
logger = logging.getLogger(__name__) # logs go to stderr, never stdout
NOTES_FILE = Path(__file__).parent / "notes.json"
mcp = MCPServer("notes")
def load_notes() -> list[dict]:
if not NOTES_FILE.exists():
return []
return json.loads(NOTES_FILE.read_text(encoding="utf-8"))
def save_notes(notes: list[dict]) -> None:
NOTES_FILE.write_text(json.dumps(notes, indent=2, ensure_ascii=False), encoding="utf-8")
@mcp.tool()
def add_note(title: str, body: str, tag: str = "general") -> str:
"""Save a new note.
Args:
title: Short title for the note
body: The note text
tag: One-word category, e.g. work, ideas, reading
"""
if not title.strip():
raise ToolError("The title cannot be empty.")
notes = load_notes()
notes.append({
"id": len(notes) + 1,
"title": title.strip(),
"body": body.strip(),
"tag": tag.strip().lower(),
"created": datetime.now().isoformat(timespec="minutes"),
})
save_notes(notes)
logger.info("Saved note %s", title)
return f"Saved note #{len(notes)}: {title}"
@mcp.tool()
def search_notes(query: str, tag: str | None = None) -> str:
"""Find notes whose title or body contains the query.
Args:
query: Word or phrase to look for (case-insensitive)
tag: Optional tag to limit the search to
"""
q = query.lower()
hits = [
n for n in load_notes()
if (q in n["title"].lower() or q in n["body"].lower())
and (tag is None or n["tag"] == tag.lower())
]
if not hits:
return "No matching notes."
return "\n\n".join(f"#{n['id']} [{n['tag']}] {n['title']}\n{n['body']}" for n in hits)
@mcp.resource("notes://all")
def all_notes() -> str:
"""Every saved note, as JSON."""
return json.dumps(load_notes(), indent=2, ensure_ascii=False)
if __name__ == "__main__":
mcp.run(transport="stdio")

What is happening:

  • @mcp.tool() turns a normal Python function into a tool. The SDK builds the tool’s definition from your type hints (which arguments exist, which are optional) and your docstring (what the tool and each argument mean). That docstring is what Claude reads to decide when and how to call the tool, so write it for Claude.
  • ToolError sends a clean error message back to Claude instead of crashing the server. Claude sees “The title cannot be empty.” and can fix its own call.
  • @mcp.resource() exposes read-only data at an address (notes://all).
  • transport="stdio" means the client starts your script as a local process and talks to it through standard input and output.

The one rule that breaks most first servers

Section titled “The one rule that breaks most first servers”

Never write to stdout in a stdio server. That channel carries the protocol messages, so a single stray print() corrupts them and the client disconnects with a confusing error. Use the logging module, which writes to stderr, as the example does.

The SDK ships with a visual tester, the MCP Inspector:

Terminal window
uv run mcp dev notes_server.py

It needs Node.js installed, because the Inspector runs through npx. It opens in your browser. Click Tools, run add_note with a test title, then search_notes, and check the Resources tab. Testing here first means that when something fails later, you know the problem is the connection, not your code.

From any terminal, register the server. Everything after -- is the command that starts it:

Terminal window
claude mcp add --transport stdio notes -- uv --directory /ABSOLUTE/PATH/TO/notes-server run notes_server.py

Choose who gets it with --scope:

ScopeWho can use itStored in
local (default)Only you, only in the current project~/.claude.json
projectEveryone on the project, via version control.mcp.json in the project root
userOnly you, in every project~/.claude.json

Then start Claude Code, run /mcp to confirm the server shows as connected, and try: “Save a note titled ‘MCP guide’ tagged work, then find all my work notes.” Claude will ask for permission the first time it uses each tool.

Useful commands: claude mcp list shows every server and its health, and claude mcp remove notes removes it.

Open the Claude Desktop config file (on macOS: ~/Library/Application Support/Claude/claude_desktop_config.json), add the server and restart the app:

{
"mcpServers": {
"notes": {
"command": "uv",
"args": ["--directory", "/ABSOLUTE/PATH/TO/notes-server", "run", "notes_server.py"]
}
}
}

If it does not appear, use the full path to uv in command (find it with which uv on macOS/Linux or where uv on Windows). Relative paths are the most common cause of “server failed to start”.

7. Design tools Claude can actually use well

Section titled “7. Design tools Claude can actually use well”

The code is the easy part. These choices decide whether Claude uses your server well (see Context Engineering for the reasoning):

  • Few tools, clear jobs. If you cannot say in one sentence when to use each tool, Claude cannot either. Two tools that overlap is a design bug.
  • Docstrings are the interface. Name the arguments plainly, give an example value, and say what the tool returns.
  • Return what Claude needs, not everything you have. A search that returns 500 full records floods the context. Return the top matches, short.
  • Make errors helpful. “No notes tagged ‘wrok’. Existing tags: work, ideas” lets Claude fix the call on the next try. A stack trace does not.
  • Separate reading from changing. Keep read-only tools and tools that write, send or delete apart, so it is obvious which ones need extra care.

An MCP server runs with your permissions and can touch real data.

  • Least privilege: give the server only the folders, keys and scopes it needs. A notes server does not need your whole disk.
  • Secrets in environment variables, never hard-coded: claude mcp add --env NOTES_API_KEY=... ....
  • Treat tool output as untrusted. Text your server returns from the web or from emails can contain instructions aimed at the model (prompt injection). See Security & Insulation.
  • Install third-party servers like any software: check who maintains them and what they can access.
  • Wrap a real API: swap the JSON file for your CRM, ticket system or database. The decorators stay the same.
  • Go remote: for a server other people use over the internet, switch to the HTTP transport and add authentication; Claude Code connects with claude mcp add --transport http <name> <url>.
  • Package it: once a second project needs it, bundle it into a Claude Code plugin with the skill that teaches Claude how to use it.

Sources: Build an MCP server (Model Context Protocol docs) and Connect Claude Code to tools via MCP (Claude Code docs). SDK details change between versions; this guide was tested with the Python MCP SDK 2.3.