postgresql-mcp-server

postgresql-mcp-server

Enables AI agents to interact with PostgreSQL databases through the Model Context Protocol, supporting SQL queries, schema management, and data operations.

Category
访问服务器

README

PostgreSQL MCP Server

npm version License: MIT Node.js Version MCP Compatible

A comprehensive PostgreSQL Model Context Protocol (MCP) server that provides full database operation capabilities for AI agents. This server enables AI assistants to interact with PostgreSQL databases through a standardized interface, supporting all major database operations from simple queries to complex schema management.

🌟 Features

🔧 Complete Database Operations

  • Connection Management: Secure database connections with pooling
  • Query Execution: Execute any SQL query (SELECT, INSERT, UPDATE, DELETE, DDL)
  • Schema Operations: List tables, describe structures, create tables and indexes
  • Data Management: Insert, update, delete with parameterized queries
  • Utilities: Database info, table backups, and more

🤖 Universal AI Agent Support

  • Claude Desktop/API: Native MCP integration
  • Custom AI Agents: Works with any MCP-compatible client
  • Multiple Platforms: Windows, macOS, Linux support
  • Easy Integration: Simple copy-and-use approach

🛡️ Production Ready

  • Security: SQL injection protection via parameterized queries
  • Performance: Connection pooling and query optimization
  • Error Handling: Comprehensive error reporting and recovery
  • Monitoring: Detailed logging and debugging support

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/halim-23/postgresql-mcp-server.git
cd postgresql-mcp-server

# Install dependencies
npm install

# Verify installation
npm run verify

Basic Usage

  1. Start the MCP server:

    npm start
    
  2. Configure your AI agent to use the server (see Configuration section)

  3. Connect to your database:

    // Use the connect_postgres tool with your connection string
    connection_string: "postgresql://username:password@host:port/database"
    
  4. Start using database operations!

🛠️ Available Tools

Tool Description Example Use Case
connect_postgres Connect to PostgreSQL database Initial setup and authentication
execute_query Execute any SQL query Complex queries, joins, aggregations
list_tables List all tables in schema Schema exploration and discovery
describe_table Get table structure details Understanding data models
create_table Create new tables Setting up new data structures
insert_data Insert records into tables Adding new data entries
update_data Update existing records Modifying data with conditions
delete_data Delete records from tables Data cleanup and removal
create_index Create database indexes Performance optimization
backup_table Create table backups Data safety and versioning
get_database_info Get database information System diagnostics and info

⚙️ Configuration

For Claude Desktop

Add to your Claude Desktop configuration (~/.claude/config.json):

{
  "mcpServers": {
    "postgresql": {
      "command": "node",
      "args": ["/path/to/postgresql-mcp-server/src/server.js"],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}

For Custom AI Agents

// Node.js example
const { spawn } = require('child_process');
const mcpServer = spawn('node', ['/path/to/postgresql-mcp-server/src/server.js']);
# Python example
import subprocess
mcp_server = subprocess.Popen([
    'node', '/path/to/postgresql-mcp-server/src/server.js'
], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

Environment Variables

# Optional: Set default connection
export POSTGRES_CONNECTION_STRING="postgresql://user:pass@host:port/db"

# Optional: Enable debug logging
export DEBUG=postgresql-mcp:*

📚 Usage Examples

Basic Database Operations

// 1. Connect to database
await callTool('connect_postgres', {
  connection_string: "postgresql://user:password@localhost:5432/mydb"
});

// 2. List all tables
const tables = await callTool('list_tables', { schema: 'public' });

// 3. Execute a custom query
const users = await callTool('execute_query', {
  query: "SELECT * FROM users WHERE age > $1",
  params: [18]
});

// 4. Insert new data
await callTool('insert_data', {
  table_name: 'users',
  data: {
    name: 'John Doe',
    email: 'john@example.com',
    age: 25
  }
});

Advanced Operations

// Create a new table
await callTool('create_table', {
  table_name: 'products',
  columns: [
    { name: 'id', type: 'SERIAL', constraints: 'PRIMARY KEY' },
    { name: 'name', type: 'VARCHAR(255)', constraints: 'NOT NULL' },
    { name: 'price', type: 'DECIMAL(10,2)' },
    { name: 'created_at', type: 'TIMESTAMP', constraints: 'DEFAULT NOW()' }
  ]
});

// Create an index for performance
await callTool('create_index', {
  index_name: 'idx_products_name',
  table_name: 'products',
  columns: ['name'],
  unique: false
});

🔧 Development

Project Structure

postgresql-mcp-server/
├── src/
│   └── server.js              # Main MCP server implementation
├── test/
│   └── test-client.js         # Test client for validation
├── scripts/
│   ├── setup.js              # Setup and initialization
│   └── verify-installation.js # Installation verification
├── docs/
│   ├── API.md                # Detailed API documentation
│   ├── EXAMPLES.md           # Usage examples
│   └── TROUBLESHOOTING.md    # Common issues and solutions
├── config/
│   └── examples/             # Configuration examples
└── README.md

Running Tests

# Run verification tests
npm run verify

# Run integration tests (requires PostgreSQL)
npm test

# Development mode with inspection
npm run dev

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit changes: git commit -m 'Add amazing feature'
  4. Push to branch: git push origin feature/amazing-feature
  5. Open a Pull Request

🔒 Security

Connection Security

  • Always use strong passwords and secure connection strings
  • Enable SSL/TLS for production databases: ?sslmode=require
  • Use environment variables for sensitive configuration
  • Implement proper database user permissions

Query Security

  • All queries use parameterized statements to prevent SQL injection
  • Input validation and sanitization
  • Connection pooling with limits to prevent resource exhaustion

📖 Documentation

🤝 Support

Getting Help

Common Issues

  • Connection Problems: Verify PostgreSQL is running and credentials are correct
  • Permission Errors: Check database user permissions
  • Module Not Found: Run npm install to install dependencies

🎯 Roadmap

  • [ ] Performance Monitoring: Built-in query performance tracking
  • [ ] Schema Migration Support: Database migration tools
  • [ ] Multiple Database Support: Connection to multiple databases
  • [ ] GUI Configuration: Web-based configuration interface
  • [ ] Docker Support: Containerized deployment options
  • [ ] TypeScript Support: Full TypeScript implementation

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

📊 Stats

GitHub stars GitHub forks GitHub issues GitHub pull requests


⭐ If this project helps you, please consider giving it a star on GitHub! ⭐

推荐服务器

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 模型以安全和受控的方式获取实时的网络信息。

官方
精选