带有MCP、Django和MongoDB的LibreChat WebUI-完整文档
📖 目录
______________________________________________________________________
此repo上有哪些功能
- 4层架构(UI、AI、API、DB)
- 10个用于数据操作的MCP工具
- 用于业务逻辑的Django REST API
- MongoDB用于数据存储
- 完全码头化
- 生产准备就绪
项目概述
带有MCP、Django和MongoDB的LibreChat WebUI 是一个完整的、可用于生产的聊天应用程序,它结合了:
- Librechat:开源聊天UI
- 谷歌双子座:先进的AI/LLM模型
- MCP(模型上下文协议):将AI连接到自定义工具
- Django REST API:业务逻辑层
- MongoDB:用于数据持久性的NoSQL数据库
这是一个 四层应用架构 完全Docker化,这意味着所有东西都可以通过一个命令在容器中运行: docker-compose up -d
用例
- 企业聊天应用程序:构建具有数据库访问功能的智能聊天机器人
- 数据分析聊天:通过自然语言查询MongoDB数据
- LLM工具集成:向任何LLM添加自定义工具
- 教育项目:学习Docker、Python、Django、MongoDB、FastAPI
______________________________________________________________________
建筑
四层体系
┌────────────────────────────────────────────────────┐
│ User Browser (http://localhost:3080) │
│ LibreChat Web UI │
└────────────────┬─────────────────────────────────┘
│
↓ (HTTP/REST)
┌────────────────────────────────────────────────────┐
│ Google Gemini API (Cloud) │
│ "List employees from MongoDB" │
└────────────────┬─────────────────────────────────┘
│
↓ (Uses MCP tools)
┌────────────────────────────────────────────────────┐
│ MCP Server (Port 8000) │
│ FastMCP / bi_universal.py │
│ - Provides 10 tools to Gemini │
│ - Routes requests to Django │
└────────────────┬─────────────────────────────────┘
│
↓ (HTTP/REST API)
┌────────────────────────────────────────────────────┐
│ Django REST API (Port 8001) │
│ Business Logic Layer │
│ - Handles data validation │
│ - Connects to MongoDB │
└────────────────┬─────────────────────────────────┘
│
↓ (MongoClient)
┌────────────────────────────────────────────────────┐
│ MongoDB (Port 27017) │
│ Database (companyDB) │
│ - Collections: employees, projects, sales, etc. │
└────────────────────────────────────────────────────┘集装箱通信
所有集装箱都在 相同的Docker网络 (librechat-network),因此它们使用服务名称进行通信:
librechat→ 会谈bi-universal在http://bi-universal:8000/mcpbi-universal→ 会谈django-api在http://django-api:8001/apidjango-api→ 会谈mongo在mongodb://admin:pass123@mongo:27017
______________________________________________________________________
特性
1. Web用户界面(librechat)
- 简洁、直观的聊天界面
- Google Gemini模型集成
- 对话历史
- 实时响应
2. MCP工具(10个可用)
query_collection-查询MongoDB数据insert_document-添加新文档update_document-修改现有数据delete_document-删除数据list_collections_via_django-显示所有收藏get_collection_info_via_django-获取收藏详细信息export_via_django-将数据导出为JSONsmart_command-自然语言命令django_health_check-API健康状况create_plot-生成图表和图形
3. Django REST API
- 完全RESTful端点
- MongoDB集成
- 请求验证
- 错误处理
- 健康检查
4. 数据库(MongoDB)
- NoSQL数据库
- 灵活的架构
- 完整的CRUD操作
- 复合查询
5. Docker和DevOps
- 多容器编排
- 卷持久性
- 健康检查
- 自动重启策略
- 环境配置
______________________________________________________________________
安装和设置
先决条件
- 已安装Docker和Docker Compose
- Google Gemini API密钥(免费https://console.google.com/gen-ai)
- ~2GB可用磁盘空间
步骤1:克隆存储库
git clone https://github.com/ys619/librechat-webui-mcp.git
cd librechat-webui-mcp步骤2:配置环境
创建或更新 .env 文件:
# Google Gemini API Key (REQUIRED)
GOOGLE_KEY=your-api-key-here
# MongoDB Configuration
MONGO_URI=mongodb://admin:pass123@mongo:27017
MONGO_DB=companyDB
MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=pass123
# MCP Configuration
DATABASE_TYPE=mongodb
ENABLE_DJANGO_API=true
DJANGO_API_URL=http://django-api:8001/api
# Django Configuration
DJANGO_SECRET_KEY=your-secret-key-here
DEBUG=True
# LibreChat Configuration
NODE_ENV=production
ALLOW_REGISTRATION=true
ALLOW_GUEST_ACCESS=false
DEFAULT_MODEL=gemini-2.0-flash步骤3:启动所有服务
# Build and start
docker-compose up -d --build
# Wait 30 seconds for services to initialize
sleep 30
# Verify all services running
docker-compose ps预期产量:
NAME STATUS PORTS
mongo Up (healthy) 27017/tcp
django-api Up 8001/tcp
bi-universal Up 8000/tcp
librechat Up (healthy) 3080/tcp步骤4:访问应用程序
- 聊天界面: http://localhost:3080
- Django API: http://localhost:8001/api/collections/
- MCP服务器: http://localhost:8000/mcp
- MongoDB:本地主机:27017(内部)
步骤5:第一次查询
- 首选http://localhost:3080
- 登录(默认凭据或创建帐户)
- 问: “列出所有收藏”
- Gemini将使用MCP工具查询MongoDB
- 获取响应:集合名称和详细信息
______________________________________________________________________
工作原理:一步一步
示例查询:“列出财务部门的员工”
步骤1:用户输入
User types in LibreChat: "List employees from the Finance department"第二步:LibreChat→ API双子星
LibreChat使用可用的工具将查询发送到Google Gemini API。
第三步:双子座决定
Gemini分析查询并决定:
- 这需要数据库中的数据
- 我应该用
query_collectionMCP工具 - 收藏:
employees - 筛选器:
{department: "Finance"}
第四步:双子座→ MCP服务器
Gemini将MCP工具命名为 http://bi-universal:8000/mcp:
{
"tool": "query_collection",
"args": {
"collection": "employees",
"filter": "{\"department\": \"Finance\"}",
"limit": 100
}
}步骤5:MCP→ Django API
MCP服务器接收请求并转发给Django API:
POST http://django-api:8001/api/collections/query/
{
"collection": "employees",
"filter": {"department": "Finance"},
"limit": 100
}第六步:Django→ MongoDB
Django REST API连接到MongoDB:
from pymongo import MongoClient
client = MongoClient('mongodb://admin:pass123@mongo:27017')
db = client['companyDB']
collection = db['employees']
results = list(collection.find({"department": "Finance"}))步骤7:MongoDB返回数据
[
{
"_id": "ObjectId(...)",
"name": "Fahad",
"department": "Finance",
"salary": 72000,
"city": "Thane"
},
{
"_id": "ObjectId(...)",
"name": "Priya",
"department": "Finance",
"salary": 68000,
"city": "Mumbai"
}
]步骤8:数据返回堆栈
- MongoDB→ Django(格式为JSON)
- 姜戈→ MCP(HTTP响应)
- MCP → Gemini(工具结果)
- 双子座→ LibreChat(自然语言响应)
步骤9:用户看到答案
LibreChat displays:
"Here are the employees in the Finance department:
- Fahad from Thane, salary: 72000
- Priya from Mumbai, salary: 68000"______________________________________________________________________
文件结构
librechat-webui-mcp/
│
├── docker-compose.yml # Main orchestration file
├── .env # Environment variables
├── .gitignore # Git ignore rules
│
├── mcp/ # MCP Server
│ ├── bi_universal.py # Main MCP server with 10 tools
│ ├── requirements.txt # Python dependencies
│ └── Dockerfile # Container config
│
├── django_project/ # Django REST API
│ ├── manage.py # Django management
│ ├── requirements.txt # Python dependencies
│ ├── Dockerfile # Container config
│ ├── django_api/ # Main Django app
│ │ ├── settings.py # Django settings
│ │ ├── urls.py # URL routing
│ │ └── wsgi.py # WSGI config
│ └── mongodb_api/ # API app
│ ├── views.py # REST API views
│ ├── urls.py # API routes
│ └── models.py # Data models
│
├── librechat.yaml # LibreChat configuration
├── docs/ # Documentation
│ ├── README.md # Project overview
│ └── README-DJANGO.md # Django documentation
│
└── workspace/ # MCP outputs
└── bi_outputs/ # Generated files (charts, logs)______________________________________________________________________
API终点
Django REST API(http://localhost:8001/api/)
| 方法 | 终点 | 目的 |
|---|---|---|
GET | /collections/ | 列出所有收藏 |
POST | /collections/query/ | 使用筛选器查询文档 |
POST | /collections/insert/ | 插入新文档 |
POST | /collections/update/ | 更新现有文档 |
POST | /collections/delete/ | 删除文档 |
POST | /collections/export/ | 将集合导出为JSON |
GET | /health/ | 健康检查 |
API调用示例
# Query employees from Finance department
curl -X POST http://localhost:8001/api/collections/query/ \
-H "Content-Type: application/json" \
-d '{
"collection": "employees",
"filter": {"department": "Finance"},
"limit": 100
}'
# Response:
{
"collection": "employees",
"documents_found": 2,
"documents": [
{"_id": "...", "name": "Fahad", "department": "Finance", ...},
{"_id": "...", "name": "Priya", "department": "Finance", ...}
],
"status": "success"
}______________________________________________________________________
🧩 MCP工具
1. 查询集合
使用过滤器、排序和限制查询MongoDB。
Input: collection name, filter dict, limit
Output: Array of documents2. insert_document
将新文档添加到集合中。
Input: collection name, document data
Output: Inserted document ID3. update_document
修改现有文档。
Input: collection name, filter, update data
Output: Number of documents updated4. 删除文档
从收藏中删除文档。
Input: collection name, filter
Output: Number of documents deleted5. list_collections_via_django
获取所有集合名称和计数。
Output: List of collections with document counts6. get_collection_info_via_django
获取收藏的详细信息。
Input: collection name
Output: Field names, data types, total documents7. export_via_django
将整个集合导出为JSON。
Input: collection name
Output: JSON file path8. 智能命令
自然语言命令执行。
Input: Natural language instruction
Output: Execution result9. django_健康检查
检查API运行状况。
Output: API status, uptime, response time10. create_plot
根据数据生成图表和图形。
Input: Data, chart type (bar, line, pie, etc.)
Output: Chart image file path______________________________________________________________________
Docker命令
常用命令
# Start all services
docker-compose up -d
# Stop all services
docker-compose down
# View logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f django-api
# Restart specific service
docker-compose restart django-api
# Remove everything (including volumes!)
docker-compose down -v
# Rebuild images
docker-compose build
# Scale a service
docker-compose up -d --scale bi-universal=2
# Check container status
docker-compose ps
# Execute command in container
docker-compose exec django-api python manage.py migrate______________________________________________________________________
故障排除
问题:服务无法启动
# Check Docker daemon is running
docker --version
# Check logs
docker-compose logs
# Common fix: restart Docker
sudo systemctl restart docker问题:“端口3080已在使用中”
# Stop other services using the port
lsof -i :3080
kill -9
# Or change port in docker-compose.yml
# Change: ports: - "3080:3080"
# To: ports: - "3081:3080"问题:MongoDB连接被拒绝
# Check MongoDB container is running
docker-compose ps mongo
# Verify credentials in .env
# Default: admin / pass123
# Check network
docker network ls问题:Django API返回404
# Check URL routing in django_api/urls.py
# Must have: path("api/", include("mongodb_api.urls"))
# Restart Django
docker-compose restart django-api问题:Gemini中没有MCP工具
# Check MCP is running
docker-compose logs bi-universal
# Verify connection
curl http://localhost:8000/mcp
# Check librechat config (librechat.yaml)
# Must have: bi-universal endpoint configured______________________________________________________________________
文件说明
docker-compose.yml
定义所有4个服务的编排文件:
- 芒果:数据库容器
- django api:REST API容器
- 双通用:MCP服务器容器
- Librechat:Web UI容器
指定:
- 每个服务的映像/Dockerfile
- 暴露的端口
- 环境变量
- 卷装载
- 健康检查
- 依赖项
- 网络配置
mcp/bi_universal.py
主MCP服务器文件:
- 定义10个MCP工具
- 将请求路由到Django API
- 处理工具执行
- 将结果返回给Gemini
主要功能:
query_via_django()-查询MongoDBinsert_via_django()-插入数据health_check()-API状态
django_project/mongodb_api/views.py
REST API视图处理:
list_collections()-列出所有收藏query_collection()-使用筛选器进行查询insert_document()-创建新记录update_document()-修改记录delete_document()-删除记录
django_project/mongodb_api/urls.py
API路由-将URL映射到视图:
GET /collections/→ list_collections()POST /collections/query/→ 查询集合()- 等等
librechat.yaml
LibreChat配置:
- MCP服务器端点
- Gemini API设置
- UI定制
- 模型选择
______________________________________________________________________
贡献
想扩展这个项目吗?
添加新的MCP工具
- 编辑
mcp/bi_universal.py - 添加新工具功能:
@mcp_server.tool()
def new_tool(arg1: str, arg2: int) -> dict:
"""Description of tool"""
# Implementation
return {"result": "value"}- 重建并重新启动:
docker-compose build bi-universal
docker-compose up -d bi-universal添加新的API端点
- 编辑
django_project/mongodb_api/views.py - 创建新视图:
class NewApiView(APIView):
def post(self, request):
# Implementation
return Response({"status": "success"})- 在中添加URL路由
urls.py:
path("new-endpoint/", views.new_api_view, name="new_endpoint")- 重新启动Django:
docker-compose restart django-api______________________________________________________________________
许可证
MIT许可证-可自由用于个人和商业项目。
______________________________________________________________________
作者
亚什·辛格 (@ys619)
- github:https://github.com/ys619
- 项目:https://github.com/ys619/librechat-webui-mcp
______________________________________________________________________
致谢
______________________________________________________________________
支持
对于问题、疑问或建议:
- 检查 故障排除 章节
- 打开GitHub问题:https://github.com/ys619/librechat-webui-mcp/issues
- 请阅读中的各个README文件
/docs/ - 如有任何疑问,请联系yashjagvirsingh17@gmail.com
______________________________________________________________________
编码愉快!
