Velamuvi AIAcademy

Lesson 9 of 9 · Building

Project: MCP Server for Your Data

Build an MCP server so AI apps can answer questions about your data: read-only SQLite, validated tools, a schema resource, a prompt, tests and a real host.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Design tools around the questions people ask about a dataset
  • Build a read-only, validated MCP server over a SQLite database
  • Add a resource and a prompt that make the server easier to use
  • Test the server and connect it to an AI app

The goal

You keep your spending in a small database. You want to ask an AI app questions like “How much did I spend eating out in October?” or “Compare groceries over the last three months”, and get answers from your real data, in any MCP-compatible app. The server should be read-only: no AI should be able to change your records.

Design the tools first

Start from the questions, not the database. Three focused tools answer most of them:

ToolAnswers questions like
spending_by_category(month)“Where did my money go in October?”
monthly_totals(category?)“Is my grocery spending going up?”
search_transactions(text, limit)“When did I last eat at Sushi Go?”

A single run_sql(query) tool would be more flexible, but riskier and harder for the model to use well (see the security lesson). Specific tools are safer and give better answers.

The logic, runnable here

The functions behind the tools are ordinary Python and SQL. Try them here, with an in-memory database of sample transactions:

Try it yourselfPython
import sqlite3

def make_sample_db(conn):
    conn.execute("CREATE TABLE IF NOT EXISTS transactions (date TEXT, merchant TEXT, category TEXT, amount REAL)")
    rows = [
        ("2026-09-02", "FreshMart", "groceries", 64.20), ("2026-09-05", "City Metro", "transport", 30.00),
        ("2026-09-11", "Pasta Bar", "eating out", 38.50), ("2026-09-19", "FreshMart", "groceries", 71.35),
        ("2026-09-27", "BookNook", "books", 22.99), ("2026-10-03", "FreshMart", "groceries", 58.10),
        ("2026-10-05", "City Metro", "transport", 30.00), ("2026-10-14", "Sushi Go", "eating out", 46.00),
        ("2026-10-22", "FreshMart", "groceries", 80.45), ("2026-10-30", "Pasta Bar", "eating out", 29.75),
        ("2026-11-02", "FreshMart", "groceries", 66.80), ("2026-11-05", "City Metro", "transport", 30.00),
        ("2026-11-09", "BookNook", "books", 15.50), ("2026-11-12", "Sushi Go", "eating out", 52.25),
    ]
    conn.executemany("INSERT INTO transactions VALUES (?, ?, ?, ?)", rows)
    conn.commit()

def spending_by_category(conn, month):
    """Total spent per category in one month (YYYY-MM), biggest first."""
    rows = conn.execute(
        "SELECT category, ROUND(SUM(amount), 2) FROM transactions "
        "WHERE substr(date, 1, 7) = ? GROUP BY category ORDER BY SUM(amount) DESC", (month,))
    return [{"category": c, "total": t} for c, t in rows]

def monthly_totals(conn, category=None):
    """Total per month, for one category or for everything."""
    sql = "SELECT substr(date, 1, 7) AS month, ROUND(SUM(amount), 2) FROM transactions"
    params = ()
    if category:
        sql += " WHERE category = ?"
        params = (category,)
    rows = conn.execute(sql + " GROUP BY month ORDER BY month", params)
    return [{"month": m, "total": t} for m, t in rows]

def search_transactions(conn, text, limit=5):
    """Transactions whose merchant or category contains `text`, newest first."""
    rows = conn.execute(
        "SELECT date, merchant, category, amount FROM transactions "
        "WHERE merchant LIKE ? OR category LIKE ? ORDER BY date DESC LIMIT ?",
        (f"%{text}%", f"%{text}%", min(limit, 50)))
    return [dict(zip(["date", "merchant", "category", "amount"], r)) for r in rows]

# ---- Try the functions the MCP server will expose as tools ----
conn = sqlite3.connect(":memory:")
make_sample_db(conn)

print("Spending by category, 2026-10:")
for row in spending_by_category(conn, "2026-10"):
    print("  ", row)
print("Eating out per month:", monthly_totals(conn, "eating out"))
print("Search 'sushi':", search_transactions(conn, "sushi"))
print("A sneaky search:", search_transactions(conn, "x' OR '1'='1"))    # parameters keep this harmless

Every query uses parameters (?), never text pasted into SQL, so the “sneaky search” is treated as plain text and matches nothing.

The server

On your computer, save this as expenses_server.py. Run python expenses_server.py --create-sample once to make a sample database, then connect it to an app as in the earlier lesson:

"""expenses_server.py: an MCP server that lets AI apps answer questions about your spending.

Run once to create a sample database:  python expenses_server.py --create-sample
Then connect it to an AI app (see the previous lesson)."""
import sqlite3
import sys
from pathlib import Path
from typing import Annotated

from pydantic import Field

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

DB_PATH = Path(__file__).parent / "expenses.db"

mcp = MCPServer("Expenses", instructions="Read-only access to the user's spending records.")


def connect():
    # mode=ro opens the database READ-ONLY: no tool can change or delete data
    return sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)


@mcp.tool()
def spending_by_category(
    month: Annotated[str, Field(description="Month in YYYY-MM format, e.g. 2026-10", pattern=r"^\d{4}-\d{2}$")],
) -> list[dict]:
    """Total spent per category in one month, biggest first. Returns category and total in euros."""
    with connect() as conn:
        rows = conn.execute(
            "SELECT category, ROUND(SUM(amount), 2) FROM transactions "
            "WHERE substr(date, 1, 7) = ? GROUP BY category ORDER BY SUM(amount) DESC", (month,)).fetchall()
    if not rows:
        raise ToolError(f"No transactions in {month}. Data covers 2026-09 to 2026-11.")
    return [{"category": c, "total": t} for c, t in rows]


@mcp.tool()
def monthly_totals(
    category: Annotated[str | None, Field(description="Optional category, e.g. 'groceries'")] = None,
) -> list[dict]:
    """Total spent per month, for one category or for everything. Returns month and total in euros."""
    sql = "SELECT substr(date, 1, 7) AS month, ROUND(SUM(amount), 2) FROM transactions"
    params: tuple = ()
    if category:
        sql += " WHERE category = ?"
        params = (category,)
    with connect() as conn:
        rows = conn.execute(sql + " GROUP BY month ORDER BY month", params).fetchall()
    return [{"month": m, "total": t} for m, t in rows]


@mcp.tool()
def search_transactions(
    text: Annotated[str, Field(description="Part of a merchant or category name, e.g. 'sushi'")],
    limit: Annotated[int, Field(ge=1, le=50, description="Maximum number of results")] = 10,
) -> list[dict]:
    """Find transactions by merchant or category, newest first."""
    with connect() as conn:
        rows = conn.execute(
            "SELECT date, merchant, category, amount FROM transactions "
            "WHERE merchant LIKE ? OR category LIKE ? ORDER BY date DESC LIMIT ?",
            (f"%{text}%", f"%{text}%", limit)).fetchall()
    return [dict(zip(["date", "merchant", "category", "amount"], r)) for r in rows]


@mcp.resource("expenses://schema", mime_type="text/plain")
def schema() -> str:
    """What the data contains."""
    return "Table transactions: date (YYYY-MM-DD), merchant, category, amount (euros)."


@mcp.prompt()
def monthly_review(month: str) -> str:
    """Review one month's spending."""
    return (f"Use the expenses tools to review my spending in {month}: totals by category, "
            "how it compares with the previous month, and one practical suggestion.")


def create_sample():
    conn = sqlite3.connect(DB_PATH)
    conn.execute("CREATE TABLE IF NOT EXISTS transactions (date TEXT, merchant TEXT, category TEXT, amount REAL)")
    conn.executemany("INSERT INTO transactions VALUES (?, ?, ?, ?)", [
        ("2026-09-02", "FreshMart", "groceries", 64.20), ("2026-09-11", "Pasta Bar", "eating out", 38.50),
        ("2026-10-03", "FreshMart", "groceries", 58.10), ("2026-10-14", "Sushi Go", "eating out", 46.00),
        ("2026-11-02", "FreshMart", "groceries", 66.80), ("2026-11-12", "Sushi Go", "eating out", 52.25),
    ])
    conn.commit()
    conn.close()


if __name__ == "__main__":
    if "--create-sample" in sys.argv:
        create_sample()
        print("Created", DB_PATH, file=sys.stderr)     # stderr: stdout belongs to the protocol
    else:
        mcp.run()

The key safety and quality features:

  • Read-only database access: mode=ro means even a buggy or tricked tool can't change data.
  • Validated arguments: the pattern on month and the ge/le limits on limit are enforced by the SDK before your code runs.
  • Helpful errors: an empty month raises ToolError with the range of available data, so the model can correct itself.
  • A resource (expenses://schema) describing the data, and a prompt (monthly_review) users can pick to start a review.
  • Logs to stderr: the --create-sample message is printed to standard error, keeping stdout clean for the protocol.

Tested with the SDK's in-memory client, a few calls give:

Output
spending_by_category {'month': '2026-10'} -> {'result': [{'category': 'groceries', 'total': 58.1}, {'category': 'eating out', 'total': 46.0}]}
spending_by_category {'month': '2025-01'} -> error: No transactions in 2025-01. Data covers 2026-09 to 2026-11.
spending_by_category {'month': 'October'} -> error: String should match pattern '^\d{4}-\d{2}$'
search_transactions {'text': 'sushi', 'limit': 99} -> error: Input should be less than or equal to 50

Things to try

  1. Add the top_merchant(month) tool from the exercise below.
  2. Add a categories resource listing every category, so the app can show the model the valid names.
  3. Point DB_PATH at a copy of a real export from your bank (as CSV converted to SQLite), and ask your own questions.
  4. Run it over HTTP with mcp.run("streamable-http") and connect with the in-memory test replaced by Client("http://localhost:8000/mcp").

Common mistakes

Practice exercise

Write the logic for one more tool your data server could offer.

Your solutionPython
transactions = [
    {"date": "2026-10-03", "merchant": "FreshMart", "amount": 58.10},
    {"date": "2026-10-14", "merchant": "Sushi Go", "amount": 46.00},
    {"date": "2026-10-22", "merchant": "FreshMart", "amount": 80.45},
    {"date": "2026-10-30", "merchant": "Pasta Bar", "amount": 29.75},
    {"date": "2026-11-02", "merchant": "FreshMart", "amount": 66.80},
]

def top_merchant(month):
    # A new tool for the expenses server: the merchant with the highest total
    # spending in `month` (YYYY-MM). Return a string like: "FreshMart: 12.34"
    return ""

print(top_merchant("2026-10"))
Knowledge check

Why does the expenses server open the database with mode=ro?

Summary

  • Design tools around the questions people ask, not around the database's tables.
  • Keep data access read-only, use parameterised queries, and let the SDK validate arguments.
  • Add resources and prompts to make the server easy to use, and return small, aggregated results.
  • Test in memory, then connect to any MCP host.

Course complete

You now understand what MCP is, how hosts, clients and servers fit together, what tools, resources and prompts are, how the stdio and Streamable HTTP transports work, how to build and test a server with the Python SDK, how to connect it to AI apps, how to keep it secure, and how to expose your own data safely.

Finished reading? Tick it off to track your progress.