On this article, you’ll be taught what Mannequin Context Protocol (MCP) is and tips on how to construct a easy, sensible task-tracker MCP server in Python utilizing FastMCP.
Matters we’ll cowl embody:
How MCP works, together with hosts, purchasers, servers, and the three core primitives.
Easy methods to implement MCP instruments, sources, and prompts with FastMCP.
Easy methods to run and check your MCP server utilizing the FastMCP consumer.
Let’s not waste any extra time.
Constructing a Easy MCP Server in Python
Picture by Editor
Introduction
Have you ever ever tried connecting a language mannequin to your individual information or instruments? In that case, you recognize it typically means writing customized integrations, managing API schemas, and wrestling with authentication. And each new AI utility can really feel like rebuilding the identical connection logic from scratch.
Mannequin Context Protocol (MCP) solves this by standardizing how massive language fashions (LLMs) and different AI fashions work together with exterior programs. FastMCP is a framework that makes constructing MCP servers easy.
On this article, you’ll be taught what MCP is, the way it works, and tips on how to construct a sensible activity tracker server utilizing FastMCP. You’ll create instruments to handle duties, sources to view activity lists, and prompts to information AI interactions.
You will get the code on GitHub.
Understanding the Mannequin Context Protocol
As talked about, Mannequin Context Protocol (MCP) is an open protocol that defines how AI purposes talk with exterior programs.
How MCP Works
MCP has three parts:
Hosts are the AI-powered purposes customers truly work together with. The host could be Claude Desktop, an IDE with AI options, or a customized app you’ve constructed. The host incorporates (or interfaces with) the language mannequin and initiates connections to MCP servers.
Purchasers connect with servers. When a bunch wants to speak to an MCP server, it creates a consumer occasion to handle that particular connection. One host can run a number of purchasers concurrently, every related to a distinct server. The consumer handles all protocol-level communication.
Servers are what you construct. They expose particular capabilities — database entry, file operations, API integrations — and reply to consumer requests by offering instruments, sources, and prompts.
So the consumer interacts with the host, the host makes use of a consumer to speak to your server, and the server returns structured outcomes again up the chain.
To be taught extra about MCP, learn The Full Information to Mannequin Context Protocol.
The Three Core Primitives
MCP servers expose three forms of performance:
Instruments are capabilities that carry out actions. They’re like executable instructions the LLM can invoke. add_task, send_an_email, and query_a_database are some examples of instruments.
Sources present read-only entry to information. They permit viewing info with out altering it. Examples embody lists of duties, configuration information, and consumer profiles.
Prompts are templates that information AI interactions. They construction how the mannequin approaches particular duties. Examples embody “Analyze these duties and recommend priorities” and “Evaluate this code for safety points.”
In observe, you’ll mix these primitives. An AI mannequin may use a useful resource to view duties, then a instrument to replace one, guided by a immediate that defines the workflow.
Setting Up Your Atmosphere
You’ll want Python 3.10 or later. Set up FastMCP utilizing pip (or uv in the event you want):
Let’s get began!
Constructing a Process Tracker Server
We’ll construct a server that manages a easy activity listing. Create a file referred to as task_server.py and add the imports:
from fastmcp import FastMCP
from datetime import datetime
from fastmcp import FastMCP
from datetime import datetime
These give us the FastMCP framework and datetime dealing with for monitoring when duties have been created.
Initializing the Server
Now arrange the server and a easy in-memory storage:
mcp = FastMCP(“TaskTracker”)
# Easy in-memory activity storage
duties = []
task_id_counter = 1
mcp = FastMCP(“TaskTracker”)
# Easy in-memory activity storage
duties = []
task_id_counter = 1
Right here’s what this does:
FastMCP(“TaskTracker”) creates your MCP server with a descriptive title.
duties is a listing that shops all duties.
task_id_counter generates distinctive IDs for every activity.
In an actual utility, you’d use a database. For this tutorial, we’ll hold it easy.
Creating Instruments
Instruments are capabilities embellished with @mcp.instrument(). Let’s create three helpful instruments.
Instrument 1: Including a New Process
First, let’s create a instrument that provides duties to our listing:
@mcp.instrument()
def add_task(title: str, description: str = “”) -> dict:
“””Add a brand new activity to the duty listing.”””
international task_id_counter
activity = {
“id”: task_id_counter,
“title”: title,
“description”: description,
“standing”: “pending”,
“created_at”: datetime.now().isoformat()
}
duties.append(activity)
task_id_counter += 1
return activity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@mcp.instrument()
def add_task(title: str, description: str = “”) -> dict:
“”“Add a brand new activity to the duty listing.”“”
international task_id_counter
activity = {
“id”: task_id_counter,
“title”: title,
“description”: description,
“standing”: “pending”,
“created_at”: datetime.now().isoformat()
}
duties.append(activity)
task_id_counter += 1
return activity
This instrument does the next:
Takes a activity title (required) and an optionally available description.
Creates a activity dictionary with a novel ID, standing, and timestamp.
Provides it to our duties listing.
Returns the created activity.
The mannequin can now name add_task(“Write documentation”, “Replace API docs”) and get a structured activity object again.
Instrument 2: Finishing a Process
Subsequent, let’s add a instrument to mark duties as full:
@mcp.instrument()
def complete_task(task_id: int) -> dict:
“””Mark a activity as accomplished.”””
for activity in duties:
if activity[“id”] == task_id:
activity[“status”] = “accomplished”
activity[“completed_at”] = datetime.now().isoformat()
return activity
return {“error”: f”Process {task_id} not discovered”}
@mcp.instrument()
def complete_task(task_id: int) -> dict:
“”“Mark a activity as accomplished.”“”
for activity in duties:
if activity[“id”] == task_id:
activity[“status”] = “accomplished”
activity[“completed_at”] = datetime.now().isoformat()
return activity
return {“error”: f“Process {task_id} not discovered”}
The instrument searches the duty listing for an identical ID, updates its standing to “accomplished”, and stamps it with a completion timestamp. It then returns the up to date activity or an error message if no match is discovered.
Instrument 3: Deleting a Process
Lastly, add a instrument to take away duties:
@mcp.instrument()
def delete_task(task_id: int) -> dict:
“””Delete a activity from the listing.”””
for i, activity in enumerate(duties):
if activity[“id”] == task_id:
deleted_task = duties.pop(i)
return {“success”: True, “deleted”: deleted_task}
return {“success”: False, “error”: f”Process {task_id} not discovered”}
@mcp.instrument()
def delete_task(task_id: int) -> dict:
“”“Delete a activity from the listing.”“”
for i, activity in enumerate(duties):
if activity[“id”] == task_id:
deleted_task = duties.pop(i)
return {“success”: True, “deleted”: deleted_task}
return {“success”: False, “error”: f“Process {task_id} not discovered”}
This instrument searches for a activity, removes it from the listing, and returns affirmation with the deleted activity information.
These three instruments give the mannequin create, learn, replace, and delete (CRUD) operations for activity administration.
Including Sources
Sources let the AI utility view information with out modifying it. Let’s create two sources.
Useful resource 1: Viewing All Duties
This useful resource returns the whole activity listing:
@mcp.useful resource(“duties://all”)
def get_all_tasks() -> str:
“””Get all duties as formatted textual content.”””
if not duties:
return “No duties discovered”
consequence = “Present Duties:nn”
for activity in duties:
status_emoji = “✅” if activity[“status”] == “accomplished” else “⏳”
consequence += f”{status_emoji} [{task[‘id’]}] {activity[‘title’]}n”
if activity[“description”]:
consequence += f” Description: {activity[‘description’]}n”
consequence += f” Standing: {activity[‘status’]}n”
consequence += f” Created: {activity[‘created_at’]}nn”
return consequence
@mcp.useful resource(“duties://all”)
def get_all_tasks() -> str:
“”“Get all duties as formatted textual content.”“”
if not duties:
return “No duties discovered”
consequence = “Present Duties:nn”
for activity in duties:
status_emoji = “✅” if activity[“status”] == “accomplished” else “⏳”
consequence += f“{status_emoji} [{task[‘id’]}] {activity[‘title’]}n”
if activity[“description”]:
consequence += f” Description: {activity[‘description’]}n”
consequence += f” Standing: {activity[‘status’]}n”
consequence += f” Created: {activity[‘created_at’]}nn”
return consequence
Right here’s how this works:
The decorator @mcp.useful resource(“duties://all”) creates a useful resource with a URI-like identifier.
The operate codecs all duties into readable textual content with emojis for visible readability.
It returns a easy message if no duties exist.
The AI utility can learn this useful resource to know the present state of all duties.
Useful resource 2: Viewing Pending Duties Solely
This useful resource filters for incomplete duties:
@mcp.useful resource(“duties://pending”)
def get_pending_tasks() -> str:
“””Get solely pending duties.”””
pending = [t for t in tasks if t[“status”] == “pending”]
if not pending:
return “No pending duties!”
consequence = “Pending Duties:nn”
for activity in pending:
consequence += f”⏳ [{task[‘id’]}] {activity[‘title’]}n”
if activity[“description”]:
consequence += f” {activity[‘description’]}n”
consequence += “n”
return consequence
@mcp.useful resource(“duties://pending”)
def get_pending_tasks() -> str:
“”“Get solely pending duties.”“”
pending = [t for t in tasks if t[“status”] == “pending”]
if not pending:
return “No pending duties!”
consequence = “Pending Duties:nn”
for activity in pending:
consequence += f“⏳ [{task[‘id’]}] {activity[‘title’]}n”
if activity[“description”]:
consequence += f” {activity[‘description’]}n”
consequence += “n”
return consequence
The useful resource filters the duty listing right down to pending gadgets solely, codecs them for straightforward studying, and returns a message if there’s nothing left to do.
Sources work properly for information the mannequin must learn continuously with out making adjustments.
Defining Prompts
Prompts information how the AI utility interacts together with your server. Let’s create a useful immediate:
@mcp.immediate()
def task_summary_prompt() -> str:
“””Generate a immediate for summarizing duties.”””
return “””Please analyze the present activity listing and supply:
1. Complete variety of duties (accomplished vs pending)
2. Any overdue or high-priority gadgets
3. Steered subsequent actions
4. General progress evaluation
Use the duties://all useful resource to entry the whole activity listing.”””
@mcp.immediate()
def task_summary_prompt() -> str:
“”“Generate a immediate for summarizing duties.”“”
return “”“Please analyze the present activity listing and supply:
1. Complete variety of duties (accomplished vs pending)
2. Any overdue or high-priority gadgets
3. Steered subsequent actions
4. General progress evaluation
Use the duties://all useful resource to entry the whole activity listing.”“”
This immediate defines a structured template for activity evaluation, tells the AI what info to incorporate, and references the useful resource to make use of for information.
Prompts make AI interactions extra constant and helpful. When the AI mannequin makes use of this immediate, it is aware of to fetch activity information and analyze it on this particular format.
Working and Testing the Server
Add this code to run your server:
if __name__ == “__main__”:
mcp.run()
if __name__ == “__main__”:
mcp.run()
Begin the server out of your terminal:
fastmcp run task_server.py
fastmcp run task_server.py
You’ll see output confirming the server is operating. Now the server is able to settle for connections from MCP purchasers.
Testing with the FastMCP Shopper
You possibly can check your server utilizing FastMCP’s built-in consumer. Create a check file referred to as test_client.py and run it:
from fastmcp import Shopper
import asyncio
async def test_server():
async with Shopper(“task_server.py”) as consumer:
# Record accessible instruments
instruments = await consumer.list_tools()
print(“Obtainable instruments:”, [t.name for t in tools.tools])
# Add a activity
consequence = await consumer.call_tool(“add_task”, {
“title”: “Study MCP”,
“description”: “Construct a activity tracker with FastMCP”
})
print(“nAdded activity:”, consequence.content material[0].textual content)
# View all duties
sources = await consumer.list_resources()
print(“nAvailable sources:”, [r.uri for r in resources.resources])
task_list = await consumer.read_resource(“duties://all”)
print(“nAll duties:n”, task_list.contents[0].textual content)
asyncio.run(test_server())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from fastmcp import Shopper
import asyncio
async def test_server():
async with Shopper(“task_server.py”) as consumer:
# Record accessible instruments
instruments = await consumer.list_tools()
print(“Obtainable instruments:”, [t.name for t in tools.tools])
# Add a activity
consequence = await consumer.call_tool(“add_task”, {
“title”: “Study MCP”,
“description”: “Construct a activity tracker with FastMCP”
})
print(“nAdded activity:”, consequence.content material[0].textual content)
# View all duties
sources = await consumer.list_resources()
print(“nAvailable sources:”, [r.uri for r in resources.resources])
task_list = await consumer.read_resource(“duties://all”)
print(“nAll duties:n”, task_list.contents[0].textual content)
asyncio.run(test_server())
You’ll see your instruments execute and sources return information. This confirms all the things works accurately.
Subsequent Steps
You’ve constructed an entire MCP server with instruments, sources, and prompts. Right here’s what you are able to do to enhance it:
Add persistence by changing in-memory storage with SQLite or PostgreSQL.
Add instruments to filter duties by standing, date, or key phrases.
Construct prompts for precedence evaluation or activity scheduling.
Use FastMCP’s built-in auth suppliers for safe entry.
Begin with easy servers like this one. As you develop extra comfy, you’ll end up constructing helpful MCP servers to simplify extra of your work. Joyful studying and constructing!


