Skip to content
Open
278 changes: 203 additions & 75 deletions servers/database-server/readme.md
Original file line number Diff line number Diff line change
@@ -1,132 +1,260 @@
# MCP Database Server
# MCP Database Server - Comprehensive Database Management Platform

Comprehensive database server supporting PostgreSQL, MySQL, and SQLite with natural language SQL query capabilities. Enables AI agents to interact with databases through both direct SQL and natural language queries.
Professional-grade database server supporting PostgreSQL, MySQL, and SQLite with complete CRUD operations and natural language SQL capabilities. Designed for AI agents requiring full database lifecycle management.

## Features
## Core Features

- **Multi-Database Support**: Works with SQLite, PostgreSQL, and MySQL
- **Natural Language Queries**: Convert natural language to SQL automatically
- **Direct SQL Execution**: Execute raw SQL with safety checks
- **Schema Inspection**: List tables and describe table structures
- **FastAPI Web Interface**: RESTful API endpoints for web integration
- **Docker Ready**: Fully containerized with health checks
### 🔍 **Query & Analysis**

- **Natural Language Processing**: Convert plain English to optimized SQL
- **Advanced Querying**: Complex joins, aggregations, and data analysis
- **Schema Inspection**: Complete database structure examination
- **Multi-Database Support**: SQLite, PostgreSQL, MySQL compatibility

### 🛠️ **Database Management**

- **Schema Operations**: Create, modify, and manage table structures
- **Data Manipulation**: Insert, update, and delete operations with safeguards
- **Connection Management**: Dynamic database switching and configuration
- **Health Monitoring**: Comprehensive status reporting and diagnostics

### 🔒 **Safety & Professional Standards**

- **Operation Warnings**: Clear notifications for destructive operations
- **Error Handling**: Detailed error reporting and recovery guidance
- **Success Confirmation**: Comprehensive feedback with affected row counts
- **Validation**: Input validation and query safety checks

## Available MCP Tools

### `query_database`
**Description**: Execute natural language queries against the database and convert them to SQL
### Core Query Operations

#### `query_database`

Transform natural language into SQL and execute queries safely.

- **Input**: Natural language question
- **Example**: "Show me all users who registered this month"
- **Output**: Structured query results with metadata

#### `list_tables`

Discover all available tables in the connected database.

- **Usage**: Database exploration and structure analysis
- **Output**: Complete table listing with metadata

#### `describe_table`

Get comprehensive schema information for any table.

- **Input**: Table name
- **Output**: Columns, types, constraints, indexes, and relationships

#### `execute_sql`

**Usage**: Ask questions like "Show me all users created in the last week" or "Find the top 10 products by sales"
Execute SELECT queries with built-in safety validation.

**Arguments**:
- `query` (string): Natural language description of what you want to query from the database
- **Input**: SQL SELECT statement
- **Safety**: Restricted to read-only operations
- **Output**: Query results with execution metadata

### `list_tables`
**Description**: List all available tables in the current database
### Connection Management

**Usage**: Ask "What tables are available?" or "Show me the database structure"
#### `connect_to_database`

### `describe_table`
**Description**: Get detailed schema information for a specific table including columns, types, and constraints
Switch between different databases dynamically.

**Usage**: Ask "Describe the users table" or "What columns does the products table have?"
- **Input**: Database connection string
- **Support**: SQLite, PostgreSQL, MySQL
- **Output**: Connection status and database information

**Arguments**:
- `table_name` (string): Name of the table to describe
#### `get_connection_examples`

### `execute_sql`
**Description**: Execute raw SQL queries with safety checks and validation
Retrieve properly formatted connection strings for all supported databases.

**Usage**: Execute specific SQL commands when you need precise control
- **Output**: Template connection strings with explanations
- **Databases**: SQLite, PostgreSQL, MySQL examples

**Arguments**:
- `query` (string): SQL query to execute
#### `get_current_database_info`

### `connect_to_database`
**Description**: Connect to a new database using provided connection details
Get detailed information about the active database connection.

**Usage**: Switch between different databases during your session
- **Output**: Database type, version, connection status, and capabilities

**Arguments**:
- `connection_string` (string): Database connection string
### Advanced Database Operations

### `get_connection_examples`
**Description**: Get example connection strings for different database types (SQLite, PostgreSQL, MySQL)
#### `execute_unsafe_sql`

**Usage**: Ask "How do I connect to a PostgreSQL database?" or "Show me connection examples"
Execute any SQL operation including DDL and DML commands.

### `get_current_database_info`
**Description**: Get information about the currently connected database including type, version, and connection status
- **Input**: Any SQL statement (CREATE, INSERT, UPDATE, DELETE, DROP)
- **Warning**: Clear notification of potential data modification
- **Output**: Execution results with affected row counts
- **Use Cases**: Schema migrations, bulk operations, administrative tasks

**Usage**: Ask "What database am I connected to?" or "Show me current connection details"
#### `create_table`

## Example Queries
Create new tables with custom schema definitions.

Here are some example questions you can ask your agent:
- **Inputs**: Table name, column definitions
- **Validation**: Schema validation and conflict checking
- **Output**: Creation confirmation and table structure

#### `insert_data`

Add new records to existing tables.

- **Inputs**: Table name, columns, values
- **Validation**: Data type checking and constraint validation
- **Output**: Insertion confirmation with row count

#### `update_data`

Modify existing records with conditional updates.

- **Inputs**: Table name, SET clause, WHERE condition
- **Safety**: Requires WHERE clause for targeted updates
- **Output**: Update confirmation with affected row count

#### `delete_data`

Remove records from tables with safety confirmations.

- **Inputs**: Table name, WHERE condition
- **Safety**: Clear warnings for destructive operations
- **Output**: Deletion confirmation with affected row count

## Usage Examples

### Basic Query Operations

```python
# Basic queries
"Show me all users in the database"
"What tables are available?"
"Describe the products table structure"

# Complex analysis
"Find the top 5 customers by total order value"
"Show me users who registered in the last month"
"What's the average product price by category?"

# Data exploration
"How many orders were placed yesterday?"
"List all products that are out of stock"
"Find duplicate email addresses in the users table"
# Natural language querying
"Show me the top 10 customers by total purchase amount"
"Find all products that are currently out of stock"
"List users who haven't logged in for 30 days"

# Schema exploration
"What tables are available in this database?"
"Describe the structure of the orders table"
"Show me the current database connection details"
```

## Configuration
### Database Administration

```python
# Table creation
create_table("user_sessions", "id INTEGER PRIMARY KEY, user_id INTEGER, session_token TEXT, created_at TIMESTAMP")

The server requires a `DATABASE_URL` environment variable with your database connection string:
# Data manipulation
insert_data("products", "name, price, category", "'Premium Widget', 99.99, 'Electronics'")
update_data("inventory", "quantity = quantity - 1", "product_id = 12345")
delete_data("expired_sessions", "created_at < '2023-01-01'")

### SQLite (recommended for testing)
# Advanced operations
execute_unsafe_sql("CREATE INDEX idx_user_email ON users(email)")
```

## Configuration

### Database Connection

Set the `DATABASE_URL` environment variable with your database connection string:

#### SQLite (Recommended for Development)

```bash
DATABASE_URL=sqlite+aiosqlite:///data/mydb.db
```

### PostgreSQL
```
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/mydb
```
#### PostgreSQL (Production Ready)

### MySQL
```bash
DATABASE_URL=postgresql+asyncpg://username:password@localhost:5432/database_name
```
DATABASE_URL=mysql+aiomysql://user:password@localhost:3306/mydb

#### MySQL (Enterprise Support)

```bash
DATABASE_URL=mysql+aiomysql://username:password@localhost:3306/database_name
```

## Docker Usage
## Docker Deployment

### Quick Start

```bash
# Run with SQLite (simplest setup)
# Development with SQLite
docker run -d \
-p 3000:3000 \
-e DATABASE_URL=sqlite+aiosqlite:///data/mydb.db \
souhardyak/mcp-db-server
souhardyak/mcp-db-server:latest

# Run with PostgreSQL
# Production with PostgreSQL
docker run -d \
-p 3000:3000 \
-e DATABASE_URL=postgresql+asyncpg://user:password@host:5432/db \
souhardyak/mcp-db-server
-e DATABASE_URL=postgresql+asyncpg://user:pass@db-host:5432/db \
souhardyak/mcp-db-server:latest
```

### Persistent Storage

# Run with persistent SQLite storage
```bash
# SQLite with persistent data
docker run -d \
-p 3000:3000 \
-v /host/data:/data \
-e DATABASE_URL=sqlite+aiosqlite:///data/mydb.db \
souhardyak/mcp-db-server
souhardyak/mcp-db-server:latest
```

## Health Check
## Health Monitoring

The server provides comprehensive health endpoints:

- **Endpoint**: `GET /health`
- **Response**: Database connectivity, version info, and operational status
- **Monitoring**: Ready for production health checks and monitoring systems

## Architecture & Performance

### Technical Stack

- **Framework**: FastAPI for high-performance API endpoints
- **Database Drivers**:
- `asyncpg` for PostgreSQL (high performance)
- `aiomysql` for MySQL (async support)
- `aiosqlite` for SQLite (lightweight development)
- **AI Processing**: Advanced natural language to SQL conversion
- **Containerization**: Optimized Docker image for production deployment

### Scalability

- **Async Architecture**: Non-blocking database operations
- **Connection Pooling**: Efficient database connection management
- **Multi-Database**: Simultaneous support for multiple database types
- **Resource Optimization**: Minimal memory footprint and fast response times

## Security & Best Practices

### Operation Safety

- **Query Validation**: SQL injection prevention and input sanitization
- **Operation Warnings**: Clear notifications for destructive operations
- **Error Handling**: Comprehensive error reporting without exposing sensitive data
- **Access Control**: Environment-based database access configuration

### Production Deployment

The server provides a health endpoint at `/health` that returns database connectivity status.
- **Docker Security**: Non-root container execution
- **Environment Variables**: Secure configuration management
- **Health Monitoring**: Production-ready monitoring and alerting
- **Documentation**: Complete deployment and operational guides

## Source Code
## Source Code & Support

Full source code and documentation available at: https://github.com/Souhar-dya/mcp-db-server
**Repository**: [https://github.com/Souhar-dya/mcp-db-server](https://github.com/Souhar-dya/mcp-db-server)
**Docker Image**: `souhardyak/mcp-db-server:latest`
**Documentation**: Complete API documentation and deployment guides
**Support**: GitHub Issues and comprehensive documentation
Loading