Skip to main content

MongoDB MCP Server - Streamable HTTP

基于 MCP 官方 SDK 实现的 MongoDB MCP Server,采用 Streamable HTTP 传输协议,完美支持 FastGPT。

项目结构

python-mcp-server/
├── src/my_mongodb_mcp/
│   ├── __init__.py
│   └── server.py          # 核心代码(11 个工具函数)
├── tests/
│   └── test_server.py
├── pyproject.toml         # 打包配置
├── .env.example           # 环境变量模板
├── .env                   # 实际环境变量(需自行配置)
├── .gitignore
└── README.md

可用工具

工具名 描述 写操作
list_databases 列出所有数据库 ❌
list_collections 列出数据库中的集合 ❌
find_documents 查询文档 ❌
count_documents 统计文档数量 ❌
aggregate 聚合管道操作 ❌
list_indexes 列出索引 ❌
get_collection_stats 获取集合统计 ❌
insert_document 插入单个文档 ✅
update_documents 更新文档 ✅
delete_documents 删除文档 ✅
create_index 创建索引 ✅

🚀 完整操作流程(SOP)

第一步:环境准备

# 1. 创建 conda 环境(需要管理员权限)
conda create -n mongodb-mcp python=3.12 -y

# 2. 激活环境
conda activate mongodb-mcp

# 3. 进入项目目录
cd C:\Develop\AI\nju-skills-0210\nju-skills\app\python-mcp-server

第二步:安装依赖

# 安装项目依赖
pip install -e ".[dev]"

第三步:配置环境变量

# 复制环境变量模板
copy .env.example .env

编辑 .env 文件,填入实际配置:

# MongoDB 连接字符串
MDB_MCP_CONNECTION_STRING=mongodb://username:password@host:27017/database?authSource=admin&directConnection=true

# 只读模式(推荐开启,防止 AI 误操作)
MDB_MCP_READ_ONLY=true

# 数据库名(可选,默认使用连接串中的数据库)
MDB_MCP_DATABASE=

第四步:启动服务器

# 启动 Streamable HTTP 模式的 MCP Server
python -m my_mongodb_mcp.server

预期输出:

🚀 MongoDB MCP Server 已启动(Streamable HTTP 模式)
📍 地址:http://localhost:8000/
📍 只读模式:是
📍 数据库:fastgpt
INFO:     Uvicorn running on http://0.0.0.0:8000

第五步:本地测试

浏览器访问:

http://localhost:8000/

或使用 curl 测试:

curl http://localhost:8000/

第六步:内网穿透(可选,用于 FastGPT 云端访问)

6.1 启动 Cloudflare Tunnel

新开一个终端窗口:

cloudflared tunnel --url http://localhost:8000

预期输出:

Tunnel URL: https://xxx-yyy-zzz.trycloudflare.com

6.2 在 FastGPT 中配置

  1. 打开 FastGPT
  2. 创建 MCP 工具
  3. 填写配置:
    • 工具类型:MCP 工具
    • 名称:MongoDB
    • MCP 地址:https://xxx-yyy-zzz.trycloudflare.com/
    • 鉴权类型:无
  4. 点击"解析"
  5. 等待工具列表加载
  6. 保存

🔧 常见问题

Q1: ModuleNotFoundError: No module named 'my_mongodb_mcp'

原因:未激活正确的 conda 环境或未安装包

解决:

conda activate mongodb-mcp
pip install -e ".[dev]"

Q2: MDB_MCP_CONNECTION_STRING environment variable is not set

原因:.env 文件未配置或路径错误

解决:

  1. 确认 .env 文件在项目根目录
  2. 确认运行命令时工作目录是项目根目录
  3. 重启终端重新加载环境变量

Q3: Cloudflare Tunnel 502 错误

原因:MCP Server 未启动或已崩溃

解决:

  1. 检查 MCP Server 终端是否有错误输出
  2. 确认 8000 端口正在监听:netstat -ano | findstr :8000
  3. 重启 MCP Server 和 Cloudflare Tunnel

Q4: FastGPT 解析失败

解决:

  1. 确认 MCP 地址正确(不要加 /sse 后缀)
  2. 等待 10-15 秒(首次连接可能较慢)
  3. 检查 FastGPT 日志获取详细错误信息

📊 技术说明

为什么选择 Streamable HTTP?

传输模式 状态 说明
Streamable HTTP ✅ 推荐 MCP 官方标准,双向通信,支持 FastGPT
SSE ⚠️ 有限支持 旧版本协议,单向通信
stdio ✅ 本地使用 仅适合本地 CLI 工具

Streamable HTTP 优势

  • ✅ 官方标准 - MCP 协议推荐的传输方式
  • ✅ 双向通信 - 支持 GET 初始化和 POST 工具调用
  • ✅ 会话管理 - 自动处理 session ID
  • ✅ FastGPT 兼容 - 完美支持 FastGPT 的 MCP 工具集

架构说明

┌─────────────────────────────────────────────────────────┐
│  FastGPT                                                 │
│  MCP 地址:https://xxx.trycloudflare.com/                │
└───────────────────┬─────────────────────────────────────┘
                    │ HTTPS
┌───────────────────▼─────────────────────────────────────┐
│  Cloudflare Tunnel                                       │
│  公网 → 本地 8000                                        │
└───────────────────┬─────────────────────────────────────┘
                    │ HTTP
┌───────────────────▼─────────────────────────────────────┐
│  MongoDB MCP Server (Streamable HTTP)                    │
│  - MCP Server (官方 SDK)                                 │
│  - StreamableHTTPServerTransport                         │
│  - 11 个 MongoDB 工具                                      │
└───────────────────┬─────────────────────────────────────┘
                    │ MongoDB Protocol
┌───────────────────▼─────────────────────────────────────┐
│  MongoDB Database                                        │
│  mongodb://user:pass@host:27017/db                       │
└─────────────────────────────────────────────────────────┘

🔒 安全建议

1. 开启只读模式

MDB_MCP_READ_ONLY=true

防止 AI 意外修改或删除数据。

2. 使用专用数据库用户

为 MCP Server 创建专用的 MongoDB 用户,只授予必要的权限。

3. 限制网络访问

如果可能,限制 MongoDB 只接受来自 MCP Server 的连接。

4. 定期备份

确保 MongoDB 数据定期备份。


📝 开发说明

添加新工具

  1. 在 server.py 中添加工具函数
  2. 在 create_mcp_server() 中注册工具
  3. 在 handle_list_tools() 中添加工具描述

测试工具

# 在 tests/test_server.py 中添加测试
async def test_list_databases():
    result = await list_databases({})
    assert len(result) > 0

License

MIT

Metadata

Release files for my-mongodb-mcp 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for my-mongodb-mcp 0.1.0
File Size Uploaded
my_mongodb_mcp-0.1.0.tar.gz 8.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for my-mongodb-mcp 0.1.0
File Interpreter ABI Platform
my_mongodb_mcp-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 15.8 kB

Release files / my_mongodb_mcp-0.1.0.tar.gz

Download URL my_mongodb_mcp-0.1.0.tar.gz
Size 8.0 kB
Tags Source
SHA-256 checksum
How to use checksums
b74aa05ac6a7346900018f021df21d14d38800493df1a696c8b0b82e4c21f6d8
BLAKE2b-256 checksum
How to use checksums
c65f4411f7335892020ce57afb164f2b4a9033c1cc87214d1ee702d810c135b5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release files / my_mongodb_mcp-0.1.0-py3-none-any.whl

Download URL my_mongodb_mcp-0.1.0-py3-none-any.whl
Size 7.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b7bf74ef36f81587381b8733c3d6d6ffc66fc0ba3ca858512fd2561824b588de
BLAKE2b-256 checksum
How to use checksums
85bafd9bfe6e778630f42d3034d79fab2d19a88c7822fd679a4e6c881f3429e4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page