PostgreSQL CRUD服务

一个提供PostgreSQL数据库表CRUD操作的Model Context Protocol (MCP)服务器,支持表级和列级访问控制、模式检查和自定义SQL查询。

  • by tobecrazy
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 tobecrazy/postgresql-mcp

使用说明

PostgreSQL MCP服务器

一种模型上下文协议(MCP)服务器,为PostgreSQL数据库表提供CRUD操作。

概述

此MCP服务器允许您通过一组工具与PostgreSQL数据库交互,这些工具在指定的表上提供创建、读取、更新和删除(CRUD)操作。服务器使用FastMCP库并在stdio模式下运行,使其与各种MCP客户端兼容。

特性

  • 连接到PostgreSQL数据库
  • 对指定表执行CRUD操作
  • 表和列级访问控制
  • 模式检查
  • 自定义SQL查询执行
  • 通过YAML文件进行配置

安装

  1. 克隆此存储库:

    git clone https://github.com/yourusername/postgresql-mcp.git
    cd postgresql-mcp
    
  2. 安装所需的依赖项:

    pip install -r requirements.txt
    

配置

服务器是使用配置的 config.yaml 文件。此文件包含:

  1. 数据库连接详细信息
  2. 表配置,包括:
    • 哪些表可以访问
    • 允许哪些列进行操作
    • 允许哪些操作(创建、读取、更新、删除)

配置示例:

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

服务器将以stdio模式启动,准备接收来自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"
)

删除记录

从指定表中删除记录。

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": [...],  // For read operations
  "record": {...},   // For create/update operations
  "count": 10        // For read operations
}

或者,如果出现错误:

{
  "status": "error",
  "message": "Error message"
}

安全考虑

  • 这 execute_query 该工具允许任意执行SQL,这可能存在安全风险。考虑限制其使用或实施额外的验证。
  • 数据库凭据以纯文本形式存储在config.yaml文件中。考虑在生产中使用环境变量或安全的秘密管理解决方案。
  • 服务器根据配置验证表和列的访问,但重要的是要确保配置本身是安全的。

许可证

MIT许可证