MCP电影数据库研讨会
全面 模型上下文协议(MCP) 通过完整的客户端-服务器架构展示AI驱动的电影数据库交互的演示项目。
🎯 项目概述
本项目演示了如何使用以下工具构建生产就绪的MCP应用程序:
- MCP服务器:基于FastMCP的服务器公开电影数据库CRUD操作
- MCP客户端:用于自然语言电影查询的Streamlit聊天机器人
- 数据库层:SQLite提供全面的电影数据和分析
- 人工智能集成:GPT-4o驱动的对话界面
🏗️ 建筑
┌─────────────────────────────────────────────────────────────┐
│ User Interface │
│ (Streamlit Web App) │
└─────────────────┬───────────────────────────────────────────┘
│ Natural Language Queries
┌─────────────────▼───────────────────────────────────────────┐
│ MCP Client │
│ (movies_chatbot.py) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ MCPAgent (GPT-4o) + MCPClient (mcp-use) │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────┬───────────────────────────────────────────┘
│ MCP Protocol (HTTP)
┌─────────────────▼───────────────────────────────────────────┐
│ MCP Server │
│ (movies_mcp_server.py) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ FastMCP Tools: CRUD Operations & Analytics │ │
│ │ • create_movie • search_movies • get_statistics │ │
│ │ • update_movie • delete_movie • advanced_search│ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────┬───────────────────────────────────────────┘
│ SQL Queries
┌─────────────────▼───────────────────────────────────────────┐
│ SQLite Database │
│ (movies.db) │
│ Indexed movie data with metadata │
└─────────────────────────────────────────────────────────────┘🚀 快速入门指南
先决条件
- Python 3.8+
- OpenAI API密钥
- 终端/命令行访问
1.安装
# Clone or navigate to the project directory
cd dds_workshop
# Install all required dependencies
pip install -r requirements.txt2.环境设置
创建一个 .env 项目根目录中的文件:
# OpenAI API Configuration (Required)
OPENAI_API_KEY=your_openai_api_key_here
# Database Configuration (Optional - defaults provided)
DB_FILE_PATH=./data/movies.db
CSV_FILE_PATH=./data/mymoviedb.csv
MCP_CONFIG_FILE_PATH="./config/mcp_config.json3.数据库设置(仅限首次)
# Ingest CSV data into SQLite database
python utilities/ingest_movies_to_sqlite.py预期产量:
Starting ingestion from: ./data/mymoviedb.csv
Reading CSV file...
Detected encoding: utf-8
Dataset info:
Total rows: [number]
Successfully inserted [number] movies into the database!
✅ Movie database ingestion completed successfully!4.启动MCP服务器
1号航站楼:
# Navigate to server directory
cd server/
# Start the MCP server
python movies_mcp_server.py预期产量:
Starting Movies Database MCP Server...
Database: ./data/movies.db
Available tools:
- create_movie
- get_movie_by_id
- search_movies_by_title
- get_movies_by_genre
- ... and more
Server is running...服务器将在以下位置可用: http://0.0.0.0:4567
5.启动MCP客户端
2号航站楼:
# Navigate to client directory
cd client/
# Start the Streamlit chatbot
streamlit run movies_chatbot.py预期产量:
You can now view your Streamlit app in your browser.
Local URL: http://localhost:8501
Network URL: http://[your-ip]:85016.使用应用程序
- 打开浏览器 向
http://localhost:8501 - 等待初始化 -“正在初始化MCP代理…”
- 开始聊天 示例查询:
- “跟我说说《黑客帝国》” - “查找收视率高的动作片” - 2023年上映了哪些电影 - “给我看2000年代的科幻电影”
📁 项目结构
dds_workshop/
├── README.md # This file - main project overview
├── requirements.txt # Python dependencies
├── .env # Environment variables (create this)
│
├── client/ # MCP Client (Streamlit Chatbot)
│ ├── movies_chatbot.py # Main chatbot application
│ └── README.md # Detailed client documentation
│
├── server/ # MCP Server (FastMCP)
│ ├── movies_mcp_server.py # MCP server with movie tools
│ └── README.md # Detailed server documentation
│
├── config/ # Configuration files
│ └── mcp_config.json # MCP server connection config
│
├── data/ # Database and source data
│ ├── movies.db # SQLite database (generated)
│ └── mymoviedb.csv # Source CSV data
│
├── utilities/ # Database utilities
│ ├── constants.py # Configuration constants
│ ├── ingest_movies_to_sqlite.py # CSV to SQLite ingestion
│ └── movies_crud.py # Direct database operations
│
└── supporting_files/ # Workshop materials
├── agenda.txt
├── mcp_architecture.png
└── react.md💬 交互示例
自然语言电影查询
🎬 User: "Tell me about Lord of the Rings movies"
🤖 Assistant: Here are the Lord of the Rings movies:
1. **The Lord of the Rings: The Fellowship of the Ring** (2001)
- Rating: 8.8/10 (1.8M votes)
- Genre: Adventure, Fantasy, Action
- Overview: A meek Hobbit from the Shire and eight companions...
2. **The Lord of the Rings: The Two Towers** (2002)
- Rating: 8.7/10 (1.6M votes)
- Genre: Adventure, Fantasy, Action
- Overview: Frodo and Sam are trekking to Mordor...
3. **The Lord of the Rings: The Return of the King** (2003)
- Rating: 9.0/10 (1.8M votes)
- Genre: Adventure, Fantasy, Action
- Overview: Aragorn is revealed as the heir to the ancient kings...高级搜索功能
🎬 User: "Find sci-fi movies from 2020-2023 with ratings above 7.5"
🤖 Assistant: Here are highly-rated sci-fi movies from 2020-2023:
1. **Dune** (2021) - Rating: 8.0/10
2. **Spider-Man: No Way Home** (2021) - Rating: 8.4/10
3. **The Batman** (2022) - Rating: 7.8/10
...🛠️ 可用特征
MCP服务器工具(共11个)
- 创建:添加带有元数据的新电影
- 搜索:标题、流派、年份、语言过滤
- 更新:修改现有电影数据
- 删除:从数据库中删除电影
- 分析:综合数据库统计
客户能力
- 自然语言处理:用简单的英语提问
- 实时响应:流式AI响应
- 聊天历史记录:持续的对话上下文
- 错误处理:优雅的错误恢复
- 查询示例:内置查询建议
🔧 故障排除
常见问题
1.找不到数据库
# Solution: Run the ingestion script first
python utilities/ingest_movies_to_sqlite.py2.MCP服务器连接失败
# Check if server is running
curl http://0.0.0.0:4567/mcp
# Verify config in config/mcp_config.json3.OpenAI API错误
# Verify API key is set
echo $OPENAI_API_KEY
# Check .env file exists and is loaded4.港口冲突
# Server: Change port in movies_mcp_server.py
mcp.run(transport="http", host="0.0.0.0", port=4568)
# Client: Use different Streamlit port
streamlit run movies_chatbot.py --server.port 8502调试模式
# Enable verbose logging
export PYTHONPATH=.
python -c "import logging; logging.basicConfig(level=logging.DEBUG)"📊 数据库信息
- 电影总数:~50000+条记录
- 日期范围:20世纪至2024年
- 语言:100多种语言
- 类型:动作、喜剧、戏剧、科幻等。
- 元数据:评级、受欢迎程度、投票数、概述
🔍 高级用法
直接数据库访问
# Use CRUD utilities directly
python utilities/movies_crud.py自定义查询
# Test MCP server tools directly
python -c "
import asyncio
from mcp_use import MCPClient
async def test():
client = MCPClient.from_config_file('config/mcp_config.json')
result = await client.call_tool('search_movies_by_title', {'title_search': 'Matrix'})
print(result)
asyncio.run(test())
"配置定制
- 服务器配置:修改
config/mcp_config.json - 代理行为:调整
max_steps在客户端代码中 - UI造型:自定义Streamlit界面
🎓 学习目标
本次研讨会展示了:
- MCP协议实现:客户端-服务器通信
- AI代理集成:LLM+工具选择
- 数据库操作:带智能查询的CRUD
- Web界面开发:实时聊天应用程序
- 错误处理:稳健的生产模式
- 配置管理:基于环境的设置
📚 额外资源
- 详细文件:
- 服务器README -完整的服务器API参考 - 客户端自述 -UI和集成详细信息
🤝 贡献
- 扩展工具:添加新的MCP服务器工具以实现其他功能
- 增强用户界面:使用新功能改进Streamlit界面
- 添加数据源:整合其他电影数据库
- 优化性能:实现缓存和查询优化
- 文档:用新功能更新README
