pg-mcp

pg-mcp

A Model Context Protocol server for PostgreSQL that enables database operations like querying, schema inspection, performance analysis, and administration through a JSON-RPC 2.0 interface.

Category
访问服务器

README

Docker Image CI

PostgreSQL Model Context Protocol (MCP) Server

A comprehensive Model Context Protocol (MCP) Server built with FastAPI that provides full PostgreSQL database operations through a standardized JSON-RPC 2.0 interface. This server can be integrated with VS Code and other MCP-compatible tools for seamless database management.

Features

🚀 Core MCP Functionality

  • JSON-RPC 2.0 compliant API
  • VS Code integration ready
  • Authentication with API key
  • Comprehensive error handling
  • Auto-fallback to mock service when PostgreSQL is unavailable

🗄️ PostgreSQL Operations

Basic Operations

  • Connection Testing - Test database connectivity and get server info
  • Query Execution - Execute any SQL query (SELECT, INSERT, UPDATE, DELETE, etc.)
  • Schema Information - Get complete database schema with tables and columns
  • Table Information - Detailed table metadata, columns, indexes, and row counts

Advanced Operations

  • Query Performance Analysis - EXPLAIN ANALYZE for query optimization
  • Database Size Information - Database and table size statistics
  • Table Statistics - Column statistics, null fractions, distinct values
  • Active Connections - Monitor current database connections
  • Locks Information - View database locks and blocking queries
  • Slow Queries Analysis - Identify performance bottlenecks (requires pg_stat_statements)

Administrative Operations

  • Table Backup - Create table copies with or without data
  • Index Creation - Create indexes on tables (regular or unique)
  • Table Optimization - VACUUM and ANALYZE tables for performance

Utility Operations

  • Echo Tool - Simple echo for testing connectivity

Available Tools

Tool Name Description Parameters
echo Echo back input message message (string)
postgres_connection_test Test PostgreSQL connection None
postgres_query Execute SQL query query (string), params (array, optional)
postgres_schema Get database schema None
postgres_table_info Get table information table_name (string), schema (string, default: "public")
postgres_query_analyze Analyze query performance query (string)
postgres_database_size Get database size info None
postgres_table_stats Get table statistics table_name (string), schema (string, default: "public")
postgres_active_connections Get active connections None
postgres_backup_table Backup table source_table (string), backup_table (string), schema (string), include_data (boolean)
postgres_create_index Create table index table_name (string), column_names (array), index_name (string, optional), schema (string), unique (boolean)
postgres_slow_queries Get slow queries limit (integer, default: 10)
postgres_optimize_table Optimize table table_name (string), schema (string, default: "public")
postgres_locks_info Get database locks None

Installation

  1. Clone the repository:
git clone <repository-url>
cd pg-mcp
  1. Install dependencies:
pip install -r requirements.txt
# or using pyproject.toml
pip install -e .
  1. Configure PostgreSQL connection: Edit app/config.py with your PostgreSQL settings:
POSTGRES_DB_CONFIG = {
    "host": "localhost",
    "port": "5432", 
    "dbname": "your_database",
    "user": "your_username",
    "password": "your_password"
}
  1. Set API key: Update MCP_API_KEY in app/config.py or set environment variable.

Usage

Start the Server

# Development
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Production
uvicorn app.main:app --host 0.0.0.0 --port 8000

VS Code Integration

  1. Install MCP extension in VS Code
  2. Configure MCP settings in .vscode/mcp.json:
{
  "mcpServers": {
    "postgres-mcp": {
      "name": "PostgreSQL MCP Server",
      "url": "http://localhost:8000/mcp",
      "apiKey": "your-secret-mcp-api-key"
    }
  }
}

Direct API Usage

Test connection:

curl -X GET http://localhost:8000/mcp \
  -H "Authorization: Bearer your-secret-mcp-api-key"

Execute query:

curl -X POST http://localhost:8000/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-secret-mcp-api-key" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "postgres_query",
      "arguments": {
        "query": "SELECT version()"
      }
    }
  }'

Testing

Comprehensive Test Suite

# Run unit tests
pytest test/

# Run comprehensive integration test
python test_postgres_mcp_comprehensive.py

Individual Tool Testing

# Test specific functionality
python test_postgres_mcp.py

Architecture

pg-mcp/
├── app/
│   ├── main.py              # FastAPI application entry point
│   ├── mcp.py               # MCP server implementation
│   ├── postgres_service.py  # PostgreSQL service layer
│   ├── postgres_mock.py     # Mock service for testing
│   ├── json_rpc.py          # JSON-RPC 2.0 implementation
│   ├── auth.py              # Authentication middleware
│   ├── config.py            # Configuration settings
│   └── logger.py            # Logging configuration
├── test/                    # Test files
├── .vscode/
│   └── mcp.json            # VS Code MCP configuration
└── pyproject.toml          # Project dependencies

Key Features

🔒 Security

  • API key authentication for all requests
  • SQL injection protection through parameterized queries
  • Error sanitization to prevent information leakage

🚀 Performance

  • Connection pooling for database connections
  • Async/await support throughout
  • Query optimization tools and analysis

🛠️ Development

  • Auto-reload support for development
  • Comprehensive logging for debugging
  • Mock service for testing without real database
  • Type hints throughout codebase

🔧 Reliability

  • Automatic fallback to mock service
  • Comprehensive error handling
  • Connection retry logic
  • Graceful degradation

Examples

Query Execution

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "postgres_query",
    "arguments": {
      "query": "SELECT * FROM users WHERE active = $1",
      "params": ["true"]
    }
  }
}

Table Backup

{
  "jsonrpc": "2.0", 
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "postgres_backup_table",
    "arguments": {
      "source_table": "users",
      "backup_table": "users_backup_20240115",
      "schema": "public",
      "include_data": true
    }
  }
}

Index Creation

{
  "jsonrpc": "2.0",
  "id": 3, 
  "method": "tools/call",
  "params": {
    "name": "postgres_create_index",
    "arguments": {
      "table_name": "users",
      "column_names": ["email", "status"], 
      "index_name": "idx_users_email_status",
      "unique": false
    }
  }
}

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

MIT License - see LICENSE file for details.

Support

For issues and questions:

  • Create an issue on GitHub
  • Check the test files for usage examples
  • Review the comprehensive test suite for full API coverage

推荐服务器

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

官方
精选