Skip to main content
Glama
SQL Query MCP Server

SQL Query MCP Server

by Tolosa527
README.md
# SQL Query MCP Server

A Model Context Protocol (MCP) server that provides safe, read-only access to SQL databases through SELECT queries. This server runs in a Docker container and can be integrated with VS Code and other MCP-compatible clients.

## Features

- **Security First**: Only SELECT queries are allowed - all data-modifying operations are blocked
- **Multi-Database Support**: Works with SQL Server (MSSQL), MySQL, and PostgreSQL
- **Containerized**: Runs in Docker for isolation and easy deployment
- **Schema Discovery**: Built-in tools to explore database structure and relationships
- **Foreign Key Detection**: Automatically discover table relationships for complex queries
- **VS Code Integration**: Ready to use as a tool in VS Code with GitHub Copilot

## Available Tools

### 1. `execute_select_query`
Execute a SELECT query on the database.

**Parameters:**
- `query` (string): The SELECT SQL query to execute

**Example:**
```sql
SELECT * FROM Users WHERE age > 18
```

### 2. `get_database_schema`
Get the complete database schema including all tables and columns with their data types.

### 3. `list_tables`
List all tables in the database.

### 4. `get_table_relationships`
Get foreign key relationships between tables. Shows which columns reference other tables, essential for understanding how to join tables in complex queries.

**Returns:**
- `constraint_name`: Name of the foreign key constraint
- `table_name`: The table that contains the foreign key
- `column_name`: The column that is a foreign key
- `referenced_table`: The table being referenced
- `referenced_column`: The column being referenced

**Example use case:**
```
Q: "Check the relationship between Orders, Customers and Products. 
    Which foreign keys should I use to create a complex query?"

A: The tool returns:
   - Orders.CustomerID → Customers.CustomerID
   - Orders.ProductID → Products.ProductID
```

## Setup

### Prerequisites

- Docker and Docker Compose
- Node.js 20+ (for local development)
- Access to a SQL database (MSSQL, MySQL, or PostgreSQL)

### Configuration

1. Copy the environment example file:
   ```bash
   cp .env.example .env
   ```

2. Edit `.env` with your database credentials:
   ```env
   DB_TYPE=mssql              # Options: mssql, mysql, postgres
   DB_HOST=host.docker.internal  # For Docker to access host machine
   DB_PORT=1433
   DB_USER=your_user
   DB_PASSWORD=your_password
   DB_NAME=your_database
   DB_ENCRYPT=false           # Set to true for Azure SQL
   ```

### Building and Running

#### Option 1: Using Docker Compose (Recommended)

```bash
docker-compose up --build
```

#### Option 2: Using Docker directly

```bash
# Build the image
docker build -t mcp-sql-query-server .

# Run the container
docker run -i \
  -e DB_TYPE=mssql \
  -e DB_HOST=host.docker.internal \
  -e DB_PORT=1433 \
  -e DB_USER=sa \
  -e DB_PASSWORD=YourPassword \
  -e DB_NAME=master \
  mcp-sql-query-server
```

#### Option 3: Local Development (without Docker)

```bash
# Install dependencies
npm install

# Build TypeScript
npm run build

# Set environment variables and run
export DB_TYPE=mssql
export DB_HOST=localhost
export DB_PORT=1433
export DB_USER=sa
export DB_PASSWORD=YourPassword
export DB_NAME=master

npm start
```

## VS Code Integration

To use this MCP server with VS Code and GitHub Copilot:

### 1. Configure MCP in VS Code

Create or edit your MCP settings file. The location depends on your OS:

- **Windows**: `%APPDATA%\Code\User\globalStorage\github.copilot-chat\mcp.json`
- **macOS**: `~/Library/Application Support/Code/User/globalStorage/github.copilot-chat/mcp.json`
- **Linux**: `~/.config/Code/User/globalStorage/github.copilot-chat/mcp.json`

### 2. Add the Server Configuration

#### For Docker Container:

```json
{
  "mcpServers": {
    "sql-query": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "--rm",
        "-e", "DB_TYPE=mssql",
        "-e", "DB_HOST=host.docker.internal",
        "-e", "DB_PORT=1433",
        "-e", "DB_USER=sa",
        "-e", "DB_PASSWORD=YourPassword",
        "-e", "DB_NAME=YourDatabase",
        "mcp-sql-query-server"
      ]
    }
  }
}
```

#### For Local Node.js:

```json
{
  "mcpServers": {
    "sql-query": {
      "command": "node",
      "args": ["c:/Users/mzulber/personal-projects/mcp-servers/sql-server-query/dist/index.js"],
      "env": {
        "DB_TYPE": "mssql",
        "DB_HOST": "localhost",
        "DB_PORT": "1433",
        "DB_USER": "sa",
        "DB_PASSWORD": "YourPassword",
        "DB_NAME": "YourDatabase"
      }
    }
  }
}
```

### 3. Restart VS Code

After adding the configuration, restart VS Code for the changes to take effect.

### 4. Using in VS Code

Once configured, you can use the SQL query tools in GitHub Copilot Chat:

**Example prompts:**
- "List all tables in the database"
- "Show me the schema for the Users table"
- "Query the top 10 orders from last month"
- "What columns are in the Products table?"
- "Check the relationship between Orders, Customers and Products. Which foreign keys should I use to create a complex query?"
- "Show me how the tables are related in this database"

The Copilot will use the MCP server to execute your queries safely.

## Security Features

1. **Query Validation**: Only SELECT statements are allowed
2. **Keyword Blocking**: Blocks queries containing INSERT, UPDATE, DELETE, DROP, CREATE, ALTER, TRUNCATE, EXEC, etc.
3. **No Dynamic SQL**: Prevents execution of stored procedures or dynamic SQL
4. **Read-Only Access**: Configure your database user with read-only permissions for additional security

## Database-Specific Notes

### SQL Server (MSSQL)
- Default port: 1433
- Supports both Windows and SQL Server authentication
- For Azure SQL, set `DB_ENCRYPT=true`

### MySQL
- Default port: 3306
- Ensure user has SELECT privileges on the target database

### PostgreSQL
- Default port: 5432
- Connects to specific database specified in `DB_NAME`

## Troubleshooting

### Container can't connect to database on host machine

Use `host.docker.internal` instead of `localhost` for `DB_HOST` when running in Docker.

### Connection timeout

- Check firewall settings
- Verify database is listening on the specified port
- Ensure database allows connections from Docker network

### VS Code doesn't see the tools

1. Check that the `mcp.json` file is in the correct location
2. Restart VS Code
3. Check VS Code Developer Tools Console for errors (Help > Toggle Developer Tools)

## Development

### Watch mode for development:

```bash
npm run watch
```

### Build only:

```bash
npm run build
```

## License

MIT

TDQS

A3.8/5.0

Scored across 4 tools

Disambiguation4/5

Each tool has a distinct action: running queries, fetching full schema, listing table names, and fetching foreign-key relationships. There is mild redundancy since list_tables and get_table_relationships return subsets of what get_database_schema already covers, but the descriptions make the intended use of each clear.

Naming Consistency5/5

All four tools follow a clean verb_noun pattern (execute_select_query, get_database_schema, list_tables, get_table_relationships) with consistent snake_case and imperative verbs.

Tool Count4/5

Four tools is on the thin side but appropriate for a deliberately narrow, read-only query server where each tool covers a distinct introspection or execution need. Slight overlap suggests one could be trimmed, but nothing is bloated.

Completeness4/5

The core read-only workflow — discover tables, inspect schema and joins, then run SELECTs — is fully covered with no dead ends. Minor gaps like explain_query, sample-row previews, or column search exist but are workarounds via execute_select_query.

Maintenance

ActivityInactive
ResponsivenessNo recent community issues