npm package: @jeevanvj/database-mcp-server
Description: A Model Context Protocol (MCP) server for natural language database querying
Author: Jeevan
Latest version: 1.0.0

# Database MCP Server

A Model Context Protocol (MCP) server that enables natural language querying of SQL and NoSQL databases. This server translates plain English queries into database-specific queries and executes them safely.

## Features

- 🗣️ Natural language to SQL/NoSQL translation
- 🛡️ Safe query execution with built-in validation
- 🔗 Multi-database support (SQLite, PostgreSQL, MySQL, MongoDB, SQL Server)
- 📊 Schema introspection and visualization
- 🔍 Query optimization suggestions
- 📝 Detailed query explanations
- 🔒 Read-only mode for production safety
- 📋 Structured logging with configurable levels

## Supported Databases

- **SQLite** - File-based database for development and testing
- **PostgreSQL** - Advanced open-source relational database
- **MySQL** - Popular relational database
- **MongoDB** - Document-oriented NoSQL database
- **SQL Server** - Microsoft's enterprise database system

## Installation

### NPM (Recommended)

```bash
npm install -g database-mcp-server
```

### From Source

```bash
npm install
npm run build
```

## Quick Start

### Using NPX (No Installation Required)

```bash
npx database-mcp-server --db sqlite:./test.db
```

### Command Line

```bash
# Start with SQLite database
database-mcp-server --db sqlite:./mydata.db

# Start with PostgreSQL
database-mcp-server --db-url postgres://user:pass@localhost/mydb

# Multiple databases
database-mcp-server --db sqlite:./test.db --db-url postgres://user:pass@localhost/prod

# Read-only mode (recommended for production)
database-mcp-server --config production.json --readonly

# Custom logging
database-mcp-server --log-level debug --log-file ./server.log
```

## MCP Client Configuration

### Cursor

**Click to install:**
[![Install in Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en/install-mcp?name=database-mcp&config=eyJjb21tYW5kIjoibnB4IC15IGRhdGFiYXNlLW1jcC1zZXJ2ZXJAbGF0ZXN0IiwiYXJncyI6WyItLWRiIiwic3FsaXRlOi4vdGVzdC5kYiJdfQ%3D%3D)

**Or configure manually:**

Go to `Cursor Settings` → `MCP` → `New MCP Server`. Add:

```json
{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "database-mcp-server@latest", "--db", "sqlite:./test.db"]
    }
  }
}
```

### Claude Desktop / Cline

Add to your MCP configuration file:

```json
{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "database-mcp-server@latest", "--db", "sqlite:./test.db"]
    }
  }
}
```

### VS Code Copilot

```bash
code --add-mcp '{"name":"database","command":"npx","args":["database-mcp-server@latest","--db","sqlite:./test.db"]}'
```

Or add to your settings:

```json
{
  "github.copilot.chat.mcp.servers": {
    "database": {
      "command": "npx",
      "args": ["database-mcp-server@latest", "--db", "sqlite:./test.db"]
    }
  }
}
```

### Production Configuration Example

Create a `config.json` file:

```json
{
  "databases": [
    {
      "name": "production-db",
      "type": "postgresql",
      "host": "db.example.com",
      "port": 5432,
      "database": "myapp",
      "username": "readonly_user",
      "password": "secure_password"
    }
  ],
  "readonly": true,
  "healthPort": 3000,
  "logLevel": "info",
  "logFile": "/var/log/database-mcp-server.log"
}
```

Then start with:

```bash
database-mcp-server --config config.json
```

## Configuration

### Command Line Options

```
Usage: database-mcp-server [options]

Options:
  -c, --config <path>       Path to configuration file (JSON or YAML)
  --log-level <level>       Logging level: trace, debug, info, warn, error, fatal (default: info)
  --log-file <path>         Path to log file (logs to stderr if not specified)
  --readonly                Enable read-only mode (blocks all write operations)
  --health-port <port>      Port for health check HTTP server (default: 3000)
  --db <connection>         Database connection shorthand (e.g., sqlite:./test.db)
  --db-url <url>            Database connection URL (e.g., postgres://user:pass@host/db)
  --transport <type>        Transport protocol (default: stdio)
  -v, --version             Show version information
  -h, --help                Show help

Examples:
  database-mcp-server --db sqlite:./test.db
  database-mcp-server --db-url postgres://user:pass@localhost/mydb
  database-mcp-server --config config.json --readonly
  database-mcp-server --log-level debug --log-file ./server.log
```

### Environment Variables

You can configure databases via environment variables:

**PostgreSQL:**
- `PG_DATABASE_HOST`, `PG_DATABASE_PORT`, `PG_DATABASE_USER`, `PG_DATABASE_PASSWORD`, `PG_DATABASE_NAME`

**MySQL:**
- `MYSQL_DATABASE_HOST`, `MYSQL_DATABASE_PORT`, `MYSQL_DATABASE_USER`, `MYSQL_DATABASE_PASSWORD`, `MYSQL_DATABASE_NAME`

**SQL Server:**
- `MSSQL_DATABASE_HOST`, `MSSQL_DATABASE_PORT`, `MSSQL_DATABASE_USER`, `MSSQL_DATABASE_PASSWORD`, `MSSQL_DATABASE_NAME`

**MongoDB:**
- `MONGO_DATABASE_HOST`, `MONGO_DATABASE_PORT`, `MONGO_DATABASE_USER`, `MONGO_DATABASE_PASSWORD`, `MONGO_DATABASE_NAME`

**General:**
- `LOG_LEVEL` - Logging level (default: info)
- `MCP_SERVER_PORT` - Health check server port (default: 3000)
- `NODE_ENV` - Runtime environment (development/production)

## MCP Tools

This server provides the following MCP tools:

### Querying
- `query_database` - Execute natural language or SQL queries

### Administration
- `add_database` - Add new database connections
- `list_databases` - List all configured connections
- `remove_database` - Remove a database connection
- `test_connection` - Test database connectivity

### Analysis
- `get_schema` - Retrieve database schema information
- `explain_query` - Get detailed explanation of a query
- `optimize_query` - Get optimization suggestions

For detailed tool documentation, see [docs/tool-reference.md](docs/tool-reference.md).

## Safety Features

- **Read-only mode** - Blocks all write operations when enabled
- **Query validation** - Prevents dangerous operations (DROP, TRUNCATE, etc.)
- **WHERE clause enforcement** - Warns about DELETE/UPDATE without WHERE
- **Query timeout limits** - Configurable execution timeouts
- **Input sanitization** - SQL injection prevention
- **Audit logging** - All queries are logged with timestamps

## Examples

### Natural Language Queries

```
"Show me all users who signed up last month"
"Count the number of orders by status"
"Find the top 10 products by sales"
"List all tables in the database"
```

### Direct SQL

```sql
SELECT * FROM users WHERE created_at > DATE('now', '-30 days');
SELECT status, COUNT(*) FROM orders GROUP BY status;
```

## Development

### Project Structure

```
src/
├── cli.ts                   # CLI entry point
├── index.ts                 # Main server implementation
├── logger.ts                # Structured logging
├── types.ts                 # TypeScript interfaces
├── database-manager.ts      # Database connection management
├── query-processor.ts       # Natural language processing
├── mcp-tools.ts            # MCP tool definitions
├── health-server.ts        # Health check endpoint
└── database-adapters/      # Database-specific adapters
    ├── postgresql-adapter.ts
    ├── mysql-adapter.ts
    ├── mongodb-adapter.ts
    ├── sqlserver-adapter.ts
    └── ...
```

### Building

```bash
npm run build
```

### Testing

```bash
npm test
npm run test:watch       # Continuous testing
npm run test:cli         # Test CLI functionality
```

### Documentation

```bash
npm run generate-docs    # Generate tool reference documentation
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Run `npm run build` and `npm test`
6. Submit a pull request

## Health Check Endpoint

The server includes an HTTP health check endpoint (default port 3000):

- `GET /health` - Basic health check
- `GET /status` - Detailed status including database connections

## License

MIT License - see LICENSE file for details.

## Requirements

- Node.js 18.0.0 or higher
- TypeScript 5.8.3 or higher

## Support

For issues and questions, please create an issue in the GitHub repository.

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for version history and updates.