Skip to main content
Glama
PostgreSQL MCP Server

PostgreSQL MCP Server

by ashish8545

PostgreSQL MCP Server

PostgreSQL MCP Node.js Docker License Version

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

Related MCP server: PostgreSQL MCP Server

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?

  2. Prerequisites

  3. Installation

  4. Configuration

  5. Starting the Server

  6. Client Setup

  7. Remote SSH Setup

  8. Available Tools

  9. Usage Examples

  10. Troubleshooting

  11. 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:

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

Step 2: Create Environment File

cp env.example .env

Step 3: Edit Configuration

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

# 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

cd ~/postgres-mcp
./start.sh

Or manually:

docker compose up -d --build

Stop

./stop.sh

Or manually:

docker compose down

View Logs

docker logs -f postgres-mcp

Check Health

curl http://localhost:3100/health

Expected response:

{"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:

{
    "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:

{
    "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):

{
    "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:

{
    "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

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

On the remote Linux machine:

cd /path/to/postgres-mcp
./start.sh

In your client's MCP configuration file (on remote machine's workspace):

{
    "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):

{
    "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:

# 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:

{"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:

docker ps

Check for port conflicts:

lsof -i :3100

View container logs:

docker logs postgres-mcp

Cannot Connect to Database

Verify credentials in .env file are correct.

Test database connectivity from the container:

docker exec -it postgres-mcp sh -c "nc -zv $DB_HOST $DB_PORT"

Check if database is accessible from your machine:

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:

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:

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 section

  2. View container logs: docker logs postgres-mcp

  3. Open an issue 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 file for details.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables exploration and querying of PostgreSQL databases through natural language. Supports listing tables, viewing schemas, executing SELECT queries, filtering records, and retrieving database statistics.
      2
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to safely interact with PostgreSQL databases, perform queries, inspect schemas, and analyze query performance.
      2
      ISC