PostgreSQL MCP Server
Supports Google Cloud SQL connections, including private IP and IAM authentication.
Allows AI assistants to interact with PostgreSQL databases through natural language queries, schema inspection, and safe SQL execution.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@PostgreSQL MCP ServerShow me all tables in the database."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
PostgreSQL MCP Server
A specialized MCP (Model Context Protocol) server for PostgreSQL database operations, built with TypeScript. This server enables AI assistants to interact with PostgreSQL databases through natural language queries, schema inspection, and safe SQL execution.
๐ Features
Database Tools
get_database_schema- Inspect database schemas, tables, and structureexecute_sql_query- Execute SQL queries with multiple output formats (table, JSON, CSV)execute_ai_generated_sql- Execute AI-generated SQL queries with explanationsnatural_language_query- Convert natural language questions to SQL and execute them
Key Capabilities
๐๏ธ Multi-Schema Support - Works with complex database structures
๐ Safe Query Execution - Built-in SQL injection protection
๐ Multiple Output Formats - Table, JSON, and CSV output options
๐ Google Cloud SQL Support - Direct and Cloud SQL Proxy connections
๐ Connection Pooling - Efficient database connection management
๐ฏ Natural Language Processing - Convert English questions to SQL
Related MCP server: PostgreSQL MCP Server
๐๏ธ Architecture
This server follows a clean, modular architecture that evolved from a monolithic structure:
src/
โโโ main.ts # MCP server entry point
โโโ config/
โ โโโ database.ts # Database configuration management
โโโ database/
โ โโโ manager.ts # Connection pool and lifecycle management
โ โโโ query-service.ts # High-level database operations
โโโ tools/
โ โโโ database-tools.ts # MCP tool implementations
โโโ types/
โ โโโ database.ts # TypeScript type definitions
โโโ utils/
โโโ query-utils.ts # Query formatting and utilitiesDesign Principles
Single Responsibility - Each module has a focused purpose
Type Safety - Comprehensive TypeScript coverage
Error Handling - Robust error management throughout
Testability - Modular design enables thorough testing
๐๏ธ Database Configuration
Configure your PostgreSQL connection using environment variables in .env:
# PostgreSQL Connection
DB_HOST=127.0.0.1
DB_PORT=5432
DB_NAME=your-database-name
DB_USER=your-username
DB_PASSWORD=your-password
# Google Cloud SQL (optional)
INSTANCE_CONNECTION_NAME=your-project:region:instance-name
# SSL Configuration (recommended for production)
DB_SSL=false
# Google Cloud Project (for IAM authentication)
GOOGLE_CLOUD_PROJECT=your-project-id๐ป Usage Examples
โ Returns all tables and their structures
AI: "Show me the schema for the customers table" โ Returns detailed schema for specific table
#### 2. Execute SQL QueriesAI: "Execute SQL: SELECT COUNT(*) FROM customers.customer_t WHERE country_code = 'SE'" โ Executes the query and returns results in table format
AI: "Run this query in JSON format: SELECT cutomer_id, customer_code FROM customers.customer_t LIMIT 5" โ Returns results in JSON format
#### 3. Natural Language QueriesAI: "How many active customers are there for Sweden?" โ Converts to SQL and executes: finds active customers for SE market
AI: "Show me all customer types in the database" โ Automatically generates and runs appropriate SQL query
#### 4. AI-Generated SQLAI: "Generate SQL to find all customers that expire in the next 7 days" โ Creates appropriate SQL query with explanation and executes it
### Supported Output Formats
- **table** (default) - Formatted table output
- **json** - JSON array format
- **csv** - Comma-separated values
### Database Features
- **Schema Discovery** - Automatically discover all schemas, tables, and columns
- **Multiple Output Formats** - Table, JSON, or CSV output
- **Natural Language Processing** - Convert questions to SQL queries
- **Google Cloud SQL Support** - Native support for Cloud SQL with private IP
- **Connection Pooling** - Efficient database connection management
- **Error Handling** - Comprehensive error handling and reporting
## ๏ฟฝ Installation & Setup
### Prerequisites
- **Node.js** 18+
- **PostgreSQL** database (local or cloud)
- **TypeScript** (installed globally or via npm)
### Quick Start
1. **Clone and install dependencies:**
```bash
git clone <repository-url>
cd mcp-test
npm installConfigure environment:
# Create .env file with your database configuration
touch .env
# Edit .env with your PostgreSQL connection detailsBuild and test:
# Build the project
npm run build
# Test database connection
npm run test:db
# Start the server
npm startDevelopment mode:
# Watch mode with auto-rebuild
npm run devEnvironment Configuration
Create a .env file with your database connection details:
# PostgreSQL Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=your-database-name
DB_USER=your-username
DB_PASSWORD=your-password
# Connection Pool Settings
DB_MAX_CONNECTIONS=5
# SSL Configuration (recommended for production)
DB_SSL=false
# Google Cloud SQL Configuration (optional)
INSTANCE_CONNECTION_NAME=your-project:region:instance-name
GOOGLE_CLOUD_PROJECT=your-project-id๐งช Testing
The project includes comprehensive testing scripts:
Database Tests
# Test database connection
npm run test:db
# Test database schema discovery
npm run test:schema
# Test MCP client integration
npm run test:client
# Run all tests
npm testManual Testing Scripts
# Direct database connection test
node scripts/test-direct-db.js
# Schema validation
node scripts/test-db-schema.js
# Get schema statistics
node scripts/get-schema-count.js๐ง Key Benefits & Features
Architecture Excellence
๐๏ธ Modular Design: Clean separation of concerns with dedicated modules for database, tools, and utilities
๐ Single Responsibility: Each component has a clear, focused purpose
๐ Type Safety: 100% TypeScript coverage prevents runtime errors
๐ก๏ธ Error Handling: Comprehensive error management throughout the stack
Database Capabilities
๐๏ธ PostgreSQL Specialized: Optimized for PostgreSQL databases with advanced features
๐ Connection Pooling: Efficient database connection management
๐ Google Cloud SQL: Native support for Cloud SQL with private IP connections
๐ Schema Discovery: Automatic discovery of all schemas, tables, and columns
๐ก๏ธ SQL Security: Protection against SQL injection with query validation
Developer Experience
๐ฏ Clear Structure: Easy to understand and navigate codebase
๐ Hot Reload: Development mode with automatic rebuilding
๐ Better Debugging: Source maps and proper error stack traces
๐ Linting: Consistent code style and best practices
๐งช Comprehensive Testing: Unit and integration tests ensure stability
Production Ready
โก Performance: Optimized queries and connection management
๐ Multiple Formats: Support for table, JSON, and CSV output
๐ง Configuration Management: Environment-specific settings centralized
๐ Documentation: Clear interfaces and comprehensive guides
๐ก Using with MCP Clients
Configuration for Claude Desktop
Add to your Claude Desktop configuration (~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"sql-assistant-server": {
"command": "node",
"args": ["/absolute/path/to/mcp-test/build/main.js"]
}
}
}VS Code Integration
This project is configured for VS Code with:
MCP Configuration (
.vscode/mcp.json) - For VS Code MCP integrationTasks - Build and run tasks accessible via
Ctrl+Shift+Pโ "Tasks: Run Task"Debug Configuration - Press
F5to debug
Available Tasks:
Build MCP Server- Compile TypeScriptStart MCP Server- Build and runWatch and Build- Development mode
Project Structure
mcp-test/
โโโ .vscode/ # VS Code configuration
โ โโโ mcp.json # MCP server config
โ โโโ tasks.json # Build tasks
โ โโโ launch.json # Debug config
โโโ src/ # Source code (TypeScript)
โ โโโ main.ts # Main server entry point
โ โโโ config/ # Configuration management
โ โ โโโ database.ts # Database configuration
โ โโโ database/ # Database layer
โ โ โโโ manager.ts # Connection management
โ โ โโโ query-service.ts # Query operations
โ โโโ tools/ # MCP tools implementation
โ โ โโโ database-tools.ts # Database tools
โ โโโ types/ # TypeScript type definitions
โ โ โโโ database.ts # Database-related types
โ โโโ utils/ # Utility functions
โ โโโ query-utils.ts # Query formatting and analysis
โโโ build/ # Compiled JavaScript output
โโโ scripts/ # Utility scripts
โ โโโ setup-dev.sh # Development setup
โ โโโ test-direct-db.js # Database connection test
โ โโโ test-db-schema.js # Database schema testing
โ โโโ test-client.js # MCP client testing
โโโ .env # Environment variables (create from template above)
โโโ Dockerfile # Docker configuration
โโโ package.json
โโโ tsconfig.json
โโโ README.md๐งโ๐ป Development
Testing
The project includes comprehensive testing scripts:
# Test database connection
npm run test:db
# Test database schema
npm run test:schema
# Test MCP client integration
npm run test:client
# Run all tests
npm testAdding New Database Tools
// In src/tools/database-tools.ts
server.tool(
"your_database_tool",
{
query: z.string().describe("SQL query or natural language request"),
format: z.enum(["table", "json", "csv"]).default("table")
},
{
title: "Your Database Tool",
description: "Custom database operation"
},
async (args) => {
const queryService = DatabaseManager.getInstance().getQueryService();
const results = await queryService.executeQuery(args.query);
return {
content: [{
type: "text",
text: formatResults(results, args.format)
}]
};
}
);Environment Configuration
Create a .env file with your database connection details:
# PostgreSQL Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=your-database-name
DB_USER=your-username
DB_PASSWORD=your-password
# Connection Pool Settings
DB_MAX_CONNECTIONS=5
# SSL Configuration (recommended for production)
DB_SSL=false
# Google Cloud SQL Configuration (optional)
INSTANCE_CONNECTION_NAME=your-project:region:instance-name
GOOGLE_CLOUD_PROJECT=your-project-idDocker Support
Build and run the server in Docker:
# Build image
docker build -t mcp-postgres-server .
# Run container
docker run -p 3000:3000 --env-file .env mcp-postgres-server๐ Learn More
๐ License
MIT License - feel free to use and modify!
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/satish-kori-27/postgres-mcp-server'
If you have feedback or need assistance with the MCP directory API, please join our Discord server