Skip to main content
Glama
PostgreSQL MCP Server

PostgreSQL MCP Server

by ashish8545
README.md
# PostgreSQL MCP Server
![PostgreSQL](https://img.shields.io/badge/PostgreSQL-Supported-4169E1?style=flat&logo=postgresql&logoColor=white)
![MCP](https://img.shields.io/badge/MCP-Protocol-8B5CF6?style=flat)
![Node.js](https://img.shields.io/badge/Node.js-18%2B-339933?style=flat&logo=node.js&logoColor=white)
![Docker](https://img.shields.io/badge/Docker-Ready-2496ED?style=flat&logo=docker&logoColor=white)
![License](https://img.shields.io/badge/License-MIT-green?style=flat)
![Version](https://img.shields.io/badge/Version-1.0.0-blue?style=flat)

A Model Context Protocol (MCP) server that gives AI assistants direct access to your PostgreSQL database, enabling intelligent database queries, schema exploration, and data analysis through natural language.

## Supported AI Clients

| Client | Status |
|--------|--------|
| **Cursor AI** | ✅ Supported |
| **Antigravity** | ✅ Supported |
| **Claude Code** | ✅ Supported |
| **VS Code + MCP Extension** | ✅ Supported |
| **Any MCP-compatible client** | ✅ Supported |

## Tech Stack

**Runtime:** Node.js 22 · Express · Docker  
**Database:** PostgreSQL · node-postgres (pg)  
**Protocol:** MCP SDK (@modelcontextprotocol/sdk)

---

## Table of Contents

1. [What is MCP?](#what-is-mcp)
2. [Prerequisites](#prerequisites)
3. [Installation](#installation)
4. [Configuration](#configuration)
5. [Starting the Server](#starting-the-server)
6. [Client Setup](#client-setup)
   - [Cursor AI](#cursor-ai)
   - [Antigravity](#antigravity)
   - [Claude Code](#claude-code)
   - [Other MCP Clients](#other-mcp-clients)
7. [Remote SSH Setup](#remote-ssh-setup)
8. [Available Tools](#available-tools)
9. [Usage Examples](#usage-examples)
10. [Troubleshooting](#troubleshooting)
11. [Security Considerations](#security-considerations)

---

## What is MCP?

Model Context Protocol (MCP) is an open standard that allows AI assistants to interact with external tools and data sources. This server exposes PostgreSQL database operations as MCP tools, allowing you to:

- Query your database using natural language
- Explore table structures and relationships
- Analyze query performance
- Search for tables and columns
- Get database statistics

Instead of writing SQL manually, you can ask your AI assistant things like:
- "Show me all tables that contain user data"
- "What columns does the orders table have?"
- "Find all columns named 'email' across all tables"
- "How many records are in the logs table?"

---

## Prerequisites

- **Docker** and **Docker Compose** installed
- An **MCP-compatible AI client** (Cursor, Antigravity, Claude Code, VS Code with MCP extension, etc.)
- Network access to your PostgreSQL database
- Database credentials (host, port, database name, username, password)

---

## Installation

### Step 1: Get the Files

Copy the `postgres-mcp` folder to your machine or clone from repository:

```bash
# If copying from another developer
cp -r /path/to/postgres-mcp ~/postgres-mcp
cd ~/postgres-mcp
```

### Step 2: Create Environment File

```bash
cp env.example .env
```

### Step 3: Edit Configuration

Open `.env` in your editor and update the database credentials:

```bash
# Example configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=your_database
DB_USER=postgres
DB_PASSWORD=your_password
MCP_PORT=3100
```

---

## Configuration

### Environment Variables

| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `DB_HOST` | PostgreSQL server hostname | `localhost` | Yes |
| `DB_PORT` | PostgreSQL server port | `5432` | Yes |
| `DB_NAME` | Database name to connect to | `postgres` | Yes |
| `DB_USER` | Database username | `postgres` | Yes |
| `DB_PASSWORD` | Database password | (empty) | Yes |
| `DB_SSL` | Enable SSL connection | `false` | No |
| `DB_SSL_REJECT_UNAUTHORIZED` | Reject self-signed certs | `true` | No |
| `MCP_PORT` | Port the MCP server listens on | `3100` | No |

### Port Selection

The default port is `3100`. If this conflicts with another service, change `MCP_PORT` in your `.env` file and remember to use the same port in your client configuration.

---

## Starting the Server

### Start

```bash
cd ~/postgres-mcp
./start.sh
```

Or manually:

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

### Stop

```bash
./stop.sh
```

Or manually:

```bash
docker compose down
```

### View Logs

```bash
docker logs -f postgres-mcp
```

### Check Health

```bash
curl http://localhost:3100/health
```

Expected response:
```json
{"status":"ok","database":"localhost","sessions":0}
```

---

## Client Setup

This MCP server works with any MCP-compatible AI client. Below are setup instructions for popular clients.

### Cursor AI

**Step 1:** Create or edit the file `.cursor/mcp.json` in your workspace root:

```json
{
    "mcpServers": {
        "postgres": {
            "url": "http://localhost:3100/mcp"
        }
    }
}
```

**Step 2:** Restart Cursor completely (Cmd+Q / Alt+F4, then reopen).

**Step 3:** Verify connection in MCP panel (View > MCP Servers) — you should see "postgres" listed as connected.

---

### Antigravity

**Step 1:** Create or edit the file `.gemini/antigravity/mcp_config.json`:

```json
{
    "mcpServers": {
        "postgres": {
            "serverUrl": "http://localhost:3100/mcp"
        }
    }
}
```

> **Note**: Antigravity uses `serverUrl` instead of `url`.

**Step 2:** Restart your IDE or reload the Antigravity extension.

---

### Claude Code

**Step 1:** Create or edit the file `~/.claude/mcp_servers.json` (or project-level `.claude/mcp_servers.json`):

```json
{
    "mcpServers": {
        "postgres": {
            "url": "http://localhost:3100/mcp"
        }
    }
}
```

**Step 2:** Restart Claude Code to load the new configuration.

---

### Other MCP Clients

For any other MCP-compatible client, use the following server URL:

```
http://localhost:3100/mcp
```

Refer to your client's documentation for the specific configuration file location and format. The general structure is:

```json
{
    "mcpServers": {
        "postgres": {
            "url": "http://localhost:3100/mcp"
        }
    }
}
```

> **Note**: If you changed `MCP_PORT`, update the URL accordingly in all configurations.

---

### Verifying Connection

After configuring your client, verify the connection by asking your AI assistant:
> "Use the database_info tool to show me the database overview"

---

## Remote SSH Setup

When using an AI client with **Remote SSH** (connecting to a remote Linux server), the MCP client typically runs on the **remote machine**, not your local machine. This affects where you should run the MCP server.

### Understanding the Architecture

```
┌─────────────────────┐         ┌─────────────────────────────────────┐
│  Local Machine      │   SSH   │  Remote Machine (Linux)             │
│  (Windows/Mac)      │ ──────► │                                     │
│                     │         │  ┌─────────────┐   ┌─────────────┐  │
│  IDE UI             │         │  │ AI Client   │   │ MCP Server  │  │
│                     │         │  │ Backend     │──►│ Container   │  │
│                     │         │  └─────────────┘   └─────────────┘  │
└─────────────────────┘         └─────────────────────────────────────┘
```

When connected via Remote SSH:
- Your IDE's UI runs on your local machine
- The AI client backend (including MCP client) runs on the remote machine
- `localhost:3100` refers to the **remote machine**, not your local machine

### Option 1: Run MCP Container on Remote Machine (Recommended)

This is the simplest setup. Run the container on the same machine where your AI client's backend runs.

**On the remote Linux machine:**
```bash
cd /path/to/postgres-mcp
./start.sh
```

**In your client's MCP configuration file (on remote machine's workspace):**
```json
{
    "mcpServers": {
        "postgres": {
            "url": "http://localhost:3100/mcp"
        }
    }
}
```

### Option 2: Run MCP Container on Local Machine

If you prefer to run the container on your local Windows/Mac machine, you need to use your local machine's IP address instead of `localhost`.

**On your local machine:**
1. Start the container using Docker Desktop
2. Find your local machine's IP address:
   - Windows: `ipconfig` (look for IPv4 Address)
   - Mac: `ifconfig` or System Preferences > Network

**In your client's MCP configuration file (on remote machine's workspace):**
```json
{
    "mcpServers": {
        "postgres": {
            "url": "http://YOUR_LOCAL_IP:3100/mcp"
        }
    }
}
```

**Requirements for Option 2:**
- Your local machine's port 3100 must be accessible from the remote machine
- Firewall must allow incoming connections on port 3100
- Both machines must be on the same network or have network routing configured

### Testing Connectivity

**From the remote machine, test if the MCP server is reachable:**

```bash
# If running on remote (Option 1)
curl http://localhost:3100/health

# If running on local (Option 2)
curl http://YOUR_LOCAL_IP:3100/health
```

Expected response:
```json
{"status":"ok","database":"localhost","sessions":0}
```

### Common Remote SSH Issues

**"Connection refused" when using localhost:**
- You're likely running the container on your local machine but using `localhost` in config
- Solution: Use Option 1 (run on remote) or use your local machine's IP (Option 2)

**Cannot reach local machine from remote:**
- Check firewall settings on your local machine
- Verify both machines can communicate (ping test)
- Ensure port 3100 is not blocked by corporate firewall

---

## Available Tools

The MCP server provides 10 tools for database interaction:

### Query Execution

| Tool | Description |
|------|-------------|
| `query` | Execute any SQL query (SELECT, INSERT, UPDATE, DELETE) |
| `explain_query` | Get query execution plan (EXPLAIN ANALYZE) |

### Schema Exploration

| Tool | Description |
|------|-------------|
| `tables` | List all tables in the database |
| `table_schema` | Get column definitions for a table |
| `table_indexes` | Get indexes on a table |
| `table_constraints` | Get foreign keys, primary keys, unique constraints |

### Search & Discovery

| Tool | Description |
|------|-------------|
| `search_tables` | Search for tables by name pattern |
| `search_columns` | Search for columns by name across all tables |

### Statistics

| Tool | Description |
|------|-------------|
| `table_row_count` | Get row count for a table (estimate or exact) |
| `database_info` | Get database overview (size, table count, etc.) |

---

## Usage Examples

Once configured, you can interact with your database through natural language in your AI assistant. Here are some examples:

### Exploring the Database

**You:** "What tables are in this database?"

**You:** "Show me all tables that start with 'cr_'"

**You:** "What columns does the users table have?"

**You:** "Find all columns named 'email' in any table"

### Running Queries

**You:** "How many records are in the logs table?"

**You:** "Show me the last 10 entries from the audit_log table"

**You:** "Get all users where status is 'active'"

### Performance Analysis

**You:** "Explain the query: SELECT * FROM orders WHERE customer_id = 123"

**You:** "What indexes exist on the transactions table?"

### Database Statistics

**You:** "Give me an overview of this database"

**You:** "What's the estimated row count for the events table?"

### Direct Tool Usage

You can also explicitly call tools:

**You:** "Use the tables tool to list all tables"

**You:** "Use search_columns with pattern '%created%' to find timestamp columns"

---

## Troubleshooting

### Server Won't Start

**Check Docker is running:**
```bash
docker ps
```

**Check for port conflicts:**
```bash
lsof -i :3100
```

**View container logs:**
```bash
docker logs postgres-mcp
```

### Cannot Connect to Database

**Verify credentials in `.env` file are correct.**

**Test database connectivity from the container:**
```bash
docker exec -it postgres-mcp sh -c "nc -zv $DB_HOST $DB_PORT"
```

**Check if database is accessible from your machine:**
```bash
psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME
```

### AI Client Doesn't See the MCP Server

1. Ensure the MCP configuration file is in the correct location for your client
2. Verify the JSON syntax is valid
3. Restart your IDE/client completely (not just reload window)
4. Check the MCP server is running: `curl http://localhost:3100/health`

### "Connection Refused" Errors

**MCP server not running:**
```bash
docker ps | grep postgres-mcp
```
If not listed, start it: `./start.sh`

**Wrong port:**
Verify `MCP_PORT` in `.env` matches the URL in your client's MCP configuration

### Build Fails (npm errors)

**Force rebuild:**
```bash
docker compose down
docker compose build --no-cache
docker compose up -d
```

---

## Security Considerations

### Database Access

- This server has **full read/write access** to the configured database
- Use a database user with appropriate permissions for your use case
- For read-only access, create a PostgreSQL user with SELECT-only privileges

### Network Exposure

- The server binds to `0.0.0.0:3100` by default
- In production, consider binding to `127.0.0.1` only
- Use firewall rules to restrict access if needed

### Credentials

- Never commit `.env` files to version control
- The `.env` file contains database credentials in plain text
- Consider using Docker secrets for production deployments

---

## File Structure

```
postgres-mcp/
├── src/
│   ├── index.js       # Main entry point
│   ├── db/
│   │   └── pool.js    # Database connection pool
│   ├── tools/
│   │   ├── index.js   # Tool registration
│   │   ├── query.js   # Query execution tools
│   │   ├── schema.js  # Schema exploration tools
│   │   ├── search.js  # Search tools
│   │   └── stats.js   # Statistics tools
│   └── utils/
│       └── format.js  # Response formatting
├── package.json       # Node.js dependencies
├── Dockerfile         # Container build instructions
├── docker-compose.yml # Container orchestration
├── env.example        # Environment template
├── start.sh           # Start script
├── stop.sh            # Stop script
├── LICENSE            # MIT License
└── README.md          # This documentation
```

---

## Support

For issues or questions:
1. Check the [Troubleshooting](#troubleshooting) section
2. View container logs: `docker logs postgres-mcp`
3. [Open an issue](https://github.com/ashish8545/postgres-mcp/issues) on GitHub

---

## Version History

- **1.0.0** - Initial release with 10 PostgreSQL tools

---

## License

This project is licensed under the **MIT License** — see the [LICENSE](LICENSE) file for details.