MCP HubMCP Hub
FreePeak

db-mcp-server

by: FreePeak

db mcp server

122created 17/03/2025
Visit
database

📌Overview

Purpose: To provide AI assistants with structured access to multiple databases simultaneously through a standardized database interface based on the Database Model Context Protocol (DB MCP).

Overview: The DB MCP Server enables seamless interaction between AI models and various database systems, allowing for the execution of SQL queries, transaction management, schema exploration, and performance analysis in a unified manner. Its architecture is based on Clean Architecture principles, which enhances maintainability and testability.

Key Features:

  • Simultaneous Multi-Database Support: Allows concurrent connections and interactions with multiple MySQL and PostgreSQL databases.

  • Database-Specific Tool Generation: Automatically generates tailored tools for each connected database facilitating diverse operations.

  • Clean Architecture: Modular design with clear separation of concerns, improving maintainability and scalability.

  • Dynamic Database Tools: Supports executing SQL queries, running data modification statements, managing transactions, exploring schemas, and analyzing performance.

  • Unified Interface: Establishes consistent interaction patterns across different database types, simplifying user experience.

  • Connection Management: Offers straightforward configuration for managing multiple database connections.


Multi Database MCP Server

License: MIT
Go Report Card
Go Reference
Contributors

A powerful multi-database server implementing the Model Context Protocol (MCP) to provide AI assistants with structured access to databases.


Overview

The DB MCP Server provides a standardized way for AI models to interact with multiple databases simultaneously. Built on the FreePeak/cortex framework, it enables AI assistants to execute SQL queries, manage transactions, explore schemas, and analyze performance across different database systems through a unified interface.


Core Concepts

Multi-Database Support

Unlike traditional database connectors, DB MCP Server can connect to and interact with multiple databases concurrently:

{
  "connections": [
    {
      "id": "mysql1",
      "type": "mysql",
      "host": "localhost",
      "port": 3306,
      "name": "db1",
      "user": "user1",
      "password": "password1"
    },
    {
      "id": "postgres1",
      "type": "postgres",
      "host": "localhost",
      "port": 5432,
      "name": "db2",
      "user": "user2",
      "password": "password2"
    }
  ]
}

Dynamic Tool Generation

For each connected database, the server automatically generates a set of specialized tools:

// For a database with ID "mysql1", these tools are generated:
query_mysql1       // Execute SQL queries
execute_mysql1     // Run data modification statements
transaction_mysql1 // Manage transactions
schema_mysql1      // Explore database schema
performance_mysql1 // Analyze query performance

Clean Architecture

The server follows Clean Architecture principles with these layers:

  1. Domain Layer: Core business entities and interfaces
  2. Repository Layer: Data access implementations
  3. Use Case Layer: Application business logic
  4. Delivery Layer: External interfaces (MCP tools)

Features

  • Simultaneous multi-database support (MySQL and PostgreSQL)
  • Database-specific auto-generated tools
  • Modular clean architecture
  • OpenAI Agents SDK compatibility
  • Tools for executing queries, managing transactions, exploring schema, and analyzing performance
  • Unified interface across database types
  • Simple connection management configuration

Supported Databases

DatabaseStatusFeatures
MySQL✅ Full SupportQueries, Transactions, Schema Analysis, Performance Insights
PostgreSQL✅ Full Support (v9.6-17)Queries, Transactions, Schema Analysis, Performance Insights

Quick Start

Using Docker

docker pull freepeak/db-mcp-server:latest

# Option 1: Run with environment variables (recommended)
docker run -p 9092:9092 \
  -v $(pwd)/config.json:/app/my-config.json \
  -e TRANSPORT_MODE=sse \
  -e CONFIG_PATH=/app/my-config.json \
  freepeak/db-mcp-server

# Option 2: Override entrypoint
docker run -p 9092:9092 \
  -v $(pwd)/config.json:/app/my-config.json \
  --entrypoint /app/server \
  freepeak/db-mcp-server \
  -t sse -c /app/my-config.json

# Option 3: Use shell to execute
docker run -p 9092:9092 \
  -v $(pwd)/config.json:/app/my-config.json \
  freepeak/db-mcp-server \
  /bin/sh -c "/app/server -t sse -c /app/my-config.json"

Platform Support

Supports:

  • linux/amd64 (Intel/AMD)
  • linux/arm64 (ARM64, Apple Silicon)

Specify platform if needed to avoid mismatch errors:

docker run --platform linux/amd64 -p 9092:9092 freepeak/db-mcp-server
docker run --platform linux/arm64 -p 9092:9092 freepeak/db-mcp-server

From Source

git clone https://github.com/FreePeak/db-mcp-server.git
cd db-mcp-server
make build
./bin/server -t sse -c config.json

Running the Server

STDIO Mode (for IDE Integration)

./server -t stdio -c config.json

Outputs JSON-RPC messages to stdout; logs go to stderr.

For integration with Cursor, configure .cursor/mcp.json accordingly.

SSE Mode (Server-Sent Events)

./server -t sse -c config.json

# Custom host and port
./server -t sse -host 0.0.0.0 -port 8080 -c config.json

Connect clients to http://localhost:9092/sse.

Docker Compose

Use provided docker-compose.yml for development with multiple database containers. This setup includes health checks, persistent volumes, and waits for databases to be ready before starting the DB MCP Server.

Commands to use:

docker-compose up -d
docker-compose logs -f db-mcp-server
docker-compose down

Ensure your config.json matches service names in the docker-compose file.


Configuration

Database Connections (config.json)

Example:

{
  "connections": [
    {
      "id": "mysql1",
      "type": "mysql",
      "host": "mysql1",
      "port": 3306,
      "name": "db1",
      "user": "user1",
      "password": "password1"
    },
    {
      "id": "mysql2",
      "type": "mysql",
      "host": "mysql2",
      "port": 3306,
      "name": "db2",
      "user": "user2",
      "password": "password2"
    },
    {
      "id": "postgres1",
      "type": "postgres",
      "host": "postgres1",
      "port": 5432,
      "name": "db1",
      "user": "user1",
      "password": "password1"
    },
    {
      "id": "postgres2",
      "type": "postgres",
      "host": "postgres2",
      "port": 5432,
      "name": "db2",
      "user": "user2",
      "password": "password2"
    },
    {
      "id": "postgres3",
      "type": "postgres",
      "host": "postgres3",
      "port": 5432,
      "name": "screenerdb",
      "user": "screener",
      "password": "screenerpass"
    }
  ]
}

Ensure host values match service names if using Docker Compose.

Command-Line Options

./server -t <transport> -c <config-file>

# Transports: stdio, sse
./server -t sse -host <hostname> -port <port> -c <config-file>

# Direct DB config via JSON string
./server -t stdio -db-config '{"connections":[...]}'

# Using environment variable
export DB_CONFIG='{"connections":[...]}'
./server -t stdio

Available Tools

The server auto-generates tools per database with the naming convention:

<tool_type>_<database_id>

Where <tool_type> is one of: query, execute, transaction, schema, performance.

Example for database ID "mysql1":

  • query_mysql1
  • execute_mysql1
  • transaction_mysql1
  • schema_mysql1
  • performance_mysql1

Database-Specific Tools

  • query_: Execute SQL queries

    {
      "query": "SELECT * FROM users WHERE age > ?",
      "params": [30]
    }
    
  • execute_: Execute SQL statements (INSERT/UPDATE/DELETE)

    {
      "statement": "INSERT INTO users (name, email) VALUES (?, ?)",
      "params": ["John Doe", "john@example.com"]
    }
    
  • transaction_: Manage transactions

    // Begin transaction
    {
      "action": "begin",
      "readOnly": false
    }
    
    // Execute within transaction
    {
      "action": "execute",
      "transactionId": "<from begin response>",
      "statement": "UPDATE users SET active = ? WHERE id = ?",
      "params": [true, 42]
    }
    
    // Commit transaction
    {
      "action": "commit",
      "transactionId": "<from begin response>"
    }
    
  • schema_: Get schema info

    {
      "random_string": "dummy"
    }
    
  • performance_: Analyze query performance

    {
      "action": "analyzeQuery",
      "query": "SELECT * FROM users WHERE name LIKE ?"
    }
    

Global Tools

  • list_databases: Lists all configured databases
    {}
    

Examples

Querying Multiple Databases

// Query the first database
{
  "name": "query_mysql1",
  "parameters": {
    "query": "SELECT * FROM users LIMIT 5"
  }
}

// Query the second database
{
  "name": "query_mysql2",
  "parameters": {
    "query": "SELECT * FROM products LIMIT 5"
  }
}

Executing Transactions

// Begin transaction
{
  "name": "transaction_mysql1",
  "parameters": {
    "action": "begin"
  }
}
// Response contains transactionId

// Execute within transaction
{
  "name": "transaction_mysql1",
  "parameters": {
    "action": "execute",
    "transactionId": "tx_12345",
    "statement": "INSERT INTO orders (user_id, product_id) VALUES (?, ?)",
    "params": [1, 2]
  }
}

// Commit transaction
{
  "name": "transaction_mysql1",
  "parameters": {
    "action": "commit",
    "transactionId": "tx_12345"
  }
}

Roadmap

Q3 2025

  • MongoDB
  • SQLite
  • MariaDB

Q4 2025

  • Microsoft SQL Server
  • Oracle Database
  • Redis

2026

  • Cassandra
  • Elasticsearch
  • CockroachDB
  • DynamoDB
  • Neo4j
  • ClickHouse

Troubleshooting

Common Issues

  1. Connection errors: Check database connection settings.
  2. Tool not found: Verify server is running and tool name prefixes.
  3. Failed queries: Validate SQL syntax and permissions.
  4. Docker volume mount errors: Avoid mounting over existing files, use different paths like /app/my-config.json.
  5. Docker command errors: Use environment variables or override entrypoint approaches.
  6. wait-for-it.sh issues: Ensure it exists, is executable, uses correct line endings; alternatively use service health checks.

Logs

  • STDIO mode: logs to stderr
  • SSE mode: logs to stdout and ./logs/db-mcp-server.log

Enable debug logging with:

./server -t sse -debug -c config.json

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Push to the branch
  5. Submit a pull request

Ensure coding standards and tests.


License

MIT License.


Support & Contact


Cursor Integration

Tool Naming Convention

Tools are named as:

mcp_<servername>_<tooltype>_<dbID>

Example:

mcp_multidb_query_mysql1

Cursor Configuration Example (~/.cursor/mcp.json)

{
  "mcpServers": {
    "multidb": {
      "command": "/path/to/db-mcp-server/server",
      "args": ["-t", "stdio", "-c", "/path/to/database_config.json"]
    }
  }
}

Using MCP Tools in Cursor

Example tool usage:

  • mcp_multidb_list_databases
  • mcp_multidb_query_mysql1 with SQL query
  • mcp_multidb_schema_mysql1
  • mcp_multidb_execute_mysql1 with statement
  • mcp_multidb_transaction_mysql1 with action

Troubleshooting

  1. Confirm server running (ps aux | grep server)
  2. Verify .cursor/mcp.json
  3. Check server_name matches environment variables
  4. Restart Cursor after changes
  5. Inspect logs in logs/ directory

OpenAI Agents SDK Integration

DB MCP Server supports integration with OpenAI's Agents SDK to enable AI agents to query and manage databases.

Basic Integration Example

from openai import OpenAI
from agents.agent import Agent, ModelSettings
from agents.tools.mcp_server import MCPServerSse, MCPServerSseParams

db_server = MCPServerSse(
    params=MCPServerSseParams(
        url="http://localhost:9095/sse",
        schema={
            "params": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string"},
                        "description": {"type": "string"},
                        "parameters": {"type": "object"}
                    }
                }
            }
        }
    ),
)

agent = Agent(
    name="Database Agent",
    model="gpt-4o",
    model_settings=ModelSettings(temperature=0.1),
    instructions="""
    You are a database helper agent. You can execute SQL queries,
    manage database transactions, and explore schema information.
    """,
    mcp_servers=[db_server],
)

Testing Integration

Run the included test script:

./test_tools/openai-agent-sdk-test/run_test.sh

Troubleshooting Agents SDK Integration

  1. Ensure server is running in SSE mode.
  2. Confirm OpenAI API key is set.
  3. Verify agent instructions mention database tools.
  4. Check server logs for errors.

End of Document