PostgreSQL MCP Server for Claude Desktop
Enables Claude Desktop to interact with PostgreSQL databases through natural language for schema exploration, data analysis, and query execution. Users can search schemas, describe tables, and perform read or write operations without needing to write manual SQL.
README
š PostgreSQL MCP Server for Claude Desktop
Connect Claude Desktop to your PostgreSQL database using the Model Context Protocol (MCP). Ask Claude questions in plain English and it will query your database, explore schemas, and analyze data ā no SQL required.
⨠Features
| Category | Tools |
|---|---|
| šļø Database Info | get_database_info, list_databases |
| š Schema Exploration | list_schemas, list_tables, describe_table, search_schema, list_indexes |
| š Querying | execute_query, get_table_sample, get_table_stats, explain_query |
| āļø Write Operations | execute_write (disabled by default ā opt-in via .env) |
| š Resources | schema://overview, table://{schema}/{table} |
| š¬ Prompts | analyze_table, write_sql_query |
š Quick Start
1. Clone the Repository
git clone https://github.com/sarotechhub/Claude-Desktop-to-PostgreSQL.git
cd Cluade-MCP-PostgreSQL
2. Create a Virtual Environment
# Windows
python -m venv .venv
.venv\Scripts\activate
# macOS / Linux
python -m venv .venv
source .venv/bin/activate
3. Install Dependencies
pip install -r requirements.txt
4. Configure Your Database
# Copy the example env file
cp .env.example .env
Edit .env with your PostgreSQL credentials:
DB_HOST=localhost
DB_PORT=5432
DB_NAME=your_database_name
DB_USER=your_username
DB_PASSWORD=your_password
# Set to "true" to allow INSERT/UPDATE/DELETE
ALLOW_WRITE_OPERATIONS=false
All credentials live only in
.envā they are never put in the Claude Desktop config file.
5. Test the Server
python main.py
You should see:
š Starting PostgreSQL MCP Server...
ā
Database connection pool ready.
Press Ctrl+C to stop.
6. Connect to Claude Desktop
Find your Claude Desktop config file:
| OS | Path |
|---|---|
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
| macOS | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Linux | ~/.config/Claude/claude_desktop_config.json |
Add the postgres block to the mcpServers section (update the path):
{
"mcpServers": {
"postgres": {
"command": "[PATH_TO_YOUR_VENV_PYTHON_EXE]",
"args": ["[PATH_TO_YOUR_PROJECT_ROOT]\\main.py"],
"cwd": "[PATH_TO_YOUR_PROJECT_ROOT]",
"env": {
"PYTHONPATH": "[PATH_TO_YOUR_PROJECT_ROOT]"
}
}
}
}
Note: No DB credentials go in this file. The server reads them automatically from your
.envfile usingpython-dotenv.
Restart Claude Desktop after saving the config.
š¬ Example Conversations with Claude
Once connected, try asking Claude:
"List all tables in my database"
"Describe the structure of the users table"
"Show me 10 sample rows from the orders table"
"How many rows are in each table in the public schema?"
"Find all columns related to 'email' across all tables"
"What indexes exist on the products table?"
"Write a query to find the top 10 customers by total order value"
"Explain why this query might be slow: SELECT * FROM orders WHERE status = 'pending'"
š§ Tool Reference
Database Info
| Tool | Description |
|---|---|
get_database_info |
PostgreSQL version, DB size, connection count, server info |
list_databases |
All databases on the server with sizes and encoding |
Schema Exploration
| Tool | Description |
|---|---|
list_schemas() |
All user-defined schemas in the connected database |
list_tables(schema) |
Tables in a schema with row counts and sizes |
describe_table(table, schema) |
Columns, types, nullable, defaults, PKs, FKs |
search_schema(keyword) |
Find tables/columns by keyword (case-insensitive) |
list_indexes(table, schema) |
Indexes on a table with type and columns |
Querying
| Tool | Description |
|---|---|
execute_query(sql, limit) |
Read-only SELECT (enforced via read-only transaction) |
get_table_sample(table, schema, limit) |
Sample rows from a table (max 100) |
get_table_stats(table, schema) |
Row counts, sizes, vacuum/analyze timestamps |
explain_query(sql) |
EXPLAIN execution plan (no data modification) |
Write Operations
| Tool | Description |
|---|---|
execute_write(sql, confirm) |
INSERT/UPDATE/DELETE ā requires ALLOW_WRITE_OPERATIONS=true in .env AND confirm=True |
š Security
- Read-only by default ā write operations require explicit opt-in in
.env - Credentials in
.envonly ā never in the Claude Desktop config - Read-only transactions ā SELECT queries run inside
readonly=Truetransactions - Input validation ā table/schema names validated with regex to prevent injection
- No DDL ā DROP, CREATE, ALTER are always blocked even when writes are enabled
.envexcluded from git ā credentials never committed
š Project Structure
Cluade-MCP-PostgreSQL/
āāā main.py # š MCP server entry point (FastMCP + stdio)
āāā database.py # š Async connection pool (asyncpg)
āāā tools/
ā āāā __init__.py
ā āāā schema_tools.py # list_schemas, list_tables, describe_table, search_schema, list_indexes
ā āāā query_tools.py # execute_query, get_table_sample, get_table_stats, explain_query
ā āāā write_tools.py # execute_write (opt-in)
ā āāā database_tools.py # get_database_info, list_databases
āāā .env # ā
Your credentials (NOT committed to git)
āāā .env.example # Template for new users
āāā .gitignore # Excludes .env, .venv, __pycache__
āāā requirements.txt # mcp[cli], asyncpg, python-dotenv, pydantic, orjson
āāā claude_desktop_config.json # Example Claude Desktop config snippet
āāā README.md
āļø Environment Variables
All configuration is done via .env:
| Variable | Default | Description |
|---|---|---|
DB_HOST |
localhost |
PostgreSQL host |
DB_PORT |
5432 |
PostgreSQL port |
DB_NAME |
ā | Database name |
DB_USER |
ā | Database user |
DB_PASSWORD |
ā | Database password |
DB_MIN_CONNECTIONS |
1 |
Min pool connections |
DB_MAX_CONNECTIONS |
10 |
Max pool connections |
ALLOW_WRITE_OPERATIONS |
false |
Enable INSERT/UPDATE/DELETE |
LOG_LEVEL |
INFO |
Logging level (DEBUG/INFO/WARNING) |
š ļø Troubleshooting
Claude doesn't see the MCP server
- Fully quit and reopen Claude Desktop after editing the config
- Check the
cwdpath ā it must point to the project folder - Verify the
.venvPython path is correct:.venv\Scripts\python.exe
Connection refused / authentication failed
- Check your
.envcredentials match your PostgreSQL setup - Test directly:
psql -h localhost -U your_user -d your_db - Ensure PostgreSQL is running:
pg_isready
mcp or asyncpg module not found
.venv\Scripts\pip install -r requirements.txt
Server starts but tools don't appear in Claude
- Open Claude Desktop ā Settings ā Developer ā MCP Servers
- Check for error messages next to the
postgresserver entry - Run
python main.pymanually and check stderr for import errors
š Requirements
- Python 3.10+
- PostgreSQL 12+
- Claude Desktop (with MCP support)
š License
MIT License ā free to use, modify, and distribute.
š¤ Contributing
Pull requests welcome! Please fork the repo, create a feature branch, and submit a PR with a clear description.
Claude-Desktop-to-PostgreSQL
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.