How to Build an MCP Server in Python (Step-by-Step)
If you want to know how to build an MCP server that connects an AI assistant to your local machine, this practical tutorial is for you. Learning how to build an MCP server allows an AI chat application to safely read personal files, save notes, and run local utilities without sending sensitive data to external servers.
If you are unfamiliar with the core protocol, explore our beginner overview: What Is MCP (Model Context Protocol)? A Beginner's Guide. If you are starting fresh, this walkthrough explains each step clearly.
By following this guide, you will master how to build an MCP server called Student Notes. It will expose clean tools to save, retrieve, and search notes on your computer using simple Python functions and variables.
What Is an MCP Server?
To understand the architecture before you learn how to build an MCP server, review its key components:
- The User: You, giving prompts to an AI assistant.
- The Host: The desktop or web app running the conversation interface.
- The MCP Client: The built-in connector inside the host app handling standardized requests.
- The MCP Server: A lightweight background program executing specific local actions.
- Tools: Specific functions you code, such as
add_noteorsearch_notes.
An MCP server is not an external web application. It runs as a local subprocess that safely exposes chosen functionality. Because the protocol is universal, one server works across any compatible AI client without custom API integrations.
For modern developer practices, see our companion article on Vibe Coding: Complete Beginner's Guide to AI Coding.
What Will We Build?
We will demonstrate how to build an MCP server equipped with three dedicated tools:
- add_note: Saves a plain text note into a local JSON file.
- read_notes: Returns all saved notes in sequential order.
- search_notes: Finds notes matching any target keyword.
This project uses no third-party APIs, requires no paid credits, and operates entirely offline on your local drive.
Prerequisites and Setup
Ensure your setup includes:
- Python 3.10+: The official MCP package requires Python 3.10 or newer.
- pip or uv: A package installer for Python libraries.
- Code Editor: VS Code or your preferred editor.
- Terminal: PowerShell, Command Prompt, or bash.
Verify your installed version:
python --version
(Use python3 --version on macOS or Linux.)
If you are new to the ecosystem, check out our Complete Python Roadmap for Beginners and browse useful utilities in Best Free Developer Tools for Students.
Step 1: Create the Project Directory
Create a dedicated workspace folder:
mkdir student-notes-mcp
cd student-notes-mcp
Your directory will contain two simple files:
student-notes-mcp/
├── server.py
└── notes.json
Step 2: Set Up Environment and Install SDK
To see how to build an MCP server cleanly, always isolate project packages within a virtual environment:
# 1. Initialize virtual environment
python -m venv venv
# 2. Activate virtual environment
# Windows:
venv\Scripts\activate
# macOS/Linux:
source venv/bin/activate
# 3. Install the MCP SDK with developer CLI tools
pip install "mcp[cli]"
Confirm the package is present:
pip show mcp
Step 3: Write the Server Code
Create server.py in your root folder. This file shows exactly how to build an MCP server with functions decorated for AI interactions:
import json
import os
from mcp.server.fastmcp import FastMCP
# Initialize the FastMCP server
mcp = FastMCP("Student Notes Server")
# Local file path for storage
NOTES_FILE = os.path.join(os.path.dirname(__file__), "notes.json")
def _load_notes() -> list[str]:
"""Helper function to load notes from disk."""
if not os.path.exists(NOTES_FILE):
return []
with open(NOTES_FILE, "r", encoding="utf-8") as f:
try:
return json.load(f)
except json.JSONDecodeError:
return []
def _save_notes(notes: list[str]) -> None:
"""Helper function to write notes to disk."""
with open(NOTES_FILE, "w", encoding="utf-8") as f:
json.dump(notes, f, indent=2)
@mcp.tool()
def add_note(text: str) -> str:
"""Add a new study note.
Args:
text: The text content of the note.
"""
clean_text = text.strip()
if not clean_text:
return "Error: Cannot save an empty note."
notes = _load_notes()
notes.append(clean_text)
_save_notes(notes)
return f"Success: Note saved. Total notes: {len(notes)}."
@mcp.tool()
def read_notes() -> str:
"""Return all saved study notes."""
notes = _load_notes()
if not notes:
return "No notes found."
return "\n".join(f"{i + 1}. {note}" for i, note in enumerate(notes))
@mcp.tool()
def search_notes(keyword: str) -> str:
"""Search notes containing a specific keyword.
Args:
keyword: The word or term to search for.
"""
notes = _load_notes()
matches = [n for n in notes if keyword.lower() in n.lower()]
if not matches:
return f"No matches found for '{keyword}'."
return "\n".join(f"- {m}" for m in matches)
if __name__ == "__main__":
mcp.run()
Step 4: Key Concepts Explained
- FastMCP Instance: Handles protocol serialization and lifecycle events behind the scenes.
@mcp.tool(): Exposes the function to connected AI clients. Function docstrings serve as the tool descriptions the AI interprets.- Type Annotations: Providing
text: strautomatically compiles schema validation definitions for client apps. - Stdio Transport:
mcp.run()sets up input/output communication channels so desktop hosts can manage it as a local child process.
Step 5: Test the Server with MCP Inspector
Before connecting to a chat application, verify how your tools run by using the built-in MCP Inspector:
mcp dev server.py
This launches an interactive testing environment in your browser window.
Run these checks:
- add_note: Submit a sample string like
"Study Python lists"to confirm success. - read_notes: Call the tool with empty arguments to list all stored notes.
- search_notes: Query
"python"to confirm case-insensitive filtering.
Step 6: Connect to an MCP Client
To connect your server to desktop applications like Claude Desktop or Cursor, configure your client's settings file with absolute system paths:
{
"mcpServers": {
"student-notes": {
"command": "python",
"args": [
"/ABSOLUTE/PATH/TO/student-notes-mcp/server.py"
]
}
}
}
Always provide the full path to your script and the virtual environment's Python binary. Save the configuration and restart your client app.
Best Practices and Troubleshooting
Quick Fixes for Common Errors
- Command Not Found: Activate your virtual environment (
source venv/bin/activateorvenv\Scripts\activate). - Inspector Fails to Start: Verify you installed dependencies with the CLI extras via
pip install "mcp[cli]". - Tools Missing in Client: Re-check your absolute file path syntax in the JSON config and restart the client.
Security Best Practices
- Scope file access strictly to your project folder to prevent unwanted file operations.
- Avoid embedding plain-text API credentials or exposing terminal command runners.
- Validate inputs and test new tools in MCP Inspector before loading them into your primary chat assistant.
Frequently Asked Questions (FAQ)
What is an MCP server?
An MCP server is a program that provides callable tools, resources, and context to AI models using the standardized Model Context Protocol.
Can a beginner learn how to build an MCP server?
Yes. The FastMCP framework makes building an MCP server easy, allowing beginners to turn standard Python functions into AI-ready tools using simple decorators.
Is Python required to create an MCP server?
No. Python is popular for its simplicity, but official Model Context Protocol SDKs are also available in TypeScript/Node.js, Kotlin, and Go.
How does MCP differ from a REST API?
A REST API requires manual endpoint documentation and custom client code. MCP uses a standard communication layer so LLMs can dynamically discover tools and their expected arguments.
Does an MCP server expose my entire drive?
No. When you build an MCP server, you control access entirely. The AI can only call the functions you implement and access the exact directories you specify.
Can one MCP server connect to multiple AI applications?
Yes. Any MCP-compliant client application can connect to and execute your local Python MCP server script.
Conclusion and Next Steps
Now that you know how to build an MCP server, you can expand its capabilities. Try adding a delete_note tool or tracking timestamps. This local architecture scales smoothly to SQL databases, internal web endpoints, and automated workflows. For complementary coding tools, check our guide to the Best AI Coding Assistants for Beginners.
Comments
Post a Comment