Postgres MCP Server

Postgres MCP Server

Enables comprehensive PostgreSQL database management through natural language including queries, schema operations, user management, and administrative tasks. Features enterprise-grade connection pooling, transaction support, and full database administration capabilities.

Category
访问服务器

README

Postgres MCP Server

MCP server for PostgreSQL database management and operations, built with a sophisticated enterprise-grade architecture.

Quick Setup

1. Installation

npm install
npm run build

2. Claude Desktop Configuration

Add this to your Claude Desktop claude_desktop_config.json:

Windows:

{
  "mcpServers": {
    "postgres": {
      "command": "node",
      "args": ["C:\\path\\to\\postgres-mcp\\dist\\index.js"],
      "env": {
        "DATABASE_URL": "postgresql://username:password@localhost:5432/dbname"
      }
    }
  }
}

macOS/Linux:

{
  "mcpServers": {
    "postgres": {
      "command": "node",
      "args": ["/path/to/postgres-mcp/dist/index.js"],
      "env": {
        "DATABASE_URL": "postgresql://username:password@localhost:5432/dbname"
      }
    }
  }
}

3. Environment Configuration

Option A: Via Claude Desktop config (recommended)

{
  "mcpServers": {
    "postgres": {
      "command": "node",
      "args": ["/Users/itsalfredakku/McpServers/postgres-mcp/dist/index.js"],
      "env": {
        "DATABASE_URL": "postgresql://postgres:password@localhost:5432/mydb",
        "POOL_MAX": "20",
        "LOG_LEVEL": "info"
      }
    }
  }
}

Option B: Using .env file Create .env in the project root:

DATABASE_URL=postgresql://username:password@localhost:5432/dbname
POOL_MAX=10
LOG_LEVEL=info

Features

  • Database Operations: Query, insert, update, delete operations
  • Schema Management: Create, alter, drop tables and indexes
  • Transaction Management: Begin, commit, rollback transactions
  • Connection Management: Advanced connection pooling
  • Data Management: Import/export, backup/restore operations
  • Monitoring: Performance metrics and query analysis
  • Admin Operations: User management, permissions, database administration

Installation

npm install

Configuration Options

Database Connection

# Required - Primary connection string
DATABASE_URL=postgresql://username:password@localhost:5432/dbname

# Alternative - Individual connection parameters
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_DATABASE=your_database
POSTGRES_SSL=false

Connection Pool Settings

POOL_MIN=2                    # Minimum connections
POOL_MAX=10                   # Maximum connections  
POOL_IDLE_TIMEOUT=30000       # Idle timeout (ms)
POOL_ACQUIRE_TIMEOUT=60000    # Acquire timeout (ms)

Performance & Caching

CACHE_ENABLED=true            # Enable query result caching
CACHE_TTL=300000             # Cache TTL (ms)
LOG_LEVEL=info               # Logging level (error|warn|info|debug)
SQL_LOGGING=false            # Log SQL queries

Usage

Development

npm run dev

Production

npm run build
npm start

Testing

npm run test
npm run test:queries

Tools

Database Operations

  • query - Execute SQL queries with transaction support, explain plans, analysis
  • tables - List, create, alter, drop tables with detailed metadata
  • schemas - FULLY IMPLEMENTED Create, drop, list schemas and manage permissions
  • indexes - FULLY IMPLEMENTED Create, drop, analyze, reindex with usage statistics

Data Management

  • data - Insert, update, delete operations with bulk support
  • transactions - Begin, commit, rollback with savepoint support

Administration & Security

  • admin - FULLY IMPLEMENTED Complete database administration and maintenance
  • permissions - Complete user/role/privilege management
  • security - SSL, authentication, encryption, auditing
  • monitoring - Performance metrics and analysis
  • connections - Connection pool management

Schema Management Features ✅

  • Schema Operations: Create, drop, list all schemas
  • Permission Management: View and manage schema-level permissions
  • Owner Management: Set schema ownership during creation
  • Conditional Operations: IF EXISTS, IF NOT EXISTS support
  • System Schema Filtering: Distinguish between user and system schemas

Index Management Features ✅

  • Index Operations: Create, drop, list, reindex indexes
  • Performance Analysis: Analyze index usage statistics
  • Unused Index Detection: Find indexes that are never used
  • Multiple Index Types: Support for btree, hash, gist, gin, brin
  • Concurrent Operations: Create and reindex with CONCURRENTLY
  • Size Monitoring: Index size tracking and reporting

Database Administration Features ✅

  • Database Information: Complete database stats and configuration
  • User Management: Create, drop, list users with detailed privileges
  • Permission Control: Grant/revoke permissions on tables and schemas
  • Maintenance Operations: VACUUM, ANALYZE, REINDEX with options
  • System Monitoring: Connection counts, database size, uptime tracking
  • Configuration Access: View database settings and parameters

Architecture

The server follows a modular architecture with:

  • Configuration Management - Environment and file-based configuration
  • Connection Pooling - Advanced PostgreSQL connection management
  • Domain APIs - Separated concerns for different database operations
  • Validation - Comprehensive parameter validation
  • Error Handling - Robust error handling with retries
  • Caching - Intelligent caching for performance
  • Logging - Structured logging with Winston

Troubleshooting

Common Issues

Connection Refused

# Check if PostgreSQL is running
brew services list | grep postgresql
# or
sudo systemctl status postgresql

# Test connection manually
psql -h localhost -p 5432 -U postgres -d your_database

Permission Denied

-- Grant necessary permissions
GRANT CONNECT ON DATABASE your_database TO your_user;
GRANT USAGE ON SCHEMA public TO your_user;
GRANT CREATE ON SCHEMA public TO your_user;

MCP Server Not Found

  • Ensure the path in claude_desktop_config.json is absolute
  • Verify npm run build completed successfully
  • Check that dist/index.js exists

Debug Mode

Set environment variables for detailed logging:

{
  "mcpServers": {
    "postgres": {
      "command": "node",
      "args": ["/path/to/postgres-mcp/dist/index.js"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost:5432/db",
        "LOG_LEVEL": "debug",
        "SQL_LOGGING": "true"
      }
    }
  }
}

Database Permissions Setup

Full Admin Access

For complete database management capabilities, ensure your PostgreSQL user has appropriate privileges:

-- Connect as superuser (postgres)
psql -U postgres

-- Create a dedicated MCP user with admin privileges
CREATE USER mcp_admin WITH PASSWORD 'secure_password';
ALTER USER mcp_admin SUPERUSER;
ALTER USER mcp_admin CREATEDB;
ALTER USER mcp_admin CREATEROLE;
ALTER USER mcp_admin REPLICATION;

-- Or grant specific privileges without superuser
CREATE USER mcp_user WITH PASSWORD 'secure_password';
GRANT ALL PRIVILEGES ON DATABASE your_database TO mcp_user;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO mcp_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO mcp_user;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO mcp_user;

-- Grant schema usage and creation
GRANT USAGE, CREATE ON SCHEMA public TO mcp_user;

-- Allow user management (requires elevated privileges)
ALTER USER mcp_user CREATEROLE;

Using MCP Permission Tools

Once connected, you can use the MCP server to manage permissions:

// List all users and their privileges
await mcpServer.callTool('permissions', { operation: 'list_users' });

// Create a new user
await mcpServer.callTool('permissions', { 
  operation: 'create_user', 
  username: 'newuser', 
  password: 'password123',
  attributes: { createdb: true, login: true }
});

// Grant all privileges to a user
await mcpServer.callTool('permissions', { 
  operation: 'grant_all_privileges', 
  username: 'newuser', 
  database: 'mydatabase' 
});

// Check user permissions
await mcpServer.callTool('permissions', { 
  operation: 'check_permissions', 
  username: 'newuser' 
});

License

MIT

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选