PostgreSQL MCP 服务器可提供 PostgreSQL 数据库表的增删改查(CRUD)操作。借助该服务器,用户能方便地与 PostgreSQL 数据库交互,对指定表执行各类操作。
此 MCP 服务器允许您通过一组工具与 PostgreSQL 数据库交互,对指定的表执行增删改查操作。该服务器使用 FastMCP 库,并以标准输入输出模式运行,使其与各种 MCP 客户端兼容。
克隆此仓库:
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 客户端的命令。
列出配置中的所有表。
response = list_tables()
在指定表中创建新记录。
response = create_record(
table_name="users",
data={
"name": "John Doe",
"email": "john@example.com"
}
)
从指定表中读取记录,带可选过滤条件。
response = read_records(
table_name="users",
filters={"name": "John Doe"},
limit=10,
offset=0
)
更新指定表中的记录。
response = update_record(
table_name="users",
record_id=1,
data={"email": "newemail@example.com"},
id_column="id"
)
从指定表中删除记录。
response = delete_record(
table_name="users",
record_id=1,
id_column="id"
)
执行自定义 SQL 查询。
response = execute_query(
query="SELECT * FROM users WHERE age > %s",
params=[18]
)
获取特定表的架构信息。
response = get_table_schema(table_name="users")
所有工具都返回标准响应格式:
{
"status": "success",
"message": "Optional message",
"records": [...], // 用于读取操作
"record": {...}, // 用于创建和更新操作
"count": 10 // 用于读取操作
}
如果发生错误,响应状态将为 error,并包含错误消息。
⚠️ 重要提示
- 数据库连接信息需要根据实际情况配置。
- 表和列的访问控制严格遵循配置文件中的定义。
- 所有 SQL 查询都需要通过参数化方式执行以防止注入攻击。