Environment Setup and Your First MCP Server
- Install FastMCP and the MCP development tools using uv or pip and verify the installation
- Explain how FastMCP derives a tool schema from Python type hints and a docstring
- Build a working three-tool notes server in Python and run it successfully
- Apply the four tool-writing rules: clear docstrings, descriptive parameter names, string return values, focused scope
What You Are Setting Up
The development environment for this track has three components:
- Python 3.11+ — required by FastMCP and the MCP Python SDK
- FastMCP — the Python framework for building MCP servers; wraps the official MCP SDK with a decorator-based API
- MCP CLI — the command-line tool for running and inspecting MCP servers
The recommended way to manage this is with uv, the fast Python package manager. If you do not have uv: pip install uv. Then create a project directory and initialise it:
mkdir mcp-agent && cd mcp-agent uv init uv add fastmcp
This creates a pyproject.toml and installs FastMCP with all its dependencies, including the MCP Python SDK. If you prefer plain pip: pip install fastmcp. Verify the install: python -c "import fastmcp; print(fastmcp.__version__)".
You will also need Node.js installed to run MCP Inspector (covered in Lesson 6). Check with node --version — any version 18+ works. If Node is not installed, download it from nodejs.org.
The FastMCP Pattern
FastMCP is built around a single object and a decorator. You create a FastMCP instance, decorate Python functions with @mcp.tool, and call mcp.run(). FastMCP derives the tool's JSON schema from the function's type hints and uses the docstring as the tool description. That is the entire API for a basic server.
from fastmcp import FastMCP
mcp = FastMCP("My Server")
@mcp.tool
def add(a: int, b: int) -> int:
"""Add two numbers and return the result."""
return a + b
if __name__ == "__main__":
mcp.run()
Save this as server.py. That is a complete, working MCP server. When you run it, it listens on stdio by default — waiting for a client to connect and send JSON-RPC requests.
Building a More Useful First Server
A calculator is fine for demonstration, but let's build something more representative of what you will use in the capstone: a simple notes server. Create notes_server.py:
import json
from datetime import datetime
from pathlib import Path
from fastmcp import FastMCP
mcp = FastMCP("Notes")
NOTES_FILE = Path("notes.json")
def _load() -> list:
if not NOTES_FILE.exists():
return []
return json.loads(NOTES_FILE.read_text())
def _save(notes: list) -> None:
NOTES_FILE.write_text(json.dumps(notes, indent=2))
@mcp.tool
def add_note(title: str, content: str) -> str:
"""Save a new research note with a title and content."""
notes = _load()
note = {
"id": len(notes) + 1,
"title": title,
"content": content,
"created": datetime.now().isoformat(),
}
notes.append(note)
_save(notes)
return f"Note {note['id']} saved: {title}"
@mcp.tool
def list_notes() -> str:
"""List all saved notes with their IDs and titles."""
notes = _load()
if not notes:
return "No notes yet."
lines = [f"[{n['id']}] {n['title']} ({n['created'][:10]})" for n in notes]
return "
".join(lines)
@mcp.tool
def get_note(note_id: int) -> str:
"""Get the full content of a note by its ID."""
notes = _load()
for note in notes:
if note["id"] == note_id:
return f"# {note['title']}
{note['created']}
{note['content']}"
return f"Note {note_id} not found."
if __name__ == "__main__":
mcp.run()
This server has three tools: add_note, list_notes, and get_note. Notes are stored in a local JSON file. Each function's type hints become the tool's input schema; each docstring becomes the tool's description that the LLM reads to decide when to call it.
What FastMCP Does For You
Looking at add_note, the input schema FastMCP generates from the type hints is:
{
"type": "object",
"properties": {
"title": { "type": "string" },
"content": { "type": "string" }
},
"required": ["title", "content"]
}
You did not write that. FastMCP derived it from title: str, content: str. The same happens for get_note: note_id: int produces a schema with an integer type and marks it as required.
FastMCP also handles serialisation: if your function returns a Python dict or list, FastMCP converts it to a JSON string. If it returns a string, the string is passed through. If it raises an exception, FastMCP converts it to a tool execution error response with isError: true — the client receives an error message instead of crashing.
Running the Server
Run the server directly to verify it starts without errors:
python notes_server.py
The process starts and blocks, waiting for a client on stdin. This is correct — the server is now ready to receive JSON-RPC connections. Press Ctrl+C to stop it. You will not interact with it directly; MCP Inspector (Lesson 6) and your Python agent code (Lesson 9) connect to it programmatically.
You can also run it with the FastMCP CLI to get a quick status:
fastmcp run notes_server.py
This starts the server in the same way and prints the server name and registered tools to stderr before waiting for connections.
Key Rules for Writing Tools
A few rules that make tools work reliably with language models:
- Write clear docstrings. The docstring is the only description the LLM sees when deciding which tool to call. "Save a new research note" is clear; "note func" is not. Be specific about what the tool does and when to use it.
- Use descriptive parameter names.
note_id: intis clearer thann: int. Parameter names appear in the schema and the LLM uses them to understand what to pass. - Return strings, not complex objects. The LLM reads the tool's return value as text in the conversation. Return a human-readable string confirming what happened, not a raw data structure.
- Keep tools focused. One tool that does one thing is easier for the LLM to call correctly than one tool that does several things based on a mode parameter. If you find yourself adding an
action: strparameter, split the tool instead.
- FastMCP derives the tool JSON schema automatically from Python type hints — you write normal typed functions, FastMCP handles the protocol layer
- The docstring on a tool function is the description the LLM reads to decide when to call it — write it for the model, not for other developers
- A server started with mcp.run() blocks on stdin waiting for a client — this is correct; it communicates via JSON-RPC over stdio when a client connects
- FastMCP catches exceptions from tool functions and returns them as isError: true error responses — the client receives an error message rather than a crash
Progress is saved in this browser only — clear your cache or switch device and it's gone. Create a free account and it follows you everywhere.