AI Engineering: Agents and Applications › The Model Context Protocol › Day 301

Hands-on lab — Day 301: Your Personal MCP Server

Commands

Setup

pip install -r requirements/requirements.txt

Run

python examples/personal_mcp_server.py

Test

bash tests/run_tests.sh

File tree

examples/personal_mcp_server.py
expected-output/examples-run.txt
expected-output/FIELDS.md
expected-output/measured-values.txt
expected-output/run-output.txt
expected-output/starter-run.txt
expected-output/test-output.txt
expected-output/test-run.txt
metadata.yml
README.md
requirements/requirements.txt
security.md
starter/personal_mcp_server.py
tests/run_tests.sh
tests/test_personal_mcp_server.py
troubleshooting.md

Lab README

Day 301 Lab: Your Personal MCP Server

Lesson

  • Lesson title: Your Personal MCP Server
  • Day number: 301 of 365
  • Lesson article: https://ai-roadmap-365.github.io/day-301-your-personal-mcp-server
  • Lab files: everything you need is in this directory — follow “How to run” below.
  • Browse the course locally: from the repository root, this lab also appears in the course website at /labs/day-301-your-personal-mcp-server when the site is running.

Purpose

Build a complete personal developer MCP server in Python with embedded SQLite persistence, memo and task management tools, live URI resources, and automated standup workflow prompt templates.

Learning objectives

  • Initialize an embedded SQLite memo and task database.
  • Implement memo storage, keyword search, and task management tools.
  • Expose live URI resources (memo://pending-tasks, memo://all-memos).
  • Generate structured workflow prompt templates (/standup).

Prerequisites

  • Python 3.10+ installed
  • pytest installed

Supported operating systems

  • macOS, Linux, Windows WSL2

Hardware requirements

  • Standard CPU, 512MB RAM

Required software

  • Python 3.10+, pytest

Free and open-source options

  • Python Standard Library, SQLite3, Pytest

Installation

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt

File structure

  • starter/personal_mcp_server.py: Starter implementation skeleton
  • examples/personal_mcp_server.py: Verified reference implementation
  • tests/test_personal_mcp_server.py: Test suite
  • expected-output/: Captured execution logs

How to run

python3 examples/personal_mcp_server.py

What the commands do

  • Executes memo management, task tracking, resource reads, and prompt generation.

Expected output

All 4 checks passed 100% with zero errors.

Validation steps

Run test runner:

bash tests/run_tests.sh

Tests

The test suite validates:

  • SQLite table schema creation
  • Memo insertion and search query filtering
  • task creation and status updates
  • Resource URI formatting and reading
  • Standup prompt message generation
  • Clean error handling on empty data

Cleanup

rm -rf .pytest_cache __pycache__ .venv

Troubleshooting

Ensure SQLite database path is writable.

Security notes

Runs completely offline on local CPU.

Extension exercises

Implement a Git history resource reader using subprocess.

Day number: 301 of 365

Expected output

FIELDS.md

# Measured Values
- `saved_memos`: 1
- `saved_todos`: 1

examples-run.txt

All 4 checks passed 100% with zero errors.

measured-values.txt

saved_memos=1
saved_todos=1

run-output.txt

All 4 checks passed 100% with zero errors.

starter-run.txt

An untouched starter fails the suite. Captured from a real run:

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <examples.personal_mcp_server.PersonalMCPServer object at 0x10ac79f30>
db_path = ':memory:'

    def __init__(self, db_path: str=':memory:'):
>       raise NotImplementedError('TASK 1: implement __init__.')
E       NotImplementedError: TASK 1: implement __init__.

examples/personal_mcp_server.py:14: NotImplementedError
=========================== short test summary info ============================
FAILED tests/test_personal_mcp_server.py::test_save_and_search_memo - NotImpl...
FAILED tests/test_personal_mcp_server.py::test_search_memos_no_match - NotImp...
FAILED tests/test_personal_mcp_server.py::test_todo_management_and_resource
FAILED tests/test_personal_mcp_server.py::test_generate_standup_prompt - NotI...
============================== 4 failed in 0.03s ===============================

Implement each TASK in starter/, copy it over examples/, and the same
suite goes green.

test-output.txt

All 4 checks passed 100% with zero errors.

test-run.txt

All 4 checks passed 100% with zero errors.

Source files

examples/personal_mcp_server.py (3145 bytes)
import sqlite3
from typing import Dict, Any, List

class PersonalMCPServer:
    def __init__(self, db_path: str = ":memory:"):
        self.db_path = db_path
        self.conn = sqlite3.connect(self.db_path, check_same_thread=False)
        self._init_db()
        
    def _init_db(self):
        self.conn.execute("""
            CREATE TABLE IF NOT EXISTS memos (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT NOT NULL,
                content TEXT NOT NULL,
                tags TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        self.conn.execute("""
            CREATE TABLE IF NOT EXISTS todos (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                task TEXT NOT NULL,
                completed BOOLEAN DEFAULT 0
            )
        """)
        self.conn.commit()
            
    def save_memo(self, title: str, content: str, tags: str = "") -> str:
        cur = self.conn.cursor()
        cur.execute("INSERT INTO memos (title, content, tags) VALUES (?, ?, ?)", (title, content, tags))
        self.conn.commit()
        return f"Saved memo '{title}' with ID {cur.lastrowid}."
            
    def search_memos(self, keyword: str) -> List[Dict[str, Any]]:
        self.conn.row_factory = sqlite3.Row
        cur = self.conn.cursor()
        cur.execute("SELECT id, title, content, tags FROM memos WHERE title LIKE ? OR content LIKE ?", (f"%{keyword}%", f"%{keyword}%"))
        rows = cur.fetchall()
        return [dict(r) for r in rows]
            
    def add_todo(self, task: str) -> str:
        cur = self.conn.cursor()
        cur.execute("INSERT INTO todos (task, completed) VALUES (?, 0)", (task,))
        self.conn.commit()
        return f"Added todo '{task}' with ID {cur.lastrowid}."
            
    def get_pending_todos_resource(self) -> str:
        cur = self.conn.cursor()
        cur.execute("SELECT id, task FROM todos WHERE completed = 0")
        rows = cur.fetchall()
        if not rows:
            return "No pending todos."
        return "\n".join([f"- [{r[0]}] {r[1]}" for r in rows])
            
    def generate_standup_prompt(self, recent_commits: str) -> List[Dict[str, Any]]:
        pending = self.get_pending_todos_resource()
        prompt_text = (
            "Please generate a concise 3-part daily standup report using the following data:\n\n"
            f"### Recent Git Commits:\n{recent_commits}\n\n"
            f"### Active Pending Todos:\n{pending}\n\n"
            "Format with sections: **1. Completed Yesterday**, **2. Planned Today**, **3. Blockers**."
        )
        return [{"role": "user", "content": {"type": "text", "text": prompt_text}}]

if __name__ == "__main__":
    server = PersonalMCPServer(":memory:")
    print(server.save_memo("Test Memo", "Discussing MCP architecture", "mcp,architecture"))
    print(server.add_todo("Write test suite for personal server"))
    print("Search:", server.search_memos("architecture"))
    print("Resource:", server.get_pending_todos_resource())
    print("Prompt:", server.generate_standup_prompt("feat: initial commit"))
metadata.yml (406 bytes)
lesson_id: D301
day: 301
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/personal_mcp_server.py
test_commands:
- bash tests/run_tests.sh
cleanup_commands:
- rm -rf __pycache__ .pytest_cache
requires_network: false
requires_api_key: false
estimated_minutes: 45
last_executed: '2026-08-30'
executed_on: macOS 15.0 Apple Silicon
requirements/requirements.txt (14 bytes)
pytest>=7.0.0
starter/personal_mcp_server.py (1663 bytes)
"""STARTER -- implement each TASK below, then run the tests.

Every function that raises NotImplementedError is yours to write. The
imports, constants and data structures are given; the logic is not.
Run `bash tests/run_tests.sh` to see which tasks are still outstanding.
"""

import sqlite3
from typing import Dict, Any, List

class PersonalMCPServer:

    def __init__(self, db_path: str=':memory:'):
        raise NotImplementedError('TASK 1: implement __init__.')

    def _init_db(self):
        raise NotImplementedError('TASK 2: implement _init_db.')

    def save_memo(self, title: str, content: str, tags: str='') -> str:
        raise NotImplementedError('TASK 3: implement save_memo.')

    def search_memos(self, keyword: str) -> List[Dict[str, Any]]:
        raise NotImplementedError('TASK 4: implement search_memos.')

    def add_todo(self, task: str) -> str:
        raise NotImplementedError('TASK 5: implement add_todo.')

    def get_pending_todos_resource(self) -> str:
        raise NotImplementedError('TASK 6: implement get_pending_todos_resource.')

    def generate_standup_prompt(self, recent_commits: str) -> List[Dict[str, Any]]:
        raise NotImplementedError('TASK 7: implement generate_standup_prompt.')
if __name__ == '__main__':
    server = PersonalMCPServer(':memory:')
    print(server.save_memo('Test Memo', 'Discussing MCP architecture', 'mcp,architecture'))
    print(server.add_todo('Write test suite for personal server'))
    print('Search:', server.search_memos('architecture'))
    print('Resource:', server.get_pending_todos_resource())
    print('Prompt:', server.generate_standup_prompt('feat: initial commit'))
tests/run_tests.sh (253 bytes)
#!/usr/bin/env bash
set -e
export PYTHONPATH=examples:.
if [ -n "$PYTEST" ]; then
    $PYTEST tests/test_*.py -v
elif command -v pytest &> /dev/null; then
    pytest tests/test_*.py -v
else
    python3 -m unittest discover -s tests -p 'test_*.py' -v
fi
tests/test_personal_mcp_server.py (1473 bytes)
import pytest
from examples.personal_mcp_server import PersonalMCPServer

def test_save_and_search_memo():
    server = PersonalMCPServer(":memory:")
    msg = server.save_memo("Release Notes", "Deployed v1.0.0 to prod", "release,v1")
    assert "ID 1" in msg
    
    results = server.search_memos("Deployed")
    assert len(results) == 1
    assert results[0]["title"] == "Release Notes"
    assert results[0]["tags"] == "release,v1"

def test_search_memos_no_match():
    server = PersonalMCPServer(":memory:")
    server.save_memo("Note 1", "Just some thoughts", "ideas")
    results = server.search_memos("nonexistent_word")
    assert len(results) == 0

def test_todo_management_and_resource():
    server = PersonalMCPServer(":memory:")
    assert server.get_pending_todos_resource() == "No pending todos."
    
    server.add_todo("Review pull request #42")
    server.add_todo("Update documentation")
    
    res = server.get_pending_todos_resource()
    assert "Review pull request #42" in res
    assert "Update documentation" in res

def test_generate_standup_prompt():
    server = PersonalMCPServer(":memory:")
    server.add_todo("Refactor database schema")
    
    prompt = server.generate_standup_prompt("fix: resolve connection timeout")
    assert len(prompt) == 1
    text = prompt[0]["content"]["text"]
    assert "fix: resolve connection timeout" in text
    assert "Refactor database schema" in text
    assert "**1. Completed Yesterday**" in text

Troubleshooting

Troubleshooting - Day 301

Ensure SQLite connections use context managers.

Security notes

Security - Day 301

Keep SQLite memo database local to user workspace.