Postgresql Mcp Server Wt6

Postgresql Mcp Server Wt6

🚀 PostgreSQL MCP 服务器

这是一个提供与 PostgreSQL 数据库交互接口的模型上下文协议 (MCP) 服务器。它允许您通过标准 API 执行查询、执行数据库操作并管理事务,为数据库操作提供了便捷、安全的解决方案。

✨ 主要特性

  • 执行带参数的 SQL 查询以防止 SQL 注入
  • 执行插入、更新和删除操作
  • 在事务中执行多个语句
  • 获取数据库模式信息
  • 安全处理参数以防止 SQL 注入

📦 安装指南

  1. 克隆仓库:
git clone https://github.com/yourusername/postgres-mcp.git
cd postgres-mcp
  1. 下载依赖项:
go mod download
  1. 配置数据库连接:
cp .env.example .env

使用 PostgreSQL 数据库凭据编辑 .env 文件。 4. 构建服务器:

go build -o postgres-mcp
  1. 运行服务器:
./postgres-mcp

💻 使用示例

该服务器公开以下 MCP 工具:

基础用法

1. execute_tool

执行单条 SQL 语句。 请求:

{
"statement": "INSERT INTO users(name, email) VALUES($1, $2)",
"arguments": ["Jane Doe", "jane@example.com"]
}

响应:

{
"rows affected": 1
}

2. query_tool

执行 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
}

3. transaction_tool

在事务中执行多条语句。 请求:

{
"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
}
]
}

4. schema_tool

获取表的模式信息。 请求:

{
"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 许可证。

  • 0 关注
  • 0 收藏,8 浏览
  • system 提出于 2025-09-23 15:03

相似服务问题