PostgreSQL MCP Server

PostgreSQL MCP Server

Provides read-only access to PostgreSQL databases with schema inspection, query execution in multiple formats (JSON, CSV, Markdown), and query history tracking with built-in security features.

Category
访问服务器

README

PostgreSQL MCP Server

A Model Context Protocol (MCP) server that provides read-only access to PostgreSQL databases. Execute SELECT queries, inspect database schema, and track query history with built-in safety features.

Features

  • Read-Only Query Execution: Execute SELECT queries with automatic read-only transaction enforcement
  • Multiple Output Formats: Results in JSON, CSV, or Markdown table format
  • Schema Inspection: List tables, describe table structures, view indexes, and explore schemas
  • Query History: Track recently executed queries with execution time and metadata
  • Connection Pooling: Efficient connection management with configurable pool sizes
  • Security: Query validation, SQL injection prevention, and read-only transaction guarantees
  • Database Statistics: View database size, table counts, and connection information

Installation

  1. Clone this repository:
git clone <repository-url>
cd postgres-mcp
  1. Install dependencies using uv:
uv sync

Configuration

Environment Variables

Create a .env file in the project root (use .env.example as a template):

# Required: PostgreSQL Connection Parameters
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DATABASE=myapp
POSTGRES_USER=readonly_user
POSTGRES_PASSWORD=secure_password

# Optional: Connection Pool Configuration
POSTGRES_POOL_MIN_SIZE=2          # Default: 2
POSTGRES_POOL_MAX_SIZE=10         # Default: 10
POSTGRES_COMMAND_TIMEOUT=60       # Default: 60 seconds
POSTGRES_CONNECTION_TIMEOUT=10    # Default: 10 seconds

# Optional: Query History Configuration
QUERY_HISTORY_SIZE=100            # Default: 100

# Optional: Logging Configuration
LOG_LEVEL=INFO                    # Default: INFO (DEBUG, INFO, WARNING, ERROR)

Database User Setup

For security, create a dedicated read-only PostgreSQL user:

-- Create read-only user
CREATE USER readonly_user WITH PASSWORD 'secure_password';

-- Grant connect permission
GRANT CONNECT ON DATABASE myapp TO readonly_user;

-- Grant schema usage
GRANT USAGE ON SCHEMA public TO readonly_user;

-- Grant select on all tables
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;

-- Grant select on future tables
ALTER DEFAULT PRIVILEGES IN SCHEMA public
    GRANT SELECT ON TABLES TO readonly_user;

Usage

Running the Server

uv run python main.py

The server communicates via stdio and can be integrated with MCP clients like Claude Desktop.

Integrating with Claude Desktop

Add this configuration to your Claude Desktop config file:

MacOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "postgres": {
      "command": "python",
      "args": ["/path/to/postgres-mcp/main.py"],
      "env": {
        "POSTGRES_HOST": "localhost",
        "POSTGRES_PORT": "5432",
        "POSTGRES_DATABASE": "myapp",
        "POSTGRES_USER": "readonly_user",
        "POSTGRES_PASSWORD": "secure_password"
      }
    }
  }
}

Alternatively, if using uv:

{
  "mcpServers": {
    "postgres": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "/path-to-postgres-mcp/postgres-mcp",
        "python",
        "main.py"
      ]
    }
}

Available Tools

1. query_database

Execute SELECT queries on the database with formatted output.

Input:

{
  "query": "SELECT * FROM users LIMIT 10",
  "format": "json",
  "timeout": 30
}

Parameters:

  • query (required): SQL SELECT query to execute
  • format (optional): Output format - json (default), csv, or markdown
  • timeout (optional): Query timeout in seconds (max 300)

Output:

{
  "rows": [...],
  "row_count": 10,
  "columns": ["id", "name", "email"],
  "execution_time_ms": 45.32,
  "format": "json",
  "formatted_output": "..."
}

2. list_tables

List all tables in the database with metadata.

Input:

{
  "schema": "public"
}

Parameters:

  • schema (optional): Filter tables by schema name

Output:

{
  "tables": [
    {
      "schema": "public",
      "name": "users",
      "row_count_estimate": 1500,
      "size": "128 KB"
    }
  ]
}

3. describe_table

Get detailed table structure including columns, types, indexes, and constraints.

Input:

{
  "table_name": "users",
  "schema": "public"
}

Parameters:

  • table_name (required): Name of the table
  • schema (optional): Schema name (default: public)

Output:

{
  "schema": "public",
  "table": "users",
  "columns": [
    {
      "name": "id",
      "type": "integer",
      "nullable": false,
      "default": "nextval('users_id_seq')",
      "primary_key": true
    }
  ],
  "indexes": [...],
  "foreign_keys": [...]
}

4. list_schemas

List all schemas in the database.

Input:

{}

Output:

{
  "schemas": ["public", "auth", "analytics"]
}

5. get_table_indexes

Get all indexes for a specific table.

Input:

{
  "table_name": "users",
  "schema": "public"
}

Parameters:

  • table_name (required): Name of the table
  • schema (optional): Schema name (default: public)

Output:

{
  "indexes": [
    {
      "name": "users_pkey",
      "type": "btree",
      "columns": ["id"],
      "unique": true,
      "primary": true
    }
  ]
}

6. get_query_history

Retrieve recent query history with execution metadata.

Input:

{
  "limit": 20
}

Parameters:

  • limit (optional): Maximum queries to return (default: 20, max: 100)

Output:

{
  "queries": [
    {
      "query": "SELECT * FROM users",
      "timestamp": "2025-12-04T10:30:00Z",
      "execution_time_ms": 45.32,
      "row_count": 10,
      "format": "json",
      "success": true,
      "error": null
    }
  ]
}

7. get_database_stats

Get overall database statistics and metadata.

Input:

{}

Output:

{
  "database_name": "myapp",
  "size": "45 MB",
  "table_count": 12,
  "connection_count": 5,
  "version": "PostgreSQL 15.3"
}

Security Features

Read-Only Enforcement

All queries are executed within read-only transactions:

async with conn.transaction(readonly=True):
    result = await conn.fetch(query)

Query Validation

Queries are validated before execution to prevent:

  • INSERT, UPDATE, DELETE operations
  • DROP, CREATE, ALTER operations
  • TRUNCATE, GRANT, REVOKE operations
  • Other write/admin operations

SQL Injection Prevention

  • Input sanitization for table and schema identifiers
  • Parameterized queries where applicable
  • Regex-based validation of identifiers

Architecture

Components

  • config.py: Environment configuration and validation
  • database.py: Connection pool management and read-only query execution
  • validators.py: Query validation and sanitization
  • formatters.py: Result formatting (JSON, CSV, Markdown)
  • history.py: Thread-safe query history tracking
  • tools.py: MCP tool implementations
  • server.py: MCP server setup and lifecycle management
  • types.py: Pydantic models for type safety

Connection Pooling

  • Min Size: 2 warm connections
  • Max Size: 10 concurrent connections
  • Timeout: 60 seconds command timeout, 10 seconds connection timeout
  • Idle Lifetime: Automatic cleanup of inactive connections

Troubleshooting

Connection Errors

Error: "Database authentication failed"

  • Verify POSTGRES_USER and POSTGRES_PASSWORD are correct
  • Check if the user exists in PostgreSQL
  • Ensure the user has CONNECT permission

Error: "Database 'myapp' not found"

  • Verify POSTGRES_DATABASE matches an existing database
  • Check database name spelling

Error: "Connection refused"

  • Verify PostgreSQL is running on the specified host and port
  • Check firewall settings
  • Verify POSTGRES_HOST and POSTGRES_PORT are correct

Query Errors

Error: "Query contains forbidden keyword: INSERT"

  • This server only allows SELECT queries
  • Use a different tool for write operations

Error: "Table does not exist"

  • Verify table name and schema are correct
  • Use list_tables to see available tables
  • Check if user has SELECT permission on the table

Error: "Query execution timeout"

  • Query took longer than the specified timeout
  • Optimize the query or increase timeout parameter
  • Check for missing indexes on large tables

Permission Errors

Error: "permission denied for table X"

  • The database user lacks SELECT permission
  • Grant appropriate permissions (see Database User Setup)

Development

Running Tests

# Add your test commands here
pytest

Project Structure

postgres-mcp/
--- .env                    # Configuration (not in git)
--- .env.example            # Configuration template
--- .gitignore
--- README.md
--- pyproject.toml
--- main.py                 # Entry point
--- src/
    --- postgres_mcp/
        --- __init__.py
        --- config.py       # Configuration
        --- database.py     # Connection pool
        --- formatters.py   # Output formatting
        --- history.py      # Query history
        --- server.py       # MCP server
        --- tools.py        # MCP tools
        --- types.py        # Pydantic models
        --- validators.py   # Query validation

License

[Add your license here]

Contributing

[Add contribution guidelines here]

推荐服务器

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

官方
精选