MCP新闻连接器
🚀 表情符号“🚀”通常表示火箭、太空旅行或快速前进,可以翻译为“🚀(火箭/太空旅行/快速前进)”。在具体语境中,可以根据需要选择最合适的翻译。 用于从MongoDB获取新闻文章的MCP连接器 - 受OpenAI在开发者日展示的披萨应用演示启发。
这个项目展示了如何构建一个模型上下文协议(MCP)服务器,该服务器能够与ChatGPT的工具调用功能集成,从而支持通过自然语言查询从MongoDB数据库中获取新闻文章。
📋 特性
- ✅ 符合MCP标准的服务器 使用FastMCP/MCP SDK构建
- ✅ MongoDB 集成 用于实时新闻检索
- ✅ 工具调用架构 与ChatGPT/OpenAI SDK兼容
- ✅ 灵活过滤按主题、限制和排序顺序
- ✅ 已准备好投入生产 带有错误处理和日志记录功能
- ✅ 记录详尽的 带有内联注释和示例
🏗️ 建筑学
┌─────────────┐
│ ChatGPT │
│ (OpenAI) │
└──────┬──────┘
│ Tool Call: get_news(topic="AI", limit=5)
↓
┌─────────────────────────────┐
│ MCP News Connector │
│ (server.py) │
│ │
│ • Validates parameters │
│ • Queries MongoDB │
│ • Returns JSON results │
└──────────┬──────────────────┘
│
↓
┌──────────────┐
│ MongoDB │
│ news_db │
│ ↳ news_ │
│ articles │
└──────────────┘🚀 快速入门
先决条件
- Python 3.8及以上版本
- MongoDB 实例(本地或 Atlas)
- OpenAI API密钥(用于客户端示例)
安装
- 克隆仓库
git clone https://github.com/vikkysarswat/mcp-news-connector.git
cd mcp-news-connector- 安装依赖项
pip install -r requirements.txt- 配置环境
cp .env.example .env
# Edit .env with your MongoDB URI and OpenAI API key- 设置MongoDB (如果使用本地实例)
# Start MongoDB
mongod --dbpath /path/to/data
# Import sample data (see "Sample Data" section)运行服务器
python server.py你应该看到:
============================================================
MCP News Connector Server
============================================================
Database: news_db
Collection: news_articles
Starting server...
✓ Connected to MongoDB at mongodb://localhost:27017/使用示例客户端进行测试
python example_query.py这展示了ChatGPT如何与MCP服务器进行交互:
======================================================================
USER: Get me the latest AI news
======================================================================
🔧 ChatGPT is calling tools...
Tool: get_news
Arguments: {
"topic": "AI",
"limit": 5,
"sort": "latest"
}
Tool Response Preview:
- Success: True
- Count: 5
- Query: {'topic': 'AI', 'limit': 5, 'sort': 'latest'}
💬 ChatGPT is formulating response...
======================================================================
ASSISTANT:
======================================================================
Here are the latest AI news articles:
1. **OpenAI Releases GPT-5 with Enhanced Reasoning** (TechCrunch)
OpenAI announces GPT-5 with breakthrough reasoning capabilities...
Published: October 15, 2025
[... more articles ...]
======================================================================📊 示例 MongoDB 数据
文档结构
其中的每一份文件 news_articles 收藏品应具备:
{
"_id": ObjectId("..."),
"title": "OpenAI Releases GPT-5 with Enhanced Reasoning",
"source": "TechCrunch",
"summary": "OpenAI announces GPT-5 with breakthrough reasoning capabilities and multimodal understanding.",
"topic": "AI",
"published_at": ISODate("2025-10-15T10:30:00Z"),
"url": "https://techcrunch.com/...",
"author": "Jane Smith"
}导入样本数据
# Connect to MongoDB
mongo
# Switch to database
use news_db
# Insert sample articles
db.news_articles.insertMany([
{
"title": "OpenAI Releases GPT-5 with Enhanced Reasoning",
"source": "TechCrunch",
"summary": "OpenAI announces GPT-5 with breakthrough reasoning capabilities.",
"topic": "AI",
"published_at": new Date("2025-10-15T10:30:00Z")
},
{
"title": "Stock Market Reaches All-Time High",
"source": "Bloomberg",
"summary": "Major indices surge as tech sector leads market rally.",
"topic": "finance",
"published_at": new Date("2025-10-14T15:45:00Z")
},
{
"title": "New Quantum Computing Breakthrough Announced",
"source": "Nature",
"summary": "Researchers achieve quantum error correction milestone.",
"topic": "technology",
"published_at": new Date("2025-10-13T08:20:00Z")
}
])
# Create index for better query performance
db.news_articles.createIndex({ "topic": 1, "published_at": -1 })🛠️ API 参考
工具: get_news
从MongoDB中灵活过滤并获取新闻文章。
参数:
| 参数 | 类型 | 必填 | 默认值 | 描述 |
|---|---|---|---|---|
topic | 字符串 | 否 | null | 按主题/类别过滤(不区分大小写) |
limit | 整数 | 否 | 5 | 最大返回文章数(1-50) |
sort | 字符串 | 否 | latest | 排序顺序: "latest" 或者 "oldest" |
返回值:
包含以下内容的JSON对象:
{
"success": true,
"count": 5,
"query": {
"topic": "AI",
"limit": 5,
"sort": "latest"
},
"articles": [
{
"title": "Article Title",
"source": "News Source",
"summary": "Brief summary...",
"published_at": "2025-10-15T10:30:00Z"
}
]
}示例查询:
# User: "Get me the latest AI news"
get_news(topic="AI", limit=5, sort="latest")
# User: "Show 3 finance headlines"
get_news(topic="finance", limit=3, sort="latest")
# User: "I want to see the oldest technology articles"
get_news(topic="technology", limit=10, sort="oldest")🔧 配置
环境变量
创建一个 .env 与……一起归档/保存
# MongoDB connection
MONGO_URI=mongodb://localhost:27017/
DATABASE_NAME=news_db
COLLECTION_NAME=news_articles
# OpenAI API (for client examples)
OPENAI_API_KEY=sk-your-key-hereMCP 表现(或“MCP 说明”、“MCP 声明”,具体翻译取决于上下文和MCP的具体含义)
这个 manifest.json 该文件定义了MCP服务器的功能:
{
"name": "news-connector",
"description": "MCP connector for fetching news articles from MongoDB",
"version": "1.0.0",
"type": "mcp-server",
"tools": [
{
"name": "get_news",
"description": "Fetch news articles from MongoDB...",
"inputSchema": { ... }
}
]
}🧪 开发
项目结构
mcp-news-connector/
├── manifest.json # MCP server definition
├── server.py # MCP server implementation
├── example_query.py # ChatGPT SDK client demo
├── requirements.txt # Python dependencies
├── .env.example # Environment template
└── README.md # Documentation添加新功能
- 添加新工具到
server.py
@mcp.tool()
def search_news_by_author(author: str) -> str:
"""Search articles by author name"""
# Implementation
pass- 更新
manifest.json
{
"tools": [
...,
{
"name": "search_news_by_author",
"description": "...",
"inputSchema": { ... }
}
]
}- 使用示例客户端进行测试
🔒 安全最佳实践
- ✅ 永远不要提交(代码/更改等)
.env包含秘密的文件 - ✅ 在生产环境中使用MongoDB认证
- ✅ 验证并清理所有用户输入
- 为API调用实现速率限制
- ✅ 使用TLS/SSL进行MongoDB连接
- 定期轮换API密钥
🐛 故障排除
MongoDB 连接问题
# Check if MongoDB is running
mongosh --eval "db.adminCommand('ping')"
# Test connection string
mongosh "mongodb://localhost:27017/news_db"MCP服务器无法启动
# Verify dependencies
pip install -r requirements.txt --upgrade
# Check for port conflicts
lsof -i :8000 # or your configured port工具未被调用
- 验证
manifest.json格式正确 - 检查工具描述的清晰度(有助于ChatGPT理解何时调用)
- 确保OpenAI API密钥有效且信用额度充足
📚 资源
🤝 贡献
欢迎投稿!请:
- 为仓库创建分支(或“克隆仓库”)
- 创建一个特性分支(
git checkout -b feature/amazing-feature) - 提交更改(
git commit -m 'Add amazing feature') - 推送到分支 (
git push origin feature/amazing-feature) - 打开一个拉取请求
📄 许可证
MIT 许可证 - 详情请参见 LICENSE 文件
🙏 致谢
- 受OpenAI在开发者日上展示的披萨应用演示启发
- 构建于 FastMCP 框架
- 感谢MCP社区对协议开发的贡献
______________________________________________________________________
有问题或疑问吗? 在GitHub上提交一个问题或联系维护者。
给这个仓库点赞⭐ 如果你觉得它有用!
