数据库管理服务器

通过模型上下文协议查询和管理PostgreSQL和MongoDB数据库,支持自动模式发现、网络范围数据库访问和零配置部署。

  • by kunwarmahen
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 kunwarmahen/db-mcp-server

使用说明

数据库MCP服务器

通过模型上下文协议查询和管理数据库。

概述

数据库MCP服务器为PostgreSQL和MongoDB提供了可供AI访问的数据库操作。它实现了:

  • PostgreSQL查询与数据管理
  • MongoDB文档操作
  • 自动模式发现
  • 通过MCP发现中心实现全网数据库访问
  • 零配置部署,自动广播

非常适合构建需要安全高效地与数据库交互的人工智能应用程序。

特点

PostgreSQL 支持

  • 获取服务器版本和数据库信息
  • 列出任何模式中的表
  • 使用可配置的限制查询数据
  • 插入新记录
  • SQL验证和安全检查

MongoDB 支持

  • 列表集合
  • 使用过滤器查找文档
  • 插入文档
  • ObjectId 处理和 JSON 序列化

网络集成

  • 用于发现的自动多播广播
  • 多传输支持(HTTP 和流式 HTTP)
  • 与MCP发现中心兼容
  • 零配置网络

安装

先决条件

  • Python 3.10及以上版本
  • PostgreSQL服务器(或MongoDB,或两者都有)
  • uv 包管理器(或 pip)

设置

# Clone or navigate to project
cd database-mcp-server

# Install dependencies
uv sync

# Or with pip:
pip install -r requirements.txt

配置

环境变量

# Transport mode
MCP_TRANSPORT=http                    # http, streamable-http, or stdio (default)

# Server settings
MCP_HOST=0.0.0.0                     # Binding host
MCP_PORT=3002                         # Server port
MCP_SERVER_NAME=Database MCP Server  # Display name

# PostgreSQL
DATABASE_URL=postgresql://user:pass@localhost:5432/dbname
# Or individual settings:
POSTGRES_USER=postgres
POSTGRES_PASSWORD=
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=postgres

# MongoDB
MONGODB_URL=mongodb://localhost:27017
MONGODB_DB=test

# Broadcasting (for MCP Discovery Hub)
MCP_ENABLE_BROADCAST=true            # Enable/disable broadcasting
MCP_BROADCAST_INTERVAL=30            # Seconds between announcements

.env 文件

创建一个 .env 项目根目录下的文件:

# Database Connections
DATABASE_URL=postgresql://postgres:password@localhost:5432/mydb
MONGODB_URL=mongodb://localhost:27017
MONGODB_DB=mydb

# MCP Server
MCP_TRANSPORT=http
MCP_PORT=3002
MCP_SERVER_NAME=Database MCP Server
MCP_ENABLE_BROADCAST=true
MCP_BROADCAST_INTERVAL=30

Docker 示例

# With PostgreSQL in Docker
docker run -d \
  -e POSTGRES_PASSWORD=mypassword \
  -p 5432:5432 \
  postgres:15

# With MongoDB in Docker
docker run -d \
  -p 27017:27017 \
  mongo:latest

# Start MCP server
MCP_TRANSPORT=http MCP_PORT=3002 uv run main.py

使用方法

以HTTP模式(带广播)启动

# Using environment variables
MCP_TRANSPORT=http MCP_PORT=3002 uv run main.py

# Or with .env file
uv run main.py

以Streamable-HTTP模式启动

MCP_TRANSPORT=streamable-http MCP_PORT=3002 uv run main.py

以标准控制台模式启动(适用于Claude)

# Default mode, works with Claude Desktop
uv run main.py

可用工具

PostgreSQL 工具

获取数据库版本

pg_version()

检索 PostgreSQL 服务器版本信息

列出表格

pg_list_tables(schema: str = "public")

列出模式中的所有表

示例:

{
  "method": "tools/call",
  "params": {
    "name": "pg_list_tables",
    "arguments": { "schema": "public" }
  }
}

列出行

pg_list_rows(table: str, limit: int = 100)

从表中查询数据并设置限制

示例:

{
  "method": "tools/call",
  "params": {
    "name": "pg_list_rows",
    "arguments": { "table": "users", "limit": 50 }
  }
}

插入行

pg_insert_row(table: str, data: dict)

插入一条新记录并返回插入的ID

示例:

{
  "method": "tools/call",
  "params": {
    "name": "pg_insert_row",
    "arguments": {
      "table": "users",
      "data": { "name": "John", "email": "john@example.com" }
    }
  }
}

MongoDB 工具

列表集合

mongo_list_collections()

获取数据库中的所有集合名称

查找文档

mongo_find(
  collection: str,
  query: dict = {},
  limit: int = 10
)

从集合中查询文档

示例:

{
  "method": "tools/call",
  "params": {
    "name": "mongo_find",
    "arguments": {
      "collection": "users",
      "query": { "status": "active" },
      "limit": 20
    }
  }
}

插入文档

mongo_insert(collection: str, doc: dict)

将一个文档插入到集合中

示例:

{
  "method": "tools/call",
  "params": {
    "name": "mongo_insert",
    "arguments": {
      "collection": "logs",
      "doc": {
        "timestamp": "2024-10-17T10:00:00Z",
        "level": "info",
        "message": "Server started"
      }
    }
  }
}

与MCP发现中心的集成

自动发现

当广播功能启用时,数据库服务器会自动注册:

  1. 服务器广播每30秒一次 239.255.255.250:5353
  2. Hub 发现发现中心接收并探测服务器
  3. 已注册的工具所有7种数据库工具均可在全网络范围内使用

多服务器设置

为不同目的部署多个数据库服务器:

Database Server 1 (PostgreSQL, port 3002)
    ↓
Database Server 2 (MongoDB, port 3003)
    ↓
Database Server 3 (Mixed, port 3004)
    ↓
MCP Discovery Hub (port 8000)
    ↓
AI Tool (Claude, etc.)

所有发现的服务器均可自动供AI使用。

API 端点(在 HTTP 模式下)

GET /

服务器信息

curl http://localhost:3002/

POST /mcp(注:这通常是一个网络请求的路径,直接翻译为中文可能无实际意义,但按字面可译为“发布到/mcp”或“向/mcp发送POST请求”,具体含义需结合上下文理解)

MCP协议端点

所有MCP通信(初始化、工具/列表、工具/调用)

用例

1. 数据分析

基于人工智能的数据库分析:

"User: Summarize user activity from the last month"
AI: I'll query the activity logs for you...
→ calls pg_list_rows(table="activity_logs", limit=1000)
→ analyzes and summarizes results

2. 自动化报告生成

从数据库数据生成报告:

"User: Create a report of orders by region"
AI: Let me fetch the order data...
→ calls pg_list_rows(table="orders", limit=10000)
→ groups and aggregates by region
→ generates report

3. 数据录入与更新

AI辅助数据录入:

"User: Add a new customer with this information"
AI: I'll add them to the database...
→ calls pg_insert_row(table="customers", data={...})

4. 文档搜索与检索

MongoDB文档管理:

"User: Find all documents with status pending"
AI: Searching for pending documents...
→ calls mongo_find(collection="tasks", query={"status": "pending"})

5. 系统监控

数据库健康状况和活动监控:

"User: Check if there are any slow queries"
AI: Let me check the query logs...
→ calls pg_list_rows(table="query_logs")
→ identifies slow queries

安全特性

输入验证

  • 表名和列名已通过正则表达式验证
  • 通过参数化查询防止SQL注入
  • 插入操作的数据类型验证

错误处理

  • 捕获并报告数据库连接错误
  • 超时保护(默认30秒)
  • 清晰的错误信息便于调试

最佳实践

  1. 首先进行只读操作在修改数据之前先进行查询
  2. 使用限制始终为查询设置合理的限制
  3. 监控日志检查 database_mcp.log 针对问题
  4. 备份数据在AI访问生产环境前确保做好备份
  5. **审计轨迹(或审计追踪)**记录来自MCP的所有数据库修改

性能考量

  • 查询性能取决于查询的复杂性和数据量
  • 连接池PostgreSQL 并发设置为连接池大小=5
  • 广播开销最小(30字节的UDP数据包)
  • 超时保护操作限制为30秒

优化技巧

  • 使用 limit 参数用于减少数据传输
  • 用以下条件筛选文档: query MongoDB中的参数
  • 为常见查询创建适当的数据库索引
  • 使用 schema 参数用于缩小PostgreSQL搜索范围

日志

服务器日志被写入到 database_mcp.log:

# View logs
tail -f database_mcp.log

# Check for errors
grep ERROR database_mcp.log

# Monitor database operations
grep "Listing tables\|Inserting\|Finding" database_mcp.log

故障排除

PostgreSQL 连接错误

# Check PostgreSQL is running
psql postgresql://user:pass@localhost:5432/db

# Verify credentials in .env
echo $DATABASE_URL

MongoDB 连接错误

# Check MongoDB is running
mongo --eval "db.version()"

# Verify connection string
echo $MONGODB_URL

广播功能无法正常工作

# Verify multicast is enabled
ip route show | grep 239.255.255.250

# Check firewall settings
sudo firewall-cmd --list-all

端口已被占用

# Use different port
MCP_PORT=3003 uv run main.py

性能指标

典型响应时间:

  • 简单SELECT操作:10-50毫秒
  • 数据库信息查询:5-20毫秒
  • MongoDB 查找操作:20-100毫秒
  • 插入操作:30-200毫秒(取决于触发条件)

网络开销(含广播):

  • 广播:0.01% 的开销
  • 发现:每台服务器一次性费用

要求

  • Python 3.10及以上版本
  • FastAPI
  • SQLAlchemy
  • PyMongo
  • FastMCP
  • python-dotenv(用于在Python中加载环境变量的库)

贡献

欢迎提出改进意见!可能的增强方向:

  • 额外的数据库支持(MySQL、SQLite)
  • 存储过程执行
  • 事务支持
  • 高级查询构建器
  • 连接池配置
  • 数据库复制支持

许可证

MIT 许可证 - 详见 LICENSE 文件

支持

  • 问题:在GitHub上报告
  • 文档:请参阅MCP发现中心维基
  • 示例:请查看examples/目录
  • 数据库文档:PostgreSQL和MongoDB官方文档