使用说明
集成AI的MCP数据库
一个项目,该项目使用FastMCP(模型上下文协议)将本地量化大型语言模型(Qwen 2.5 3B)与多个数据库服务器(SQLite、MongoDB、PostgreSQL)集成在一起。
📋 目录
🎯 概述
这个项目展示了如何将本地AI模型与多个数据库系统连接起来,使您能够:
- 与AI助手聊天
- 在SQLite中管理开销
- 在MongoDB中存储联系人
- 在 PostgreSQL 中跟踪书籍
- 从您的数据中获取AI驱动的见解
✨ 特点/功能
- 本地人工智能模型使用Qwen 2.5 3B量化模型(4位)
- 多数据库支持SQLite、MongoDB 和 PostgreSQL
- FastMCP 集成工具调用的模型上下文协议
- **交互式命令行界面(CLI)**自然语言接口
- 实时分析AI按需分析您的数据
- 无云依赖所有内容都在本地运行
🏗️ 建筑学
┌─────────────────┐
│ Qwen Model │
│ (Quantized) │
└────────┬────────┘
│
│ llama-cpp-python
│
┌────────▼────────┐
│ Client Script │
│ (Python) │
└────────┬────────┘
│
│ FastMCP
│
┌────┴────┬──────────┬──────────┐
│ │ │ │
┌───▼──┐ ┌───▼──┐ ┌────▼────┐ ┌───▼────┐
│SQLite│ │MongoDB│ │PostgreSQL│ │ Others │
└──────┘ └───────┘ └─────────┘ └────────┘
📦 先决条件
系统要求
- **操作系统(OS)**Linux(推荐使用Ubuntu/Debian)、macOS,或带有WSL的Windows
- **RAM(随机存取存储器)**最低8GB(建议16GB)
- 存储~5GB 空闲空间
- python3.10或更高版本
软件依赖项
- Python 3.10及以上版本
- MongoDB(可选,用于联系人服务器)
- PostgreSQL(可选,用于书籍服务器)
- SQLite(随Python一起提供)
🚀 安装
步骤1:克隆仓库
git clone <your-repo-url>
cd mcp_databases
步骤2:设置Python环境
使用 uv (推荐):
# Install uv if not already installed
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create virtual environment
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
uv add fastmcp pymongo psycopg2-binary llama-cpp-python
使用 pip:
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install fastmcp pymongo psycopg2-binary llama-cpp-python
步骤3:下载模型
下载Qwen 2.5 3B量化模型:
# Create models directory
mkdir -p models
# Download from Hugging Face (example)
wget https://huggingface.co/.../qwen25-3b-q4_K_M.gguf -O models/qwen25-3b-q4_K_M.gguf
步骤4:设置数据库
SQLite (自动 - 无需设置)
MongoDB(蒙哥达数据库) (可选):
# Using system package manager
sudo apt install mongodb-server
sudo systemctl start mongod
# Or using Docker
docker run -d -p 27017:27017 --name mongodb mongo
PostgreSQL (可选):
# Install PostgreSQL
sudo apt install postgresql postgresql-contrib
# Start PostgreSQL
sudo systemctl start postgresql
# Create database
sudo -u postgres createdb booksdb
# Set password
sudo -u postgres psql
ALTER USER postgres PASSWORD 'your_password';
\q
📁 项目结构
mcp_databases/
├── README.md
├── .venv/ # Virtual environment
├── models/
│ └── qwen25-3b-q4_K_M.gguf # AI model
├── servers/
│ ├── sqlite_expenses_server.py # Expenses database server
│ ├── mongo_contacts_server.py # Contacts database server
│ └── postgres_books_server.py # Books database server
├── unified_client.py # Multi-server client
├── simple_client.py # Single-server client
├── expenses.db # SQLite database (auto-created)
└── requirements.txt # Python dependencies
🗄️ 数据库服务器
1. SQLite费用服务器
文件: servers/sqlite_expenses_server.py
工具:
add_expense(category, amount, note)- 添加新费用list_expenses()- 列出所有费用total_expense()- 获取总支出
用法:
# Run standalone
python servers/sqlite_expenses_server.py
2. MongoDB 联系人服务器
文件: servers/mongo_contacts_server.py
工具:
add_contact(uri, db, name, phone, email)- 添加新联系人list_contacts(uri, db)- 列出所有联系人
配置:
MONGO_URI = "mongodb://localhost:27017"
MONGO_DB = "contactsdb"
3. PostgreSQL书籍服务器
文件: servers/postgres_books_server.py
工具:
add_book(host, dbname, user, password, title, author, year)- 添加新书list_books(host, dbname, user, password)- 列出所有书籍
配置:
POSTGRES_CONFIG = {
"host": "localhost",
"dbname": "booksdb",
"user": "postgres",
"password": "your_password"
}
💻 使用方法
选项1:简单客户端(仅支持SQLite)
python simple_client.py
命令:
You: add expense Food 500 Lunch
AI: ✅ Added expense: Food - 500 PKR
You: list expenses
AI: Expenses:
[1] Food: 500 PKR - 2025-10-16 10:30:00 (Lunch)
You: total
AI: 💰 Total: 500 PKR
You: What is 2+2?
AI: 2+2 equals 4.
You: quit
👋 Goodbye!
选项2:统一客户端(所有数据库)
python unified_client.py
特点/功能:
- 连接到所有三个数据库服务器
- 运行自动化演示
- 与所有数据库的交互模式
- 基于人工智能的跨数据库洞察
📝 示例
添加费用
You: add expense Food 850 Dinner at restaurant
AI: ✅ Added expense: Food - 850 PKR
You: add expense Transport 300 Taxi fare
AI: ✅ Added expense: Transport - 300 PKR
列出并分析
You: list expenses
AI: Expenses:
[2] Transport: 300 PKR - 2025-10-16 10:31:00 (Taxi fare)
[1] Food: 850 PKR - 2025-10-16 10:30:00 (Dinner at restaurant)
You: total
AI: 💰 Total: 1150 PKR
自然语言聊天
You: Should I reduce my food expenses?
AI: Based on your current spending, food expenses account for 74% of your total.
Consider meal planning and cooking at home to reduce costs.
You: What's the weather like?
AI: I'm an AI assistant focused on helping you manage your data. I don't have
access to real-time weather information, but I can help you track expenses,
contacts, and books!
添加联系人(MongoDB)
You: add contact Ali Khan +92-300-1234567 ali@example.com
AI: 👤 Added contact: Ali Khan
You: list contacts
AI: [{'name': 'Ali Khan', 'phone': '+92-300-1234567', 'email': 'ali@example.com'}]
添加书籍(PostgreSQL)
You: add book The Alchemist by Paulo Coelho 1988
AI: 📘 Added book: The Alchemist by Paulo Coelho
You: list books
AI: [(1, 'The Alchemist', 'Paulo Coelho', 1988)]
⚙️ 配置
模型配置
编辑 MODEL_PATH 在你的客户端脚本中:
MODEL_PATH = "/path/to/your/qwen25-3b-q4_K_M.gguf"
# Adjust model parameters
llm = Llama(
model_path=MODEL_PATH,
n_ctx=4096, # Context window size
n_threads=4, # CPU threads to use
n_gpu_layers=0, # GPU layers (0 = CPU only, >0 for GPU)
verbose=False
)
数据库配置
MongoDB:
MONGO_URI = "mongodb://localhost:27017"
MONGO_DB = "contactsdb"
PostgreSQL(注:这是一个专有名词,直接翻译为“波斯特高斯奎尔”并不准确,通常保持原名不译):
POSTGRES_CONFIG = {
"host": "localhost",
"dbname": "booksdb",
"user": "postgres",
"password": "your_password"
}
SQLite:
DB_PATH = "expenses.db" # Auto-created in project directory
🐛 故障排除
模型加载问题
问题模型加载失败
Error: Failed to load model
解决方案:
- 检查模型路径是否正确
- 确保模型文件未损坏
- 确认您的内存(RAM)足够(至少8GB)
- 尝试减少
n_ctx到2048年
数据库连接问题
MongoDB 连接失败:
# Check if MongoDB is running
sudo systemctl status mongod
# Start MongoDB
sudo systemctl start mongod
# Or check Docker container
docker ps | grep mongo
PostgreSQL 连接失败:
# Check PostgreSQL status
sudo systemctl status postgresql
# Test connection
psql -U postgres -d booksdb
MCP服务器无法启动
问题服务器连接超时
解决方案:
# Test server independently
python servers/sqlite_expenses_server.py
# Check for port conflicts
lsof -i :8000
# Verify Python dependencies
pip list | grep fastmcp
内存问题
问题内存不足错误
解决方案:
- 关闭其他应用程序
- 使用更小的模型(如果可用)
- 减少
n_ctx参数 - 在Linux上添加交换空间:
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
导入错误
问题: ModuleNotFoundError
解决方案:
# Verify virtual environment is activated
which python
# Reinstall dependencies
pip install -r requirements.txt
# Or with uv
uv sync
🔧 高级配置
GPU加速
如果您拥有一块兼容的GPU:
llm = Llama(
model_path=MODEL_PATH,
n_ctx=4096,
n_threads=4,
n_gpu_layers=35, # Offload layers to GPU
verbose=False
)
自定义服务器路径
# In unified_client.py
await client.connect_server("expenses", "custom/path/sqlite_expenses_server.py")
await client.connect_server("contacts", "custom/path/mongo_contacts_server.py")
await client.connect_server("books", "custom/path/postgres_books_server.py")
修改人工智能行为
def chat(self, prompt, max_tokens=512):
response = self.llm(
prompt,
max_tokens=max_tokens,
temperature=0.7, # Higher = more creative (0.0-2.0)
top_p=0.9, # Nucleus sampling (0.0-1.0)
repeat_penalty=1.1, # Reduce repetition
stop=["User:", "Human:"]
)
return response['choices'][0]['text'].strip()
📚 资源
🤝 贡献
欢迎投稿!请:
- 为仓库创建分支(或“克隆仓库”)
- 创建一个特性分支(
git checkout -b feature/amazing-feature) - 提交您的更改(
git commit -m 'Add amazing feature') - 推送至分支(
git push origin feature/amazing-feature) - 提交一个拉取请求
📄 许可证
这个项目是开源的,并遵循MIT许可协议。
🙏 致谢
- Anthropic(公司名,可译为“安萨里克”或根据具体语境保留原名) 为克劳德提供帮助
- Qwen团队 对于该模型
- FastMCP 创作者
- llama.cpp 项目
📧 联系方式
如有问题或需要支持,请在GitHub上提交一个议题。
使用本地人工智能和开源工具,满怀热爱地打造