article
README
🚀 PostgreSQL MCP 服务器
PostgreSQL MCP 服务器可提供 PostgreSQL 数据库表的增删改查(CRUD)操作。借助该服务器,用户能方便地与 PostgreSQL 数据库交互,对指定表执行各类操作。
🚀 快速开始
此 MCP 服务器允许您通过一组工具与 PostgreSQL 数据库交互,对指定的表执行增删改查操作。该服务器使用 FastMCP 库,并以标准输入输出模式运行,使其与各种 MCP 客户端兼容。
✨ 主要特性
- 连接 PostgreSQL 数据库
- 对指定表执行增删改查操作
- 表级和列级访问控制
- 数据库表结构检查
- 执行自定义 SQL 查询
- 通过 YAML 文件配置
📦 安装指南
-
克隆此仓库:
git clone https://github.com/yourusername/postgresql-mcp.git cd postgresql-mcp -
安装所需的依赖项:
pip install -r requirements.txt
📚 详细文档
配置
服务器通过 config.yaml 文件进行配置。此文件包含:
- 数据库连接详细信息
- 表配置,包括:
- 哪些表是可访问的
- 允许哪些列进行操作
- 允许哪些操作(创建、读取、更新、删除)
示例配置:
database:
host: localhost
port: 5432
dbname: postgres
user: postgres
password: postgres
tables:
- name: users
allowed_columns:
- id
- name
- email
- created_at
allowed_operations:
- create
- read
- update
- delete
- name: products
allowed_columns:
- id
- name
- price
- description
- category
allowed_operations:
- create
- read
- update
- delete
使用
运行 MCP 服务器:
python postgresql_mcp_server.py
服务器将以标准输入输出模式启动,准备接收来自 MCP 客户端的命令。
可用 MCP 工具
list_tables
列出配置中的所有表。
response = list_tables()
create_record
在指定表中创建新记录。
response = create_record(
table_name="users",
data={
"name": "John Doe",
"email": "john@example.com"
}
)
read_records
从指定表中读取记录,带可选过滤条件。
response = read_records(
table_name="users",
filters={"name": "John Doe"},
limit=10,
offset=0
)
update_record
更新指定表中的记录。
response = update_record(
table_name="users",
record_id=1,
data={"email": "newemail@example.com"},
id_column="id"
)
delete_record
从指定表中删除记录。
response = delete_record(
table_name="users",
record_id=1,
id_column="id"
)
execute_query
执行自定义 SQL 查询。
response = execute_query(
query="SELECT * FROM users WHERE age > %s",
params=[18]
)
get_table_schema
获取特定表的架构信息。
response = get_table_schema(table_name="users")
响应格式
所有工具都返回标准响应格式:
{
"status": "success",
"message": "Optional message",
"records": [...], // 用于读取操作
"record": {...}, // 用于创建和更新操作
"count": 10 // 用于读取操作
}
如果发生错误,响应状态将为 error,并包含错误消息。
⚠️ 注意事项
⚠️ 重要提示
- 数据库连接信息需要根据实际情况配置。
- 表和列的访问控制严格遵循配置文件中的定义。
- 所有 SQL 查询都需要通过参数化方式执行以防止注入攻击。
微信扫一扫