Tutorial · Python · Model Context Protocol
Write one useful tool, test it in memory and over stdio, then connect it to Claude Code – with the two mistakes that quietly break servers.
This guide builds a small but production-shaped MCP server in Python with the official SDK v2: one read-only tool, input validation that reports useful errors, automated tests, a check over real stdio, and a connection to Claude Code. Every command and output below comes from a real run.
Tested with: MCP Python SDK 2.3.0, Python 3.13, Claude Code 2.1.318, Linux. The SDK documentation lists Python 3.11+ for v2.
What an MCP server is (in one picture)
The Model Context Protocol lets an AI app (the host) call tools that live outside it. A local server is just a program the host starts as a subprocess; they exchange JSON-RPC messages over stdin and stdout.
Step 1 – Install the SDK
$ python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\Activate.ps1 $ pip install "mcp[cli]>=2,<3" $ pip show mcp | grep Version Version: 2.3.0
Pinning >=2,<3 matters: v2 renamed FastMCP to MCPServer, and the old import fails outright:
$ python -c "from mcp.server.fastmcp import FastMCP" ModuleNotFoundError: No module named 'mcp.server.fastmcp'. This is mcp 2.x, where FastMCP was renamed to MCPServer ...
So most v1 tutorials need small changes – the SDK’s migration guide lists them.
Step 2 – Write the server
Our example answers “what does X cost and is it in stock?” from a CSV file. Save this as products.csv:
sku,name,price_usd,stock
KB-100,Mechanical keyboard,89.00,14
MS-220,Wireless mouse,29.50,0
HD-310,USB-C hub,45.00,7
And this as server.py:
"""Product lookup MCP server: read-only search over products.csv."""
import csv
import logging
import sys
from pathlib import Path
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
# stdout carries the MCP protocol, so logs must go to stderr
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
DATA = Path(__file__).with_name("products.csv")
mcp = MCPServer("Product Lookup")
def load():
with DATA.open(newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
@mcp.tool()
def find_product(query: str, limit: int = 5) -> list[dict]:
"""Find products by SKU or name. Read-only. Use when the user asks about a product's price or stock."""
q = query.strip().lower()
if not 1 <= len(q) <= 60:
raise ToolError("query must be 1-60 characters")
if not 1 <= limit <= 20:
raise ToolError("limit must be between 1 and 20")
hits = [r for r in load() if q in r["sku"].lower() or q in r["name"].lower()]
return [{"sku": r["sku"], "name": r["name"], "price_usd": float(r["price_usd"]),
"in_stock": int(r["stock"]) > 0} for r in hits[:limit]]
if __name__ == "__main__":
mcp.run() # stdio transport by default
Three choices in this file do most of the work:
- The docstring is for the model. The host shows it to the model as the tool description, so say what the tool does and when to use it.
- Arguments are validated – length and range – before anything is read. Cap everything that controls how much data comes back.
- Expected failures raise
ToolError. More on why below; it changes what the model sees.
Step 3 – Test it without a host
The SDK ships a Client that can connect to the server object in memory, so tests need no subprocess and no AI app:
import asyncio
import json
import logging
import unittest
from mcp import Client
from server import mcp
logging.getLogger("mcp").setLevel(logging.WARNING)
def call(name, args):
async def go():
async with Client(mcp) as client:
tools = await client.list_tools()
result = await client.call_tool(name, args)
return tools, result
return asyncio.run(go())
class TestServer(unittest.TestCase):
def test_lists_one_tool(self):
tools, _ = call("find_product", {"query": "kb"})
self.assertEqual([t.name for t in tools.tools], ["find_product"])
def test_finds_by_name(self):
_, result = call("find_product", {"query": "mouse"})
self.assertFalse(result.is_error)
self.assertEqual(json.loads(result.content[0].text)["sku"], "MS-220")
def test_blank_query_is_a_tool_error(self):
_, result = call("find_product", {"query": " "})
self.assertTrue(result.is_error)
self.assertIn("1-60 characters", result.content[0].text)
def test_limit_is_checked(self):
_, result = call("find_product", {"query": "a", "limit": 500})
self.assertTrue(result.is_error)
if __name__ == "__main__":
unittest.main()
$ python -m unittest -v test_server.py test_blank_query_is_a_tool_error (test_server.TestServer.test_blank_query_is_a_tool_error) ... ok test_finds_by_name (test_server.TestServer.test_finds_by_name) ... ok test_limit_is_checked (test_server.TestServer.test_limit_is_checked) ... ok test_lists_one_tool (test_server.TestServer.test_lists_one_tool) ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.084s OK
Step 4 – Test it over stdio, like a host does
In-memory tests skip the transport. This client starts server.py as a subprocess, exactly as Claude Code will:
"""Call the server the way a host does: start it as a subprocess over stdio."""
import asyncio
import sys
from mcp import Client
from mcp.client.stdio import StdioServerParameters
async def main():
params = StdioServerParameters(command=sys.executable, args=["server.py"])
async with Client(params) as client:
tools = await client.list_tools()
print("tools:", [t.name for t in tools.tools])
ok = await client.call_tool("find_product", {"query": "hub"})
print("is_error:", ok.is_error, "| structured:", ok.structured_content)
bad = await client.call_tool("find_product", {"query": ""})
print("is_error:", bad.is_error, "|", bad.content[0].text)
asyncio.run(main())
$ python demo_client.py 2>/dev/null
tools: ['find_product']
is_error: False | structured: {'result': [{'sku': 'HD-310', 'name': 'USB-C hub', 'price_usd': 45.0, 'in_stock': True}]}
is_error: True | Error executing tool find_product: query must be 1-60 characters
Note that the return value arrives as structured content as well as text, because the function has a return type annotation (list[dict]).
For clicking through tools by hand, mcp dev server.py opens the MCP Inspector in your browser (it needs Node.js / npx).
Step 5 – Connect it to Claude Code
Run this in your terminal (not inside a Claude session). Everything after -- is the command Claude Code runs to start your server; use absolute paths so it works from any directory:
$ claude mcp add products -- /path/to/product-lookup/.venv/bin/python /path/to/product-lookup/server.py Added stdio MCP server products with command: /path/to/product-lookup/.venv/bin/python /path/to/product-lookup/server.py to local config $ claude mcp list Checking MCP server health… products: /path/to/product-lookup/.venv/bin/python /path/to/product-lookup/server.py - √ Connected
Our terminal printed √; most terminals show ✔ Connected. Start claude and ask something like “What does the USB-C hub cost?” – the tool call is labelled with the server name. Inside a session, /mcp shows the server and its tools.
| Scope flag | Saved in | Available to |
|---|---|---|
--scope local (default) | ~/.claude.json, under this project | You, this project only |
--scope project | .mcp.json in the project root | Everyone who clones the repo (after approving it) |
--scope user | ~/.claude.json, top-level mcpServers | You, all projects |
For the Claude Desktop chat app, the SDK’s CLI has mcp install server.py, which writes the entry into the desktop app’s config for you.
Gotcha 1: plain exceptions hide your message
We raised the same validation error two ways (the first in a throwaway test tool called boom) and compared what the client received:
| Raised in the tool | is_error | Text the model sees |
|---|---|---|
raise ValueError("query must be 1-60 characters") | True | Error executing tool boom |
raise ToolError("query must be 1-60 characters") | True | Error executing tool find_product: query must be 1-60 characters |
With a plain exception the model only learns that something failed, so it cannot correct its input. Use ToolError for anything the caller can fix; let genuine bugs stay plain exceptions so internals don’t leak.
Gotcha 2: never print to stdout
Stdout is the protocol channel. We added one print() at startup and checked two clients:
$ claude mcp list products-broken: /path/to/product-lookup/.venv/bin/python /path/to/product-lookup/server_broken.py - √ Connected $ python demo_client2.py server_broken.py # excerpt pydantic_core._pydantic_core.ValidationError: 1 validation error for union[JSONRPCRequest,JSONRPCNotification,JSONRPCResponse,JSONRPCError] Invalid JSON: expected value at line 1 column 1 [type=json_invalid, input_value='Product Lookup server starting...', input_type=str] tools: ['find_product']
Both survived this time – Claude Code connected and the Python client logged a validation error, then carried on. Don’t rely on that tolerance: other hosts may drop the connection, and output that happens to look like JSON can corrupt a real message. Log with logging to stderr, as server.py does.
A checklist before you share a server
- One job per tool, with a docstring that says when to use it.
- Every argument validated: type, length, range; allow-lists for anything that picks a file, table or column.
- Results capped (
limit), and explicit fields such asin_stockrather than raw rows. ToolErrorfor fixable input, plain exceptions for bugs.- No
print(); logs to stderr. - Read-only by default. If a tool must change something, have it return a draft and let a person apply it.
- Tests in memory and one check over stdio.
Get a tested starter server
The free starter has a complete FAQ-search server with the same structure (logic in core.py, MCP adapter in server.py), 6 tests and a one-page cheat sheet. The full pack adds nine more servers – CSV aggregation with allow-lists, JSON diff, triage, threshold checks, citation audit and draft-only approvals – with 60 tests, a stdio smoke test for every server and a 16-point security checklist.
FAQ
Do I need Claude to build an MCP server?
No. The server is plain Python; the in-memory and stdio tests above use only the SDK. You need a host only to use it from an AI app.
stdio or HTTP?
Start with stdio for tools that run on your own machine. Use an HTTP transport when the server must run remotely or serve several users – that also means adding authentication.
Will this work with other MCP hosts?
The server speaks the standard protocol, so any MCP host that supports stdio servers can start it. Config file names and locations differ per host; check its documentation.
Sources
- MCP Python SDK v2 documentation
- mcp on PyPI
- MCP Python SDK v2 migration guide
- Claude Code: Connect to MCP servers
- Model Context Protocol introduction
AI Stack Nav is independent. Product names are trademarks of their owners.