feat: mcp-v1.0.3 新增日期解析工具,增加 mcp 使用文档英文版,增强 github 推送的稳定性

This commit is contained in:
sansan 2025-11-26 19:43:01 +08:00
parent 39738cc821
commit c02e5cb55f
9 changed files with 1062 additions and 85 deletions

View File

@ -1,22 +1,28 @@
name: Hot News Crawler name: Hot News Crawler
on: on:
schedule: schedule:
# 我们使用的是 github 官方提供的资源来进行的推送,而每个账号的资源是限额的,为了不被官方判定为滥用而面临封号的风险,不建议比半小时更低 - cron: "0 * * * *"
- cron: "0 * * * *" # 每小时整点运行一次(实际有偏差) 或者 "*/30 * * * *" (每半小时执行一次) 或者 "*/30 0-14 * * *"(每天早上 8 点到晚上 10 点期间,每半小时运行一次)
workflow_dispatch: workflow_dispatch:
# 添加权限设置 concurrency:
group: crawler-main-branch
cancel-in-progress: true
permissions: permissions:
contents: write contents: write
jobs: jobs:
crawl: crawl:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 30
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v3 uses: actions/checkout@v3
with:
ref: main
fetch-depth: 0
clean: true
- name: Set up Python - name: Set up Python
uses: actions/setup-python@v4 uses: actions/setup-python@v4
@ -31,19 +37,14 @@ jobs:
- name: Verify required files - name: Verify required files
run: | run: |
echo "🔍 检查必需的配置文件..." echo "🔍 检查必需的配置文件..."
if [ ! -f config/config.yaml ]; then if [ ! -f config/config.yaml ]; then
echo "❌ 错误: config/config.yaml 文件不存在" echo "❌ 错误: config/config.yaml 文件不存在"
echo "请参考项目文档创建配置文件"
exit 1 exit 1
fi fi
if [ ! -f config/frequency_words.txt ]; then if [ ! -f config/frequency_words.txt ]; then
echo "❌ 错误: config/frequency_words.txt 文件不存在" echo "❌ 错误: config/frequency_words.txt 文件不存在"
echo "请参考项目文档创建频率词配置文件"
exit 1 exit 1
fi fi
echo "✅ 配置文件检查通过" echo "✅ 配置文件检查通过"
- name: Run crawler - name: Run crawler
@ -71,5 +72,39 @@ jobs:
run: | run: |
git config --global user.name 'GitHub Actions' git config --global user.name 'GitHub Actions'
git config --global user.email 'actions@github.com' git config --global user.email 'actions@github.com'
echo "🔄 Syncing with remote..."
git fetch origin main
# 保存当前更改
git stash --include-untracked || echo "Nothing to stash"
# 同步到远程最新
git reset --hard origin/main
# 恢复本次更改
git stash pop || echo "Nothing to pop"
git add -A git add -A
git diff --quiet && git diff --staged --quiet || (git commit -m "Auto update by GitHub Actions at $(TZ=Asia/Shanghai date)" && git push)
if git diff --quiet && git diff --staged --quiet; then
echo "📭 No changes to commit"
exit 0
fi
echo "📝 Committing changes..."
TIMESTAMP=$(TZ=Asia/Shanghai date "+%Y-%m-%d %H:%M:%S")
git commit -m "Auto update by GitHub Actions at $TIMESTAMP"
echo "⬆️ Pushing changes with retry..."
for i in {1..5}; do
git pull --rebase origin main && git push origin main && {
echo "✅ Successfully pushed on attempt $i"
exit 0
}
echo "⚠️ Attempt $i/$i failed, waiting $((i*3)) seconds..."
sleep $((i * 3))
done
echo "❌ Failed to push after 5 attempts"
exit 1

View File

@ -15,7 +15,7 @@
[![GitHub Forks](https://img.shields.io/github/forks/sansan0/TrendRadar?style=flat-square&logo=github&color=blue)](https://github.com/sansan0/TrendRadar/network/members) [![GitHub Forks](https://img.shields.io/github/forks/sansan0/TrendRadar?style=flat-square&logo=github&color=blue)](https://github.com/sansan0/TrendRadar/network/members)
[![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg?style=flat-square)](LICENSE) [![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg?style=flat-square)](LICENSE)
[![Version](https://img.shields.io/badge/version-v3.4.0-blue.svg)](https://github.com/sansan0/TrendRadar) [![Version](https://img.shields.io/badge/version-v3.4.0-blue.svg)](https://github.com/sansan0/TrendRadar)
[![MCP](https://img.shields.io/badge/MCP-v1.0.2-green.svg)](https://github.com/sansan0/TrendRadar) [![MCP](https://img.shields.io/badge/MCP-v1.0.3-green.svg)](https://github.com/sansan0/TrendRadar)
[![WeWork](https://img.shields.io/badge/WeWork-Notification-00D4AA?style=flat-square)](https://work.weixin.qq.com/) [![WeWork](https://img.shields.io/badge/WeWork-Notification-00D4AA?style=flat-square)](https://work.weixin.qq.com/)
[![WeChat](https://img.shields.io/badge/WeChat-Notification-00D4AA?style=flat-square)](https://weixin.qq.com/) [![WeChat](https://img.shields.io/badge/WeChat-Notification-00D4AA?style=flat-square)](https://weixin.qq.com/)
@ -212,7 +212,7 @@ No longer controlled by platform algorithms, TrendRadar reorganizes all trending
### **Multi-Channel Real-Time Push** ### **Multi-Channel Real-Time Push**
Supports **WeWork** (+ WeChat push solution), **Feishu**, **DingTalk**, **Telegram**, **Email**, **ntfy** — messages delivered directly to phone and email. Supports **WeWork** (+ WeChat push solution), **Feishu**, **DingTalk**, **Telegram**, **Email**, **ntfy**, **Bark**, **Slack** — messages delivered directly to phone and email.
### **Multi-Platform Support** ### **Multi-Platform Support**
- **GitHub Pages**: Auto-generate beautiful web reports, PC/mobile adapted - **GitHub Pages**: Auto-generate beautiful web reports, PC/mobile adapted
@ -225,7 +225,7 @@ Supports **WeWork** (+ WeChat push solution), **Feishu**, **DingTalk**, **Telegr
AI conversational analysis system based on MCP (Model Context Protocol), enabling deep data mining with natural language. AI conversational analysis system based on MCP (Model Context Protocol), enabling deep data mining with natural language.
- **Conversational Query**: Ask in natural language, like "Query yesterday's Zhihu trending" or "Analyze recent Bitcoin popularity trends" - **Conversational Query**: Ask in natural language, like "Query yesterday's Zhihu trending" or "Analyze recent Bitcoin popularity trends"
- **13 Analysis Tools**: Basic query, smart search, trend analysis, data insights, sentiment analysis, etc. - **14 Analysis Tools**: Date parsing, basic query, smart search, trend analysis, data insights, sentiment analysis, etc.
- **Multi-Client Support**: Cherry Studio (GUI config), Claude Desktop, Cursor, Cline, etc. - **Multi-Client Support**: Cherry Studio (GUI config), Claude Desktop, Cursor, Cline, etc.
- **Deep Analysis Capabilities**: - **Deep Analysis Capabilities**:
- Topic trend tracking (popularity changes, lifecycle, viral detection, trend prediction) - Topic trend tracking (popularity changes, lifecycle, viral detection, trend prediction)
@ -294,6 +294,13 @@ Transform from "algorithm recommendation captivity" to "actively getting the inf
**🔧 Upgrade Instructions**: **🔧 Upgrade Instructions**:
- **GitHub Fork Users**: Update `main.py`, `config/config.yaml`, `.github/workflows/crawler.yml` - **GitHub Fork Users**: Update `main.py`, `config/config.yaml`, `.github/workflows/crawler.yml`
### 2025/11/26 - mcp-v1.0.3
**MCP Module Update:**
- Added date parsing tool resolve_date_range to resolve AI model date calculation inconsistencies
- Support natural language date expression parsing (this week, last 7 days, last month, etc.)
- Tool count increased from 13 to 14
<details> <details>
<summary>👉 Click to expand: <strong>Historical Updates</strong></summary> <summary>👉 Click to expand: <strong>Historical Updates</strong></summary>
@ -340,12 +347,6 @@ Transform from "algorithm recommendation captivity" to "actively getting the inf
**🔧 Upgrade Instructions**: **🔧 Upgrade Instructions**:
- **GitHub Fork Users**: Update `main.py`, `config/config.yaml` - **GitHub Fork Users**: Update `main.py`, `config/config.yaml`
### 2025/11/18 - mcp-v1.0.2
**MCP Module Update:**
- Fix issue where today's news query may return articles from past dates
### 2025/11/22 - v3.1.1 ### 2025/11/22 - v3.1.1
- **Fixed data anomaly crash issue**: Resolved `'float' object has no attribute 'lower'` error encountered by some users in GitHub Actions environment - **Fixed data anomaly crash issue**: Resolved `'float' object has no attribute 'lower'` error encountered by some users in GitHub Actions environment
@ -376,6 +377,7 @@ Transform from "algorithm recommendation captivity" to "actively getting the inf
- Optional update: `.github/workflows/crawler.yml` (if using GitHub Actions) - Optional update: `.github/workflows/crawler.yml` (if using GitHub Actions)
- Recommended: Use minor version upgrade method - copy and replace the files above - Recommended: Use minor version upgrade method - copy and replace the files above
### 2025/11/12 - v3.0.5 ### 2025/11/12 - v3.0.5
- Fixed email sending SSL/TLS port configuration logic error - Fixed email sending SSL/TLS port configuration logic error
@ -2248,7 +2250,8 @@ MCP Inspector is the official debug tool for testing MCP connections:
3. **Connect in Browser**: 3. **Connect in Browser**:
- Visit: `http://localhost:3333/mcp` - Visit: `http://localhost:3333/mcp`
- Test "Ping Server" function to verify connection - Test "Ping Server" function to verify connection
- Check "List Tools" returns 13 tools: - Check "List Tools" returns 14 tools:
- Date Parsing: resolve_date_range
- Basic Query: get_latest_news, get_news_by_date, get_trending_topics - Basic Query: get_latest_news, get_news_by_date, get_trending_topics
- Smart Search: search_news, search_related_news_history - Smart Search: search_news, search_related_news_history
- Advanced Analysis: analyze_topic_trend, analyze_data_insights, analyze_sentiment, find_similar_news, generate_summary_report - Advanced Analysis: analyze_topic_trend, analyze_data_insights, analyze_sentiment, find_similar_news, generate_summary_report

544
README-MCP-FAQ-EN.md Normal file
View File

@ -0,0 +1,544 @@
<div align="center">
**[中文](README-MCP-FAQ.md)** | **English**
</div>
# TrendRadar MCP Tool Usage Q&A
> AI Query Guide - How to Use News Trend Analysis Tools Through Conversation
## ⚙️ Default Settings Explanation (Important!)
The following optimization strategies are adopted by default, mainly to save AI token consumption:
| Default Setting | Description | How to Adjust |
| -------------- | --------------------------------------- | ------------------------------------- |
| **Result Limit** | Default returns 50 news items | Say "return top 10" or "give me 100 items" in conversation |
| **Time Range** | Default queries today's data | Say "query yesterday", "last week" or "Jan 1 to 7" |
| **URL Links** | Default no links (saves ~160 tokens/item) | Say "need links" or "include URLs" |
| **Keyword List** | Default does not use frequency_words.txt to filter news | Only used when calling "trending topics" tool |
**⚠️ Important:** The choice of AI model directly affects the tool call effectiveness. The smarter the AI, the more accurate the calls. When you remove the above restrictions, for example, from querying today to querying a week, first you need to have a week's data locally, and secondly, token consumption may multiply (why "may", for example, if I query "analyze 'Apple' trend in the last week", if there isn't much Apple news in that week, then token consumption may actually be less).
**💡 Tip:** This project provides a dedicated date parsing tool `resolve_date_range`, which can accurately parse natural language date expressions like "last 7 days", "this week", ensuring all AI models get consistent date ranges. Recommended to use this tool first, see Q14 below for details.
## 💰 AI Models
Below I use the **[SiliconFlow](https://cloud.siliconflow.cn)** platform as an example, which has many large models to choose from. During the development and testing of this project, I used this platform for many functional tests and validations.
### 📊 Registration Method Comparison
| Registration Method | Direct Registration Without Referral | Registration With Referral Link |
|:-------:|:-------:|:-----------------:|
| Registration Link | [siliconflow.cn](https://cloud.siliconflow.cn) | [Referral Link](https://cloud.siliconflow.cn/i/fqnyVaIU) |
| Free Quota | 0 tokens | **20 million tokens** (≈$2) |
| Extra Benefits | ❌ | ✅ Referrer also gets 20 million tokens |
> 💡 **Tip**: The above gift quota should allow for **200+ queries**
### 🚀 Quick Start
#### 1⃣ Register and Get API Key
1. Complete registration using the link above
2. Visit [API Key Management Page](https://cloud.siliconflow.cn/me/account/ak)
3. Click "Create New API Key"
4. Copy the generated key (please keep it safe)
#### 2⃣ Configure in Cherry Studio
1. Open **Cherry Studio**
2. Go to "Model Service" settings
3. Find "SiliconFlow"
4. Paste the copied key into the **[API Key]** input box
5. Ensure the checkbox in the top right corner shows **green** when enabled ✅
---
### ✨ Configuration Complete!
Now you can start using this project and enjoy stable and fast AI services!
After testing one query, please immediately check the [SiliconFlow Billing](https://cloud.siliconflow.cn/me/bills) to see the consumption and have an estimate in mind.
## Basic Queries
### Q1: How to view the latest news?
**You can ask like this:**
- "Show me the latest news"
- "Query today's trending news"
- "Get the latest 10 news from Zhihu and Weibo"
- "View latest news, need links included"
**Tool called:** `get_latest_news`
**Tool return behavior:**
- MCP tool returns the latest 50 news items from all platforms to AI
- Does not include URL links (saves tokens)
**AI display behavior (Important):**
- ⚠️ **AI usually auto-summarizes**, only showing partial news (like TOP 10-20 items)
- ✅ If you want to see all 50 items, need to explicitly request: "show all news" or "list all 50 items completely"
- 💡 This is the AI model's natural behavior, not a tool limitation
**Can be adjusted:**
- Specify platform: like "only Zhihu"
- Adjust quantity: like "return top 20"
- Include links: like "need links"
- **Request full display**: like "show all, don't summarize"
---
### Q2: How to query news from a specific date?
**You can ask like this:**
- "Query yesterday's news"
- "Check Zhihu news from 3 days ago"
- "What news was there on 2025-10-10"
- "News from last Monday"
- "Show me the latest news" (automatically queries today)
**Tool called:** `get_news_by_date`
**Supported date formats:**
- Relative dates: today, yesterday, day before yesterday, 3 days ago
- Days of week: last Monday, this Wednesday, last monday
- Absolute dates: 2025-10-10, October 10
**Tool return behavior:**
- Automatically queries today when date not specified (saves tokens)
- MCP tool returns 50 news items from all platforms to AI
- Does not include URL links
**AI display behavior (Important):**
- ⚠️ **AI usually auto-summarizes**, only showing partial news (like TOP 10-20 items)
- ✅ If you want to see all, need to explicitly request: "show all news, don't summarize"
---
### Q3: How to view my followed topic frequency statistics?
**You can ask like this:**
- "How many times did my followed words appear today"
- "Check which words in my follow list are most popular"
- "Count the frequency of followed words in frequency_words.txt"
**Tool called:** `get_trending_topics`
**Important note:**
- This tool **does not** automatically extract news hotspots
- Rather, it counts your **personal followed words** set in `config/frequency_words.txt`
- This is a **customizable** list, you can add followed words based on your interests
---
## Search and Retrieval
### Q4: How to search for news containing specific keywords?
**You can ask like this:**
- "Search for news containing 'artificial intelligence'"
- "Find reports about 'Tesla price cut'"
- "Search for news about Musk, return top 20"
- "Find news about 'iPhone 16' in the last 7 days"
- "Find news about 'Tesla' from January 1 to 7, 2025"
- "Find the link to the news 'iPhone 16 release'"
**Tool called:** `search_news`
**Tool return behavior:**
- Uses keyword mode search
- Default searches today's data
- AI automatically converts relative time like "last 7 days", "last week" to specific date ranges
- MCP tool returns up to 50 results to AI
- Does not include URL links
**AI display behavior (Important):**
- ⚠️ **AI usually auto-summarizes**, only showing partial search results
- ✅ If you want to see all, need to explicitly request: "show all search results"
**Can be adjusted:**
- Specify time range:
- Relative way: "search last week" (AI automatically calculates dates)
- Absolute dates: "search from January 1 to 7, 2025"
- Specify platform: like "only search Zhihu"
- Adjust sorting: like "sort by weight"
- Include links: like "need links"
**Recommended usage flow:**
```
User: Search for news about "AI breakthrough" in the last 7 days
Recommended steps:
1. First call resolve_date_range("last 7 days") to get precise date range
2. Then call search_news with the date range
User: Find "Tesla" reports from January 2025
AI: (date_range={"start": "2025-01-01", "end": "2025-01-31"})
```
---
### Q5: How to find historical related news?
**You can ask like this:**
- "Find news related to 'AI breakthrough' from yesterday"
- "Search for historical reports about 'Tesla' from last week"
- "Find news related to 'ChatGPT' from last month"
- "Look for historical news related to 'iPhone launch event'"
**Tool called:** `search_related_news_history`
**Tool return behavior:**
- Searches yesterday's data
- Similarity threshold 0.4
- MCP tool returns up to 50 results to AI
- Does not include URL links
**AI display behavior (Important):**
- ⚠️ **AI usually auto-summarizes**, only showing partial related news
- ✅ If you want to see all, need to explicitly request: "show all related news"
---
## Trend Analysis
### Q6: How to analyze topic heat trends?
**You can ask like this:**
- "Analyze the heat trend of 'artificial intelligence' in the last week"
- "See if 'Tesla' topic is a flash in the pan or sustained hot topic"
- "Detect which topics suddenly went viral today"
- "Predict potential hot topics coming up"
- "Analyze the lifecycle of 'Bitcoin' in December 2024"
**Tool called:** `analyze_topic_trend`
**Tool return behavior:**
- Supports multiple analysis modes: heat trend, lifecycle, anomaly detection, prediction
- AI automatically converts relative time like "last week" to specific date ranges
- Default analyzes last 7 days of data
- Statistics by day granularity
**AI display behavior:**
- Usually displays trend analysis results and charts
- AI may summarize key findings
**Recommended usage flow:**
```
User: Analyze the lifecycle of 'artificial intelligence' in the last week
Recommended steps:
1. First call resolve_date_range("last week") to get precise date range
2. Then call analyze_topic_trend with the date range
User: See if 'Bitcoin' in December 2024 is a flash in the pan or sustained hot topic
AI: (date_range={"start": "2024-12-01", "end": "2024-12-31"})
```
---
## Data Insights
### Q7: How to compare different platforms' attention to topics?
**You can ask like this:**
- "Compare different platforms' attention to 'artificial intelligence' topic"
- "See which platform updates most frequently"
- "Analyze which keywords often appear together"
**Tool called:** `analyze_data_insights`
**Three insight modes:**
| Mode | Function | Example Question |
| -------------- | ---------------- | -------------------------- |
| **Platform Compare** | Compare platform attention | "Compare platforms' attention to 'AI'" |
| **Activity Stats** | Count platform posting frequency | "See which platform updates most frequently" |
| **Keyword Co-occurrence** | Analyze keyword associations | "Which keywords often appear together" |
**Tool return behavior:**
- Platform compare mode
- Analyzes today's data
- Keyword co-occurrence minimum frequency 3 times
**AI display behavior:**
- Usually displays analysis results and statistical data
- AI may summarize insight findings
---
## Sentiment Analysis
### Q8: How to analyze news sentiment?
**You can ask like this:**
- "Analyze today's news sentiment"
- "See if 'Tesla' related news is positive or negative"
- "Analyze different platforms' sentiment towards 'artificial intelligence'"
- "See the sentiment of 'Bitcoin' within a week, choose the top 20 most important"
**Tool called:** `analyze_sentiment`
**Tool return behavior:**
- Analyzes today's data
- MCP tool returns up to 50 news items to AI
- Sorted by weight (prioritizing important news)
- Does not include URL links
**AI display behavior (Important):**
- ⚠️ This tool returns **AI prompts**, not direct sentiment analysis results
- AI generates sentiment analysis reports based on prompts
- Usually displays sentiment distribution, key findings, and representative news
**Can be adjusted:**
- Specify topic: like "about 'Tesla'"
- Specify time: like "last week"
- Adjust quantity: like "return top 20"
---
### Q9: How to find similar news reports?
**You can ask like this:**
- "Find news similar to 'Tesla price cut'"
- "Find similar reports about iPhone launch"
- "See if there are reports similar to this news"
- "Find similar news, need links"
**Tool called:** `find_similar_news`
**Tool return behavior:**
- Similarity threshold 0.6
- MCP tool returns up to 50 results to AI
- Does not include URL links
**AI display behavior (Important):**
- ⚠️ **AI usually auto-summarizes**, only showing partial similar news
- ✅ If you want to see all, need to explicitly request: "show all similar news"
---
### Q10: How to generate daily or weekly hotspot summaries?
**You can ask like this:**
- "Generate today's news summary report"
- "Give me a weekly hotspot summary"
- "Generate news analysis report for the past 7 days"
**Tool called:** `generate_summary_report`
**Report types:**
- Daily summary: Summarizes the day's hotspot news
- Weekly summary: Summarizes a week's hotspot trends
---
## System Management
### Q11: How to view system configuration?
**You can ask like this:**
- "View current system configuration"
- "Display configuration file content"
- "What platforms are available?"
- "What's the current weight configuration?"
**Tool called:** `get_current_config`
**Can query:**
- Available platform list
- Crawler configuration (request interval, timeout settings)
- Weight configuration (ranking weight, frequency weight)
- Notification configuration (DingTalk, WeChat)
---
### Q12: How to check system running status?
**You can ask like this:**
- "Check system status"
- "Is the system running normally?"
- "When was the last crawl?"
- "How many days of historical data?"
**Tool called:** `get_system_status`
**Return information:**
- System version and status
- Last crawl time
- Historical data days
- Health check results
---
### Q13: How to manually trigger a crawl task?
**You can ask like this:**
- "Please crawl current Toutiao news" (temporary query)
- "Help me fetch latest news from Zhihu and Weibo and save" (persistent)
- "Trigger a crawl and save data" (persistent)
- "Get real-time data from 36Kr but don't save" (temporary query)
**Tool called:** `trigger_crawl`
**Two modes:**
| Mode | Purpose | Example |
| -------------- | -------------------- | -------------------- |
| **Temporary Crawl** | Only return data without saving | "Crawl Toutiao news" |
| **Persistent Crawl** | Save to output folder | "Fetch and save Zhihu news" |
**Tool return behavior:**
- Temporary crawl mode (no save)
- Crawls all platforms
- Does not include URL links
**AI display behavior (Important):**
- ⚠️ **AI usually summarizes crawl results**, only showing partial news
- ✅ If you want to see all, need to explicitly request: "show all crawled news"
**Can be adjusted:**
- Specify platform: like "only crawl Zhihu"
- Save data: say "and save" or "save locally"
- Include links: say "need links"
---
### Q14: How to parse natural language date expressions? (Recommended to use first)
**You can ask like this:**
- "Parse what days 'this week' is"
- "What date range does 'last 7 days' correspond to"
- "Last month's date range"
- "Help me convert 'last 30 days' to specific dates"
**Tool called:** `resolve_date_range`
**Why is this tool needed?**
Users often use natural language like "this week", "last 7 days" to express dates, but different AI models calculating dates on their own will produce inconsistent results. This tool uses server-side precise time calculations to ensure all AI models get consistent date ranges.
**Supported date expressions:**
| Type | Chinese Expression | English Expression |
|------|---------|---------|
| Single Day | 今天、昨天 | today, yesterday |
| Week | 本周、上周 | this week, last week |
| Month | 本月、上月 | this month, last month |
| Last N Days | 最近7天、最近30天 | last 7 days, last 30 days |
| Dynamic | 最近N天 (any number) | last N days |
**Return format:**
```json
{
"success": true,
"expression": "this week",
"date_range": {
"start": "2025-11-18",
"end": "2025-11-26"
},
"current_date": "2025-11-26",
"description": "This week (Monday to Sunday, 11-18 to 11-26)"
}
```
**Recommended usage flow:**
```
User: Analyze AI's sentiment this week
Recommended steps:
1. AI first calls resolve_date_range("this week") → gets {"start": "2025-11-18", "end": "2025-11-26"}
2. AI calls analyze_sentiment(topic="AI", date_range=date_range from previous step)
User: Check Tesla news from last 7 days
Recommended steps:
1. AI calls resolve_date_range("last 7 days") → gets precise date range
2. AI calls search_news(query="Tesla", date_range=date_range from previous step)
```
**Usage advantages:**
- ✅ **Consistency**: All AI models get the same date range
- ✅ **Accuracy**: Based on server-side Python `datetime.now()` calculation
- ✅ **Standardization**: Returns standard `YYYY-MM-DD` format
- ✅ **Flexibility**: Supports Chinese/English, dynamic days (last N days)
---
## 💡 Usage Tips
### 1. How to make AI display all data instead of auto-summarizing?
**Background**: Sometimes AI automatically summarizes data, only showing partial content, even if the tool returned complete 50 items of data.
**If AI still summarizes, you can**:
- **Method 1 - Explicit request**: "Please show all news, don't summarize"
- **Method 2 - Specify quantity**: "Show all 50 news items"
- **Method 3 - Question the behavior**: "Why only showed 15? I want to see all"
- **Method 4 - State upfront**: "Query today's news, fully display all results"
**Note**: AI may still adjust display method based on context.
### 2. How to combine multiple tools?
**Example: In-depth analysis of a topic**
1. Search first: "Search for news about 'artificial intelligence'"
2. Then analyze trends: "Analyze the heat trend of 'artificial intelligence'"
3. Finally sentiment analysis: "Analyze sentiment of 'artificial intelligence' news"
**Example: Track an event**
1. View latest: "Query today's news about 'iPhone'"
2. Find history: "Find historical news related to 'iPhone' from last week"
3. Find similar reports: "Find news similar to 'iPhone launch event'"

View File

@ -1,3 +1,9 @@
<div align="center">
**中文** | **[English](README-MCP-FAQ-EN.md)**
</div>
# TrendRadar MCP 工具使用问答 # TrendRadar MCP 工具使用问答
> AI 提问指南 - 如何通过对话使用新闻热点分析工具 > AI 提问指南 - 如何通过对话使用新闻热点分析工具
@ -15,7 +21,7 @@
**⚠️ 重要:** AI 模型的选择直接影响工具调用效果AI 越智能调用越准确。当你解除上面的限制比如从今天的查询放宽到一周的查询首先你要在本地有一周的数据其次token 消耗量可能会倍增(为什么说可能,比如我查询 分析'苹果'最近一周的热度趋势,如果一周中没多少苹果的新闻,那么 token消耗量可能反而很少 **⚠️ 重要:** AI 模型的选择直接影响工具调用效果AI 越智能调用越准确。当你解除上面的限制比如从今天的查询放宽到一周的查询首先你要在本地有一周的数据其次token 消耗量可能会倍增(为什么说可能,比如我查询 分析'苹果'最近一周的热度趋势,如果一周中没多少苹果的新闻,那么 token消耗量可能反而很少
**💡 提示:** 当你说"最近7天"时AI会自动计算对应的日期范围如 2025-10-18 至 2025-10-25并传递给工具 **💡 提示:** 本项目提供了专门的日期解析工具 `resolve_date_range`,可以准确解析"最近7天"、"本周"等自然语言日期表达式,确保所有 AI 模型获得一致的日期范围。推荐优先使用该工具,详见下方 Q14
## 💰 AI 模型 ## 💰 AI 模型
@ -178,11 +184,13 @@
- 调整排序:如"按权重排序" - 调整排序:如"按权重排序"
- 包含链接:如"需要链接" - 包含链接:如"需要链接"
**示例对话** **推荐使用流程**
``` ```
用户搜索最近7天关于"人工智能突破"的新闻 用户搜索最近7天关于"人工智能突破"的新闻
AI自动计算date_range={"start": "2025-10-18", "end": "2025-10-25"} 推荐步骤:
1. 先调用 resolve_date_range("最近7天") 获取精确日期范围
2. 再调用 search_news 并传入日期范围
用户查找2025年1月的"特斯拉"报道 用户查找2025年1月的"特斯拉"报道
AIdate_range={"start": "2025-01-01", "end": "2025-01-31"} AIdate_range={"start": "2025-01-01", "end": "2025-01-31"}
@ -241,11 +249,13 @@ AIdate_range={"start": "2025-01-01", "end": "2025-01-31"}
- 通常会展示趋势分析结果和图表 - 通常会展示趋势分析结果和图表
- AI 可能会总结关键发现 - AI 可能会总结关键发现
**示例对话** **推荐使用流程**
``` ```
用户:分析'人工智能'最近一周的生命周期 用户:分析'人工智能'最近一周的生命周期
AI自动计算date_range={"start": "2025-10-18", "end": "2025-10-25"} 推荐步骤:
1. 先调用 resolve_date_range("最近一周") 获取精确日期范围
2. 再调用 analyze_topic_trend 并传入日期范围
用户:看看'比特币'在2024年12月是昙花一现还是持续热点 用户:看看'比特币'在2024年12月是昙花一现还是持续热点
AIdate_range={"start": "2024-12-01", "end": "2024-12-31"} AIdate_range={"start": "2024-12-01", "end": "2024-12-31"}
@ -440,6 +450,69 @@ AIdate_range={"start": "2024-12-01", "end": "2024-12-31"}
--- ---
### Q14: 如何解析自然语言日期表达式?(推荐优先使用)
**你可以这样问:**
- "解析'本周'是哪几天"
- "最近7天对应的日期范围是什么"
- "上月的日期范围"
- "帮我把'最近30天'转换为具体日期"
**调用的工具:** `resolve_date_range`
**为什么需要这个工具?**
用户经常使用"本周"、"最近7天"等自然语言表达日期,但不同的 AI 模型自行计算日期时会产生不一致的结果。此工具使用服务器端的精确时间计算,确保所有 AI 模型获得一致的日期范围。
**支持的日期表达式:**
| 类型 | 中文表达 | 英文表达 |
|------|---------|---------|
| 单日 | 今天、昨天 | today, yesterday |
| 周 | 本周、上周 | this week, last week |
| 月 | 本月、上月 | this month, last month |
| 最近N天 | 最近7天、最近30天 | last 7 days, last 30 days |
| 动态 | 最近N天任意数字 | last N days |
**返回格式:**
```json
{
"success": true,
"expression": "本周",
"date_range": {
"start": "2025-11-18",
"end": "2025-11-26"
},
"current_date": "2025-11-26",
"description": "本周周一到周日11-18 至 11-26"
}
```
**推荐使用流程:**
```
用户:分析 AI 本周的情感倾向
推荐步骤:
1. AI 先调用 resolve_date_range("本周") → 获取 {"start": "2025-11-18", "end": "2025-11-26"}
2. AI 调用 analyze_sentiment(topic="AI", date_range=上一步返回的date_range)
用户看看最近7天的特斯拉新闻
推荐步骤:
1. AI 调用 resolve_date_range("最近7天") → 获取精确日期范围
2. AI 调用 search_news(query="特斯拉", date_range=上一步返回的date_range)
```
**使用优势:**
- ✅ **一致性**:所有 AI 模型获得相同的日期范围
- ✅ **准确性**:基于服务器端 Python `datetime.now()` 计算
- ✅ **标准化**:返回标准 `YYYY-MM-DD` 格式
- ✅ **灵活性**支持中英文、动态天数最近N天
---
## 💡 使用技巧 ## 💡 使用技巧
### 1. 如何让 AI 展示全部数据而不是自动总结? ### 1. 如何让 AI 展示全部数据而不是自动总结?

View File

@ -15,7 +15,7 @@
[![GitHub Forks](https://img.shields.io/github/forks/sansan0/TrendRadar?style=flat-square&logo=github&color=blue)](https://github.com/sansan0/TrendRadar/network/members) [![GitHub Forks](https://img.shields.io/github/forks/sansan0/TrendRadar?style=flat-square&logo=github&color=blue)](https://github.com/sansan0/TrendRadar/network/members)
[![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg?style=flat-square)](LICENSE) [![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg?style=flat-square)](LICENSE)
[![Version](https://img.shields.io/badge/version-v3.4.0-blue.svg)](https://github.com/sansan0/TrendRadar) [![Version](https://img.shields.io/badge/version-v3.4.0-blue.svg)](https://github.com/sansan0/TrendRadar)
[![MCP](https://img.shields.io/badge/MCP-v1.0.2-green.svg)](https://github.com/sansan0/TrendRadar) [![MCP](https://img.shields.io/badge/MCP-v1.0.3-green.svg)](https://github.com/sansan0/TrendRadar)
[![企业微信通知](https://img.shields.io/badge/企业微信-通知-00D4AA?style=flat-square)](https://work.weixin.qq.com/) [![企业微信通知](https://img.shields.io/badge/企业微信-通知-00D4AA?style=flat-square)](https://work.weixin.qq.com/)
[![个人微信通知](https://img.shields.io/badge/个人微信-通知-00D4AA?style=flat-square)](https://weixin.qq.com/) [![个人微信通知](https://img.shields.io/badge/个人微信-通知-00D4AA?style=flat-square)](https://weixin.qq.com/)
@ -277,7 +277,7 @@
### **多渠道实时推送** ### **多渠道实时推送**
支持**企业微信**(+ 微信推送方案)、**飞书**、**钉钉**、**Telegram**、**邮件**、**ntfy**,消息直达手机和邮箱 支持**企业微信**(+ 微信推送方案)、**飞书**、**钉钉**、**Telegram**、**邮件**、**ntfy**、**Bark**、**Slack**,消息直达手机和邮箱
### **多端适配** ### **多端适配**
- **GitHub Pages**自动生成精美网页报告PC/移动端适配 - **GitHub Pages**自动生成精美网页报告PC/移动端适配
@ -337,6 +337,13 @@ GitHub 一键 Fork 即可使用,无需编程基础。
- **大版本升级**:从 v1.x 升级到 v2.y建议删除现有 fork 后重新 fork这样更省力且避免配置冲突 - **大版本升级**:从 v1.x 升级到 v2.y建议删除现有 fork 后重新 fork这样更省力且避免配置冲突
### 2025/11/26 - mcp-v1.0.3
**MCP 模块更新:**
- 新增日期解析工具 resolve_date_range,解决 AI 模型计算日期不一致的问题
- 支持自然语言日期表达式解析(本周、最近7天、上月等)
- 工具总数从 13 个增加到 14 个
### 2025/11/25 - v3.4.0 ### 2025/11/25 - v3.4.0
**🎉 新增 Slack 推送支持** **🎉 新增 Slack 推送支持**
@ -404,6 +411,7 @@ GitHub 一键 Fork 即可使用,无需编程基础。
**🔧 升级说明** **🔧 升级说明**
- **GitHub Fork 用户**:更新 `main.py`、`config/config.yaml` - **GitHub Fork 用户**:更新 `main.py`、`config/config.yaml`
### 2025/11/18 - mcp-v1.0.2 ### 2025/11/18 - mcp-v1.0.2
**MCP 模块更新:** **MCP 模块更新:**

View File

@ -15,6 +15,8 @@ from .tools.analytics import AnalyticsTools
from .tools.search_tools import SearchTools from .tools.search_tools import SearchTools
from .tools.config_mgmt import ConfigManagementTools from .tools.config_mgmt import ConfigManagementTools
from .tools.system import SystemManagementTools from .tools.system import SystemManagementTools
from .utils.date_parser import DateParser
from .utils.errors import MCPError
# 创建 FastMCP 2.0 应用 # 创建 FastMCP 2.0 应用
@ -35,6 +37,77 @@ def _get_tools(project_root: Optional[str] = None):
return _tools_instances return _tools_instances
# ==================== 日期解析工具(优先调用)====================
@mcp.tool
async def resolve_date_range(
expression: str
) -> str:
"""
推荐优先调用将自然语言日期表达式解析为标准日期范围
**为什么需要这个工具**
用户经常使用"本周""最近7天"等自然语言表达日期 AI 模型自己计算日期
可能导致不一致的结果此工具在服务器端使用精确的当前时间计算确保所有
AI 模型获得一致的日期范围
**推荐使用流程**
1. 用户说"分析AI本周的情感倾向"
2. AI 调用 resolve_date_range("本周") 获取精确日期范围
3. AI 调用 analyze_sentiment(topic="ai", date_range=上一步返回的date_range)
Args:
expression: 自然语言日期表达式支持
- 单日: "今天", "昨天", "today", "yesterday"
- : "本周", "上周", "this week", "last week"
- : "本月", "上月", "this month", "last month"
- 最近N天: "最近7天", "最近30天", "last 7 days", "last 30 days"
- 动态: "最近5天", "last 10 days"任意天数
Returns:
JSON格式的日期范围可直接用于其他工具的 date_range 参数
{
"success": true,
"expression": "本周",
"date_range": {
"start": "2025-11-18",
"end": "2025-11-26"
},
"current_date": "2025-11-26",
"description": "本周周一到周日11-18 至 11-26"
}
Examples:
用户"分析AI本周的情感倾向"
AI调用步骤
1. resolve_date_range("本周")
{"date_range": {"start": "2025-11-18", "end": "2025-11-26"}, ...}
2. analyze_sentiment(topic="ai", date_range={"start": "2025-11-18", "end": "2025-11-26"})
用户"看看最近7天的特斯拉新闻"
AI调用步骤
1. resolve_date_range("最近7天")
{"date_range": {"start": "2025-11-20", "end": "2025-11-26"}, ...}
2. search_news(query="特斯拉", date_range={"start": "2025-11-20", "end": "2025-11-26"})
"""
try:
result = DateParser.resolve_date_range_expression(expression)
return json.dumps(result, ensure_ascii=False, indent=2)
except MCPError as e:
return json.dumps({
"success": False,
"error": e.to_dict()
}, ensure_ascii=False, indent=2)
except Exception as e:
return json.dumps({
"success": False,
"error": {
"code": "INTERNAL_ERROR",
"message": str(e)
}
}, ensure_ascii=False, indent=2)
# ==================== 数据查询工具 ==================== # ==================== 数据查询工具 ====================
@mcp.tool @mcp.tool
@ -165,6 +238,11 @@ async def analyze_topic_trend(
""" """
统一话题趋势分析工具 - 整合多种趋势分析模式 统一话题趋势分析工具 - 整合多种趋势分析模式
**重要日期范围处理**
当用户使用"本周""最近7天"等自然语言时请先调用 resolve_date_range 工具获取精确日期
1. 调用 resolve_date_range("本周") 获取 {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
2. 将返回的 date_range 传入本工具
Args: Args:
topic: 话题关键词必需 topic: 话题关键词必需
analysis_type: 分析类型可选值 analysis_type: 分析类型可选值
@ -173,12 +251,8 @@ async def analyze_topic_trend(
- "viral": 异常热度检测识别突然爆火的话题 - "viral": 异常热度检测识别突然爆火的话题
- "predict": 话题预测预测未来可能的热点 - "predict": 话题预测预测未来可能的热点
date_range: 日期范围trend和lifecycle模式可选 date_range: 日期范围trend和lifecycle模式可选
- **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}必须是标准日期格式 - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
- **说明**: AI必须根据当前日期自动计算并填入具体日期不能使用"今天"等自然语言 - **获取方式**: 调用 resolve_date_range 工具解析自然语言日期
- **计算示例**:
- 用户说"最近7天" AI计算: {"start": "2025-11-11", "end": "2025-11-17"}假设今天是11-17
- 用户说"上周" AI计算: {"start": "2025-11-11", "end": "2025-11-17"}上周一到上周日
- 用户说"本月" AI计算: {"start": "2025-11-01", "end": "2025-11-17"}11月1日到今天
- **默认**: 不指定时默认分析最近7天 - **默认**: 不指定时默认分析最近7天
granularity: 时间粒度trend模式默认"day"仅支持 day因为底层数据按天聚合 granularity: 时间粒度trend模式默认"day"仅支持 day因为底层数据按天聚合
threshold: 热度突增倍数阈值viral模式默认3.0 threshold: 热度突增倍数阈值viral模式默认3.0
@ -189,19 +263,16 @@ async def analyze_topic_trend(
Returns: Returns:
JSON格式的趋势分析结果 JSON格式的趋势分析结果
**AI使用说明** Examples:
当用户使用相对时间表达时"最近7天""过去一周""上个月" 用户"分析AI本周的趋势"
AI必须根据当前日期从环境 <env> 获取计算出具体的 YYYY-MM-DD 格式日期 推荐调用流程
1. resolve_date_range("本周") {"date_range": {"start": "2025-11-18", "end": "2025-11-26"}}
2. analyze_topic_trend(topic="AI", date_range={"start": "2025-11-18", "end": "2025-11-26"})
**重要**date_range 不接受"今天""昨天"等自然语言必须是 YYYY-MM-DD 格式 用户"看看特斯拉最近30天的热度"
推荐调用流程
Examples (假设今天是 2025-11-17): 1. resolve_date_range("最近30天") {"date_range": {"start": "2025-10-28", "end": "2025-11-26"}}
- 用户"分析AI最近7天的趋势" 2. analyze_topic_trend(topic="特斯拉", analysis_type="lifecycle", date_range=...)
analyze_topic_trend(topic="人工智能", analysis_type="trend", date_range={"start": "2025-11-11", "end": "2025-11-17"})
- 用户"看看特斯拉本月的热度"
analyze_topic_trend(topic="特斯拉", analysis_type="lifecycle", date_range={"start": "2025-11-01", "end": "2025-11-17"})
- analyze_topic_trend(topic="比特币", analysis_type="viral", threshold=3.0)
- analyze_topic_trend(topic="ChatGPT", analysis_type="predict", lookahead_hours=6)
""" """
tools = _get_tools() tools = _get_tools()
result = tools['analytics'].analyze_topic_trend_unified( result = tools['analytics'].analyze_topic_trend_unified(
@ -272,16 +343,21 @@ async def analyze_sentiment(
""" """
分析新闻的情感倾向和热度趋势 分析新闻的情感倾向和热度趋势
**重要日期范围处理**
当用户使用"本周""最近7天"等自然语言时请先调用 resolve_date_range 工具获取精确日期
1. 调用 resolve_date_range("本周") 获取 {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
2. 将返回的 date_range 传入本工具
Args: Args:
topic: 话题关键词可选 topic: 话题关键词可选
platforms: 平台ID列表 ['zhihu', 'weibo', 'douyin'] platforms: 平台ID列表 ['zhihu', 'weibo', 'douyin']
- 不指定时使用 config.yaml 中配置的所有平台 - 不指定时使用 config.yaml 中配置的所有平台
- 支持的平台来自 config/config.yaml platforms 配置 - 支持的平台来自 config/config.yaml platforms 配置
- 每个平台都有对应的name字段"知乎""微博"方便AI识别 - 每个平台都有对应的name字段"知乎""微博"方便AI识别
date_range: **对象类型** 日期范围可选 date_range: 日期范围可选
- **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"} - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
- **示例**: {"start": "2025-01-01", "end": "2025-01-07"} - **获取方式**: 调用 resolve_date_range 工具解析自然语言日期
- **重要**: 必须是对象格式不能传递整数 - **默认**: 不指定则默认查询今天的数据
limit: 返回新闻数量默认50最大100 limit: 返回新闻数量默认50最大100
注意本工具会对新闻标题进行去重同一标题在不同平台只保留一次 注意本工具会对新闻标题进行去重同一标题在不同平台只保留一次
因此实际返回数量可能少于请求的 limit 因此实际返回数量可能少于请求的 limit
@ -291,6 +367,17 @@ async def analyze_sentiment(
Returns: Returns:
JSON格式的分析结果包含情感分布热度趋势和相关新闻 JSON格式的分析结果包含情感分布热度趋势和相关新闻
Examples:
用户"分析AI本周的情感倾向"
推荐调用流程
1. resolve_date_range("本周") {"date_range": {"start": "2025-11-18", "end": "2025-11-26"}}
2. analyze_sentiment(topic="AI", date_range={"start": "2025-11-18", "end": "2025-11-26"})
用户"分析特斯拉最近7天的新闻情感"
推荐调用流程
1. resolve_date_range("最近7天") {"date_range": {"start": "2025-11-20", "end": "2025-11-26"}}
2. analyze_sentiment(topic="特斯拉", date_range={"start": "2025-11-20", "end": "2025-11-26"})
**重要数据展示策略** **重要数据展示策略**
- 本工具返回完整的分析结果和新闻列表 - 本工具返回完整的分析结果和新闻列表
- **默认展示方式**展示完整的分析结果包括所有新闻 - **默认展示方式**展示完整的分析结果包括所有新闻
@ -386,6 +473,11 @@ async def search_news(
""" """
统一搜索接口支持多种搜索模式 统一搜索接口支持多种搜索模式
**重要日期范围处理**
当用户使用"本周""最近7天"等自然语言时请先调用 resolve_date_range 工具获取精确日期
1. 调用 resolve_date_range("本周") 获取 {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
2. 将返回的 date_range 传入本工具
Args: Args:
query: 搜索关键词或内容片段 query: 搜索关键词或内容片段
search_mode: 搜索模式可选值 search_mode: 搜索模式可选值
@ -394,10 +486,8 @@ async def search_news(
- "entity": 实体名称搜索适合搜索人物/地点/机构 - "entity": 实体名称搜索适合搜索人物/地点/机构
date_range: 日期范围可选 date_range: 日期范围可选
- **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"} - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
- **示例**: {"start": "2025-01-01", "end": "2025-01-07"} - **获取方式**: 调用 resolve_date_range 工具解析自然语言日期
- **说明**: AI需要根据用户的自然语言"最近7天"自动计算日期范围
- **默认**: 不指定时默认查询今天的新闻 - **默认**: 不指定时默认查询今天的新闻
- **注意**: start和end可以相同表示单日查询
platforms: 平台ID列表 ['zhihu', 'weibo', 'douyin'] platforms: 平台ID列表 ['zhihu', 'weibo', 'douyin']
- 不指定时使用 config.yaml 中配置的所有平台 - 不指定时使用 config.yaml 中配置的所有平台
- 支持的平台来自 config/config.yaml platforms 配置 - 支持的平台来自 config/config.yaml platforms 配置
@ -415,31 +505,24 @@ async def search_news(
Returns: Returns:
JSON格式的搜索结果包含标题平台排名等信息 JSON格式的搜索结果包含标题平台排名等信息
Examples:
用户"搜索本周的AI新闻"
推荐调用流程
1. resolve_date_range("本周") {"date_range": {"start": "2025-11-18", "end": "2025-11-26"}}
2. search_news(query="AI", date_range={"start": "2025-11-18", "end": "2025-11-26"})
用户"最近7天的特斯拉新闻"
推荐调用流程
1. resolve_date_range("最近7天") {"date_range": {"start": "2025-11-20", "end": "2025-11-26"}}
2. search_news(query="特斯拉", date_range={"start": "2025-11-20", "end": "2025-11-26"})
用户"今天的AI新闻"默认今天无需解析
search_news(query="AI")
**重要数据展示策略** **重要数据展示策略**
- 本工具返回完整的搜索结果列表 - 本工具返回完整的搜索结果列表
- **默认展示方式**展示全部返回的新闻无需总结或筛选 - **默认展示方式**展示全部返回的新闻无需总结或筛选
- 仅在用户明确要求"总结""挑重点"时才进行筛选 - 仅在用户明确要求"总结""挑重点"时才进行筛选
**AI使用说明**
当用户使用相对时间表达时"最近7天""过去一周""最近半个月"
AI必须根据当前日期从环境 <env> 获取计算出具体的 YYYY-MM-DD 格式日期
**重要**date_range 不接受"今天""昨天"等自然语言必须是 YYYY-MM-DD 格式
**计算规则**假设从 <env> 获取今天是 2025-11-17
- "今天" 不传 date_range默认查今天
- "最近7天" {"start": "2025-11-11", "end": "2025-11-17"}
- "过去一周" {"start": "2025-11-11", "end": "2025-11-17"}
- "上周" 计算上周一到上周日 {"start": "2025-11-11", "end": "2025-11-17"}
- "本月" {"start": "2025-11-01", "end": "2025-11-17"}
- "最近30天" {"start": "2025-10-19", "end": "2025-11-17"}
Examples (假设今天是 2025-11-17):
- 用户"今天的AI新闻" search_news(query="人工智能")
- 用户"最近7天的AI新闻" search_news(query="人工智能", date_range={"start": "2025-11-11", "end": "2025-11-17"})
- 精确日期: search_news(query="人工智能", date_range={"start": "2025-01-01", "end": "2025-01-07"})
- 模糊搜索: search_news(query="特斯拉降价", search_mode="fuzzy", threshold=0.4)
""" """
tools = _get_tools() tools = _get_tools()
result = tools['search'].search_news_unified( result = tools['search'].search_news_unified(
@ -605,9 +688,8 @@ def run_server(
print(" 协议: MCP over stdio (标准输入输出)") print(" 协议: MCP over stdio (标准输入输出)")
print(" 说明: 通过标准输入输出与 MCP 客户端通信") print(" 说明: 通过标准输入输出与 MCP 客户端通信")
elif transport == 'http': elif transport == 'http':
print(f" 监听地址: http://{host}:{port}") print(f" 协议: MCP over HTTP (生产环境)")
print(f" HTTP端点: http://{host}:{port}/mcp") print(f" 服务器监听: {host}:{port}")
print(" 协议: MCP over HTTP (生产环境)")
if project_root: if project_root:
print(f" 项目目录: {project_root}") print(f" 项目目录: {project_root}")
@ -616,6 +698,9 @@ def run_server(
print() print()
print(" 已注册的工具:") print(" 已注册的工具:")
print(" === 日期解析工具(推荐优先调用)===")
print(" 0. resolve_date_range - 解析自然语言日期为标准格式")
print()
print(" === 基础数据查询P0核心===") print(" === 基础数据查询P0核心===")
print(" 1. get_latest_news - 获取最新新闻") print(" 1. get_latest_news - 获取最新新闻")
print(" 2. get_news_by_date - 按日期查询新闻(支持自然语言)") print(" 2. get_news_by_date - 按日期查询新闻(支持自然语言)")

View File

@ -6,6 +6,7 @@
import re import re
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Tuple, Dict, Optional
from .errors import InvalidParameterError from .errors import InvalidParameterError
@ -27,6 +28,55 @@ class DateParser:
"yesterday": 1, "yesterday": 1,
} }
# 日期范围表达式(用于 resolve_date_range_expression
RANGE_EXPRESSIONS = {
# 中文表达式
"今天": "today",
"昨天": "yesterday",
"本周": "this_week",
"这周": "this_week",
"当前周": "this_week",
"上周": "last_week",
"本月": "this_month",
"这个月": "this_month",
"当前月": "this_month",
"上月": "last_month",
"上个月": "last_month",
"最近3天": "last_3_days",
"近3天": "last_3_days",
"最近7天": "last_7_days",
"近7天": "last_7_days",
"最近一周": "last_7_days",
"过去一周": "last_7_days",
"最近14天": "last_14_days",
"近14天": "last_14_days",
"最近两周": "last_14_days",
"过去两周": "last_14_days",
"最近30天": "last_30_days",
"近30天": "last_30_days",
"最近一个月": "last_30_days",
"过去一个月": "last_30_days",
# 英文表达式
"today": "today",
"yesterday": "yesterday",
"this week": "this_week",
"current week": "this_week",
"last week": "last_week",
"this month": "this_month",
"current month": "this_month",
"last month": "last_month",
"last 3 days": "last_3_days",
"past 3 days": "last_3_days",
"last 7 days": "last_7_days",
"past 7 days": "last_7_days",
"past week": "last_7_days",
"last 14 days": "last_14_days",
"past 14 days": "last_14_days",
"last 30 days": "last_30_days",
"past 30 days": "last_30_days",
"past month": "last_30_days",
}
# 星期映射 # 星期映射
WEEKDAY_CN = { WEEKDAY_CN = {
"": 0, "": 1, "": 2, "": 3, "": 0, "": 1, "": 2, "": 3,
@ -276,3 +326,182 @@ class DateParser:
f"日期太久远: {date.strftime('%Y-%m-%d')} ({days_ago}天前)", f"日期太久远: {date.strftime('%Y-%m-%d')} ({days_ago}天前)",
suggestion=f"请查询{max_days}天内的数据" suggestion=f"请查询{max_days}天内的数据"
) )
@staticmethod
def resolve_date_range_expression(expression: str) -> Dict:
"""
将自然语言日期表达式解析为标准日期范围
这是专门为 MCP 工具设计的方法用于在服务器端解析日期表达式
避免 AI 模型自己计算日期导致的不一致问题
Args:
expression: 自然语言日期表达式支持
- 单日: "今天", "昨天", "today", "yesterday"
- 本周/上周: "本周", "上周", "this week", "last week"
- 本月/上月: "本月", "上月", "this month", "last month"
- 最近N天: "最近7天", "最近30天", "last 7 days", "last 30 days"
- 动态N天: "最近5天", "last 10 days"
Returns:
解析结果字典
{
"success": True,
"expression": "本周",
"normalized": "this_week",
"date_range": {
"start": "2025-11-18",
"end": "2025-11-24"
},
"current_date": "2025-11-26",
"description": "本周(周一到周日)"
}
Raises:
InvalidParameterError: 无法识别的日期表达式
Examples:
>>> DateParser.resolve_date_range_expression("本周")
{"success": True, "date_range": {"start": "2025-11-18", "end": "2025-11-24"}, ...}
>>> DateParser.resolve_date_range_expression("最近7天")
{"success": True, "date_range": {"start": "2025-11-20", "end": "2025-11-26"}, ...}
"""
if not expression or not isinstance(expression, str):
raise InvalidParameterError(
"日期表达式不能为空",
suggestion="请提供有效的日期表达式本周、最近7天、last week"
)
expression_lower = expression.strip().lower()
today = datetime.now()
today_str = today.strftime("%Y-%m-%d")
# 1. 尝试匹配预定义表达式
normalized = DateParser.RANGE_EXPRESSIONS.get(expression_lower)
# 2. 尝试匹配动态 "最近N天" / "last N days" 模式
if not normalized:
# 中文: 最近N天
cn_match = re.match(r'最近(\d+)天', expression_lower)
if cn_match:
days = int(cn_match.group(1))
normalized = f"last_{days}_days"
# 英文: last N days
en_match = re.match(r'(?:last|past)\s+(\d+)\s+days?', expression_lower)
if en_match:
days = int(en_match.group(1))
normalized = f"last_{days}_days"
if not normalized:
# 提供支持的表达式列表
supported_cn = ["今天", "昨天", "本周", "上周", "本月", "上月",
"最近7天", "最近30天", "最近N天"]
supported_en = ["today", "yesterday", "this week", "last week",
"this month", "last month", "last 7 days", "last N days"]
raise InvalidParameterError(
f"无法识别的日期表达式: {expression}",
suggestion=f"支持的表达式:\n中文: {', '.join(supported_cn)}\n英文: {', '.join(supported_en)}"
)
# 3. 根据 normalized 类型计算日期范围
start_date, end_date, description = DateParser._calculate_date_range(
normalized, today
)
return {
"success": True,
"expression": expression,
"normalized": normalized,
"date_range": {
"start": start_date.strftime("%Y-%m-%d"),
"end": end_date.strftime("%Y-%m-%d")
},
"current_date": today_str,
"description": description
}
@staticmethod
def _calculate_date_range(
normalized: str,
today: datetime
) -> Tuple[datetime, datetime, str]:
"""
根据标准化的日期类型计算实际日期范围
Args:
normalized: 标准化的日期类型
today: 当前日期
Returns:
(start_date, end_date, description) 元组
"""
# 单日类型
if normalized == "today":
return today, today, "今天"
if normalized == "yesterday":
yesterday = today - timedelta(days=1)
return yesterday, yesterday, "昨天"
# 本周(周一到周日)
if normalized == "this_week":
# 计算本周一
weekday = today.weekday() # 0=周一, 6=周日
start = today - timedelta(days=weekday)
end = start + timedelta(days=6)
# 如果本周还没结束end 不能超过今天
if end > today:
end = today
return start, end, f"本周(周一到周日,{start.strftime('%m-%d')}{end.strftime('%m-%d')}"
# 上周(上周一到上周日)
if normalized == "last_week":
weekday = today.weekday()
# 本周一
this_monday = today - timedelta(days=weekday)
# 上周一
start = this_monday - timedelta(days=7)
end = start + timedelta(days=6)
return start, end, f"上周({start.strftime('%m-%d')}{end.strftime('%m-%d')}"
# 本月本月1日到今天
if normalized == "this_month":
start = today.replace(day=1)
return start, today, f"本月({start.strftime('%m-%d')}{today.strftime('%m-%d')}"
# 上月上月1日到上月最后一天
if normalized == "last_month":
# 上月最后一天 = 本月1日 - 1天
first_of_this_month = today.replace(day=1)
end = first_of_this_month - timedelta(days=1)
start = end.replace(day=1)
return start, end, f"上月({start.strftime('%Y-%m-%d')}{end.strftime('%Y-%m-%d')}"
# 最近N天 (last_N_days 格式)
match = re.match(r'last_(\d+)_days', normalized)
if match:
days = int(match.group(1))
start = today - timedelta(days=days - 1) # 包含今天,所以是 days-1
return start, today, f"最近{days}天({start.strftime('%m-%d')}{today.strftime('%m-%d')}"
# 兜底:返回今天
return today, today, "今天(默认)"
@staticmethod
def get_supported_expressions() -> Dict[str, list]:
"""
获取支持的日期表达式列表
Returns:
分类的表达式列表
"""
return {
"单日": ["今天", "昨天", "today", "yesterday"],
"": ["本周", "上周", "this week", "last week"],
"": ["本月", "上月", "this month", "last month"],
"最近N天": ["最近3天", "最近7天", "最近14天", "最近30天",
"last 3 days", "last 7 days", "last 14 days", "last 30 days"],
"动态天数": ["最近N天", "last N days"]
}

View File

@ -1,6 +1,6 @@
[project] [project]
name = "trendradar-mcp" name = "trendradar-mcp"
version = "1.0.1" version = "1.0.3"
description = "TrendRadar MCP Server - 新闻热点聚合工具" description = "TrendRadar MCP Server - 新闻热点聚合工具"
requires-python = ">=3.10" requires-python = ">=3.10"
dependencies = [ dependencies = [

View File

@ -1,9 +1,9 @@
@echo off @echo off
chcp 65001 >nul chcp 65001 >nul
echo ╔════════════════════════════════════════╗ echo ============================================================
echo TrendRadar MCP Server (HTTP 模式) echo TrendRadar MCP Server (HTTP 模式)
echo ╚════════════════════════════════════════╝ echo ============================================================
echo. echo.
REM 检查虚拟环境 REM 检查虚拟环境