AI Engineering Β· Build lab 11 of 14
Build an MCP server in Python: tools, resources, prompts, tests and a local agent
Build a Model Context Protocol server in Python with the official SDK: typed tools, a resource and a prompt over stdio. Test it with the MCP Inspector, a Python client and pytest, plug it into Claude Desktop, drive it from a local-model agent, and serve it over HTTP.
β± 75 minIntermediateπΈ Free (local model)10 steps
Python 3.12uvmcp 2.3 (official MCP Python SDK)Ollamallama3.2:3bopenai SDKpytestMCP Inspector (Node.js, optional)
Overview video
What you will build
A team-notes MCP server: a small program that gives any AI app safe access to a folder of Markdown notes. It offers three tools (search the notes, read one, add one), a resource (the list of notes, and each note by address) and a prompt (a ready-made "summarize the notes about X" request).
MCP (Model Context Protocol) is the standard plug between AI apps and your code. You write the server once; desktop chat apps, IDEs and your own agents all connect to it the same way. In this lab you connect it to four clients: the MCP Inspector (a test UI), a Python client you write, Claude Desktop, and an agent loop that lets the free local model from lab 1 call your tools.
Along the way you make it safe: every argument is validated before your code runs, note names cannot escape the folder, writes never overwrite, the agent only gets the read-only tools, and there is no shell anywhere. Everything is tested with pytest, without a model.
Before you start
- Lab 1 done: Your first LLM call. This lab reuses its
.envandconfig.py. - Lab 4 helps a lot: Tool calling by hand. Step 8 reuses its agent loop; here the tools come from an MCP server instead of your own Python functions.
- Python you will see: async and await (the MCP SDK is async) and Type hints and Pydantic (
Annotated,Field). Each new piece is explained where it appears. - The idea behind it (8 minutes): The Model Context Protocol.
Setup
S1Install uv (the Python project tool)
uv installs Python for you, creates the virtual environment and manages packages. One tool instead of pyenv + venv + pip. Already have it from lab 1? Skip to the next item.
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" everything's installed!
S2Check uv works
The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.
uv --version uv 0.x.y
S3Install Ollama (runs models on your machine)
Only needed for step 8, where an agent uses the server. Download it from ollama.com/download and open it once. It runs a small server on port 11434 that speaks the same chat API as the hosted providers, tool calling included.
ollama --version ollama version is 0.x.y
S4Pull the model (llama3.2:3b, about 2 GB)
Skip this if you pulled it for lab 1. llama3.2:3b was trained for tool calling, which step 8 needs. ollama show llama3.2:3b lists tools under Capabilities.
ollama pull llama3.2:3b pulling manifest ... success
S5Node.js, for the MCP Inspector (optional)
The MCP Inspector (step 5) is a Node.js app you start with npx, the Node package runner (like uv run for JavaScript tools). The current Inspector needs Node 22.23.4 or newer on the 22 line, or 24.22.1 or newer on the 24 line. Get it from nodejs.org if node --version shows an older version or nothing. You can skip the Inspector: steps 6 and 10 test the server from Python.
node --version v24.x.y
S6Claude Desktop (optional)
Step 7 plugs the server into a desktop AI app. The lab uses Claude Desktop because its config file is a simple JSON file; other MCP hosts (IDEs, other chat apps) take the same command in their own config. Install it from its website and open it once, so it creates its settings folder. You can skip step 7 and do everything else.
Create the project
A fresh project with the MCP SDK, the OpenAI SDK and pytest, plus the settings from lab 1.
uv init creates a folder with pyproject.toml (the project file, like package.json or pom.xml). uv add installs packages into the project's own virtual environment and records them, so anyone can recreate it with uv sync.
Packages: mcp is the official MCP Python SDK. It holds both halves: the server you build and a client to test it. openai is the SDK from lab 1, used in step 8 to talk to Ollama. python-dotenv reads .env, and pytest runs the tests (a dev dependency, like testImplementation in Gradle).
This lab uses mcp 2.x, the current major version. It renamed a few things: the server class that 1.x tutorials call FastMCP (from mcp.server.fastmcp import FastMCP) is now MCPServer. If you follow an older tutorial, that is the first line that changes.
Then create the three files below. .env and config.py are lab 1's, plus one new setting: notes_dir, the folder the server is allowed to use.
# Local model through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
# Where the notes live. Leave it commented out to use the notes folder next to server.py.
# NOTES_DIR=/absolute/path/to/notes - Ollama's OpenAI-compatible API, the same as lab 1. Only the agent in step 8 uses it: the MCP server itself never talks to a model.line 2
- A
#comments the line out. Uncomment it to serve a different folder. Use an absolute path: AI apps start your server from their own working folder, not yours.line 7
import os
from dataclasses import dataclass
from pathlib import Path
from dotenv import load_dotenv
load_dotenv() # read .env into environment variables (real env vars win)
HERE = Path(__file__).resolve().parent
@dataclass(frozen=True)
class Settings:
base_url: str
api_key: str
model: str
notes_dir: Path
def settings() -> Settings:
return Settings(
base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
api_key=os.environ.get("LLM_API_KEY", "ollama"),
model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
notes_dir=Path(os.environ.get("NOTES_DIR", HERE / "notes")),
) load_dotenv()copies.envintoos.environ. Variables already set in your shell win, which is what you want on a server.line 7__file__is the path of this file..resolve().parentis its folder as an absolute path, soHERE / "notes"works no matter which folder the server was started from. The/operator joins paths, likePath.resolve()in Java.line 9frozen=Truemakes the settings read-only, like a Java record.line 12- The one new setting.
os.environ.get(name, default)returns the default when the variable is missing, so by default the server uses thenotesfolder next to it.line 25
.venv/
__pycache__/
.env - Never commit
.env: one day it holds a real key.line 3
uv init team-notes-mcp
cd team-notes-mcp
uv add mcp openai python-dotenv
uv add --dev pytest Initialized project `team-notes-mcp` at `.../team-notes-mcp` Resolved 35 packages in 420ms Installed 32 packages in 36ms + anyio==4.16.0 + mcp==2.3.0 + openai==3.60.0 + pydantic==2.14.4 + python-dotenv==1.2.4 + uvicorn==0.55.0 ...
Stuck on this step?
uv: command not found- Run
export PATH="$HOME/.local/bin:$PATH"(macOS and Linux), or open a new terminal so the installer's PATH change applies. - uv also created
main.py - Newer uv versions write a hello-world
main.py. This lab does not use it: delete it. - You see
mcp==1.xin the output - An old version was pinned somewhere. Run
uv add "mcp>=2.3,<3"to get the version this lab is written for.
The notes, and a store that cannot leave its folder
Plain Python that reads, searches and adds notes, and refuses any name that could reach a file outside the notes folder.
Write the notes logic before any MCP code. An MCP server is a thin layer over ordinary code, and that code should be testable on its own. Make a folder called notes with the three files below.
Now the security part, because an MCP server is a door into your machine. The model (or whoever controls the text it reads) chooses the arguments. If read_note accepted any path, the request read_note("../../.ssh/id_rsa") would read your private SSH key. This is called path traversal, and it is the classic bug in file tools.
The fix is an allow-list: a note name may only contain lowercase letters, digits and dashes (server-costs), checked with a regular expression. No dots and no slashes means no way out of the folder. Checking for a good shape is much safer than trying to spot every bad one (.., /, \, URL-encoded tricks, ...).
# Server costs, March
The two app servers cost 140 dollars a month each.
The database costs 310 dollars a month. Backups add 25 dollars.
Idea: move the staging server to a smaller size to save about 60 dollars. # Onboarding a new developer
Day 1: laptop, accounts, read the architecture page.
Day 2: run the app locally and fix one small bug.
Ask the team lead for access to the production logs. # Release checklist
Run the tests and the database migrations on staging first.
Check the error dashboard for 30 minutes after the release.
Write the release notes for the support team. import re
from pathlib import Path
NAME_PATTERN = r"^[a-z0-9][a-z0-9-]{0,49}$"
MAX_NOTE_CHARS = 10_000
class NoteError(Exception):
"""A problem the caller can fix: a bad name, a missing note, a note that is too long."""
class NoteStore:
"""Markdown notes in one folder. Nothing outside that folder can be read or written."""
def __init__(self, folder: Path):
self.folder = Path(folder).resolve()
def _path(self, name: str) -> Path:
if not re.fullmatch(NAME_PATTERN, name):
raise NoteError(f"invalid note name {name!r}: use lowercase letters, digits and dashes")
return self.folder / f"{name}.md"
def names(self) -> list[str]:
return sorted(p.stem for p in self.folder.glob("*.md") if re.fullmatch(NAME_PATTERN, p.stem))
def read(self, name: str) -> str:
path = self._path(name)
if not path.is_file():
raise NoteError(f"no note called {name!r}. Known notes: {', '.join(self.names())}")
return path.read_text(encoding="utf-8")
def search(self, query: str, limit: int = 5) -> list[dict]:
words = query.lower().split()
hits = []
for name in self.names():
text = self.read(name)
score = sum(text.lower().count(word) for word in words)
if score:
hits.append({"name": name, "title": text.splitlines()[0].lstrip("# "), "score": score})
hits.sort(key=lambda hit: (-hit["score"], hit["name"]))
return hits[:limit]
def add(self, name: str, text: str) -> None:
path = self._path(name)
if len(text) > MAX_NOTE_CHARS:
raise NoteError(f"the note has {len(text)} characters; the limit is {MAX_NOTE_CHARS}")
if path.exists():
raise NoteError(f"a note called {name!r} already exists")
self.folder.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8") - The allow-list.
^and$mark the start and the end;[a-z0-9]is one lowercase letter or digit;[a-z0-9-]{0,49}is up to 49 more, dashes allowed. So 1 to 50 characters, never starting with a dash.r"..."is a raw string: backslashes stay as they are, handy for regexes.line 4 - A size limit on new notes. Every input from a model needs a limit: without one, a confused model can fill your disk.line 5
- One exception type for problems the **caller** can fix. The server turns it into a message the model reads (step 4).line 8
.resolve()makes the folder absolute once, at the start.line 16- The leading
_marks a private helper by convention. Python has noprivatekeyword.line 18 re.fullmatchsucceeds only if the **whole** name matches, likeString.matches()in Java. This one check is what keeps every read and write inside the folder.line 19- Only now is the name turned into a path.
self.folder / f"{name}.md"can only ever be a file directly in the notes folder.line 21 - Every
.mdfile in the folder, as names without the extension (p.stem). Files whose names break the pattern are skipped, soreadnever sees them.line 24 - A helpful error: say what exists. The model reads this and can pick a real name on its next try.line 29
- A deliberately simple keyword search: count how often each query word appears. A real server might use the embeddings search from the search labs; the MCP part would not change.line 37
- The first line of the note without the leading
#, so# Server costs, MarchbecomesServer costs, March.line 39 - Sort by score, highest first (
-score), and by name when scores tie, so the order is always the same.line 40 - Writes never overwrite. A tool that can replace a file can destroy it, so "add" and "replace" would be two tools with two decisions.line 47
from config import settings
from store import NoteError, NoteStore
store = NoteStore(settings().notes_dir)
print("notes:", store.names())
for hit in store.search("server costs"):
print("hit:", hit)
print("first line:", store.read("onboarding").splitlines()[0])
for name in ["../../.ssh/id_rsa", "/etc/passwd", "Server-Costs", "holidays"]:
try:
store.read(name)
except NoteError as e:
print("refused:", e) - "server" appears 3 times in server-costs.md (the heading, "app servers", "staging server") and "costs" twice: a score of 5.line 6
- Three attacks and one honest mistake. All four must fail with a clear
NoteError.line 10
uv run try_store.py notes: ['onboarding', 'release-checklist', 'server-costs']
hit: {'name': 'server-costs', 'title': 'Server costs, March', 'score': 5}
first line: # Onboarding a new developer
refused: invalid note name '../../.ssh/id_rsa': use lowercase letters, digits and dashes
refused: invalid note name '/etc/passwd': use lowercase letters, digits and dashes
refused: invalid note name 'Server-Costs': use lowercase letters, digits and dashes
refused: no note called 'holidays'. Known notes: onboarding, release-checklist, server-costs Stuck on this step?
notes: []- The
notesfolder is not next toconfig.py, or the files do not end in.md. Check withls notes(Windows:dir notes).
Your first MCP server: one tool
Turn `search_notes` into an MCP tool and see the schema the SDK builds from your type hints and docstring.
An MCP server offers things to AI apps. Three words to keep straight: the host is the AI app the user talks to (a desktop chat app, an IDE, your agent); inside it, an MCP client connects to one server; the server is what you build. The server never talks to a model. It answers requests such as "list your tools" and "call this tool with these arguments", sent as JSON-RPC messages.
MCPServer does all the protocol work. You write ordinary functions and put @mcp.tool() on them. The SDK reads three things from each function: the name (the function name), the description (the docstring, the text in triple quotes) and the arguments (the type hints). The model reads that description and schema to decide when and how to call the tool, so write them for the model: say what the tool does and give an example value.
Annotated[str, Field(...)] adds rules to an argument: min_length, ge (greater or equal), le (less or equal). They end up in the JSON Schema, and the SDK checks every call against them before your function runs. These are the same Pydantic rules as in lab 3.
How to run it: mcp.run() speaks MCP over stdio, the process's standard input and output. The AI app starts your server as a child process, writes requests to its stdin and reads answers from its stdout. You can try uv run server.py yourself: it prints nothing and waits for a client to speak first. That silence is correct. Press Ctrl+C to stop it.
To look inside without any app, show_server.py connects the SDK's own Client to the server object in the same process: no subprocess and no network. The tests in step 10 use the same trick.
from typing import Annotated
from mcp.server import MCPServer
from mcp.types import ToolAnnotations
from pydantic import BaseModel, Field
from config import settings
from store import NoteStore
store = NoteStore(settings().notes_dir)
mcp = MCPServer(
"team-notes",
instructions="Team notes. Search them before answering questions about the team.",
log_level="WARNING",
)
READ_ONLY = ToolAnnotations(read_only_hint=True, open_world_hint=False)
class Hit(BaseModel):
name: str
title: str
score: int
@mcp.tool(annotations=READ_ONLY)
def search_notes(
query: Annotated[str, Field(min_length=2, max_length=200, description="Words to look for, like 'server costs'.")],
limit: Annotated[int, Field(ge=1, le=10, description="How many notes to return at most.")] = 5,
) -> list[Hit]:
"""Search the team notes by keywords. Returns matching note names, best match first."""
return [Hit(**hit) for hit in store.search(query, limit)]
if __name__ == "__main__":
mcp.run() Annotated[type, extra]attaches extra information to a type hint. Here the extra is a PydanticFieldwith rules.line 1- The server class. mcp 1.x called it
FastMCP(inmcp.server.fastmcp); in 2.x it isMCPServer.line 3 - One store for the whole server, created when the module loads.line 10
- The server's name: hosts show it, and clients get it when they connect.line 12
instructionsis sent to the client on connect. Hosts may put it into the model's context, so keep it to one useful sentence.line 13- The SDK logs to stderr (never stdout, which carries the protocol). The default is INFO, one line per rejected call; WARNING keeps this lab's output clean and still shows crashes. Use
"INFO"or"DEBUG"while you debug.line 14 - Tool annotations are **hints** for the host: this tool only reads, and it works on a closed set of data (not the open web). A host can use them to decide whether to ask the user before running the tool. They are not security: never rely on a client honouring them.line 16
- A Pydantic model for one search hit, like a Java record. Returning typed objects gives the tool an **output schema** too, so clients get structured data.line 19
- The decorator registers the function as a tool named
search_notes. That is the whole registration.line 25 querymust be 2 to 200 characters. Thedescriptionis what the model reads about this argument.line 27= 5makeslimitoptional: it disappears fromrequiredand the schema gets"default": 5.ge=1, le=10becomes"minimum": 1, "maximum": 10.line 28- The docstring becomes the tool description. This sentence is how the model knows what the tool is for.line 30
Hit(**hit)unpacks the dict into keyword arguments:Hit(name=..., title=..., score=...). A list comprehension builds oneHitper result.line 31- Runs the server only when you start this file directly (
uv run server.py). When another file importsserver(step 3's script, the tests),__name__is"server", not"__main__", so the import does not start a server. Like amainmethod that only runs for the class you launch.line 34 - No arguments: the stdio transport. It blocks until the client disconnects.line 35
import asyncio
import json
from mcp import Client
from server import mcp
async def main() -> None:
async with Client(mcp) as client:
listing = await client.list_tools()
for tool in listing.tools:
print("name:", tool.name)
print("description:", tool.description)
print("input schema:", json.dumps(tool.input_schema, indent=2))
result = await client.call_tool("search_notes", {"query": "staging"})
print("is_error:", result.is_error)
print("content:", [block.text for block in result.content])
print("structured_content:", result.structured_content)
asyncio.run(main()) - The MCP SDK is asynchronous (async/await, like JavaScript promises).
asyncioruns the async code.line 1 - Importing
serverbuilds the server object but does not run it: theif __name__guard sees a module name, not"__main__".line 6 async defmakesmaina coroutine, like anasync functionin JavaScript.line 9Client(mcp)connects to the server object directly, in memory. The sameClientclass takes a URL (step 9) or a command to start.async withopens the connection and always closes it at the end, like try-with-resources.line 10awaitwaits for the answer without blocking, likeawaitin JavaScript. This sends thetools/listrequest.line 11input_schemais the JSON Schema the SDK built from the type hints.indent=2pretty-prints it.line 15- Calls the tool by name with a dict of arguments: the
tools/callrequest a host sends when the model asks for the tool.line 17 contentis a list of blocks the **model** reads. A list return becomes one JSON text block per item.line 19structured_contentis the same data as JSON for the **application**, checked against the output schema. A list or a plain value is wrapped in{"result": ...}.line 20- Starts the event loop and runs
main()to the end.line 23
uv run show_server.py name: search_notes
description: Search the team notes by keywords. Returns matching note names, best match first.
input schema: {
"type": "object",
"properties": {
"query": {
"description": "Words to look for, like 'server costs'.",
"maxLength": 200,
"minLength": 2,
"title": "Query",
"type": "string"
},
"limit": {
"default": 5,
"description": "How many notes to return at most.",
"maximum": 10,
"minimum": 1,
"title": "Limit",
"type": "integer"
}
},
"required": [
"query"
],
"title": "search_notesArguments"
}
is_error: False
content: ['{\n "name": "release-checklist",\n "title": "Release checklist",\n "score": 1\n}', '{\n "name": "server-costs",\n "title": "Server costs, March",\n "score": 1\n}']
structured_content: {'result': [{'name': 'release-checklist', 'title': 'Release checklist', 'score': 1}, {'name': 'server-costs', 'title': 'Server costs, March', 'score': 1}]} Stuck on this step?
ModuleNotFoundError: No module named 'mcp.server.fastmcp'- You copied code written for mcp 1.x. In 2.x write
from mcp.server import MCPServerandmcp = MCPServer("name"). uv run server.pyseems to hang- That is correct: a stdio server waits silently for a client. Press Ctrl+C. To see it work, use
uv run show_server.py.
All three MCP primitives: tools, a resource and a prompt
Add a read tool and a write tool with safe errors, the notes as resources, and a reusable prompt.
MCP servers offer three kinds of things, and the difference is who decides to use them:
- Tools are chosen by the model: it decides to call
search_noteswhile answering. Like aPOSTendpoint: it does something, and may change things. - Resources are chosen by the application: the host (or the user, from a menu) attaches a note to the conversation as context. Like a
GET: read-only data with an address, herenotes://indexandnotes://server-costs. - Prompts are chosen by the user: a ready-made request they pick from a menu, like a saved query or a slash command.
Errors come in two kinds. When a call can be fixed by a better call (a note that does not exist), raise ToolError: the call returns normally with is_error=True and your message, and the model reads it and tries again. Any other exception is treated as a crash: the model learns only that the tool failed, without the details (they could leak your internals), and the server logs the traceback. Never return an error text: it would look like a successful answer.
Notice what is not here: no tool that runs shell commands, no "read any file" tool, no "delete note". A server should offer the smallest set of narrow actions the job needs (least privilege). An MCP tool that runs a shell command hands your machine to whatever text the model last read, a web page or an email included (prompt injection).
from typing import Annotated
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ResourceNotFoundError, ToolError
from mcp.types import ToolAnnotations
from pydantic import BaseModel, Field
from config import settings
from store import MAX_NOTE_CHARS, NAME_PATTERN, NoteError, NoteStore
store = NoteStore(settings().notes_dir)
mcp = MCPServer(
"team-notes",
instructions="Team notes. Search them before answering questions about the team.",
log_level="WARNING",
)
READ_ONLY = ToolAnnotations(read_only_hint=True, open_world_hint=False)
WRITES = ToolAnnotations(read_only_hint=False, destructive_hint=False, idempotent_hint=False, open_world_hint=False)
NoteName = Annotated[str, Field(pattern=NAME_PATTERN, description="A note name like 'server-costs'.")]
class Hit(BaseModel):
name: str
title: str
score: int
@mcp.tool(annotations=READ_ONLY)
def search_notes(
query: Annotated[str, Field(min_length=2, max_length=200, description="Words to look for, like 'server costs'.")],
limit: Annotated[int, Field(ge=1, le=10, description="How many notes to return at most.")] = 5,
) -> list[Hit]:
"""Search the team notes by keywords. Returns matching note names, best match first."""
return [Hit(**hit) for hit in store.search(query, limit)]
@mcp.tool(annotations=READ_ONLY)
def read_note(name: NoteName) -> str:
"""Read one note in full. Get the name from search_notes first."""
try:
return store.read(name)
except NoteError as e:
raise ToolError(str(e)) from e
@mcp.tool(annotations=WRITES)
def add_note(
name: NoteName,
text: Annotated[str, Field(min_length=1, max_length=MAX_NOTE_CHARS, description="The note, in Markdown.")],
) -> str:
"""Save a new note. Never overwrites: fails if a note with that name exists."""
try:
store.add(name, text)
except NoteError as e:
raise ToolError(str(e)) from e
return f"saved note {name!r}"
@mcp.resource("notes://index")
def index() -> str:
"""The names of all notes, one per line."""
return "\n".join(store.names())
@mcp.resource("notes://{name}", mime_type="text/markdown")
def note(name: str) -> str:
"""One note, by name."""
try:
return store.read(name)
except NoteError as e:
raise ResourceNotFoundError(str(e)) from e
@mcp.prompt()
def summarize_notes(topic: Annotated[str, Field(description="What to summarize, like 'costs'.")]) -> str:
"""Summarize what the team notes say about a topic."""
return (
f"Use search_notes to find the notes about {topic}, read the best ones with read_note, "
"then summarize them in at most five bullet points. Name the note each fact comes from."
)
if __name__ == "__main__":
mcp.run() ToolErrorfor problems the model can fix;ResourceNotFoundErrorfor a resource address that has no data.line 4- Hints for a tool that writes: it is not read-only, it does not destroy data (
destructive_hint=False, it never overwrites) and calling it twice is not the same as once (idempotent_hint=False, the second call fails). Hosts use these to decide when to ask the user first.line 18 - A type alias: one reusable "note name" type with the regex from
store.py.patterngoes into the JSON Schema, so a bad name is refused before your function runs. The store checks again: two layers.line 19 - A second tool. The argument type is the alias, so the schema says
"pattern": "^[a-z0-9][a-z0-9-]{0,49}$".line 38 raise X from ekeeps the original exception attached, likenew RuntimeException(msg, cause). The model sees "Error executing tool read_note: no note called ...".line 43- The write tool.
max_lengthmatches the store's limit, so an oversized note is refused by the schema check already.line 49 - The docstring tells the model the rule ("never overwrites") so it does not try to update notes with this tool.line 51
- A resource with a fixed address. Hosts list it, and read it when they want it in the model's context. The function runs only when it is read.line 59
- A **resource template**:
{name}in the address matches the function parameter. Readingnotes://onboardingcallsnote("onboarding").mime_typetells the host it is Markdown.line 65 - Resources have no
is_errorresult: a read either returns data or fails as a protocol error.ResourceNotFoundErroris the standard "no data at that address" error.line 71 - A prompt: its arguments become a form in the host, and the string it returns becomes a user message.line 74
- The prompt tells the model how to use **this** server's tools well. Prompts are a good place to share what works.line 78
import asyncio
import textwrap
from mcp import Client
from server import mcp
def signature(tool) -> str:
"""Turn a tool's input schema into a one-line signature like search_notes(query, limit=5)."""
args = []
for arg, spec in tool.input_schema["properties"].items():
args.append(f"{arg}={spec['default']}" if "default" in spec else arg)
return f"{tool.name}({', '.join(args)})"
async def main() -> None:
async with Client(mcp) as client:
print("tools:")
for tool in (await client.list_tools()).tools:
kind = "read-only" if tool.annotations.read_only_hint else "writes"
print(f" {signature(tool):<28} {kind:<9} {tool.description}")
print("resources:", [r.uri for r in (await client.list_resources()).resources])
print("templates:", [t.uri_template for t in (await client.list_resource_templates()).resource_templates])
print("prompts:", [p.name for p in (await client.list_prompts()).prompts])
index = await client.read_resource("notes://index")
print("\nnotes://index ->", index.contents[0].text.split("\n"))
prompt = await client.get_prompt("summarize_notes", {"topic": "costs"})
print("summarize_notes ->", prompt.messages[0].role, "message:", prompt.messages[0].content.text)
for name, args in [("search_notes", {"query": "costs", "limit": 99}), ("read_note", {"name": "holidays"})]:
result = await client.call_tool(name, args)
print(f"\n{name} {args} -> is_error={result.is_error}")
print(textwrap.indent(result.content[0].text, " "))
asyncio.run(main()) textwrap.indentputs four spaces in front of every line of a text, for readable output.line 2- A plain function that turns a tool's schema back into a signature. It is your own code, not part of MCP.line 9
a if condition else bis Python'scondition ? a : b. Optional arguments show their default.line 13(await client.list_tools()).tools: wait for the result first (inside the parentheses), then take its.tools.line 20- Reads the annotation you set. Hosts do the same to decide whether to ask the user before running a tool.line 21
:<28pads to 28 characters, left-aligned, so the columns line up.line 22- Fixed resources, then templates: a template has no single address to list until someone fills in
{name}.line 23 - Reading a resource returns
contents, a list (a resource can have several parts). Ours has one text part.line 27 - Getting a prompt runs your prompt function with the arguments and returns the finished messages.line 29
- Two calls that must fail: a
limitover the maximum, and a note that does not exist.line 32 - The exact text the model would see.line 35
uv run show_server.py tools:
search_notes(query, limit=5) read-only Search the team notes by keywords. Returns matching note names, best match first.
read_note(name) read-only Read one note in full. Get the name from search_notes first.
add_note(name, text) writes Save a new note. Never overwrites: fails if a note with that name exists.
resources: ['notes://index']
templates: ['notes://{name}']
prompts: ['summarize_notes']
notes://index -> ['onboarding', 'release-checklist', 'server-costs']
summarize_notes -> user message: Use search_notes to find the notes about costs, read the best ones with read_note, then summarize them in at most five bullet points. Name the note each fact comes from.
search_notes {'query': 'costs', 'limit': 99} -> is_error=True
Error executing tool search_notes: 1 validation error for search_notesArguments
limit
Input should be less than or equal to 10 [type=less_than_equal, input_value=99, input_type=int]
For further information visit https://errors.pydantic.dev/2.14/v/less_than_equal
read_note {'name': 'holidays'} -> is_error=True
Error executing tool read_note: no note called 'holidays'. Known notes: onboarding, release-checklist, server-costs limit=99 against le=10 and answered with the exact rule. The second is your ToolError message. Both arrive as normal results with is_error=True, so in an agent the model reads them and corrects itself, like a developer reading a compiler error.Stuck on this step?
ValueError: Mismatch between URI parameters {'name'} and function parameters ...- The
{name}in the resource address and the function's parameter name must be the same. The SDK checks this when the module loads. - The pydantic link says
2.15(or another version) - The link contains your installed Pydantic version. Everything else is the same.
Explore it in the MCP Inspector
Click through your tools, resources and prompt in the official test UI, exactly as a host sees them.
The MCP Inspector is the official web UI for testing MCP servers. It starts your server the way a host does (as a child process over stdio) and gives you a form for every tool, built from the schemas. Nothing to install: npx downloads it the first time (it needs Node.js, see setup).
Run it from the project folder. Everything after the package name is the command that starts your server:
npx @modelcontextprotocol/inspector uv run server.py
Starting MCP inspector...
MCP Inspector Web is up and running at:
http://127.0.0.1:6274?MCP_INSPECTOR_API_TOKEN=3f9c...
Opening browser...
The token in the address is a per-launch password that stops other web pages from driving the Inspector. If the browser does not open on its own, copy the whole address, token included.
Then, in the browser:
- The server you gave on the command line is already filled in. If it is not connected yet, click Connect. It shows team-notes and its instructions.
- Tools: pick
search_notes. The form has a requiredquerytext field and an optionallimitnumber, built from your type hints. Run it withquery = staging: you get the two hits, as content blocks and as structured content. - Set
limitto 99 and run it again: a red error with "Input should be less than or equal to 10". Your function never ran. - Resources:
notes://indexis listed;notes://{name}is under templates. Fill inonboardingand read it. - Prompts: get
summarize_noteswithtopic = costsand look at the user message it builds. - Look at the log of requests and responses: every click is one JSON-RPC message (
tools/list,tools/call,resources/read, ...). That is the whole protocol.
Press Ctrl+C in the terminal to stop it. The Inspector also has a command-line mode, handy in scripts and CI. It prints the JSON answer:
npx @modelcontextprotocol/inspector --cli uv run server.py --method tools/call --tool-name search_notes --tool-arg query=database
Stuck on this step?
npm warn EBADENGINEor the Inspector exits with a syntax error- Your Node.js is too old. Install a current version from nodejs.org (22.23.4+ or 24.22.1+), then check with
node --version. - The Inspector shows "connection failed" or the server exits at once
- Run
uv run server.pyyourself: a traceback (a typo, a missing package) is the real problem. It should print nothing and wait. - You are on a remote machine or in a container
- The Inspector listens on 127.0.0.1:6274 only. Forward that port (for example
ssh -L 6274:127.0.0.1:6274 host), or use the--climode.
A Python client over stdio
Start the server as a child process and talk to it with `ClientSession`, the way a host does.
Now play the host yourself. stdio_client starts the server command as a subprocess and connects to its stdin and stdout. ClientSession speaks the protocol on top: it sends the handshake, then your requests, and matches each answer to its request.
Two nested async with blocks: the outer one owns the process (it stops it at the end), the inner one owns the MCP session. initialize() is the handshake: client and server agree on a protocol version and tell each other what they support. Every other call only works after it.
The search uses two words, so you see the ranking: server-costs mentions "database" and "backups", release-checklist only "database".
import asyncio
import sys
from mcp import ClientSession, StdioServerParameters, stdio_client
SERVER = StdioServerParameters(command=sys.executable, args=["server.py"])
async def main() -> None:
async with stdio_client(SERVER) as (read, write):
async with ClientSession(read, write) as session:
info = await session.initialize()
print(f"connected to {info.server_info.name} (protocol {info.protocol_version})")
print("instructions:", info.instructions)
listing = await session.list_tools()
print("tools:", [tool.name for tool in listing.tools])
result = await session.call_tool("search_notes", {"query": "database backups"})
print("search_notes ->", result.structured_content["result"])
result = await session.call_tool("read_note", {"name": "../../etc/passwd"})
print("read_note ../../etc/passwd -> is_error:", result.is_error)
note = await session.read_resource("notes://release-checklist")
print("notes://release-checklist ->", note.contents[0].text.splitlines()[0])
asyncio.run(main()) - The low-level client pieces:
stdio_client(the transport),ClientSession(the protocol) andStdioServerParameters(the command to start).line 4 sys.executableis the Python running this script, the project's own. So the server gets the same packages, and it works on every OS.argsare the command-line arguments: runserver.pyfrom the current folder.line 6- Starts the server process.
as (read, write)unpacks the two message streams it yields: answers coming in, requests going out.line 10 - The handshake.
initialize()performs the classic handshake, so you see protocol2025-11-25. The high-levelClient(step 9) negotiates the newer2026-07-28version when the server supports it. Your server speaks both.line 12 - The
instructionsyou gaveMCPServerarrive here. A host may give them to the model.line 14 structured_content["result"]is the list of hits as plain dicts.line 20- Path traversal through the protocol: refused by the schema check, as a tool error, before
read_noteruns.line 22 - Reads a concrete address from the template. The result has the text of
release-checklist.md.line 25
uv run client.py connected to team-notes (protocol 2025-11-25)
instructions: Team notes. Search them before answering questions about the team.
tools: ['search_notes', 'read_note', 'add_note']
search_notes -> [{'name': 'server-costs', 'title': 'Server costs, March', 'score': 2}, {'name': 'release-checklist', 'title': 'Release checklist', 'score': 1}]
read_note ../../etc/passwd -> is_error: True
notes://release-checklist -> # Release checklist Client(StdioServerParameters(...)), which wraps the same two pieces.Stuck on this step?
mcp.shared.exceptions.MCPError: Connection closedright after starting- The server crashed on start (its traceback is printed just above). Run
uv run server.pyto see the traceback. Aprint()at the top ofserver.pyalso breaks it: on stdio, stdout is the protocol, so log withlogging(it writes to stderr) instead. FileNotFoundErrororcan't open file 'server.py'- Run
client.pyfrom the project folder:args=["server.py"]is relative to the folder you start it in.
Connect it to Claude Desktop
Register the server in a desktop AI app with one JSON entry, and use your tools from a chat.
A host only needs the command that starts your server. Claude Desktop reads it from claude_desktop_config.json, under the key mcpServers. Other hosts (IDEs, other chat apps, agent tools) use the same idea: a name, a command and its args, in their own config file or settings screen.
Where the file is:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json(~is your home folder; in Finder press Cmd+Shift+G and paste the folder path) - Windows:
%APPDATA%\Claude\claude_desktop_config.json(paste%APPDATA%\Claudeinto the Explorer address bar)
If the file does not exist yet, create it with the content below. If it exists, add the team-notes entry inside its mcpServers object, keeping the other entries.
Use absolute paths. The app starts your server from its own working folder, with a short PATH that may not include uv. So give the full path to uv and the full path to the project. The command below prints both for you. uv --directory <folder> run server.py means "go to the project folder, then run server.py with that project's packages".
On Windows the paths look like "C:\\Users\\you\\.local\\bin\\uv.exe": in JSON every backslash is written twice.
After saving, quit the app completely (not just its window: on macOS use Quit from the menu, on Windows quit from the tray icon) and open it again. Hosts read the config only at start. Your server shows up in the app's list of connectors or tools, with its three tools. Ask: "What do my team notes say about server costs?" Apps usually ask your permission before a tool runs; allow it, and the answer comes from server-costs.md.
If it does not show up, look at the logs: on macOS ~/Library/Logs/Claude/mcp-server-team-notes.log has your server's stderr (tracebacks land there), and mcp.log the connection; on Windows they are in %APPDATA%\Claude\logs.
{
"mcpServers": {
"team-notes": {
"command": "/Users/you/.local/bin/uv",
"args": ["--directory", "/Users/you/code/team-notes-mcp", "run", "server.py"]
}
}
} - Every server the app should start goes in this object, one entry each.line 2
- The name the app shows (and the log file name:
mcp-server-team-notes.log).line 3 - Replace with the output of the command below: the absolute path to
uv.line 4 - Replace the folder with your project folder (the second line of the output below). The app runs
uv --directory <folder> run server.py, exactly what you could type in a terminal.line 5
which uv
pwdwhich uv
pwd(Get-Command uv).Source
(Get-Location).Path /Users/you/.local/bin/uv /Users/you/code/team-notes-mcp
Stuck on this step?
- The server does not appear in the app at all
- The JSON is invalid (a missing comma or quote) or the app was not fully restarted. Paste the file into any JSON validator, then quit and reopen the app.
- It appears but says it failed or disconnected
- Check
mcp-server-team-notes.log. Usuallyuvwas not found (use the absolute path fromwhich uv) or the folder path is wrong. Test the exact command in a terminal:/Users/you/.local/bin/uv --directory /Users/you/code/team-notes-mcp run server.pymust start and wait silently. - The tools are there but the model never uses them
- Ask more directly ("search my team notes for ..."). Small or busy contexts sometimes skip tools; the tool descriptions are what the model goes by, so make them say clearly when to use the tool.
An agent loop with the local model
Let the free local model use your MCP tools: turn MCP tool descriptions into the OpenAI tool format and run lab 4's loop.
A desktop app is one host. Your own program can be another. The agent below is lab 4's loop with one change: the tools come from the MCP server. It lists them, converts each one to the format the chat API expects, and when the model asks for a tool, it calls session.call_tool() instead of a local function.
The conversion is small because both sides use JSON Schema:
MCP tool (from tools/list) |
OpenAI-style tool (for tools=) |
|---|---|
name |
function.name |
description |
function.description |
inputSchema |
function.parameters |
Least privilege again: the agent offers the model only search_notes and read_note. add_note writes to disk, so it stays out of an unattended loop; if the model asks for it anyway, it gets an error message instead. Do not rely on the server's read_only_hint for this: it is the server describing itself, and you decide what your agent may do.
One Python detail you will meet with every async library: the MCP client runs background tasks inside a task group, and any exception that leaves the async with block arrives wrapped in an ExceptionGroup. A normal except openai.APIConnectionError around asyncio.run() would not match it. So the errors are caught inside the block and turned into a message, and sys.exit runs after the blocks have closed.
import asyncio
import json
import sys
import openai
from mcp import ClientSession, StdioServerParameters, stdio_client
from openai import AsyncOpenAI
from config import settings
SERVER = StdioServerParameters(command=sys.executable, args=["server.py"])
ALLOWED_TOOLS = {"search_notes", "read_note"}
SYSTEM = (
"You answer questions about the team's notes. Always call search_notes first, "
"then read_note for the notes you need. Answer in two or three sentences "
"and name the notes you used."
)
class TooManySteps(Exception):
pass
def to_openai_tool(tool) -> dict:
"""One MCP tool description -> the tool format of OpenAI-compatible chat APIs."""
return {
"type": "function",
"function": {
"name": tool.name,
"description": tool.description or "",
"parameters": tool.input_schema,
},
}
def result_text(result) -> str:
"""The text the model should read from an MCP tool result."""
text = "\n".join(block.text for block in result.content if block.type == "text")
return f"ERROR: {text}" if result.is_error else text
async def run_agent(question: str, session, llm, model: str, max_steps: int = 5) -> str:
listing = await session.list_tools()
tools = [to_openai_tool(t) for t in listing.tools if t.name in ALLOWED_TOOLS]
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": question},
]
for _ in range(max_steps):
resp = await llm.chat.completions.create(model=model, messages=messages, tools=tools, temperature=0)
msg = resp.choices[0].message
if not msg.tool_calls:
return msg.content or ""
messages.append({
"role": "assistant",
"content": msg.content or "",
"tool_calls": [
{"id": c.id, "type": "function", "function": {"name": c.function.name, "arguments": c.function.arguments}}
for c in msg.tool_calls
],
})
for c in msg.tool_calls:
name = c.function.name
print(f" model calls {name}({c.function.arguments})")
if name not in ALLOWED_TOOLS:
content = f"ERROR: tool {name!r} is not available"
else:
try:
args = json.loads(c.function.arguments or "{}")
except json.JSONDecodeError:
content = "ERROR: arguments must be a JSON object"
else:
content = result_text(await session.call_tool(name, args))
messages.append({"role": "tool", "tool_call_id": c.id, "content": content})
raise TooManySteps(f"no final answer after {max_steps} requests")
async def main() -> None:
question = " ".join(sys.argv[1:]) or "What do my notes say about server costs?"
s = settings()
llm = AsyncOpenAI(base_url=s.base_url, api_key=s.api_key, timeout=120, max_retries=2)
async with stdio_client(SERVER) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
try:
print(await run_agent(question, session, llm, s.model))
return
except TooManySteps as e:
error = f"Stopped: {e}"
except openai.APITimeoutError:
error = "The model took too long. Try a shorter question."
except openai.APIConnectionError:
error = "Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)"
except openai.NotFoundError:
error = f"Model '{s.model}' not found. Run: ollama list"
sys.exit(error)
if __name__ == "__main__":
asyncio.run(main()) AsyncOpenAI: the async version of lab 1's client. Inside async code, use async clients, so a slow model call does not block the MCP connection running in the same event loop.line 7- The allow-list of tools this agent may use. A
set, written with braces, likeSet.of(...).line 12 - Small models follow short, direct rules best: search first, then read, then answer and cite.line 13
- The whole bridge between MCP and the chat API: three fields copied into a dict. Both use JSON Schema, so the schema goes over unchanged.line 24
- A result has a list of content blocks. Keep the text ones (
search_notesreturns one block per hit) and join them with newlines.line 38 - Mark errors clearly. The model reads the message (like "no note called ...") and can correct its call.line 39
sessioncan be aClientSession(here) or the in-memoryClient(the tests): both havelist_tools()andcall_tool(). Python checks for the methods when they are called ("duck typing"), so no shared interface is needed.line 42- Only the allowed tools are converted and sent, so the model only learns about those two. It can still invent a tool name; line 65 handles that.line 44
for _ in range(max_steps): loop at most 5 times._is the usual name for a loop variable you do not use.line 49- Every request sends the whole conversation and the tools again: the model keeps no state between requests.line 50
- No tool calls: the model has written its answer.line 52
- The assistant message with its tool calls goes into the conversation first, as a plain dict, exactly as in lab 4.line 54
- Prints each call, so you can follow the agent.line 64
- Least privilege, enforced here: a tool outside the allow-list is never called, whatever the model asks.line 65
- Models write arguments as a JSON **string**. Broken JSON becomes an error message for the model, not a crash.line 69
try / except / else: theelseruns only when the JSON parsed. Then the call goes to the MCP server.line 72- One
toolmessage per call, tied to the request bytool_call_id.line 74 - A confused model can call tools forever. The cap turns that into a clear error.line 75
- The same nested blocks as
client.py: start the server, open a session, handshake.line 82 returninsideasync withstill closes both blocks properly (the session first, then the server process).line 87- Errors are caught here, **inside** the blocks, and only remembered.line 88
- Timeout before connection error on purpose:
APITimeoutErroris a subclass ofAPIConnectionError, and Python uses the firstexceptthat matches.line 90 - Only reached after an error, once the blocks have closed.
sys.exit(text)prints the text to stderr and exits with code 1.line 96 - The guard again: the tests import
run_agentfrom this file without starting an agent.line 99
uv run agent.py "What do my notes say about server costs?" model calls search_notes({"query":"server costs"})
model calls read_note({"name":"server-costs"})
The two app servers cost 140 dollars a month each, the database 310 dollars and backups 25 dollars (server-costs). The note also suggests moving the staging server to a smaller size to save about 60 dollars. Stuck on this step?
Cannot reach the model server. Is Ollama running?- Open the Ollama app or run
ollama serve, and checkLLM_BASE_URLin.env. - The model answers without calling any tool
- Small models skip tools sometimes. Ask with the words of the tool ("search my notes for ..."), or try
llama3.1:8b(ollama pull llama3.1:8b, about 5 GB, thenLLM_MODEL=llama3.1:8b uv run agent.py "..."). - Only
search_notesis called, and the answer is vague and general - The model stopped after the search and answered from its own knowledge, not from the note. See the verify section for why and for two fixes (a stricter
SYSTEMrule, and a check in code). A bigger model (llama3.1:8b) does it far less often. - A tool result says
ERROR: ... should match pattern - The model invented a note name like
Server Costs. That is the schema doing its job: the model sees the error and usually callssearch_notesand tries again with the real name. - A long traceback ending in
ExceptionGroup: unhandled errors in a TaskGroup - An error escaped the
async withblocks. Look at the innermost exception at the bottom: that is the real error. Catch it inside the block, asmain()does.
Serve it over HTTP (Streamable HTTP)
Run the same server on a port, so programs on other machines can use it, and know what that changes for security.
stdio is for local servers: one app starts one copy, on the same machine. To share a server (a team tool, a service other agents call), MCP uses Streamable HTTP: the server listens on a URL and clients send each request as an HTTP POST. The server code does not change; only the run() call does.
Start it in one terminal and leave it running:
uv run http_server.py
MCP server on http://127.0.0.1:8000/mcp (press Ctrl+C to stop)
Then open a second terminal in the same folder and run the client. The high-level Client takes a URL and picks the HTTP transport by itself:
HTTP changes the security picture. On stdio only the app that started the server can talk to it. On a port, anyone who can reach the port can. So: listen on 127.0.0.1 (this machine only) until you have authentication; put a real login (OAuth or at least a secret token checked by a reverse proxy) in front of anything you expose; and keep TLS (HTTPS) between machines. The SDK also has DNS-rebinding protection switched on for local addresses: a request whose Host header is not 127.0.0.1, localhost or [::1] gets 421 Misdirected Request, so a malicious web page cannot reach your local server through a trick DNS name. When you deploy behind a real hostname, list it with transport_security= (the SDK's deployment docs show how) instead of switching the check off.
from server import mcp
print("MCP server on http://127.0.0.1:8000/mcp (press Ctrl+C to stop)")
try:
mcp.run(transport="streamable-http", host="127.0.0.1", port=8000)
except KeyboardInterrupt:
print("stopped") - The same server object, tools and all. Only the transport differs.line 1
- A
printis fine here, unlike in a stdio server: over HTTP, stdout is not the protocol channel.line 3 - Listens on port 8000 at the path
/mcp.host="127.0.0.1"accepts connections from this machine only.0.0.0.0would accept the whole network: do that only behind authentication.line 5 - Ctrl+C raises
KeyboardInterrupt. Catching it ends the server with one line instead of a traceback.line 6
import asyncio
from mcp import Client
async def main() -> None:
async with Client("http://127.0.0.1:8000/mcp") as client:
print("connected over HTTP, protocol", client.protocol_version)
listing = await client.list_tools()
print("tools:", [tool.name for tool in listing.tools])
result = await client.call_tool("search_notes", {"query": "release staging"})
print("search_notes ->", result.structured_content["result"])
asyncio.run(main()) - A URL means Streamable HTTP. This
Clientnegotiates the newest protocol version both sides support.line 7 2026-07-28this time: the newer protocol revision, where each request is self-contained (no session to keep), which makes servers easier to scale.line 8- The same
call_toolas before. The transport is invisible to your code.line 11
uv run http_client.py connected over HTTP, protocol 2026-07-28
tools: ['search_notes', 'read_note', 'add_note']
search_notes -> [{'name': 'release-checklist', 'title': 'Release checklist', 'score': 4}, {'name': 'server-costs', 'title': 'Server costs, March', 'score': 1}] Stuck on this step?
httpx2.ConnectError/All connection attempts failed- The server is not running. Start
uv run http_server.pyin the other terminal first, and keep it open. [Errno 48] Address already in use(Linux:[Errno 98])- Something else uses port 8000. Change
port=8000inhttp_server.pyand the URL inhttp_client.pyto another port, like 8001.
Test it with pytest, without a model
Tests for the store, every tool, resource and prompt, the stdio transport and the agent loop, all in about two seconds.
Three levels of tests. The store is plain Python, tested directly. The server is tested in memory with Client(server.mcp), the same trick as show_server.py: real MCP requests, no process. The transport gets one test that starts the real server over stdio, the way a host does. And the agent runs against the in-memory server with a fake model that returns scripted replies, as in lab 4.
The tests are async def functions, because the MCP client is async. pytest needs a plugin to run them: anyio, which the mcp package already installs. @pytest.mark.anyio marks a test as async, and the anyio_backend fixture says "run it on asyncio".
conftest.py is a special pytest file: fixtures defined in it are available to every test file in the folder, without an import. A fixture is a function that prepares something a test needs; a test asks for it by naming it as a parameter (pytest injects it, like @Autowired). tmp_path and monkeypatch are fixtures built into pytest: a fresh temporary folder per test, and a way to swap a value for the length of one test.
import pytest
from mcp import Client
import server
from store import NoteStore
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.fixture
def store(tmp_path, monkeypatch):
(tmp_path / "server-costs.md").write_text("# Server costs\nThe database costs 310 dollars a month.\n")
(tmp_path / "onboarding.md").write_text("# Onboarding\nDay 1: laptop and accounts.\n")
notes = NoteStore(tmp_path)
monkeypatch.setattr(server, "store", notes)
return notes
@pytest.fixture
async def client(store):
async with Client(server.mcp, raise_exceptions=True) as c:
yield c - The tests import the server module to reach its
mcpobject and itsstore. Theif __name__guard keeps the import from starting a server.line 4 - Tells anyio's pytest plugin to run async tests on asyncio (the other choice is trio).line 9
tmp_pathis a new, empty folder for each test, deleted later. The tests never touch your real notes.line 14- Two small notes, written fresh for every test, so every test starts from the same known state.line 15
- The key line: replace
server.storewith a store over the temporary folder, for this test only. The tools look upstorewhen they run, so they use the test notes.monkeypatchputs the original back afterwards.line 18 - An async fixture: pytest awaits it. Asking for
clientalso buildsstore, because this fixture asks for it.line 23 raise_exceptions=Truemakes unexpected server crashes show their real message in the test, instead of a generic "internal error".line 24yieldhands the connected client to the test; the code after it (closing theasync with) runs when the test ends. Setup and teardown in one function, like@BeforeEachand@AfterEach.line 25
import pytest
from store import NoteError
def test_search_ranks_by_matches(store):
hits = store.search("database costs")
assert [h["name"] for h in hits] == ["server-costs"]
assert hits[0]["title"] == "Server costs"
@pytest.mark.parametrize("name", ["../secrets", "/etc/passwd", "a/b", "Notes", "", "x" * 51])
def test_names_that_could_escape_the_folder_are_refused(store, name):
with pytest.raises(NoteError):
store.read(name)
def test_add_then_read(store):
store.add("team-lunch", "# Team lunch\nFriday at noon.\n")
assert "Friday" in store.read("team-lunch")
def test_add_never_overwrites(store):
with pytest.raises(NoteError, match="already exists"):
store.add("onboarding", "replaced!") - Uses the
storefixture fromconftest.py: two notes in a temporary folder.line 6 parametrizeruns the test once per value: six tests from one function, like JUnit's@ParameterizedTest."x" * 51is a 51-character name, one over the limit.line 12- The test passes only if the block raises
NoteError.line 14 match=also checks the message, with a regular expression search.line 24
import pytest
pytestmark = pytest.mark.anyio
async def test_tools_and_their_schemas(client):
listing = await client.list_tools()
tools = {t.name: t for t in listing.tools}
assert set(tools) == {"search_notes", "read_note", "add_note"}
schema = tools["search_notes"].input_schema
assert schema["required"] == ["query"]
assert schema["properties"]["limit"]["maximum"] == 10
assert tools["search_notes"].description.startswith("Search the team notes")
async def test_search_notes(client):
result = await client.call_tool("search_notes", {"query": "database"})
assert not result.is_error
assert result.structured_content["result"][0]["name"] == "server-costs"
async def test_bad_arguments_never_reach_your_code(client):
result = await client.call_tool("search_notes", {"query": "database", "limit": 99})
assert result.is_error
assert "less than or equal to 10" in result.content[0].text
async def test_path_traversal_is_rejected(client):
result = await client.call_tool("read_note", {"name": "../../etc/passwd"})
assert result.is_error
assert "should match pattern" in result.content[0].text
async def test_missing_note_is_a_tool_error_the_model_can_read(client):
result = await client.call_tool("read_note", {"name": "holidays"})
assert result.is_error
assert "no note called 'holidays'" in result.content[0].text
async def test_add_note_writes_a_file(client, store):
result = await client.call_tool("add_note", {"name": "team-lunch", "text": "Friday at noon."})
assert result.structured_content == {"result": "saved note 'team-lunch'"}
assert store.read("team-lunch") == "Friday at noon."
async def test_resources_and_prompt(client):
index = await client.read_resource("notes://index")
assert index.contents[0].text == "onboarding\nserver-costs"
note = await client.read_resource("notes://onboarding")
assert note.contents[0].text.startswith("# Onboarding")
prompt = await client.get_prompt("summarize_notes", {"topic": "costs"})
assert "costs" in prompt.messages[0].content.text pytestmarkapplies the mark to every test in the file, so eachasync deftest runs with anyio.line 3- Asks for the
clientfixture: a connected in-memory client over the test notes.line 6 - Checks the description too: it is part of your contract with the model.line 13
- The schema check works: your function never ran, and the error names the rule.line 25
- Path traversal is refused by the pattern, at the protocol level.line 31
- The write tool really writes, into the temporary folder.line 43
import sys
import pytest
from mcp import ClientSession, StdioServerParameters, stdio_client
@pytest.mark.anyio
async def test_server_runs_over_stdio():
params = StdioServerParameters(command=sys.executable, args=["server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
info = await session.initialize()
assert info.server_info.name == "team-notes"
listing = await session.list_tools()
assert "search_notes" in [t.name for t in listing.tools] - One test with a real subprocess over stdio. It is slower than the in-memory ones, so keep most tests in memory and only a few like this one.line 7
- Starts
server.pyexactly asclient.pydoes. This catches what in-memory tests cannot: aprint()that corrupts stdout, or a crash at start-up.line 9
import copy
import json
from types import SimpleNamespace
import pytest
from agent import TooManySteps, run_agent
pytestmark = pytest.mark.anyio
def ask_for(name, args, call_id="call_1"):
call = SimpleNamespace(id=call_id, function=SimpleNamespace(name=name, arguments=json.dumps(args)))
return SimpleNamespace(content="", tool_calls=[call])
def say(text):
return SimpleNamespace(content=text, tool_calls=None)
class FakeLLM:
"""Stands in for AsyncOpenAI: hands out the given replies in order and records every request."""
def __init__(self, *replies):
self.replies = list(replies)
self.requests = []
self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))
async def create(self, **kwargs):
self.requests.append(copy.deepcopy(kwargs))
return SimpleNamespace(choices=[SimpleNamespace(message=self.replies.pop(0))])
async def test_mcp_tools_become_openai_tools(client):
llm = FakeLLM(say("Hello"))
await run_agent("hi", client, llm, "fake-model")
tools = llm.requests[0]["tools"]
assert [t["function"]["name"] for t in tools] == ["search_notes", "read_note"]
assert tools[0]["function"]["parameters"]["required"] == ["query"]
async def test_tool_result_goes_back_to_the_model(client):
llm = FakeLLM(ask_for("search_notes", {"query": "database"}), say("It costs 310 dollars."))
answer = await run_agent("What does the database cost?", client, llm, "fake-model")
assert answer == "It costs 310 dollars."
tool_message = llm.requests[1]["messages"][-1]
assert tool_message["role"] == "tool" and tool_message["tool_call_id"] == "call_1"
assert "server-costs" in tool_message["content"]
async def test_tool_errors_are_sent_back_too(client):
llm = FakeLLM(ask_for("read_note", {"name": "holidays"}), say("I could not find that note."))
await run_agent("Read holidays", client, llm, "fake-model")
assert llm.requests[1]["messages"][-1]["content"].startswith("ERROR: ")
async def test_write_tools_are_not_offered_or_run(client, store):
llm = FakeLLM(ask_for("add_note", {"name": "x", "text": "hacked"}), say("Done."))
await run_agent("Add a note", client, llm, "fake-model")
assert llm.requests[1]["messages"][-1]["content"] == "ERROR: tool 'add_note' is not available"
assert store.names() == ["onboarding", "server-costs"]
async def test_stops_after_max_steps(client):
llm = FakeLLM(*[ask_for("search_notes", {"query": "loop"}, f"call_{i}") for i in range(3)])
with pytest.raises(TooManySteps):
await run_agent("loop forever", client, llm, "fake-model", max_steps=3) - Builds a fake reply in which the model asks for one tool.
SimpleNamespace(a=1)is a quick object with attributea, like a JavaScript object literal.line 12 - The fake model. It only needs
chat.completions.create, because that is allrun_agentuses.line 21 async def, becauserun_agentawaits it.line 29copy.deepcopystores a snapshot:run_agentkeeps appending to the samemessageslist, and the test wants to see each request as it was sent.line 30pop(0)takes the first queued reply, likequeue.poll().line 31- The conversion test: only the allowed tools are sent, with their MCP schema as
parameters.line 38 - The second request must end with the tool result, tied to the call id.line 46
- The model asks for the write tool: it gets an error, and no file is written.line 60
- Three tool calls in a row with
max_steps=3: the loop must stop withTooManySteps.line 65
uv run pytest -q ...................... [100%] 22 passed in 1.68s
Stuck on this step?
- The tests fail with
async def functions are not natively supported - The
@pytest.mark.anyiomark (or thepytestmarkline) is missing, oranyiois not installed. It comes withmcp; runuv sync. test_stdio.pyfails withConnection closed- Run pytest from the project folder, so
server.pyis found, and check thatuv run server.pystarts without errors.
Check it works
Two checks: all tests pass with no model, and the agent answers a question through your MCP server and the local model, showing the tool calls it made.
If you did step 7, also ask the same question in Claude Desktop. The answer should come from release-checklist.md.
The output above is a real run on llama3.2:3b, and it is a failure worth recognising. The model searched, found the right note, and then did not read it: it answered from general knowledge ("testing, quality assurance") and told you to read the note yourself. Nothing in the answer comes from release-checklist.md. The tool line shows it at once: no read_note call. A good run calls read_note({"name":"release-checklist"}) and then names the real steps from the note (tests and migrations on staging, watching the error dashboard, release notes for support).
Run it a few times, or try llama3.1:8b. To make it reliable with a small model, tighten the rule in SYSTEM: "Never answer from search results alone: call read_note on the best match, and answer only from what read_note returned." For a stronger guarantee, check in code, as the LangGraph lab does: if the model answers after search_notes without any read_note, send one nudge and ask again.
uv run pytest -q && uv run agent.py "What do my notes say about the release checklist?" 22 passed in 0.53s
model calls search_notes({"query":"release checklist"})
According to your notes, the release checklist is a critical process that ensures all necessary steps are taken before releasing new software. It typically includes tasks such as testing, quality assurance, and deployment preparation. You can find more details about the specific steps involved in the release checklist by reading the "release-checklist" note. Troubleshooting
ModuleNotFoundError: No module named 'mcp.server.fastmcp'
Code written for mcp 1.x. In 2.x the class is MCPServer: from mcp.server import MCPServer. Attribute names are snake_case too: tool.input_schema, result.structured_content, result.is_error. The SDK's migration guide lists every change.
The host connects, then drops the server at once
Something wrote to stdout, which on stdio is the protocol channel. Remove print() calls from the server (and from anything it imports at start-up) and use logging, which writes to stderr. Run uv run client.py to check.
Works in a terminal, fails in the desktop app
Relative paths. The app starts the server from its own folder with a short PATH. Use absolute paths for uv and for --directory, and read mcp-server-team-notes.log for the real error.
The model calls a tool with wrong arguments again and again
Improve what the model reads: a clearer docstring, description= on each argument with an example, and helpful ToolError messages that say what is valid (like the list of known notes). The schema rules make sure wrong calls never run.
421 Misdirected Request from the HTTP server after deploying
DNS-rebinding protection only accepts local Host headers by default. Pass transport_security=TransportSecuritySettings(allowed_hosts=[...]) with your real hostname (from mcp.server.transport_security), as the SDK's deploy guide shows.
A long ExceptionGroup traceback from a client script
The real error is the innermost one at the bottom (often a connection refused or a model error). Catch errors inside the async with blocks, as agent.py does.
What changes in production
- Least privilege. Offer the smallest set of narrow tools the job needs, scoped to one folder, table or API. A read tool and a write tool are separate decisions; destructive actions (delete, overwrite, send, pay) need a human confirmation in the host or should not be tools at all.
- Never expose a shell or
eval. A "run command" tool turns any text the model reads (a web page, an email, a note) into commands on your machine: prompt injection becomes remote code execution. Expose specific actions with validated arguments instead. - Validate every argument and limit every size. Type hints with
Fieldrules are checked before your code runs; check again in the code that touches files or databases (allow-lists, not block-lists), cap lengths and result counts, and set timeouts on anything slow. - Over HTTP, authenticate and encrypt. Bind to
127.0.0.1until there is a login in front (OAuth or a token checked by a gateway), use HTTPS between machines, allow-list your hostnames withtransport_security, and log every tool call with who called it. - Pin the SDK major version (
mcp>=2.3,<3) and keep the in-memory tests in CI: they catch schema changes, because the schema is generated from your type hints.
Interview angle
βWhat is MCP, and how would you build and secure an MCP server?β
MCP, the Model Context Protocol, is a standard way for AI apps (hosts) to connect to external capabilities. A server exposes tools, which the model decides to call, resources, which the application loads as context, and prompts, which the user picks. Messages are JSON-RPC over stdio for local servers or Streamable HTTP for remote ones. In Python I use the official SDK: a function with type hints and a docstring becomes a tool, and the SDK generates the JSON Schema and validates every call before my code runs. For security I treat every argument as untrusted: allow-list validation (for example note names that cannot contain path separators), size limits, narrow tools scoped to one folder or API, no shell, separate read and write tools, and errors the model can read via ToolError without leaking internals. Over HTTP I add authentication, TLS and the host allow-list. I test in memory with the SDK client, plus one stdio test, and connect it to an agent by mapping each MCP tool to the chat API's tool format.
Clean up
If you added the server to Claude Desktop, remove the team-notes entry from claude_desktop_config.json and restart the app, so it stops starting your server. Stop http_server.py with Ctrl+C. Keep the project: the evals lab measures agents like this one. To free disk space, delete the virtual environment (uv sync recreates it).
rm -rf .venvrm -rf .venvRemove-Item -Recurse -Force .venv Practice
No model needed: these run in your browser and check your answer.
Turn an MCP tool into an OpenAI tool
Over the wire, an MCP tool description is JSON with name, description (it may be missing) and inputSchema. Write to_openai_tool(tool) that takes that dict and returns the chat API format: {"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}}. A missing description becomes "".
def to_openai_tool(tool):
# tool: {"name": ..., "description": ... (optional), "inputSchema": {...}}
return {"type": "function", "function": {"name": tool["name"]}}
search = {"name": "search_notes", "description": "Search notes.", "inputSchema": {"type": "object", "properties": {"query": {"type": "string"}}}}
print(to_openai_tool(search))
Hint
`tool.get("description", "")` returns `""` when the key is missing. The schema needs no conversion: both sides use JSON Schema.
A safe file name check
A tool lets the model download reports by name. Write safe_report_name(name): return True only when the name is 1 to 40 characters of lowercase letters, digits, dashes and underscores, does not start with a dash or underscore, and ends with .csv (the .csv is not counted in the 40). Everything else, including ../ tricks, absolute paths and other extensions, returns False.
def safe_report_name(name):
# a block-list: easy to get wrong
return ".." not in name and name.endswith(".csv")
print(safe_report_name("sales-2026.csv"), safe_report_name("../secrets.csv"))
Hint
Use an allow-list regex with `re.fullmatch`: one allowed first character, then up to 39 more, then a literal `\.csv`. Write it as a raw string, like `r"[a-z0-9][a-z0-9_-]{0,39}\.csv"`.
The full project
Every file from this lab, as it is after the last step.