Chapter 19 · Hands-on: build real projects
Build a simple MCP server
An MCP server is a small program that offers tools to AI apps through a standard protocol.
Chapter 19 · Hands-on: build real projects
An MCP server is a small program that offers tools to AI apps through a standard protocol.
…
Your server is a small program with named tools…
An MCP server is a small program that lists a few named tools. An AI app connects, asks what tools exist, and calls them when the model needs. Your tools will search a folder of notes and nothing else.
As in the MCP lesson, the Model Context Protocol (MCP) is a standard way for AI apps to use tools. You write the tools once, and any app that speaks MCP can use them. Here you write a server in Python with the official SDK. These tutorials are for Windows, macOS and Linux desktops.
We start a new small project, mcp-notes. You need the terminal and Python skills from Terminal basics for AI work and Set up Python and a virtual environment.
Create the folder, make a virtual environment inside it, activate it and install the official package, which is called mcp on pip. It is a modest download.
mkdir mcp-notes
cd mcp-notes
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install mcp Check: The line starts with (.venv) and the install ends without a red error.
Inside mcp-notes create a folder called notes and two text files in it: library.txt and canteen.md. Use the lines below or your own notes. This folder is the only place your server will ever read.
The library closes at 8 pm on weekdays.
Books can be borrowed for two weeks.# Canteen
Lunch is served from 12 to 2.
Fresh vegetables are on the menu every day. Check: You have mcp-notes/notes/library.txt and mcp-notes/notes/canteen.md.
Save this as notes_server.py inside mcp-notes (next to notes, not inside it). Read it slowly:
MCPServer("notes") creates the server and names it.@mcp.tool() turns a plain Python function into a tool. The function name becomes the tool name, the type hints become its inputs, and the docstring (the text in triple quotes) is what the model reads to decide when to use it. Write it clearly.notes with the extension .txt or .md. read_note compares the name with the list of allowed files instead of opening whatever path it is given, so a request like ../secret.txt cannot escape the folder.mcp.run() starts the server and talks over standard input and output.from pathlib import Path
from mcp.server.mcpserver import MCPServer
NOTES_DIR = (Path(__file__).parent / "notes").resolve()
ALLOWED = {".txt", ".md"}
mcp = MCPServer("notes")
def note_files():
return sorted(p for p in NOTES_DIR.iterdir() if p.is_file() and p.suffix in ALLOWED)
@mcp.tool()
def list_notes() -> str:
"""List the names of all note files."""
names = [p.name for p in note_files()]
return "\n".join(names) if names else "No notes found."
@mcp.tool()
def search_notes(query: str, max_results: int = 5) -> str:
"""Find note lines that contain the query (case does not matter)."""
max_results = max(1, min(max_results, 20)) # never return more than 20
matches = []
for path in note_files():
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
if query.lower() in line.lower():
matches.append(f"{path.name}:{number}: {line.strip()}")
if not matches:
return "No matching lines."
return "\n".join(matches[:max_results])
@mcp.tool()
def read_note(name: str) -> str:
"""Return the full text of one note file, by file name."""
for path in note_files():
if path.name == name:
return path.read_text(encoding="utf-8")
return f"No note called {name}. Use list_notes to see the names."
if __name__ == "__main__":
mcp.run() # talks to the AI app over standard input and output Check: The file is saved in mcp-notes. Running it directly just waits quietly, which is normal; press Ctrl+C to stop it.
Before any AI app, test the server yourself. This client script starts your server, completes the handshake, asks for its tools and calls two of them. The second call deliberately asks for a file outside the folder to prove it is refused. Save as test_client.py and run it.
import asyncio
import sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
params = StdioServerParameters(command=sys.executable, args=["notes_server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
print("Tools:", [t.name for t in tools.tools])
result = await session.call_tool("search_notes", {"query": "lunch"})
print("search_notes ->", result.content[0].text)
result = await session.call_tool("read_note", {"name": "../notes_server.py"})
print("read_note (outside the folder) ->", result.content[0].text)
asyncio.run(main())python test_client.py Check: You see Tools: ['list_notes', 'search_notes', 'read_note'], a line from canteen.md for “lunch”, and a refusal for the outside file.
Use the builder below to make a starter tool. Paste it into notes_server.py above the if __name__ line, replace the echo line with your own logic (counting words, adding two numbers, a note’s length), and add a line to test_client.py to call it. Keep it safe: no deleting, no writing, no running commands, no web requests.
Check: Your tool appears in the Tools: list when you run the test client again.
In the next lesson, Connect your MCP server to an AI app, you plug this server into a real app.
Name your tool, its input and what it does, then copy the starter into your server. This only writes Python; it does not run anything.
@mcp.tool()
def word_count(text: str) -> str:
"""Count the words in a piece of text."""
return f"You sent: {text}"This starter only echoes its input. Replace the last line with your own safe logic. Nothing you type leaves this page.
What do you see?
What does the model read to decide whether to use a tool?
Why does read_note check the name against a list instead of opening any path?
Why must a stdio server avoid print()?