[正文内容]

stuzero/pg-mcp

main

BranchesTags Go to file Code

Folders and files

Name| Name| Last commit message| Last commit date
---|---|---|---

Latest commit

History

9 Commits
client| client
server| server
.env.example| .env.example
.gitignore| .gitignore
.python-version| .python-version
Dockerfile| Dockerfile
README.md| README.md
docker-compose.yml| docker-compose.yml
pyproject.toml| pyproject.toml
test.py| test.py
uv.lock| uv.lock
View all files

Repository files navigation

PostgreSQL Model Context Protocol (PG-MCP) Server

一个用于 PostgreSQL 数据库的模型上下文协议 (MCP) 服务器,增强了 AI agent 的能力。

概述

PG-MCP 是一个针对 PostgreSQL 数据库的 Model Context Protocol 的服务器实现。它为 AI agent 提供了一个全面的 API,通过 MCP 的面向资源的架构来发现、连接、查询和理解 PostgreSQL 数据库。

此实现构建于并扩展了 reference Postgres MCP implementation,并具有以下几个关键增强功能:

  1. 完整的服务器实现:构建为一个完整的服务器,具有 SSE 传输,可用于生产环境。
  2. 多数据库支持:同时连接到多个 PostgreSQL 数据库。
  3. 丰富的目录信息:从数据库目录中提取并公开表/列描述。
  4. 扩展上下文:提供基于 YAML 的关于 PostgreSQL 扩展(如 PostGIS 和 pgvector)的详细知识。
  5. 查询解释:包含一个用于分析查询执行计划的专用工具。
  6. 健壮的连接管理:具有安全的连接 ID 处理的数据库连接的适当生命周期。

功能

连接管理

查询工具

模式发现资源

数据访问资源

扩展上下文

内置的 PostgreSQL 扩展的上下文信息,例如:

可以通过 YAML 配置文件轻松添加其他扩展。

安装

前提条件

使用 Docker

# 克隆仓库
git clone https://github.com/stuzero/pg-mcp.git
cd pg-mcp
# 使用 Docker Compose 构建并运行
docker-compose up -d

手动安装

# 克隆仓库
git clone https://github.com/stuzero/pg-mcp.git
cd pg-mcp
# 创建并激活虚拟环境
python -m venv .venv
source .venv/bin/activate # 在 Windows 上: .venv\Scripts\activate
# 使用 uv 安装
uv sync --frozen
# 运行服务器
python -m server.app

用法

测试服务器

该仓库包含用于验证服务器功能的测试脚本:

# 基本服务器功能测试
python test.py "postgresql://username:password@hostname:port/database"
# Claude 驱动的自然语言到 SQL 转换
python client/claude_cli.py "Show me the top 5 customers by total sales"

claude_cli.py 脚本需要以下环境变量:

# .env 文件
DATABASE_URL=postgresql://username:password@hostname:port/database
ANTHROPIC_API_KEY=your-anthropic-api-key
PG_MCP_URL=http://localhost:8000/sse

对于 AI Agent

用于 agent 的示例提示:

Use the PostgreSQL MCP server to analyze the database. 
Available tools:
- connect: Register a database connection string and get a connection ID
- disconnect: Close a database connection
- pg_query: Execute SQL queries using a connection ID
- pg_explain: Get query execution plans
You can explore schema resources via:
pgmcp://{conn_id}/schemas
pgmcp://{conn_id}/schemas/{schema}/tables
pgmcp://{conn_id}/schemas/{schema}/tables/{table}/columns

架构

此服务器构建于:

安全注意事项

贡献

欢迎贡献!可扩展的领域:

关于

No description, website, or topics provided.

Resources

Readme Activity

Stars

8 stars

Watchers

2 watching

Forks

0 forks Report repository

Releases

No releases published

Packages 0

No packages published

Languages

Footer

© 2025 GitHub, Inc.

Footer navigation

You can’t perform that action at this time.