MCP Explained: Build Your First AI Tool Server With Claude
Learn what Model Context Protocol is and how to build your first AI tool server from scratch using Claude, with a practical step-by-step guide.

The Model Context Protocol (MCP) gives AI applications a standard way to connect to external tools and data. Instead of writing a separate integration for every AI app, you can build an MCP server and connect it to compatible hosts such as Claude Desktop or Claude Code.
This tutorial builds a local task manager backed by SQLite. Claude will help draft the code, but you will inspect it, test it and decide what permissions it should have. The finished server exposes three tools: add a task, list tasks and mark a task complete.
The guide targets the current v2 line of the official Python SDK. Older tutorials may use the v1 FastMCP import; in v2, the documented high-level server class is MCPServer. Always check the official installation guide before copying code from an older tutorial.
1. What MCP does
A language model can generate text, but it cannot automatically inspect your local database, read a private project or call an application API. Those abilities must be exposed by software the model can reach.
MCP standardises how an AI application discovers available capabilities, sends arguments, calls a tool and receives results. It is a protocol—not an AI model, database or application API. Your server still contains the business logic. The host decides how to present capabilities and when to ask the model to use them.
Host, client and server
- Host: the AI application you interact with, such as Claude Desktop or Claude Code.
- Client: the MCP component inside the host. It connects to servers and passes requests and results between the host and server.
- Server: your program. It advertises tools, resources and prompts, then handles requests from the client.
flowchart LR
U[You] --> H[Claude host]
H --> C[MCP client]
C <-->|MCP over stdio| S[Your MCP server]
S --> D[(SQLite task database)]The model does not directly open your Python file or database. The host's MCP client communicates with the server.
2. Tools, resources and prompts
MCP servers can expose three common kinds of capabilities:
| Capability | Purpose | Task-manager example |
|---|---|---|
| Tools | Actions the model can request | Add a task or complete one |
| Resources | Data the application can provide as context | A read-only task summary |
| Prompts | Reusable prompt templates | A template for reviewing today's tasks |
This project implements tools. A tool can have side effects, so do not assume it is safe just because it uses MCP. A tool that deletes files or sends money still needs careful design and permission checks.
3. Prepare the project
You need Python 3.11+, uv, Claude Desktop or Claude Code, and Node.js/npm for the MCP Inspector.
Create a project and install the SDK with its CLI extra:
mkdir claude-task-mcp
cd claude-task-mcp
uv init
uv add "mcp[cli]"The current SDK v2 is a major version with breaking changes from v1. If an example imports FastMCP, check which SDK version it targets before mixing it with this tutorial.
4. Ask Claude to vibe-code the implementation
Give Claude a specific brief rather than asking it to “make an MCP server”:
Build a local task-manager MCP server in Python using the current v2 API
from the official Model Context Protocol Python SDK.
Requirements:
- Import MCPServer from mcp.server.
- Store tasks in SQLite in tasks.db beside server.py.
- Expose exactly three tools: add_task, list_tasks and complete_task.
- Reject blank or overlong titles.
- list_tasks accepts only open, completed or all.
- complete_task accepts a positive integer ID and errors if it does not exist.
- Use SQL parameter binding. Never build SQL from user input.
- Do not add shell execution, arbitrary file access or network tools.
- Keep stdout reserved for MCP protocol messages.
- Use an if __name__ == "__main__": guard and call mcp.run().
- Explain the code and provide test commands.
Use current SDK v2 documentation, not old FastMCP v1 examples.Ask Claude to explain each function before accepting the result. Check imports, tool names, argument types, validation and database operations. Remove any extra capabilities you did not request. AI-generated code is a draft, not a security review.
5. Build the server
Create server.py with this implementation:
import sqlite3
from pathlib import Path
from mcp.server import MCPServer
mcp = MCPServer("Local Tasks")
DB_PATH = Path(__file__).with_name("tasks.db")
def open_database():
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
return connection
def initialise_database():
connection = open_database()
try:
connection.execute(
"""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
completed INTEGER NOT NULL DEFAULT 0
)
"""
)
connection.commit()
finally:
connection.close()
@mcp.tool()
def add_task(title: str) -> dict:
"""Add a task to the local task list."""
title = title.strip()
if not title:
raise ValueError("Task title cannot be blank.")
if len(title) > 200:
raise ValueError("Task title must be 200 characters or fewer.")
connection = open_database()
try:
cursor = connection.execute(
"INSERT INTO tasks (title) VALUES (?)", (title,)
)
connection.commit()
return {
"id": cursor.lastrowid,
"title": title,
"completed": False,
}
finally:
connection.close()
@mcp.tool()
def list_tasks(status: str = "open") -> list[dict]:
"""List tasks with status open, completed or all."""
if status not in {"open", "completed", "all"}:
raise ValueError("Status must be open, completed or all.")
connection = open_database()
try:
if status == "open":
rows = connection.execute(
"SELECT id, title, completed FROM tasks "
"WHERE completed = 0 ORDER BY id"
).fetchall()
elif status == "completed":
rows = connection.execute(
"SELECT id, title, completed FROM tasks "
"WHERE completed = 1 ORDER BY id"
).fetchall()
else:
rows = connection.execute(
"SELECT id, title, completed FROM tasks ORDER BY id"
).fetchall()
return [
{
"id": row["id"],
"title": row["title"],
"completed": bool(row["completed"]),
}
for row in rows
]
finally:
connection.close()
@mcp.tool()
def complete_task(task_id: int) -> dict:
"""Mark a task as complete using its numeric ID."""
if task_id < 1:
raise ValueError("Task ID must be positive.")
connection = open_database()
try:
cursor = connection.execute(
"UPDATE tasks SET completed = 1 WHERE id = ?",
(task_id,),
)
connection.commit()
if cursor.rowcount == 0:
raise ValueError(f"No task found with ID {task_id}.")
return {"id": task_id, "completed": True}
finally:
connection.close()
if __name__ == "__main__":
initialise_database()
mcp.run()The database is created beside server.py when the server starts. SQLite is included with Python, so you do not need to run a separate database service.
The code keeps a narrow permission boundary: it validates titles, allow-lists status values, checks IDs and uses SQL placeholders. It does not expose arbitrary SQL, shell commands or unrestricted file access.
The SDK uses Python type hints and docstrings to describe tool inputs. It handles protocol details, so you write application functions instead of implementing JSON-RPC yourself. See the official Python SDK.
6. Test with MCP Inspector
Test the server before connecting Claude:
uv run mcp dev server.pyThe command starts MCP Inspector and prints a local URL. It uses npx, so Node.js and npm must be installed and available on your PATH.
In the Inspector:
- Open Tools and call
add_taskwith a title such as “Read the MCP specification”. - Call
list_taskswith statusopen. - Copy the returned ID and call
complete_taskwith that ID. - Call
list_tasksagain and check that the task is marked complete. - Try an invalid status and a nonexistent ID. Confirm that the server returns clear errors.
This is a manual MCP-level test, not just a Python syntax check. The code in this article has not been executed in the reader's environment.
7. Connect to Claude Desktop
The official SDK provides an installer:
uv run mcp install server.pyIt writes a launch configuration for Claude Desktop. The official SDK guide lists these config paths:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
Using the installer helps avoid relative-path mistakes. If you edit the JSON manually, use absolute paths because the host may launch the process from a different working directory.
Fully quit Claude Desktop and reopen it. Start a conversation and ask Claude to list your open tasks. When it offers to call a task tool, inspect the action and approve it. Then ask it to add a task and list the tasks again.
If the server does not appear, check the connection logs and server stderr. Do not add debug print() calls to stdout: stdio uses stdout for MCP protocol messages.
8. Connect to Claude Code
Register the local server through the Claude Code CLI. Replace the example path with the absolute path to your own server.py:
claude mcp add local-tasks -- uv run --with "mcp[cli]" mcp run /absolute/path/to/claude-task-mcp/server.pyOpen Claude Code and enter:
/mcpThe server should appear in the MCP server list with its tools. Ask Claude Code to add a task, list open tasks and complete one. Claude Desktop and Claude Code can use the same server file; you do not need two implementations.
9. What happens when Claude calls a tool?
When you ask Claude to add a task, the host makes the tool description and input schema available to the model. The model can decide that add_task is appropriate and prepare arguments. The host's MCP client sends the call to the server over stdio. The Python function validates the title, inserts it into SQLite and returns a result. The client passes that result back to the host, which can show it in the conversation.
sequenceDiagram
participant You
participant Claude as Claude host/model
participant Client as MCP client
participant Server as Python server
participant DB as SQLite
You->>Claude: "Add a task to review MCP"
Claude->>Client: add_task(title)
Client->>Server: MCP tool call over stdio
Server->>DB: INSERT task
DB-->>Server: New task ID
Server-->>Client: Tool result
Client-->>Claude: Result
Claude-->>You: Confirms the task was addedThe model proposes the tool call; the host controls the connection and may ask you to approve it. A tool description is not a security boundary, and a model's decision to call a tool does not prove the action is safe.
10. Troubleshooting
| Symptom | What to check |
|---|---|
| Server exits immediately | Run the launch command in a terminal and read the traceback. Check imports and the Python environment. |
| Claude cannot find the server | Use absolute paths for the server file and, if needed, uv. |
| Server appears offline after config changes | Fully quit and restart Claude Desktop or restart the Claude Code session. |
| Inspector does not open | Confirm Node.js and npx are installed and on PATH. |
| Tools are missing | Confirm the server starts and the host is using the expected configuration. |
| Protocol/JSON errors | Remove stray stdout output; send diagnostics to stderr or logging. |
| Tasks seem to reset | Check that you are launching the same server.py; the database lives beside it. |
The SDK's real-host guide includes additional connection troubleshooting. Its testing guide covers deeper tests.
11. Security: an MCP server is code you run
A local stdio server is launched as a child process. It generally has the operating-system permissions of the user running the host. A malicious or poorly designed server may therefore access files, environment variables or other resources available to that process.
For a first server:
- Expose only the tools the project needs. Avoid arbitrary shell execution and unrestricted file access.
- Validate every argument on the server. Model-generated arguments are untrusted input.
- Use parameterised SQL and allow-lists for values such as status.
- Keep secrets out of source code and logs. Give the server only the credentials it needs.
- Make side effects obvious. For destructive actions, add explicit confirmation and consider a read-only mode.
- Review third-party MCP servers and their source before connecting them.
- Keep stdout reserved for the stdio protocol; send diagnostics to stderr.
- Protect remote servers with authentication, origin/host validation and appropriate network controls.
For remote MCP, the SDK supports Streamable HTTP and documents authorization separately. Do not expose a development server directly to the public internet. The SDK authorization guide explains how an MCP server validates bearer tokens; it is not a complete identity provider.
12. Local versus remote MCP
This tutorial uses stdio: Claude Desktop or Claude Code starts the server on the same machine and communicates through stdin/stdout. That is suitable for personal tools and local development.
If other people should connect without installing your Python project, deploy the server behind a stable HTTPS endpoint and use Streamable HTTP. You will also need authentication, authorization, hosting, logging, rate limits and clear data-access boundaries. Remote connector setup is separate from the local process configuration shown above.
For a new deployment, follow the current SDK transport guidance rather than copying an older tutorial that uses legacy SSE patterns.
What you built
You now have a small MCP server with persistent storage and three narrowly scoped tools. You used Claude to accelerate implementation, reviewed the generated code, tested it with Inspector and connected the same server to Claude Desktop and Claude Code.
That is the useful approach to vibe coding an MCP integration: let AI help draft the implementation, but keep requirements, code review, validation, tests and permission boundaries under your control. Start with one well-defined task, prove that it works, then expand deliberately.
Further reading
AI-assisted content
This story was drafted and/or edited with AI assistance and reviewed before publishing.
