Marcio Cunha

How to connect LLMs to databases using the MCP protocol

Practical guide on Anthropic's Model Context Protocol to expose databases and local tools securely and standardly to AI assistants.

Marcio Cunha•3 min
Also available in:PortuguêsEspañol
Summary
  • The Model Context Protocol standardizes communication between AI assistants and local data sources.
  • The client-server architecture separates the chat interface from sensitive corporate database access.
  • MCP servers run local commands with restricted permissions to protect the host operating system.
  • AI tools gain dynamic query capabilities without exposing plain-text credentials.
  • Integration reduces hallucinations by providing real context directly from relational tables.

The challenge of giving real context to AI assistants

When chatting with an artificial intelligence, we quickly realize it knows plenty of theory but absolutely nothing about the files, servers, or data on your local machine. To solve this limitation without opening security holes, Anthropic created the Model Context Protocol, known as MCP. In practice, this protocol acts like a universal wall plug allowing language models to converse with databases and local tools in a standardized way. Just like advanced automation routines explored in topics like how to run a local LLM at night to automate tasks, the pursuit of secure autonomy in local systems is one of today's hottest engineering topics.

How the client-server architecture works in MCP

The core of MCP relies on a clear division of responsibilities based on the client-server model. On one side sits the client, typically the chat app or development environment where the AI runs. On the other side are MCP servers, small programs focused on specific tasks like querying a PostgreSQL database, reading system logs, or searching files in a folder. Client and server communicate through structured messages using secure transport, ensuring the AI assistant never directly accesses critical infrastructure without passing through strict filters.

Exposing relational tables securely

Connecting a database to an AI used to require fragile scripts riddled with security risks like SQL injection. With MCP, the database server acts as an intelligent and controlled translator. It exposes only permitted operations, hiding the complexity of access credentials and complex queries. To ensure data remains secure and isolated from human error or accidental exposure, many developers combine this approach with hardening techniques inspired by concepts like how to isolate AI tokens and secure data with Edera, keeping absolute control over the bot's blast radius.

Implementing an MCP server for databases

Let's build a small Python-based MCP server that allows an assistant to query local tables. The code below creates a lightweight server capable of responding to MCP client calls and returning formatted database results.

from mcp.server import Server, NotificationOptions
import mcp.types as types
import sqlite3

app = Server("database-server")

@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
    if name == "query_users":
        conn = sqlite3.connect("dados.db")
        cursor = conn.cursor()
        cursor.execute("SELECT id, nome FROM usuarios LIMIT 5")
        rows = cursor.fetchall()
        conn.close()
        return [types.TextContent(type="text", text=str(rows))]
    raise ValueError(f"Unknown tool: {name}")

This snippet defines a tool named 'query_users' running locally on the isolated server. The AI assistant can request the execution of this tool when it needs to retrieve customer info, receiving only the data strictly necessary to answer the user's prompt.

Pros and cons of adopting the MCP protocol

Adopting the Model Context Protocol brings incredible advantages for development teams and data engineers. The main benefit is standardization: any MCP-compliant client can talk to any MCP server, eliminating the need to build custom integrations for every tool. On the flip side, there are important operational challenges, such as managing extra processes on the local machine and ensuring MCP server permissions are rigorously audited to prevent accidental leaks of sensitive corporate data.

Conclusion and next steps for your infrastructure

The Model Context Protocol represents a paradigm shift in how we integrate language models into our local workspaces and database servers. By separating the chat interface from data access logic through a standardized client-server architecture, we gain security, modularity, and operational flexibility. The secret to a successful implementation is starting small, exposing only lower-criticality data sources, and strictly auditing each tool made available to the artificial intelligence.