On this article, you’ll be taught what Mannequin Context Protocol (MCP) is and easy methods to construct a easy, sensible task-tracker MCP server in Python utilizing FastMCP.
Matters we’ll cowl embody:
- How MCP works, together with hosts, shoppers, servers, and the three core primitives.
- The way to implement MCP instruments, assets, and prompts with FastMCP.
- The way to run and check your MCP server utilizing the FastMCP shopper.
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 personal knowledge or instruments? If that’s the case, you understand 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 giant 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 easy methods to construct a sensible process tracker server utilizing FastMCP. You’ll create instruments to handle duties, assets to view process lists, and prompts to information AI interactions.
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 really work together with. The host might be Claude Desktop, an IDE with AI options, or a customized app you’ve constructed. The host comprises (or interfaces with) the language mannequin and initiates connections to MCP servers.
Purchasers hook up with servers. When a number wants to speak to an MCP server, it creates a shopper occasion to handle that particular connection. One host can run a number of shoppers concurrently, every linked to a distinct server. The shopper handles all protocol-level communication.
Servers are what you construct. They expose particular capabilities — database entry, file operations, API integrations — and reply to shopper requests by offering instruments, assets, and prompts.
So the consumer interacts with the host, the host makes use of a shopper 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 varieties of performance:
Instruments are features 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.
Assets present read-only entry to knowledge. 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 “Overview this code for safety points.”
In apply, 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 Surroundings
You’ll want Python 3.10 or later. Set up FastMCP utilizing pip (or uv should you choose):
Let’s get began!
Constructing a Job Tracker Server
We’ll construct a server that manages a easy process checklist. Create a file referred to as task_server.py and add the imports:
|
from fastmcp import FastMCP from datetime import datetime |
These give us the FastMCP framework and datetime dealing with for monitoring when duties had been created.
Initializing the Server
Now arrange the server and a easy in-memory storage:
|
mcp = FastMCP(“TaskTracker”)
# Easy in-memory process storage duties = [] task_id_counter = 1 |
Right here’s what this does:
FastMCP("TaskTracker")creates your MCP server with a descriptive title.dutiesis an inventory that shops all duties.task_id_countergenerates distinctive IDs for every process.
In an actual utility, you’d use a database. For this tutorial, we’ll maintain it easy.
Creating Instruments
Instruments are features adorned with @mcp.instrument(). Let’s create three helpful instruments.
Instrument 1: Including a New Job
First, let’s create a instrument that provides duties to our checklist:
|
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 process to the duty checklist.”“” international task_id_counter
process = { “id”: task_id_counter, “title”: title, “description”: description, “standing”: “pending”, “created_at”: datetime.now().isoformat() }
duties.append(process) task_id_counter += 1
return process |
This instrument does the next:
- Takes a process title (required) and an non-obligatory description.
- Creates a process dictionary with a singular ID, standing, and timestamp.
- Provides it to our
dutieschecklist. - Returns the created process.
The mannequin can now name add_task("Write documentation", "Replace API docs") and get a structured process object again.
Instrument 2: Finishing a Job
Subsequent, let’s add a instrument to mark duties as full:
|
@mcp.instrument() def complete_task(task_id: int) -> dict: “”“Mark a process as accomplished.”“” for process in duties: if process[“id”] == task_id: process[“status”] = “accomplished” process[“completed_at”] = datetime.now().isoformat() return process
return {“error”: f“Job {task_id} not discovered”} |
The instrument searches the duty checklist for an identical ID, updates its standing to “accomplished”, and stamps it with a completion timestamp. It then returns the up to date process or an error message if no match is discovered.
Instrument 3: Deleting a Job
Lastly, add a instrument to take away duties:
|
@mcp.instrument() def delete_task(task_id: int) -> dict: “”“Delete a process from the checklist.”“” for i, process in enumerate(duties): if process[“id”] == task_id: deleted_task = duties.pop(i) return {“success”: True, “deleted”: deleted_task}
return {“success”: False, “error”: f“Job {task_id} not discovered”} |
This instrument searches for a process, removes it from the checklist, and returns affirmation with the deleted process knowledge.
These three instruments give the mannequin create, learn, replace, and delete (CRUD) operations for process administration.
Including Assets
Assets let the AI utility view knowledge with out modifying it. Let’s create two assets.
Useful resource 1: Viewing All Duties
This useful resource returns the whole process checklist:
|
@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 process in duties: status_emoji = “✅” if process[“status”] == “accomplished” else “⏳” consequence += f“{status_emoji} [{task[‘id’]}] {process[‘title’]}n” if process[“description”]: consequence += f” Description: {process[‘description’]}n” consequence += f” Standing: {process[‘status’]}n” consequence += f” Created: {process[‘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 grasp 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 process in pending: consequence += f“⏳ [{task[‘id’]}] {process[‘title’]}n” if process[“description”]: consequence += f” {process[‘description’]}n” consequence += “n”
return consequence |
The useful resource filters the duty checklist all the way down to pending objects solely, codecs them for straightforward studying, and returns a message if there’s nothing left to do.
Assets work nicely for knowledge the mannequin must learn regularly with out making modifications.
Defining Prompts
Prompts information how the AI utility interacts along 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 process checklist and supply:
1. Whole variety of duties (accomplished vs pending) 2. Any overdue or high-priority objects 3. Urged subsequent actions 4. General progress evaluation
Use the duties://all useful resource to entry the whole process checklist.”“” |
This immediate defines a structured template for process evaluation, tells the AI what info to incorporate, and references the useful resource to make use of for knowledge.
Prompts make AI interactions extra constant and helpful. When the AI mannequin makes use of this immediate, it is aware of to fetch process knowledge and analyze it on this particular format.
Working and Testing the Server
Add this code to run your server:
|
if __name__ == “__main__”: mcp.run() |
Begin the server out of your terminal:
|
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 shoppers.
Testing with the FastMCP Consumer
You may check your server utilizing FastMCP’s built-in shopper. Create a check file referred to as test_client.py and run it:
|
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 Consumer import asyncio
async def test_server(): async with Consumer(“task_server.py”) as shopper: # Record accessible instruments instruments = await shopper.list_tools() print(“Out there instruments:”, [t.name for t in tools.tools])
# Add a process consequence = await shopper.call_tool(“add_task”, { “title”: “Study MCP”, “description”: “Construct a process tracker with FastMCP” }) print(“nAdded process:”, consequence.content material[0].textual content)
# View all duties assets = await shopper.list_resources() print(“nAvailable assets:”, [r.uri for r in resources.resources])
task_list = await shopper.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 assets return knowledge. This confirms the whole lot works appropriately.
Subsequent Steps
You’ve constructed a whole MCP server with instruments, assets, 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 process scheduling.
- Use FastMCP’s built-in auth suppliers for safe entry.
Begin with easy servers like this one. As you develop extra snug, you’ll end up constructing helpful MCP servers to simplify extra of your work. Completely happy studying and constructing!
On this article, you’ll be taught what Mannequin Context Protocol (MCP) is and easy methods to construct a easy, sensible task-tracker MCP server in Python utilizing FastMCP.
Matters we’ll cowl embody:
- How MCP works, together with hosts, shoppers, servers, and the three core primitives.
- The way to implement MCP instruments, assets, and prompts with FastMCP.
- The way to run and check your MCP server utilizing the FastMCP shopper.
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 personal knowledge or instruments? If that’s the case, you understand 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 giant 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 easy methods to construct a sensible process tracker server utilizing FastMCP. You’ll create instruments to handle duties, assets to view process lists, and prompts to information AI interactions.
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 really work together with. The host might be Claude Desktop, an IDE with AI options, or a customized app you’ve constructed. The host comprises (or interfaces with) the language mannequin and initiates connections to MCP servers.
Purchasers hook up with servers. When a number wants to speak to an MCP server, it creates a shopper occasion to handle that particular connection. One host can run a number of shoppers concurrently, every linked to a distinct server. The shopper handles all protocol-level communication.
Servers are what you construct. They expose particular capabilities — database entry, file operations, API integrations — and reply to shopper requests by offering instruments, assets, and prompts.
So the consumer interacts with the host, the host makes use of a shopper 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 varieties of performance:
Instruments are features 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.
Assets present read-only entry to knowledge. 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 “Overview this code for safety points.”
In apply, 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 Surroundings
You’ll want Python 3.10 or later. Set up FastMCP utilizing pip (or uv should you choose):
Let’s get began!
Constructing a Job Tracker Server
We’ll construct a server that manages a easy process checklist. Create a file referred to as task_server.py and add the imports:
|
from fastmcp import FastMCP from datetime import datetime |
These give us the FastMCP framework and datetime dealing with for monitoring when duties had been created.
Initializing the Server
Now arrange the server and a easy in-memory storage:
|
mcp = FastMCP(“TaskTracker”)
# Easy in-memory process storage duties = [] task_id_counter = 1 |
Right here’s what this does:
FastMCP("TaskTracker")creates your MCP server with a descriptive title.dutiesis an inventory that shops all duties.task_id_countergenerates distinctive IDs for every process.
In an actual utility, you’d use a database. For this tutorial, we’ll maintain it easy.
Creating Instruments
Instruments are features adorned with @mcp.instrument(). Let’s create three helpful instruments.
Instrument 1: Including a New Job
First, let’s create a instrument that provides duties to our checklist:
|
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 process to the duty checklist.”“” international task_id_counter
process = { “id”: task_id_counter, “title”: title, “description”: description, “standing”: “pending”, “created_at”: datetime.now().isoformat() }
duties.append(process) task_id_counter += 1
return process |
This instrument does the next:
- Takes a process title (required) and an non-obligatory description.
- Creates a process dictionary with a singular ID, standing, and timestamp.
- Provides it to our
dutieschecklist. - Returns the created process.
The mannequin can now name add_task("Write documentation", "Replace API docs") and get a structured process object again.
Instrument 2: Finishing a Job
Subsequent, let’s add a instrument to mark duties as full:
|
@mcp.instrument() def complete_task(task_id: int) -> dict: “”“Mark a process as accomplished.”“” for process in duties: if process[“id”] == task_id: process[“status”] = “accomplished” process[“completed_at”] = datetime.now().isoformat() return process
return {“error”: f“Job {task_id} not discovered”} |
The instrument searches the duty checklist for an identical ID, updates its standing to “accomplished”, and stamps it with a completion timestamp. It then returns the up to date process or an error message if no match is discovered.
Instrument 3: Deleting a Job
Lastly, add a instrument to take away duties:
|
@mcp.instrument() def delete_task(task_id: int) -> dict: “”“Delete a process from the checklist.”“” for i, process in enumerate(duties): if process[“id”] == task_id: deleted_task = duties.pop(i) return {“success”: True, “deleted”: deleted_task}
return {“success”: False, “error”: f“Job {task_id} not discovered”} |
This instrument searches for a process, removes it from the checklist, and returns affirmation with the deleted process knowledge.
These three instruments give the mannequin create, learn, replace, and delete (CRUD) operations for process administration.
Including Assets
Assets let the AI utility view knowledge with out modifying it. Let’s create two assets.
Useful resource 1: Viewing All Duties
This useful resource returns the whole process checklist:
|
@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 process in duties: status_emoji = “✅” if process[“status”] == “accomplished” else “⏳” consequence += f“{status_emoji} [{task[‘id’]}] {process[‘title’]}n” if process[“description”]: consequence += f” Description: {process[‘description’]}n” consequence += f” Standing: {process[‘status’]}n” consequence += f” Created: {process[‘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 grasp 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 process in pending: consequence += f“⏳ [{task[‘id’]}] {process[‘title’]}n” if process[“description”]: consequence += f” {process[‘description’]}n” consequence += “n”
return consequence |
The useful resource filters the duty checklist all the way down to pending objects solely, codecs them for straightforward studying, and returns a message if there’s nothing left to do.
Assets work nicely for knowledge the mannequin must learn regularly with out making modifications.
Defining Prompts
Prompts information how the AI utility interacts along 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 process checklist and supply:
1. Whole variety of duties (accomplished vs pending) 2. Any overdue or high-priority objects 3. Urged subsequent actions 4. General progress evaluation
Use the duties://all useful resource to entry the whole process checklist.”“” |
This immediate defines a structured template for process evaluation, tells the AI what info to incorporate, and references the useful resource to make use of for knowledge.
Prompts make AI interactions extra constant and helpful. When the AI mannequin makes use of this immediate, it is aware of to fetch process knowledge and analyze it on this particular format.
Working and Testing the Server
Add this code to run your server:
|
if __name__ == “__main__”: mcp.run() |
Begin the server out of your terminal:
|
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 shoppers.
Testing with the FastMCP Consumer
You may check your server utilizing FastMCP’s built-in shopper. Create a check file referred to as test_client.py and run it:
|
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 Consumer import asyncio
async def test_server(): async with Consumer(“task_server.py”) as shopper: # Record accessible instruments instruments = await shopper.list_tools() print(“Out there instruments:”, [t.name for t in tools.tools])
# Add a process consequence = await shopper.call_tool(“add_task”, { “title”: “Study MCP”, “description”: “Construct a process tracker with FastMCP” }) print(“nAdded process:”, consequence.content material[0].textual content)
# View all duties assets = await shopper.list_resources() print(“nAvailable assets:”, [r.uri for r in resources.resources])
task_list = await shopper.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 assets return knowledge. This confirms the whole lot works appropriately.
Subsequent Steps
You’ve constructed a whole MCP server with instruments, assets, 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 process scheduling.
- Use FastMCP’s built-in auth suppliers for safe entry.
Begin with easy servers like this one. As you develop extra snug, you’ll end up constructing helpful MCP servers to simplify extra of your work. Completely happy studying and constructing!
















