这是一个提供与 PostgreSQL 数据库交互接口的模型上下文协议 (MCP) 服务器。它允许您通过标准 API 执行查询、执行数据库操作并管理事务,为数据库操作提供了便捷、安全的解决方案。
git clone https://github.com/yourusername/postgres-mcp.git
cd postgres-mcp
go mod download
cp .env.example .env
使用 PostgreSQL 数据库凭据编辑 .env
文件。
4. 构建服务器:
go build -o postgres-mcp
./postgres-mcp
该服务器公开以下 MCP 工具:
执行单条 SQL 语句。 请求:
{
"statement": "INSERT INTO users(name, email) VALUES($1, $2)",
"arguments": ["Jane Doe", "jane@example.com"]
}
响应:
{
"rows affected": 1
}
执行 SELECT 查询并返回结果。 请求:
{
"statement": "SELECT * FROM users WHERE id = $1",
"arguments": [1]
}
响应:
{
"rows": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
],
"columns": ["id", "name", "email"],
"rowCount": 1
}
在事务中执行多条语句。 请求:
{
"statements": [
"INSERT INTO users(name, email) VALUES($1, $2)",
"INSERT INTO user_roles(user_id, role) VALUES($1, $2)"
],
"arguments": [
["Alice", "alice@example.com"],
[1, "admin"]
]
}
响应:
{
"results": [
{
"statement": 0,
"rowsAffected": 1
},
{
"statement": 1,
"rowsAffected": 1
}
]
}
获取表的模式信息。 请求:
{
"table_name": "users"
}
响应:
{
"table": "users",
"columns": [
{
"name": "id",
"type": "integer",
"nullable": false,
"default": "nextval('users_id_seq'::regclass)"
},
{
"name": "name",
"type": "text",
"nullable": true
}
]
}
以下是一个使用 Go 调用 query_tool
的示例:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type QueryRequest struct {
Statement string `json:"statement"`
Arguments []string `json:"arguments"`
}
func main() {
query := &QueryRequest{
Statement: "SELECT * FROM users WHERE id = $1",
Arguments: []string{strconv.Itoa(1)},
}
jsonReq, err := json.Marshal(query)
if err != nil {
panic(err)
}
resp, err := http.Post("http://localhost:8080/query", "application/json", bytes.NewBuffer(jsonReq))
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var result map[string]interface{}
json.Unmarshal(body, &result)
fmt.Printf("%#v\n", result)
}
⚠️ 重要提示
- 使用参数化查询来防止 SQL 注入
- 限制数据库用户的权限
- 在生产环境中启用 SSL/TLS 加密
- 避免在查询中暴露敏感信息
- 定期审计和监控数据库活动
该项目采用 MIT 许可证。