AI Hints
Home›MCP Tutorial›Async, State and Databases
MCP · Lesson 21 of 120

A Database Tool

SQLite.

⏱ 2 min read▶ Video at 18:51🎓 Free
Watch this lesson in the MCP courseWatch on YouTube ↗Full MCP course

Most real tools read from a database. Let's give the model safe access to Northwind's orders, using SQLite. The tool runs one fixed query, and the model only supplies the order number.

A Database Tool
From the video: A Database Tool
  • Real data
  • SQLite
  • One fixed query

Orders from SQLite

We create an orders table, with two orders. The tool runs a query with a question mark placeholder, so the order number can't change the SQL. Run it. One order is found, and the other is reported missing.

db_tool.pypython
import sqlite3
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from tester import call

db = sqlite3.connect(":memory:", check_same_thread=False)
db.execute("CREATE TABLE orders (id INT, status TEXT, total REAL)")
db.executemany("INSERT INTO orders VALUES (?, ?, ?)", [(1042, "shipped", 89.0), (1043, "packing", 24.5)])
mcp = MCPServer("orders")

@mcp.tool()
def order_status(order_id: int) -> str:
    """Look up a Northwind order's status and total."""
    row = db.execute("SELECT status, total FROM orders WHERE id = ?", (order_id,)).fetchone()
    if not row: raise ToolError(f"Order {order_id} not found")
    return f"{row[0]}, £{row[1]:.2f}"

for n in [1042, 9999]:
    print(n, "->", call(mcp, "order_status", {"order_id": n}).content[0].text)
Output
1042 -> shipped, £89.00
9999 -> Error executing tool order_status: Order 9999 not found
Also uses tester.py
import asyncio
from mcp import Client

def call(server, tool, args=None, **options):
    async def go():
        async with Client(server, **options) as client:
            return await client.call_tool(tool, args or {})
    return asyncio.run(go())

def tools(server):
    async def go():
        async with Client(server) as client:
            return (await client.list_tools()).tools
    return asyncio.run(go())

Fixed query or free SQL

A run any SQL tool is powerful, but the model could read or delete anything. Fixed queries with placeholders do one safe job each. Start with fixed queries.

Run any SQL

  • Very flexibleCan read anythingCan delete data

Fixed queries

  • One job eachPlaceholdersSafe by design

Summary

Give the model fixed, parameterised queries, not raw SQL. Next, safe file tools.

Key takeaways
  • SQLite
  • ? placeholders
  • Fixed queries
Next up: Safe File Tools — stay inside a folder