Skip to content

manohar02/mcp-database

Repository files navigation

MySQL Database MCP Server

A secure FastMCP implementation that enables LLMs to interact with MySQL databases through natural language queries.

Features

  • ✅ Secure database connections with connection pooling
  • ✅ SQL injection prevention and query validation
  • ✅ Automatic schema analysis and metadata extraction
  • ✅ Natural language to SQL query generation
  • ✅ Safe query execution with parameterized statements
  • ✅ Real-time streaming of large result sets
  • ✅ Schema visualization support (Mermaid.js and PlantUML)
  • ✅ Full MCP protocol compliance
  • ✅ Context-aware error reporting
  • ✅ Thread-safe server instance management
  • ✅ Resource cleanup and connection management

Security Features

  • ✅ SQL injection prevention
  • ✅ Input validation for queries
  • ✅ Parameterized queries support
  • ✅ Connection pooling with timeout
  • ✅ Resource cleanup on errors
  • ✅ Thread-safe server instances
  • ✅ Safe schema analysis

Setup

  1. Install dependencies:
pip install -r requirements.txt
  1. Configure your database connection:
# Create database configuration
config = DatabaseConfig(
    host="localhost",
    port=3306,
    user="your_username",
    password="your_password",
    database="your_database"
)

Usage

1. Start the MCP Server

python mcp_server.py

The server will start on port 8000.

2. Configure MCP Server in Claude Desktop

  1. Create a file named mcp_servers.json in your project directory:
{
    "mcpServers": {
        "database": {
            "command": "uv",
            "args": [
                "--directory",
                "/ABSOLUTE/PATH/TO/PARENT/FOLDER/db-mcp-windsurf",
                "run",
                "mcp_server.py"
            ]
        }
    }
}
  1. Make sure the MCP server is running (from step 1)
  2. In Claude Desktop, you can now use the MCP server by referencing it as database:// in your conversations.

3. Configure Database Connection

In your Claude conversation, configure the database connection:

config = {
    "host": "your_host",
    "port": 3306,
    "user": "your_username",
    "password": "your_password",
    "database": "your_database",
    "read_only": true
}

4. Using the MCP Server in Claude

Once configured, you can use the MCP server in any Claude conversation by referencing it as database://. For example:

# Connect to database
await database.tools.connect_database(config)

# Generate SQL from natural language
await database.tools.generate_sql("Find all users who joined in the last 30 days")

# Execute SQL query
await database.tools.execute_query("SELECT * FROM users LIMIT 10")

# Get database schema
await database.read_resource("schema://database")

# Get schema description
await database.read_resource("schema://description")

# Get ER diagram
await database.read_resource("schema://er-diagram/mermaid")

# Validate SQL query
await database.tools.validate_query("SELECT * FROM users")

# Disconnect from database
await database.tools.disconnect_database(config)

5. MCP Server Configuration

The MCP server is configured to run with uvicorn using the following command:

uvicorn mcp_server:mcp --host 0.0.0.0 --port 8000 --reload

This will start the MCP server on port 8000 with hot-reload enabled for development.

Once configured, you can use the MCP server in any Claude conversation by referencing it as database://. For example:

# Connect to database
await database.tools.connect_database(config)

# Generate SQL from natural language
await database.tools.generate_sql("Find all users who joined in the last 30 days")

# Execute SQL query
await database.tools.execute_query("SELECT * FROM users LIMIT 10")

# Get database schema
await database.read_resource("schema://database")

# Get schema description
await database.read_resource("schema://description")

# Get ER diagram
await database.read_resource("schema://er-diagram/mermaid")

# Validate SQL query
await database.tools.validate_query("SELECT * FROM users")

# Disconnect from database
await database.tools.disconnect_database(config)

Once configured, you can use the plugin in any Claude conversation by referencing it as database://. For example:

# Connect to database
await database.tools.connect_database(config)

# Generate SQL from natural language
await database.tools.generate_sql("Find all users who joined in the last 30 days")

# Execute SQL query
await database.tools.execute_query("SELECT * FROM users LIMIT 10")

# Get database schema
await database.read_resource("schema://database")

# Get schema description
await database.read_resource("schema://description")

# Get ER diagram
await database.read_resource("schema://er-diagram/mermaid")

# Validate SQL query
await database.tools.validate_query("SELECT * FROM users")

# Disconnect from database
await database.tools.disconnect_database(config)

Once configured, you can use the plugin in any Claude conversation. The plugin provides the following capabilities:

  1. Natural Language to SQL

    • Ask Claude questions about your database
    • The plugin will automatically generate and execute SQL queries
    • Results will be displayed in a readable format
  2. Schema Analysis

    • Get detailed database schema information
    • View table relationships and dependencies
    • Generate ER diagrams
  3. Query Validation

    • All queries are validated against your schema
    • Read-only mode protection
    • SQL injection prevention
  4. Performance Optimization

    • Automatic query optimization
    • Proper indexing suggestions
    • Performance monitoring

5. Plugin Commands in Claude

You can use these commands directly in Claude conversations:

# Connect to database
await mcp.tools.connect_database(config)

# Generate SQL from natural language
await mcp.tools.generate_sql("Find all users who joined in the last 30 days")

# Execute SQL query
await mcp.tools.execute_query("SELECT * FROM users LIMIT 10")

# Get database schema
await mcp.read_resource("schema://database")

# Get schema description
await mcp.read_resource("schema://description")

# Get ER diagram
await mcp.read_resource("schema://er-diagram/mermaid")

# Validate SQL query
await mcp.tools.validate_query("SELECT * FROM users")

# Disconnect from database
await mcp.tools.disconnect_database(config)

MCP Tools

  1. Connect Database
# Connect to database
await mcp.tools.connect_database(config)
  1. Disconnect Database
# Clean up resources
await mcp.tools.disconnect_database(config)
  1. Generate SQL
# Generate SQL from natural language
await mcp.tools.generate_sql("Show me total sales per category")
  1. Execute Query
# Execute query with safety
await mcp.tools.execute_query("SELECT * FROM products LIMIT 10")
  1. Get Schema
# Get database schema
await mcp.read_resource("schema://database")
  1. Get Schema Description
# Get human-readable schema description
await mcp.read_resource("schema://description")
  1. Get ER Diagram
# Get ER diagram in Mermaid format
await mcp.read_resource("schema://er-diagram/mermaid")
  1. Validate Query
# Validate SQL query against schema
await mcp.tools.validate_query("SELECT * FROM products")

Schema Analysis

The server automatically analyzes the connected database and extracts:

  • Table names and columns with detailed info (type, null, key, default, extra)
  • Primary and foreign key relationships
  • Indexes (names, involved columns, uniqueness)
  • Table relationships (inferred from foreign keys)
  • Table and column comments
  • Schema visualization capabilities

Error Handling

The server implements comprehensive error handling:

  • Context-aware error reporting
  • Detailed error messages
  • Automatic logging
  • Input validation
  • Safe database operations
  • Resource cleanup on errors
  • Thread safety
  • Connection pooling management

Development

The project uses FastMCP for MCP protocol implementation and SQLAlchemy for database interactions. Key features include:

  • Async/await support
  • Context-based logging
  • Resource templates
  • Tool-based architecture
  • Extensible error handling
  • Schema visualization support
  • Secure query execution
  • Thread-safe operations
  • Resource cleanup

Security Best Practices

  1. Always validate input before execution
  2. Use parameterized queries for all database operations
  3. Implement proper connection pooling
  4. Clean up resources when done
  5. Use thread-safe operations
  6. Validate schema against queries
  7. Implement proper error handling
  8. Use connection timeouts and recycling
  9. Implement query validation
  10. Use secure database configurations

Performance Tips

  1. Use connection pooling for better performance
  2. Implement proper query optimization
  3. Use LIMIT clauses for large result sets
  4. Implement proper indexing
  5. Use proper data types
  6. Implement proper caching strategies
  7. Use streaming for large result sets
  8. Implement proper connection timeout
  9. Use proper connection recycling
  10. Implement proper resource cleanup

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages