mcp-news-sentiment-analyzer
by su3g4829
README.md
# MCP News Sentiment Analyzer
以 Python 與 Model Context Protocol(MCP)SDK 2.x 建立的新聞搜尋與情緒分析練習專案。使用者輸入自然語言問題後,MCP Client 會依固定工具鏈呼叫新聞搜尋與情緒分析工具,並輸出 JSON、Markdown 報告與最終摘要。
## 專案特色
- 使用 MCP SDK 2.x 的 `MCPServer` 與高階 `Client`
- 透過 stdio 在本機 Client 與 Server 之間通訊
- 使用 Serper API 搜尋 Google News
- 透過 Groq 的 OpenAI-compatible API 進行情緒分析
- 強制執行「搜尋 → 驗證 → 分析 → 摘要」流程,避免模型跳過工具
- 搜尋失敗時立即中止,不會把錯誤訊息當成新聞分析
- 支援繁體與簡體中文查詢關鍵字
- 自動輸出新聞 JSON、情緒分析 Markdown 與對話記錄
- API Key 透過 `.env` 管理,不會提交到版本控制
## 執行流程
```text
使用者問題
↓
MCP Client(client.py)
↓ stdio
MCP Server(server.py)
↓
search_google_news → Serper API
↓ 搜尋成功才繼續
analyze_sentiment → Groq API
↓
Markdown 報告與最終繁體中文摘要
```
## 使用技術
- Python 3.10+(開發與測試環境為 Python 3.13)
- Model Context Protocol Python SDK 2.x
- Groq API
- Serper API
- OpenAI Python SDK
- HTTPX
- python-dotenv
## 專案結構
```text
mcp-project/
├── client.py # MCP Client、固定工具鏈與命令列介面
├── server.py # MCP Server 與新聞/情緒分析工具
├── pyproject.toml # Python 專案及依賴設定
├── .env.example # 不含秘密資訊的環境變數範例
├── .gitignore # 忽略秘密、虛擬環境及執行輸出
├── examples/ # 經人工檢查、可公開的成功輸出範例
│ ├── white-dolphin-news.json
│ ├── white-dolphin-sentiment-report.md
│ └── white-dolphin-final-response.txt
├── google_news/ # 執行時產生,不提交 Git
├── sentiment_reports/ # 執行時產生,不提交 Git
└── llm_outputs/ # 執行時產生,不提交 Git
```
## 安裝
### 1. 複製專案
```powershell
git clone https://github.com/YOUR_USERNAME/mcp-news-sentiment-analyzer.git
cd mcp-news-sentiment-analyzer
```
### 2. 建立並啟用虛擬環境
```powershell
python -m venv .venv
.\.venv\Scripts\Activate.ps1
```
若 PowerShell 阻擋腳本,可只針對目前 Terminal 暫時允許:
```powershell
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
.\.venv\Scripts\Activate.ps1
```
### 3. 安裝依賴
```powershell
python -m pip install --upgrade pip
python -m pip install .
```
### 4. 設定環境變數
複製範例檔:
```powershell
Copy-Item .env.example .env
```
編輯 `.env`:
```env
DASHSCOPE_API_KEY=your_groq_api_key
BASE_URL=https://api.groq.com/openai/v1
MODEL=openai/gpt-oss-20b
SERPER_API_KEY=your_serper_api_key
```
`DASHSCOPE_API_KEY` 是原教學沿用的變數名稱;本專案目前在其中放置 Groq API Key。
## 執行
在專案根目錄執行:
```powershell
python client.py
```
範例問題:
```text
查詢白海豚的新聞,並分析情緒
```
輸入 `quit` 可結束程式。
## 輸出
程式執行後會建立:
- `google_news/*.json`:Serper 新聞搜尋結果
- `sentiment_reports/*.md`:Groq 產生的情緒分析報告
- `llm_outputs/*.txt`:最終模型摘要與對話記錄
自動產生的檔案不會提交 Git;經人工確認且適合公開的成果放在 [`examples`](examples/):
- [新聞搜尋範例](examples/white-dolphin-news.json)
- [情緒分析報告範例](examples/white-dolphin-sentiment-report.md)
- [最終模型回答範例](examples/white-dolphin-final-response.txt)
## 安全與限制
- 請勿提交 `.env` 或在程式碼中寫死 API Key。
- Serper 與 Groq 的免費額度及速率限制可能變動。
- 情緒分析由生成式模型完成,結果可能因模型版本及輸入內容而異。
- 本專案目前將寄信工具保留在程式碼中,但未註冊為 MCP 工具。
- 本專案用於學習與作品展示,不建議未經額外驗證直接用於生產環境。
## 履歷摘要範例
> 使用 Python 與 MCP SDK 2.x 建立新聞搜尋及情緒分析工具鏈,整合 Serper 與 Groq API,實作確定性工具串接、錯誤中止、秘密資訊管理及 JSON/Markdown 報告輸出。
This server cannot be deployed
Maintenance
ActivitySlowing
ResponsivenessNo issues