How to Run SQL Queries Across Multiple Applications with MCP

Model Context Protocol (MCP) enables AI agents to query PostgreSQL, MySQL, SQLite, and Snowflake through a unified, language-agnostic API without requiring native database drivers.

The Model Context Protocol (MCP) standardizes how AI assistants interact with external data sources. According to the punkpeye/awesome-mcp-servers repository, you can run SQL queries across multiple applications with MCP by leveraging specialized database servers that expose standardized tools through a single JSON-RPC endpoint, as cataloged in the Databases section of README.md at lines 922-928 and validated by the CI workflow in .github/workflows/check-glama.yml.

MCP Architecture for Multi-Database Queries

The system relies on three core components working together to abstract database heterogeneity.

MCP Database Servers

Individual servers implement tool definitions that describe available actions. Each server ships a manifest.json declaring tools such as run_query, which accepts parameters for dialect, query, and limit.

Unified Dispatch Layer

Tools like mcp-multi-db or anyquery aggregate multiple MCP database servers behind a single endpoint. The dispatcher routes requests to the appropriate backend based on the dialect field you supply, exposing a common set of read-only tools regardless of the underlying engine.

Agent Integration

An LLM or client script sends JSON-RPC requests to the MCP endpoint. The server validates the request, enforces safety policies, translates the request into native SQL, executes the query, and returns normalized results.

Key MCP Database Servers

The punkpeye/awesome-mcp-servers repository lists several implementations for multi-database querying:

  • mcp-multi-db (Node.js): Supports PostgreSQL, MySQL, and SQLite via npx -y mcp-multi-db
  • anyquery (Go): Supports 40+ applications including Postgres and MySQL via brew install anyquery
  • sql-query-mcp (Python): Read-only PostgreSQL and MySQL support via pip install sql-query-mcp
  • querywise-mcp (Python): Supports SQLite, PostgreSQL, BigQuery, and Databricks

How Query Execution Works Under the Hood

Before execution, MCP database servers perform several validation steps to ensure safety and compatibility.

Tool Definition Validation

Each server validates requests against a JSON schema. The run_query tool requires:

{
  "type": "object",
  "properties": {
    "dialect": { "enum": ["postgres", "mysql", "sqlite"] },
    "query":   { "type": "string" },
    "limit":   { "type": "integer", "minimum": 1, "maximum": 1000 }
  },
  "required": ["dialect","query"]
}

Safety Enforcement

Servers parse SQL using dialect-aware parsers like sqlglot to block destructive statements (DROP, TRUNCATE, ALTER). This guarantees read-only execution unless explicitly disabled. Credentials are stored in encrypted .env files or OCI secret managers, and servers open read-only connection pools to prevent accidental data modification.

Result Normalization

Query results return in a canonical JSON shape:

{
  "columns": ["orders"],
  "rows": [{"orders": 542}]
}

This normalization allows LLMs to reason about column names without knowing the underlying database engine.

Implementation Examples

Querying PostgreSQL via HTTP

Use mcp-multi-db to expose a unified HTTP endpoint:


# Start the server

npx -y mcp-multi-db &

# Execute a query

curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{
        "tool": "run_query",
        "args": {
          "dialect": "postgres",
          "query": "SELECT COUNT(*) AS orders FROM orders WHERE created_at > now() - interval '\''7 day'\'';",
          "limit": 10
        }
      }'

Change the dialect field to mysql or sqlite to target different databases without modifying client code.

Cross-Database Joins with Anyquery

The anyquery tool enables joins across different database engines:

brew install anyquery

anyquery -c "
  SELECT p.id, p.name, o.total
  FROM postgres://user:pass@db1.example.com:5432/shop.products AS p
  JOIN mysql://user:pass@db2.example.com:3306/orders AS o
    ON p.id = o.product_id
  WHERE o.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY);
"

Python Integration with sql-query-mcp

For programmatic access in Python:

import json, requests

MCP_ENDPOINT = "https://sql-query.mcp.example.com/mcp"

def run_query(dialect, sql):
    payload = {
        "tool": "run_query",
        "args": {
            "dialect": dialect,
            "query": sql,
            "limit": 100
        }
    }
    r = requests.post(MCP_ENDPOINT, json=payload)
    r.raise_for_status()
    return r.json()

result = run_query("sqlite", "SELECT name, sales FROM products ORDER BY sales DESC LIMIT 5")
print(json.dumps(result, indent=2))

No-Code Setup with Claude Desktop

For AI assistant integration without writing code:

  1. Open Claude Desktop → Settings → MCP → Add Server
  2. Enter URL http://localhost:3000
  3. Prompt: "Use the MCP tool run_query to get the last 10 rows from the events table in the SQLite database."

Claude automatically calls the MCP endpoint and receives structured rows for further reasoning.

Security and Read-Only Guarantees

MCP database servers enforce strict safety policies. The sql-query-mcp implementation specifically operates in read-only mode by default, parsing all incoming SQL through sqlglot to detect and block data manipulation commands. Connection pools are initialized with read-only credentials, providing defense in depth against accidental schema modifications or data deletion.

Summary

  • MCP standardizes database access through unified tool definitions like run_query, eliminating the need for multiple database drivers in your application code.
  • Dispatchers like mcp-multi-db route queries to PostgreSQL, MySQL, or SQLite based on the dialect parameter while maintaining consistent safety policies.
  • Read-only enforcement occurs at multiple layers: SQL parsing blocks destructive commands, and connection pools use restricted credentials to prevent accidental writes.
  • Normalized JSON results return in a consistent format regardless of the underlying database, simplifying LLM consumption and cross-database analytics.

Frequently Asked Questions

What databases support MCP querying?

MCP supports PostgreSQL, MySQL, SQLite, Snowflake, BigQuery, Databricks, and over 40 other applications through specialized servers listed in the punkpeye/awesome-mcp-servers repository. Each server exposes the same tool interface, allowing you to switch between database engines by changing the dialect parameter.

How does MCP prevent destructive SQL operations?

MCP database servers implement a safety layer using parsers like sqlglot to analyze incoming queries and block destructive statements such as DROP, TRUNCATE, and ALTER. Additionally, servers use read-only connection pools and encrypted credential storage to ensure queries cannot modify data unless explicitly configured otherwise.

Can I join tables across different database engines using MCP?

Yes. Tools like anyquery allow you to execute federated queries that join tables across heterogeneous databases—for example, joining a PostgreSQL products table with a MySQL orders table in a single SQL statement. The dispatcher handles the protocol translation and execution across the different backends.

Do I need to install database drivers to use MCP?

No. MCP eliminates SDK overhead by providing a unified JSON-RPC interface. You only need the MCP client (such as npx mcp-multi-db or the anyquery binary), which handles all native driver communication internally. This allows AI agents to query databases without importing libraries like psycopg2 or mysql-connector.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →