MCP Database Integrations

Introduction to Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Why Add a Database to the Timezone Server?

 

  • Query power: filter, search, and sort without loading the whole dataset
  • Scale: fast lookups with database indexes

database_connection.png

Introduction to Model Context Protocol (MCP)

Why Add a Database to the Timezone Server?

 

  • Query power: filter, search, and sort without loading the whole dataset
  • Scale: fast lookups with database indexes
  • Concurrency: multiple tool calls or clients hit the DB safely
  • Production-ready: backups, replication, and a single source of truth

database_pros.png

Introduction to Model Context Protocol (MCP)

Data Access: Tools vs. Resources

tools_icon.jpg

  • Dynamic, heavily user-input dependent, writing operations
  • Examples: Data analytics and operations

resources_icon.jpg

  • Read-only, static data, reference information
  • Examples: Guidelines, docs, policies
Introduction to Model Context Protocol (MCP)

Connection Lifecycle

database_connections.png

Introduction to Model Context Protocol (MCP)

Database Resource: timezone_server.py

from mcp.server.fastmcp import FastMCP
import sqlite3

mcp = FastMCP("Timezone Converter")

# Create connection at startup; reuse in handlers
conn = sqlite3.connect("timezones.db")
conn.row_factory = sqlite3.Row

@mcp.resource("db://timezones") def get_locations() -> str: try: cursor = conn.execute("SELECT timezone FROM locations") rows = cursor.fetchall() return "\n".join(r["timezone"] for r in rows) except sqlite3.Error as e: return f"Error: {e}"
Introduction to Model Context Protocol (MCP)

Database Lookup Tool: timezone_server.py

@mcp.tool()
def lookup_locations(prefix: str) -> str:
    """Find timezones that contain the given prefix."""
    try:
        cursor = conn.execute(
            "SELECT timezone FROM locations WHERE timezone LIKE ? LIMIT 50", (f"%{prefix}%",))
        rows = cursor.fetchall()
        return "\n".join(r["timezone"] for r in rows)
    except sqlite3.Error as e: return f"Error: {e}"

if __name__ == "__main__": try: mcp.run(transport="stdio") finally: conn.close()
Introduction to Model Context Protocol (MCP)

Safety and Production Habits

 

  • Parameterized (?) queries: never string-format user or LLM input into SQL
    • Prompt injection → malicious injection of code through prompts
SELECT timezone FROM locations WHERE timezone LIKE ? LIMIT 50
  • Prefer read-only and tightly scoped database access for the MCP server
  • Apply limits: max rows and timeouts
Introduction to Model Context Protocol (MCP)

Let's practice!

Introduction to Model Context Protocol (MCP)

Preparing Video For Download...