Skip to main content

On This Page

Build a Task Tracker MCP Server in Python with FastMCP

5 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

Building a Simple MCP Server in Python - MachineLearningMastery.com

Model Context Protocol (MCP) standardizes AI model interactions with external systems. FastMCP is a framework simplifying the creation of MCP servers, enabling LLMs to connect to custom data and tools.

Why This Matters

Connecting large language models (LLMs) to proprietary data or custom tools traditionally involves complex custom integrations, schema management, and authentication overhead. Each new AI application often requires rebuilding this foundational connection logic from scratch. MCP addresses this by providing a standardized protocol for AI models to communicate with external systems. This standardization reduces development time and complexity, allowing developers to focus on the core AI capabilities rather than the integration plumbing. FastMCP, a framework for building MCP servers, further simplifies this process by offering a streamlined approach to exposing tools, resources, and prompts.

Key Insights

  • Model Context Protocol (MCP) defines how AI applications communicate with external systems, comprising Hosts, Clients, and Servers (MachineLearningMastery.com).
  • MCP servers expose three core primitives: Tools for actions (e.g., add_task), Resources for read-only data access (e.g., tasks://all), and Prompts for guiding AI interactions (MachineLearningMastery.com).
  • FastMCP simplifies MCP server development in Python, requiring Python 3.10+ and installation via pip install fastmcp (MachineLearningMastery.com).
  • A practical task tracker server can be built using FastMCP, exposing tools for CRUD operations on tasks, resources for viewing task lists, and prompts for structured AI analysis (MachineLearningMastery.com).
  • Testing MCP servers is facilitated by the FastMCP client, allowing programmatic interaction with defined tools and resources (MachineLearningMastery.com).

Working Examples

Full Python code for a task tracker MCP server using FastMCP, including tools for adding, completing, and deleting tasks, resources for viewing tasks, and a prompt for task summarization.

from fastmcp import FastMCP
from datetime import datetime

mcp = FastMCP("TaskTracker")

# Simple in-memory task storage
tasks = []
task_id_counter = 1

@mcp.tool()
def add_task(title: str, description: str = "") -> dict:
    """Add a new task to the task list."""
    global task_id_counter
    task = {
        "id": task_id_counter,
        "title": title,
        "description": description,
        "status": "pending",
        "created_at": datetime.now().isoformat()
    }
    tasks.append(task)
    task_id_counter += 1
    return task

@mcp.tool()
def complete_task(task_id: int) -> dict:
    """Mark a task as completed."""
    for task in tasks:
        if task["id"] == task_id:
            task["status"] = "completed"
            task["completed_at"] = datetime.now().isoformat()
            return task
    return {"error": f"Task {task_id} not found"}

@mcp.tool()
def delete_task(task_id: int) -> dict:
    """Delete a task from the list."""
    for i, task in enumerate(tasks):
        if task["id"] == task_id:
            deleted_task = tasks.pop(i)
            return {"success": True, "deleted": deleted_task}
    return {"success": False, "error": f"Task {task_id} not found"}

@mcp.resource("tasks://all")
def get_all_tasks() -> str:
    """Get all tasks as formatted text."""
    if not tasks:
        return "No tasks found"
    result = "Current Tasks:\n\n"
    for task in tasks:
        status_emoji = "✅" if task["status"] == "completed" else "⏳"
        result += f"{status_emoji} [{task['id']}] {task['title']}\n"
        if task["description"]:
            result += f" Description: {task['description']}\n"
        result += f" Status: {task['status']}\n"
        result += f" Created: {task['created_at']}\n\n"
    return result

@mcp.resource("tasks://pending")
def get_pending_tasks() -> str:
    """Get only pending tasks."""
    pending = [t for t in tasks if t["status"] == "pending"]
    if not pending:
        return "No pending tasks!"
    result = "Pending Tasks:\n\n"
    for task in pending:
        result += f"⏳ [{task['id']}] {task['title']}\n"
        if task["description"]:
            result += f" {task['description']}\n"
        result += "\n"
    return result

@mcp.prompt()
def task_summary_prompt() -> str:
    """Generate a prompt for summarizing tasks."""
    return """Please analyze the current task list and provide: 1. Total number of tasks (completed vs pending) 2. Any overdue or high-priority items 3. Suggested next actions 4. Overall progress assessment Use the tasks://all resource to access the complete task list."""

if __name__ == "__main__":
    mcp.run()

Python code using the FastMCP client to test the task tracker server by listing tools, adding a task, listing resources, and reading the task list.

from fastmcp import Client
import asyncio

async def test_server():
    async with Client("task_server.py") as client:
        # List available tools
        tools = await client.list_tools()
        print("Available tools:", [t.name for t in tools.tools])

        # Add a task
        result = await client.call_tool("add_task", {
            "title": "Learn MCP",
            "description": "Build a task tracker with FastMCP"
        })
        print("\nAdded task:", result.content[0].text)

        # View all tasks
        resources = await client.list_resources()
        print("\nAvailable resources:", [r.uri for r in resources.resources])
        task_list = await client.read_resource("tasks://all")
        print("\nAll tasks:\n", task_list.contents[0].text)

asyncio.run(test_server())

Practical Applications

  • AI Assistant (System + Behavior): An AI assistant uses MCP tools to interact with a task management system, allowing users to add, update, and query tasks via natural language prompts.
  • Data Integration (System + Behavior): An LLM integrates with a company’s internal knowledge base by using MCP resources to fetch relevant documentation and tools to update records.
  • Development Workflow (Pitfall + Consequence): Relying solely on ad-hoc API integrations for LLM-tool interaction leads to duplicated effort and maintenance overhead across projects.
  • Automated Reporting (System + Behavior): An MCP server provides access to financial data resources and tools for generating reports, enabling an AI to provide real-time financial summaries.

References:

Continue reading

Next article

Genesys to Deploy on AWS European Sovereign Cloud for Data Compliance

Related Content