MCP-database-integraties

Introductie tot Model Context Protocol (MCP)

James Chapman

AI Curriculum Manager, DataCamp

Waarom een database aan de Timezone-server toevoegen?

 

  • Query-kracht: filteren, zoeken en sorteren zonder de hele dataset te laden
  • Schaal: snelle lookups met database-indexen

database_connection.png

Introductie tot Model Context Protocol (MCP)

Waarom een database aan de Timezone-server toevoegen?

 

  • Query-kracht: filteren, zoeken en sorteren zonder de hele dataset te laden
  • Schaal: snelle lookups met database-indexen
  • Gelijktijdigheid: meerdere tool-calls of clients raken de DB veilig
  • Productieklaar: back-ups, replicatie en één bron van waarheid

database_pros.png

Introductie tot Model Context Protocol (MCP)

Data-toegang: Tools vs. Resources

tools_icon.jpg

  • Dynamisch, sterk afhankelijk van gebruikersinvoer, schrijfoperaties
  • Voorbeelden: data-analyse en operaties

resources_icon.jpg

  • Alleen-lezen, statische data, referentie-informatie
  • Voorbeelden: richtlijnen, docs, beleid
Introductie tot Model Context Protocol (MCP)

Levenscyclus van een connectie

database_connections.png

Introductie tot 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}"
Introductie tot Model Context Protocol (MCP)

Database-zoektool: 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()
Introductie tot Model Context Protocol (MCP)

Veiligheid en productiegewoonten

 

  • Geparameteriseerde (?) queries: formatteer nooit gebruikers- of LLM-invoer in SQL
    • Prompt injection → kwaadaardige code-injectie via prompts
SELECT timezone FROM locations WHERE timezone LIKE ? LIMIT 50
  • Geef de voorkeur aan read-only en nauw afgebakende database-toegang voor de MCP-server
  • Beperkingen toepassen: max. rijen en time-outs
Introductie tot Model Context Protocol (MCP)

Laten we oefenen!

Introductie tot Model Context Protocol (MCP)

Preparing Video For Download...