PostgreSQL MCP服务器

一个基于Rust的模块化能力提供者(MCP)服务器,使Amazon Q能够通过聊天界面查询PostgreSQL数据库结构并执行只读查询。

  • by qthanh04
  • Makefile
  • 本地部署
  • 更新于
在 GitHub 查看 quangthanhg13/amazon-q-postgresql-mcp-server

使用说明

用于Amazon Q的PostgreSQL MCP服务器

一个基于Rust的模块化能力提供者(MCP)服务器,支持Amazon Q交互PostgreSQL数据库。服务器允许用户通过Amazon Q聊天界面查询数据库结构的只读查询。

概述

此项目实现了一个遵循Amazon Q CLI使用的MCP协议的PostgreSQL服务器

  1. 列出PostgreSQL数据库中的所有表
  2. 获取特定表的架构信息
  3. 执行只读SQL查询,结果返回为JSON

先决条件

  • 锈蚀1.70
  • 货物包装经理
cargo new postgresql_server
  • PostgreSQL数据库
  • 亚马逊Q CLI

安装

  1. 克隆存储库:
git clone ...
cd postgresql-mcp-server
  1. 构建项目:
cargo build --release --bin postgresql_server

用法

运行服务器

  • 服务器需要PostgreSQL连接字符串作为命令行参数:
./target/release/postgresql_server "postgresql://username:password@hostname:port/database"

与Amazo Q CLI集成

  1. 创建或编辑MCP
vim ~/.aws/amazonq/mcp.json
  1. 将PosgreSQL服务器配置添加到文件
{
  "mcpServers": {
    "calculator": {
      "command": "/home/ec2-user/sample-building-mcp-servers-with-rust/target/release/calculator_server",
      "args": []
    },
    "rds": {
      "command": "/home/ec2-user/sample-building-mcp-servers-with-rust/target/release/rds_server",
      "args": []
    },
    "s3": {
      "command": "/home/ec2-user/sample-building-mcp-servers-with-rust/target/release/s3_server",
      "args": []
    },
    "postgres": {
      "command": "/home/ec2-user/sample-building-mcp-servers-with-rust/target/release/postgresql_server",
      "args": [
        "postgresql://postgres:<DB-PASSWORD>@<DB-ENDPOINT>.com:5432/demo"
      ]
    }
  }
}
  1. 测试Q Amanzon服务器
  • 开始Q亚马逊
qchat
  • 要求Amazon Q列出数据库中的表 Can you list all tables in my PostgreSQL database using the postgres operator?

  • 尝试询问特定表的架构: What columns are in the student table?

  • 执行SQL查询: List 100 students sorted by name.

项目结构

  • src/main.rs:命令行参数、日志设置和服务器初始化的入口点
  • src/operator.rs 使用数据库交互工具实现PostgreSQL。

工具实施 operator.rs

服务器使用RMCP框架中的工具artribute实现了三个主要工具:

  1. 列表表格:
#[tool(description = "List tables in the PostgreSQL database")]
async fn list_tables(&self) -> String {
    // Implementation that queries information_schema.tables
    // and returns a JSON string of table names
}
  1. 获取表架构:
#[tool(description = "Get schema for a specific table")]
async fn get_table_schema(
    &self,
    #[tool(param)]
    #[schemars(description = "Name of the table to get schema for")]
    table_name: String,
) -> String {
    // Implementation that queries information_schema.columns
    // and returns a JSON string of column names and data types
}

  1. 执行SQL查询:
#[tool(description = "Run a read-only SQL query")]
async fn query(
    &self,
    #[tool(param)]
    #[schemars(description = "SQL query to execute (read-only)")]
    sql: String,
) -> String {
    // Implementation that executes the SQL query
    // and returns a JSON string of the results
}