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

1 / 8

0 of 10 steps done

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

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.

Run
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
You should see
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.

Run
uv --version
You should see
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.

Run
ollama --version
You should see
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.

Run
ollama pull llama3.2:3b
You should see
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.

Run
node --version
You should see
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.

1

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.

.env
# 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
  1. 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
  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
config.py
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")),
    )
  1. load_dotenv() copies .env into os.environ. Variables already set in your shell win, which is what you want on a server.line 7
  2. __file__ is the path of this file. .resolve().parent is its folder as an absolute path, so HERE / "notes" works no matter which folder the server was started from. The / operator joins paths, like Path.resolve() in Java.line 9
  3. frozen=True makes the settings read-only, like a Java record.line 12
  4. The one new setting. os.environ.get(name, default) returns the default when the variable is missing, so by default the server uses the notes folder next to it.line 25
.gitignore
.venv/
__pycache__/
.env
  1. Never commit .env: one day it holds a real key.line 3
Run
uv init team-notes-mcp
cd team-notes-mcp
uv add mcp openai python-dotenv
uv add --dev pytest
You should seeyour text will differ: the model writes it
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.x in the output
An old version was pinned somewhere. Run uv add "mcp>=2.3,<3" to get the version this lab is written for.
2

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, ...).

notes/server-costs.md
# 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.
notes/onboarding.md
# 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.
notes/release-checklist.md
# 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.
store.py
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")
  1. 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
  2. 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
  3. One exception type for problems the **caller** can fix. The server turns it into a message the model reads (step 4).line 8
  4. .resolve() makes the folder absolute once, at the start.line 16
  5. The leading _ marks a private helper by convention. Python has no private keyword.line 18
  6. re.fullmatch succeeds only if the **whole** name matches, like String.matches() in Java. This one check is what keeps every read and write inside the folder.line 19
  7. 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
  8. Every .md file in the folder, as names without the extension (p.stem). Files whose names break the pattern are skipped, so read never sees them.line 24
  9. A helpful error: say what exists. The model reads this and can pick a real name on its next try.line 29
  10. 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
  11. The first line of the note without the leading # , so # Server costs, March becomes Server costs, March.line 39
  12. Sort by score, highest first (-score), and by name when scores tie, so the order is always the same.line 40
  13. 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
try_store.py
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)
  1. "server" appears 3 times in server-costs.md (the heading, "app servers", "staging server") and "costs" twice: a score of 5.line 6
  2. Three attacks and one honest mistake. All four must fail with a clear NoteError.line 10
Run
uv run try_store.py
You should see
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
Why this way? Validation lives in the store, not only in the MCP layer, so it protects every path into the data: the tools, the resources in step 4 and any future caller. Step 4 adds a second check in the tool schema, so bad names are refused even earlier. Two layers is the point: one mistake does not open the door.
Stuck on this step?
notes: []
The notes folder is not next to config.py, or the files do not end in .md. Check with ls notes (Windows: dir notes).
3

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.

server.py
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()
  1. Annotated[type, extra] attaches extra information to a type hint. Here the extra is a Pydantic Field with rules.line 1
  2. The server class. mcp 1.x called it FastMCP (in mcp.server.fastmcp); in 2.x it is MCPServer.line 3
  3. One store for the whole server, created when the module loads.line 10
  4. The server's name: hosts show it, and clients get it when they connect.line 12
  5. instructions is sent to the client on connect. Hosts may put it into the model's context, so keep it to one useful sentence.line 13
  6. 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
  7. 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
  8. 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
  9. The decorator registers the function as a tool named search_notes. That is the whole registration.line 25
  10. query must be 2 to 200 characters. The description is what the model reads about this argument.line 27
  11. = 5 makes limit optional: it disappears from required and the schema gets "default": 5. ge=1, le=10 becomes "minimum": 1, "maximum": 10.line 28
  12. The docstring becomes the tool description. This sentence is how the model knows what the tool is for.line 30
  13. Hit(**hit) unpacks the dict into keyword arguments: Hit(name=..., title=..., score=...). A list comprehension builds one Hit per result.line 31
  14. Runs the server only when you start this file directly (uv run server.py). When another file imports server (step 3's script, the tests), __name__ is "server", not "__main__", so the import does not start a server. Like a main method that only runs for the class you launch.line 34
  15. No arguments: the stdio transport. It blocks until the client disconnects.line 35
show_server.py
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())
  1. The MCP SDK is asynchronous (async/await, like JavaScript promises). asyncio runs the async code.line 1
  2. Importing server builds the server object but does not run it: the if __name__ guard sees a module name, not "__main__".line 6
  3. async def makes main a coroutine, like an async function in JavaScript.line 9
  4. Client(mcp) connects to the server object directly, in memory. The same Client class takes a URL (step 9) or a command to start. async with opens the connection and always closes it at the end, like try-with-resources.line 10
  5. await waits for the answer without blocking, like await in JavaScript. This sends the tools/list request.line 11
  6. input_schema is the JSON Schema the SDK built from the type hints. indent=2 pretty-prints it.line 15
  7. Calls the tool by name with a dict of arguments: the tools/call request a host sends when the model asks for the tool.line 17
  8. content is a list of blocks the **model** reads. A list return becomes one JSON text block per item.line 19
  9. structured_content is 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
  10. Starts the event loop and runs main() to the end.line 23
Run
uv run show_server.py
You should see
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}]}
Why this way? You wrote no JSON Schema and no request handling: the function signature is the contract. Compare it with lab 4, where you generated the schema yourself and parsed the arguments by hand. With MCP, that work happens once, in the server, and every host gets the same tool.
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 MCPServer and mcp = MCPServer("name").
uv run server.py seems 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.
4

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_notes while answering. Like a POST endpoint: 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, here notes://index and notes://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).

server.py 48 new or changed lines
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()
  1. ToolError for problems the model can fix; ResourceNotFoundError for a resource address that has no data.line 4
  2. 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
  3. A type alias: one reusable "note name" type with the regex from store.py. pattern goes into the JSON Schema, so a bad name is refused before your function runs. The store checks again: two layers.line 19
  4. A second tool. The argument type is the alias, so the schema says "pattern": "^[a-z0-9][a-z0-9-]{0,49}$".line 38
  5. raise X from e keeps the original exception attached, like new RuntimeException(msg, cause). The model sees "Error executing tool read_note: no note called ...".line 43
  6. The write tool. max_length matches the store's limit, so an oversized note is refused by the schema check already.line 49
  7. The docstring tells the model the rule ("never overwrites") so it does not try to update notes with this tool.line 51
  8. 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
  9. A **resource template**: {name} in the address matches the function parameter. Reading notes://onboarding calls note("onboarding"). mime_type tells the host it is Markdown.line 65
  10. Resources have no is_error result: a read either returns data or fails as a protocol error. ResourceNotFoundError is the standard "no data at that address" error.line 71
  11. A prompt: its arguments become a form in the host, and the string it returns becomes a user message.line 74
  12. The prompt tells the model how to use **this** server's tools well. Prompts are a good place to share what works.line 78
show_server.py
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())
  1. textwrap.indent puts four spaces in front of every line of a text, for readable output.line 2
  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
  3. a if condition else b is Python's condition ? a : b. Optional arguments show their default.line 13
  4. (await client.list_tools()).tools: wait for the result first (inside the parentheses), then take its .tools.line 20
  5. Reads the annotation you set. Hosts do the same to decide whether to ask the user before running a tool.line 21
  6. :<28 pads to 28 characters, left-aligned, so the columns line up.line 22
  7. Fixed resources, then templates: a template has no single address to list until someone fills in {name}.line 23
  8. Reading a resource returns contents, a list (a resource can have several parts). Ours has one text part.line 27
  9. Getting a prompt runs your prompt function with the arguments and returns the finished messages.line 29
  10. Two calls that must fail: a limit over the maximum, and a note that does not exist.line 32
  11. The exact text the model would see.line 35
Run
uv run show_server.py
You should see
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
Why this way? Look at the two errors. The first never reached your code: the SDK checked 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.
5

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:

  1. 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.
  2. Tools: pick search_notes. The form has a required query text field and an optional limit number, built from your type hints. Run it with query = staging: you get the two hits, as content blocks and as structured content.
  3. Set limit to 99 and run it again: a red error with "Input should be less than or equal to 10". Your function never ran.
  4. Resources: notes://index is listed; notes://{name} is under templates. Fill in onboarding and read it.
  5. Prompts: get summarize_notes with topic = costs and look at the user message it builds.
  6. 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
Why this way? Test a server on its own before you plug it into an app. When something fails inside a chat app, you cannot tell whether the server, the config or the model is wrong. The Inspector shows you the server alone, request by request.
Stuck on this step?
npm warn EBADENGINE or 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.py yourself: 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 --cli mode.
6

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".

client.py
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())
  1. The low-level client pieces: stdio_client (the transport), ClientSession (the protocol) and StdioServerParameters (the command to start).line 4
  2. sys.executable is the Python running this script, the project's own. So the server gets the same packages, and it works on every OS. args are the command-line arguments: run server.py from the current folder.line 6
  3. Starts the server process. as (read, write) unpacks the two message streams it yields: answers coming in, requests going out.line 10
  4. The handshake. initialize() performs the classic handshake, so you see protocol 2025-11-25. The high-level Client (step 9) negotiates the newer 2026-07-28 version when the server supports it. Your server speaks both.line 12
  5. The instructions you gave MCPServer arrive here. A host may give them to the model.line 14
  6. structured_content["result"] is the list of hits as plain dicts.line 20
  7. Path traversal through the protocol: refused by the schema check, as a tool error, before read_note runs.line 22
  8. Reads a concrete address from the template. The result has the text of release-checklist.md.line 25
Run
uv run client.py
You should see
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
Why this way? This is all a host does: start your command, run the handshake, list the tools, call them. Seeing it in 30 lines takes the mystery out of the config in the next step, and it is the base of the agent in step 8. The SDK also has a one-object shortcut, Client(StdioServerParameters(...)), which wraps the same two pieces.
Stuck on this step?
mcp.shared.exceptions.MCPError: Connection closed right after starting
The server crashed on start (its traceback is printed just above). Run uv run server.py to see the traceback. A print() at the top of server.py also breaks it: on stdio, stdout is the protocol, so log with logging (it writes to stderr) instead.
FileNotFoundError or can't open file 'server.py'
Run client.py from the project folder: args=["server.py"] is relative to the folder you start it in.
7

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%\Claude into 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.

claude_desktop_config.json
{
  "mcpServers": {
    "team-notes": {
      "command": "/Users/you/.local/bin/uv",
      "args": ["--directory", "/Users/you/code/team-notes-mcp", "run", "server.py"]
    }
  }
}
  1. Every server the app should start goes in this object, one entry each.line 2
  2. The name the app shows (and the log file name: mcp-server-team-notes.log).line 3
  3. Replace with the output of the command below: the absolute path to uv.line 4
  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
Run
which uv
pwd
You should seeyour text will differ: the model writes it
/Users/you/.local/bin/uv
/Users/you/code/team-notes-mcp
Why this way? The host runs your server as you, with your file permissions, every time the app starts. That is why the earlier steps limited it to one folder and to narrow tools. Before you add any third-party server to a config like this, read what its tools can do: you are giving that code the same access.
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. Usually uv was not found (use the absolute path from which 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.py must 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.
8

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.

agent.py
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())
  1. 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
  2. The allow-list of tools this agent may use. A set, written with braces, like Set.of(...).line 12
  3. Small models follow short, direct rules best: search first, then read, then answer and cite.line 13
  4. 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
  5. A result has a list of content blocks. Keep the text ones (search_notes returns one block per hit) and join them with newlines.line 38
  6. Mark errors clearly. The model reads the message (like "no note called ...") and can correct its call.line 39
  7. session can be a ClientSession (here) or the in-memory Client (the tests): both have list_tools() and call_tool(). Python checks for the methods when they are called ("duck typing"), so no shared interface is needed.line 42
  8. 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
  9. for _ in range(max_steps): loop at most 5 times. _ is the usual name for a loop variable you do not use.line 49
  10. Every request sends the whole conversation and the tools again: the model keeps no state between requests.line 50
  11. No tool calls: the model has written its answer.line 52
  12. The assistant message with its tool calls goes into the conversation first, as a plain dict, exactly as in lab 4.line 54
  13. Prints each call, so you can follow the agent.line 64
  14. Least privilege, enforced here: a tool outside the allow-list is never called, whatever the model asks.line 65
  15. Models write arguments as a JSON **string**. Broken JSON becomes an error message for the model, not a crash.line 69
  16. try / except / else: the else runs only when the JSON parsed. Then the call goes to the MCP server.line 72
  17. One tool message per call, tied to the request by tool_call_id.line 74
  18. A confused model can call tools forever. The cap turns that into a clear error.line 75
  19. The same nested blocks as client.py: start the server, open a session, handshake.line 82
  20. return inside async with still closes both blocks properly (the session first, then the server process).line 87
  21. Errors are caught here, **inside** the blocks, and only remembered.line 88
  22. Timeout before connection error on purpose: APITimeoutError is a subclass of APIConnectionError, and Python uses the first except that matches.line 90
  23. 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
  24. The guard again: the tests import run_agent from this file without starting an agent.line 99
Run
uv run agent.py "What do my notes say about server costs?"
You should seeyour text will differ: the model writes it
  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.
Why this way? This is the payoff of MCP. The same server now works in a desktop app, in the Inspector and in your own agent, with no changes. Without MCP, each of those would need its own copy of the tool definitions and the glue code. With it, the agent needs one small conversion function, and any MCP server you plug in next works the same way.
Stuck on this step?
Cannot reach the model server. Is Ollama running?
Open the Ollama app or run ollama serve, and check LLM_BASE_URL in .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, then LLM_MODEL=llama3.1:8b uv run agent.py "...").
Only search_notes is 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 SYSTEM rule, 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 calls search_notes and tries again with the real name.
A long traceback ending in ExceptionGroup: unhandled errors in a TaskGroup
An error escaped the async with blocks. Look at the innermost exception at the bottom: that is the real error. Catch it inside the block, as main() does.
9

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.

http_server.py
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")
  1. The same server object, tools and all. Only the transport differs.line 1
  2. A print is fine here, unlike in a stdio server: over HTTP, stdout is not the protocol channel.line 3
  3. Listens on port 8000 at the path /mcp. host="127.0.0.1" accepts connections from this machine only. 0.0.0.0 would accept the whole network: do that only behind authentication.line 5
  4. Ctrl+C raises KeyboardInterrupt. Catching it ends the server with one line instead of a traceback.line 6
http_client.py
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())
  1. A URL means Streamable HTTP. This Client negotiates the newest protocol version both sides support.line 7
  2. 2026-07-28 this time: the newer protocol revision, where each request is self-contained (no session to keep), which makes servers easier to scale.line 8
  3. The same call_tool as before. The transport is invisible to your code.line 11
Run
uv run http_client.py
You should see
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}]
Why this way? Same server, two transports: stdio for "an app on my machine starts it", HTTP for "a service many clients reach". Older guides mention an SSE transport; it was replaced by Streamable HTTP in 2025, so do not build new servers on it.
Stuck on this step?
httpx2.ConnectError / All connection attempts failed
The server is not running. Start uv run http_server.py in the other terminal first, and keep it open.
[Errno 48] Address already in use (Linux: [Errno 98])
Something else uses port 8000. Change port=8000 in http_server.py and the URL in http_client.py to another port, like 8001.
10

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.

conftest.py
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
  1. The tests import the server module to reach its mcp object and its store. The if __name__ guard keeps the import from starting a server.line 4
  2. Tells anyio's pytest plugin to run async tests on asyncio (the other choice is trio).line 9
  3. tmp_path is a new, empty folder for each test, deleted later. The tests never touch your real notes.line 14
  4. Two small notes, written fresh for every test, so every test starts from the same known state.line 15
  5. The key line: replace server.store with a store over the temporary folder, for this test only. The tools look up store when they run, so they use the test notes. monkeypatch puts the original back afterwards.line 18
  6. An async fixture: pytest awaits it. Asking for client also builds store, because this fixture asks for it.line 23
  7. raise_exceptions=True makes unexpected server crashes show their real message in the test, instead of a generic "internal error".line 24
  8. yield hands the connected client to the test; the code after it (closing the async with) runs when the test ends. Setup and teardown in one function, like @BeforeEach and @AfterEach.line 25
test_store.py
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!")
  1. Uses the store fixture from conftest.py: two notes in a temporary folder.line 6
  2. parametrize runs the test once per value: six tests from one function, like JUnit's @ParameterizedTest. "x" * 51 is a 51-character name, one over the limit.line 12
  3. The test passes only if the block raises NoteError.line 14
  4. match= also checks the message, with a regular expression search.line 24
test_server.py
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
  1. pytestmark applies the mark to every test in the file, so each async def test runs with anyio.line 3
  2. Asks for the client fixture: a connected in-memory client over the test notes.line 6
  3. Checks the description too: it is part of your contract with the model.line 13
  4. The schema check works: your function never ran, and the error names the rule.line 25
  5. Path traversal is refused by the pattern, at the protocol level.line 31
  6. The write tool really writes, into the temporary folder.line 43
test_stdio.py
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]
  1. 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
  2. Starts server.py exactly as client.py does. This catches what in-memory tests cannot: a print() that corrupts stdout, or a crash at start-up.line 9
test_agent.py
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)
  1. Builds a fake reply in which the model asks for one tool. SimpleNamespace(a=1) is a quick object with attribute a, like a JavaScript object literal.line 12
  2. The fake model. It only needs chat.completions.create, because that is all run_agent uses.line 21
  3. async def, because run_agent awaits it.line 29
  4. copy.deepcopy stores a snapshot: run_agent keeps appending to the same messages list, and the test wants to see each request as it was sent.line 30
  5. pop(0) takes the first queued reply, like queue.poll().line 31
  6. The conversion test: only the allowed tools are sent, with their MCP schema as parameters.line 38
  7. The second request must end with the tool result, tied to the call id.line 46
  8. The model asks for the write tool: it gets an error, and no file is written.line 60
  9. Three tool calls in a row with max_steps=3: the loop must stop with TooManySteps.line 65
Run
uv run pytest -q
You should see
......................                                                   [100%]
22 passed in 1.68s
Why this way? In-memory tests talk real MCP (the same requests and validation as a host), so they test your schemas and errors, not just your functions, and still run in milliseconds. One stdio test covers the transport. Whether a particular model uses your tools well is a different question, answered by evals (lab 12), not unit tests.
Stuck on this step?
The tests fail with async def functions are not natively supported
The @pytest.mark.anyio mark (or the pytestmark line) is missing, or anyio is not installed. It comes with mcp; run uv sync.
test_stdio.py fails with Connection closed
Run pytest from the project folder, so server.py is found, and check that uv run server.py starts 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.

Test
uv run pytest -q && uv run agent.py "What do my notes say about the release checklist?"
You should see
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 Field rules 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.1 until there is a login in front (OAuth or a token checked by a gateway), use HTTPS between machines, allow-list your hostnames with transport_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).

Run
rm -rf .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 "".

Exercise
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.

Exercise
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.

Download Python project (.zip)