server.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. """
  2. TrendRadar MCP Server - FastMCP 2.0 实现
  3. 使用 FastMCP 2.0 提供生产级 MCP 工具服务器。
  4. 支持 stdio 和 HTTP 两种传输模式。
  5. """
  6. import json
  7. from typing import List, Optional, Dict, Union
  8. from fastmcp import FastMCP
  9. from .tools.data_query import DataQueryTools
  10. from .tools.analytics import AnalyticsTools
  11. from .tools.search_tools import SearchTools
  12. from .tools.config_mgmt import ConfigManagementTools
  13. from .tools.system import SystemManagementTools
  14. from .tools.storage_sync import StorageSyncTools
  15. from .utils.date_parser import DateParser
  16. from .utils.errors import MCPError
  17. # 创建 FastMCP 2.0 应用
  18. mcp = FastMCP('trendradar-news')
  19. # 全局工具实例(在第一次请求时初始化)
  20. _tools_instances = {}
  21. def _get_tools(project_root: Optional[str] = None):
  22. """获取或创建工具实例(单例模式)"""
  23. if not _tools_instances:
  24. _tools_instances['data'] = DataQueryTools(project_root)
  25. _tools_instances['analytics'] = AnalyticsTools(project_root)
  26. _tools_instances['search'] = SearchTools(project_root)
  27. _tools_instances['config'] = ConfigManagementTools(project_root)
  28. _tools_instances['system'] = SystemManagementTools(project_root)
  29. _tools_instances['storage'] = StorageSyncTools(project_root)
  30. return _tools_instances
  31. # ==================== 日期解析工具(优先调用)====================
  32. @mcp.tool
  33. async def resolve_date_range(
  34. expression: str
  35. ) -> str:
  36. """
  37. 【推荐优先调用】将自然语言日期表达式解析为标准日期范围
  38. **为什么需要这个工具?**
  39. 用户经常使用"本周"、"最近7天"等自然语言表达日期,但 AI 模型自己计算日期
  40. 可能导致不一致的结果。此工具在服务器端使用精确的当前时间计算,确保所有
  41. AI 模型获得一致的日期范围。
  42. **推荐使用流程:**
  43. 1. 用户说"分析AI本周的情感倾向"
  44. 2. AI 调用 resolve_date_range("本周") → 获取精确日期范围
  45. 3. AI 调用 analyze_sentiment(topic="ai", date_range=上一步返回的date_range)
  46. Args:
  47. expression: 自然语言日期表达式,支持:
  48. - 单日: "今天", "昨天", "today", "yesterday"
  49. - 周: "本周", "上周", "this week", "last week"
  50. - 月: "本月", "上月", "this month", "last month"
  51. - 最近N天: "最近7天", "最近30天", "last 7 days", "last 30 days"
  52. - 动态: "最近5天", "last 10 days"(任意天数)
  53. Returns:
  54. JSON格式的日期范围,可直接用于其他工具的 date_range 参数:
  55. {
  56. "success": true,
  57. "expression": "本周",
  58. "date_range": {
  59. "start": "2025-11-18",
  60. "end": "2025-11-26"
  61. },
  62. "current_date": "2025-11-26",
  63. "description": "本周(周一到周日,11-18 至 11-26)"
  64. }
  65. Examples:
  66. 用户:"分析AI本周的情感倾向"
  67. AI调用步骤:
  68. 1. resolve_date_range("本周")
  69. → {"date_range": {"start": "2025-11-18", "end": "2025-11-26"}, ...}
  70. 2. analyze_sentiment(topic="ai", date_range={"start": "2025-11-18", "end": "2025-11-26"})
  71. 用户:"看看最近7天的特斯拉新闻"
  72. AI调用步骤:
  73. 1. resolve_date_range("最近7天")
  74. → {"date_range": {"start": "2025-11-20", "end": "2025-11-26"}, ...}
  75. 2. search_news(query="特斯拉", date_range={"start": "2025-11-20", "end": "2025-11-26"})
  76. """
  77. try:
  78. result = DateParser.resolve_date_range_expression(expression)
  79. return json.dumps(result, ensure_ascii=False, indent=2)
  80. except MCPError as e:
  81. return json.dumps({
  82. "success": False,
  83. "error": e.to_dict()
  84. }, ensure_ascii=False, indent=2)
  85. except Exception as e:
  86. return json.dumps({
  87. "success": False,
  88. "error": {
  89. "code": "INTERNAL_ERROR",
  90. "message": str(e)
  91. }
  92. }, ensure_ascii=False, indent=2)
  93. # ==================== 数据查询工具 ====================
  94. @mcp.tool
  95. async def get_latest_news(
  96. platforms: Optional[List[str]] = None,
  97. limit: int = 50,
  98. include_url: bool = False
  99. ) -> str:
  100. """
  101. 获取最新一批爬取的新闻数据,快速了解当前热点
  102. Args:
  103. platforms: 平台ID列表,如 ['zhihu', 'weibo', 'douyin']
  104. - 不指定时:使用 config.yaml 中配置的所有平台
  105. - 支持的平台来自 config/config.yaml 的 platforms 配置
  106. - 每个平台都有对应的name字段(如"知乎"、"微博"),方便AI识别
  107. limit: 返回条数限制,默认50,最大1000
  108. 注意:实际返回数量可能少于请求值,取决于当前可用的新闻总数
  109. include_url: 是否包含URL链接,默认False(节省token)
  110. Returns:
  111. JSON格式的新闻列表
  112. **重要:数据展示建议**
  113. 本工具会返回完整的新闻列表(通常50条)给你。但请注意:
  114. - **工具返回**:完整的50条数据 ✅
  115. - **建议展示**:向用户展示全部数据,除非用户明确要求总结
  116. - **用户期望**:用户可能需要完整数据,请谨慎总结
  117. **何时可以总结**:
  118. - 用户明确说"给我总结一下"或"挑重点说"
  119. - 数据量超过100条时,可先展示部分并询问是否查看全部
  120. **注意**:如果用户询问"为什么只显示了部分",说明他们需要完整数据
  121. """
  122. tools = _get_tools()
  123. result = tools['data'].get_latest_news(platforms=platforms, limit=limit, include_url=include_url)
  124. return json.dumps(result, ensure_ascii=False, indent=2)
  125. @mcp.tool
  126. async def get_trending_topics(
  127. top_n: int = 10,
  128. mode: str = 'current'
  129. ) -> str:
  130. """
  131. 获取个人关注词的新闻出现频率统计(基于 config/frequency_words.txt)
  132. 注意:本工具不是自动提取新闻热点,而是统计你在 config/frequency_words.txt 中
  133. 设置的个人关注词在新闻中出现的频率。你可以自定义这个关注词列表。
  134. Args:
  135. top_n: 返回TOP N关注词,默认10
  136. mode: 模式选择
  137. - daily: 当日累计数据统计
  138. - current: 最新一批数据统计(默认)
  139. Returns:
  140. JSON格式的关注词频率统计列表
  141. """
  142. tools = _get_tools()
  143. result = tools['data'].get_trending_topics(top_n=top_n, mode=mode)
  144. return json.dumps(result, ensure_ascii=False, indent=2)
  145. @mcp.tool
  146. async def get_news_by_date(
  147. date_query: Optional[str] = None,
  148. platforms: Optional[List[str]] = None,
  149. limit: int = 50,
  150. include_url: bool = False
  151. ) -> str:
  152. """
  153. 获取指定日期的新闻数据,用于历史数据分析和对比
  154. Args:
  155. date_query: 日期查询,可选格式:
  156. - 自然语言: "今天", "昨天", "前天", "3天前"
  157. - 标准日期: "2024-01-15", "2024/01/15"
  158. - 默认值: "今天"(节省token)
  159. platforms: 平台ID列表,如 ['zhihu', 'weibo', 'douyin']
  160. - 不指定时:使用 config.yaml 中配置的所有平台
  161. - 支持的平台来自 config/config.yaml 的 platforms 配置
  162. - 每个平台都有对应的name字段(如"知乎"、"微博"),方便AI识别
  163. limit: 返回条数限制,默认50,最大1000
  164. 注意:实际返回数量可能少于请求值,取决于指定日期的新闻总数
  165. include_url: 是否包含URL链接,默认False(节省token)
  166. Returns:
  167. JSON格式的新闻列表,包含标题、平台、排名等信息
  168. **重要:数据展示建议**
  169. 本工具会返回完整的新闻列表(通常50条)给你。但请注意:
  170. - **工具返回**:完整的50条数据 ✅
  171. - **建议展示**:向用户展示全部数据,除非用户明确要求总结
  172. - **用户期望**:用户可能需要完整数据,请谨慎总结
  173. **何时可以总结**:
  174. - 用户明确说"给我总结一下"或"挑重点说"
  175. - 数据量超过100条时,可先展示部分并询问是否查看全部
  176. **注意**:如果用户询问"为什么只显示了部分",说明他们需要完整数据
  177. """
  178. tools = _get_tools()
  179. result = tools['data'].get_news_by_date(
  180. date_query=date_query,
  181. platforms=platforms,
  182. limit=limit,
  183. include_url=include_url
  184. )
  185. return json.dumps(result, ensure_ascii=False, indent=2)
  186. # ==================== 高级数据分析工具 ====================
  187. @mcp.tool
  188. async def analyze_topic_trend(
  189. topic: str,
  190. analysis_type: str = "trend",
  191. date_range: Optional[Union[Dict[str, str], str]] = None,
  192. granularity: str = "day",
  193. threshold: float = 3.0,
  194. time_window: int = 24,
  195. lookahead_hours: int = 6,
  196. confidence_threshold: float = 0.7
  197. ) -> str:
  198. """
  199. 统一话题趋势分析工具 - 整合多种趋势分析模式
  200. **重要:日期范围处理**
  201. 当用户使用"本周"、"最近7天"等自然语言时,请先调用 resolve_date_range 工具获取精确日期:
  202. 1. 调用 resolve_date_range("本周") → 获取 {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
  203. 2. 将返回的 date_range 传入本工具
  204. Args:
  205. topic: 话题关键词(必需)
  206. analysis_type: 分析类型,可选值:
  207. - "trend": 热度趋势分析(追踪话题的热度变化)
  208. - "lifecycle": 生命周期分析(从出现到消失的完整周期)
  209. - "viral": 异常热度检测(识别突然爆火的话题)
  210. - "predict": 话题预测(预测未来可能的热点)
  211. date_range: 日期范围(trend和lifecycle模式),可选
  212. - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
  213. - **获取方式**: 调用 resolve_date_range 工具解析自然语言日期
  214. - **默认**: 不指定时默认分析最近7天
  215. granularity: 时间粒度(trend模式),默认"day"(仅支持 day,因为底层数据按天聚合)
  216. threshold: 热度突增倍数阈值(viral模式),默认3.0
  217. time_window: 检测时间窗口小时数(viral模式),默认24
  218. lookahead_hours: 预测未来小时数(predict模式),默认6
  219. confidence_threshold: 置信度阈值(predict模式),默认0.7
  220. Returns:
  221. JSON格式的趋势分析结果
  222. Examples:
  223. 用户:"分析AI本周的趋势"
  224. 推荐调用流程:
  225. 1. resolve_date_range("本周") → {"date_range": {"start": "2025-11-18", "end": "2025-11-26"}}
  226. 2. analyze_topic_trend(topic="AI", date_range={"start": "2025-11-18", "end": "2025-11-26"})
  227. 用户:"看看特斯拉最近30天的热度"
  228. 推荐调用流程:
  229. 1. resolve_date_range("最近30天") → {"date_range": {"start": "2025-10-28", "end": "2025-11-26"}}
  230. 2. analyze_topic_trend(topic="特斯拉", analysis_type="lifecycle", date_range=...)
  231. """
  232. tools = _get_tools()
  233. result = tools['analytics'].analyze_topic_trend_unified(
  234. topic=topic,
  235. analysis_type=analysis_type,
  236. date_range=date_range,
  237. granularity=granularity,
  238. threshold=threshold,
  239. time_window=time_window,
  240. lookahead_hours=lookahead_hours,
  241. confidence_threshold=confidence_threshold
  242. )
  243. return json.dumps(result, ensure_ascii=False, indent=2)
  244. @mcp.tool
  245. async def analyze_data_insights(
  246. insight_type: str = "platform_compare",
  247. topic: Optional[str] = None,
  248. date_range: Optional[Union[Dict[str, str], str]] = None,
  249. min_frequency: int = 3,
  250. top_n: int = 20
  251. ) -> str:
  252. """
  253. 统一数据洞察分析工具 - 整合多种数据分析模式
  254. Args:
  255. insight_type: 洞察类型,可选值:
  256. - "platform_compare": 平台对比分析(对比不同平台对话题的关注度)
  257. - "platform_activity": 平台活跃度统计(统计各平台发布频率和活跃时间)
  258. - "keyword_cooccur": 关键词共现分析(分析关键词同时出现的模式)
  259. topic: 话题关键词(可选,platform_compare模式适用)
  260. date_range: **【对象类型】** 日期范围(可选)
  261. - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
  262. - **示例**: {"start": "2025-01-01", "end": "2025-01-07"}
  263. - **重要**: 必须是对象格式,不能传递整数
  264. min_frequency: 最小共现频次(keyword_cooccur模式),默认3
  265. top_n: 返回TOP N结果(keyword_cooccur模式),默认20
  266. Returns:
  267. JSON格式的数据洞察分析结果
  268. Examples:
  269. - analyze_data_insights(insight_type="platform_compare", topic="人工智能")
  270. - analyze_data_insights(insight_type="platform_activity", date_range={"start": "2025-01-01", "end": "2025-01-07"})
  271. - analyze_data_insights(insight_type="keyword_cooccur", min_frequency=5, top_n=15)
  272. """
  273. tools = _get_tools()
  274. result = tools['analytics'].analyze_data_insights_unified(
  275. insight_type=insight_type,
  276. topic=topic,
  277. date_range=date_range,
  278. min_frequency=min_frequency,
  279. top_n=top_n
  280. )
  281. return json.dumps(result, ensure_ascii=False, indent=2)
  282. @mcp.tool
  283. async def analyze_sentiment(
  284. topic: Optional[str] = None,
  285. platforms: Optional[List[str]] = None,
  286. date_range: Optional[Union[Dict[str, str], str]] = None,
  287. limit: int = 50,
  288. sort_by_weight: bool = True,
  289. include_url: bool = False
  290. ) -> str:
  291. """
  292. 分析新闻的情感倾向和热度趋势
  293. **重要:日期范围处理**
  294. 当用户使用"本周"、"最近7天"等自然语言时,请先调用 resolve_date_range 工具获取精确日期:
  295. 1. 调用 resolve_date_range("本周") → 获取 {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
  296. 2. 将返回的 date_range 传入本工具
  297. Args:
  298. topic: 话题关键词(可选)
  299. platforms: 平台ID列表,如 ['zhihu', 'weibo', 'douyin']
  300. - 不指定时:使用 config.yaml 中配置的所有平台
  301. - 支持的平台来自 config/config.yaml 的 platforms 配置
  302. - 每个平台都有对应的name字段(如"知乎"、"微博"),方便AI识别
  303. date_range: 日期范围(可选)
  304. - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
  305. - **获取方式**: 调用 resolve_date_range 工具解析自然语言日期
  306. - **默认**: 不指定则默认查询今天的数据
  307. limit: 返回新闻数量,默认50,最大100
  308. 注意:本工具会对新闻标题进行去重(同一标题在不同平台只保留一次),
  309. 因此实际返回数量可能少于请求的 limit 值
  310. sort_by_weight: 是否按热度权重排序,默认True
  311. include_url: 是否包含URL链接,默认False(节省token)
  312. Returns:
  313. JSON格式的分析结果,包含情感分布、热度趋势和相关新闻
  314. Examples:
  315. 用户:"分析AI本周的情感倾向"
  316. 推荐调用流程:
  317. 1. resolve_date_range("本周") → {"date_range": {"start": "2025-11-18", "end": "2025-11-26"}}
  318. 2. analyze_sentiment(topic="AI", date_range={"start": "2025-11-18", "end": "2025-11-26"})
  319. 用户:"分析特斯拉最近7天的新闻情感"
  320. 推荐调用流程:
  321. 1. resolve_date_range("最近7天") → {"date_range": {"start": "2025-11-20", "end": "2025-11-26"}}
  322. 2. analyze_sentiment(topic="特斯拉", date_range={"start": "2025-11-20", "end": "2025-11-26"})
  323. **重要:数据展示策略**
  324. - 本工具返回完整的分析结果和新闻列表
  325. - **默认展示方式**:展示完整的分析结果(包括所有新闻)
  326. - 仅在用户明确要求"总结"或"挑重点"时才进行筛选
  327. """
  328. tools = _get_tools()
  329. result = tools['analytics'].analyze_sentiment(
  330. topic=topic,
  331. platforms=platforms,
  332. date_range=date_range,
  333. limit=limit,
  334. sort_by_weight=sort_by_weight,
  335. include_url=include_url
  336. )
  337. return json.dumps(result, ensure_ascii=False, indent=2)
  338. @mcp.tool
  339. async def find_similar_news(
  340. reference_title: str,
  341. threshold: float = 0.6,
  342. limit: int = 50,
  343. include_url: bool = False
  344. ) -> str:
  345. """
  346. 查找与指定新闻标题相似的其他新闻
  347. Args:
  348. reference_title: 新闻标题(完整或部分)
  349. threshold: 相似度阈值,0-1之间,默认0.6
  350. 注意:阈值越高匹配越严格,返回结果越少
  351. limit: 返回条数限制,默认50,最大100
  352. 注意:实际返回数量取决于相似度匹配结果,可能少于请求值
  353. include_url: 是否包含URL链接,默认False(节省token)
  354. Returns:
  355. JSON格式的相似新闻列表,包含相似度分数
  356. **重要:数据展示策略**
  357. - 本工具返回完整的相似新闻列表
  358. - **默认展示方式**:展示全部返回的新闻(包括相似度分数)
  359. - 仅在用户明确要求"总结"或"挑重点"时才进行筛选
  360. """
  361. tools = _get_tools()
  362. result = tools['analytics'].find_similar_news(
  363. reference_title=reference_title,
  364. threshold=threshold,
  365. limit=limit,
  366. include_url=include_url
  367. )
  368. return json.dumps(result, ensure_ascii=False, indent=2)
  369. @mcp.tool
  370. async def generate_summary_report(
  371. report_type: str = "daily",
  372. date_range: Optional[Union[Dict[str, str], str]] = None
  373. ) -> str:
  374. """
  375. 每日/每周摘要生成器 - 自动生成热点摘要报告
  376. Args:
  377. report_type: 报告类型(daily/weekly)
  378. date_range: **【对象类型】** 自定义日期范围(可选)
  379. - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
  380. - **示例**: {"start": "2025-01-01", "end": "2025-01-07"}
  381. - **重要**: 必须是对象格式,不能传递整数
  382. Returns:
  383. JSON格式的摘要报告,包含Markdown格式内容
  384. """
  385. tools = _get_tools()
  386. result = tools['analytics'].generate_summary_report(
  387. report_type=report_type,
  388. date_range=date_range
  389. )
  390. return json.dumps(result, ensure_ascii=False, indent=2)
  391. # ==================== 智能检索工具 ====================
  392. @mcp.tool
  393. async def search_news(
  394. query: str,
  395. search_mode: str = "keyword",
  396. date_range: Optional[Union[Dict[str, str], str]] = None,
  397. platforms: Optional[List[str]] = None,
  398. limit: int = 50,
  399. sort_by: str = "relevance",
  400. threshold: float = 0.6,
  401. include_url: bool = False
  402. ) -> str:
  403. """
  404. 统一搜索接口,支持多种搜索模式
  405. **重要:日期范围处理**
  406. 当用户使用"本周"、"最近7天"等自然语言时,请先调用 resolve_date_range 工具获取精确日期:
  407. 1. 调用 resolve_date_range("本周") → 获取 {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
  408. 2. 将返回的 date_range 传入本工具
  409. Args:
  410. query: 搜索关键词或内容片段
  411. search_mode: 搜索模式,可选值:
  412. - "keyword": 精确关键词匹配(默认,适合搜索特定话题)
  413. - "fuzzy": 模糊内容匹配(适合搜索内容片段,会过滤相似度低于阈值的结果)
  414. - "entity": 实体名称搜索(适合搜索人物/地点/机构)
  415. date_range: 日期范围(可选)
  416. - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
  417. - **获取方式**: 调用 resolve_date_range 工具解析自然语言日期
  418. - **默认**: 不指定时默认查询今天的新闻
  419. platforms: 平台ID列表,如 ['zhihu', 'weibo', 'douyin']
  420. - 不指定时:使用 config.yaml 中配置的所有平台
  421. - 支持的平台来自 config/config.yaml 的 platforms 配置
  422. - 每个平台都有对应的name字段(如"知乎"、"微博"),方便AI识别
  423. limit: 返回条数限制,默认50,最大1000
  424. 注意:实际返回数量取决于搜索匹配结果(特别是 fuzzy 模式下会过滤低相似度结果)
  425. sort_by: 排序方式,可选值:
  426. - "relevance": 按相关度排序(默认)
  427. - "weight": 按新闻权重排序
  428. - "date": 按日期排序
  429. threshold: 相似度阈值(仅fuzzy模式有效),0-1之间,默认0.6
  430. 注意:阈值越高匹配越严格,返回结果越少
  431. include_url: 是否包含URL链接,默认False(节省token)
  432. Returns:
  433. JSON格式的搜索结果,包含标题、平台、排名等信息
  434. Examples:
  435. 用户:"搜索本周的AI新闻"
  436. 推荐调用流程:
  437. 1. resolve_date_range("本周") → {"date_range": {"start": "2025-11-18", "end": "2025-11-26"}}
  438. 2. search_news(query="AI", date_range={"start": "2025-11-18", "end": "2025-11-26"})
  439. 用户:"最近7天的特斯拉新闻"
  440. 推荐调用流程:
  441. 1. resolve_date_range("最近7天") → {"date_range": {"start": "2025-11-20", "end": "2025-11-26"}}
  442. 2. search_news(query="特斯拉", date_range={"start": "2025-11-20", "end": "2025-11-26"})
  443. 用户:"今天的AI新闻"(默认今天,无需解析)
  444. → search_news(query="AI")
  445. **重要:数据展示策略**
  446. - 本工具返回完整的搜索结果列表
  447. - **默认展示方式**:展示全部返回的新闻,无需总结或筛选
  448. - 仅在用户明确要求"总结"或"挑重点"时才进行筛选
  449. """
  450. tools = _get_tools()
  451. result = tools['search'].search_news_unified(
  452. query=query,
  453. search_mode=search_mode,
  454. date_range=date_range,
  455. platforms=platforms,
  456. limit=limit,
  457. sort_by=sort_by,
  458. threshold=threshold,
  459. include_url=include_url
  460. )
  461. return json.dumps(result, ensure_ascii=False, indent=2)
  462. @mcp.tool
  463. async def search_related_news_history(
  464. reference_text: str,
  465. time_preset: str = "yesterday",
  466. threshold: float = 0.4,
  467. limit: int = 50,
  468. include_url: bool = False
  469. ) -> str:
  470. """
  471. 基于种子新闻,在历史数据中搜索相关新闻
  472. Args:
  473. reference_text: 参考新闻标题(完整或部分)
  474. time_preset: 时间范围预设值,可选:
  475. - "yesterday": 昨天
  476. - "last_week": 上周 (7天)
  477. - "last_month": 上个月 (30天)
  478. - "custom": 自定义日期范围(需要提供 start_date 和 end_date)
  479. threshold: 相关性阈值,0-1之间,默认0.4
  480. 注意:综合相似度计算(70%关键词重合 + 30%文本相似度)
  481. 阈值越高匹配越严格,返回结果越少
  482. limit: 返回条数限制,默认50,最大100
  483. 注意:实际返回数量取决于相关性匹配结果,可能少于请求值
  484. include_url: 是否包含URL链接,默认False(节省token)
  485. Returns:
  486. JSON格式的相关新闻列表,包含相关性分数和时间分布
  487. **重要:数据展示策略**
  488. - 本工具返回完整的相关新闻列表
  489. - **默认展示方式**:展示全部返回的新闻(包括相关性分数)
  490. - 仅在用户明确要求"总结"或"挑重点"时才进行筛选
  491. """
  492. tools = _get_tools()
  493. result = tools['search'].search_related_news_history(
  494. reference_text=reference_text,
  495. time_preset=time_preset,
  496. threshold=threshold,
  497. limit=limit,
  498. include_url=include_url
  499. )
  500. return json.dumps(result, ensure_ascii=False, indent=2)
  501. # ==================== 配置与系统管理工具 ====================
  502. @mcp.tool
  503. async def get_current_config(
  504. section: str = "all"
  505. ) -> str:
  506. """
  507. 获取当前系统配置
  508. Args:
  509. section: 配置节,可选值:
  510. - "all": 所有配置(默认)
  511. - "crawler": 爬虫配置
  512. - "push": 推送配置
  513. - "keywords": 关键词配置
  514. - "weights": 权重配置
  515. Returns:
  516. JSON格式的配置信息
  517. """
  518. tools = _get_tools()
  519. result = tools['config'].get_current_config(section=section)
  520. return json.dumps(result, ensure_ascii=False, indent=2)
  521. @mcp.tool
  522. async def get_system_status() -> str:
  523. """
  524. 获取系统运行状态和健康检查信息
  525. 返回系统版本、数据统计、缓存状态等信息
  526. Returns:
  527. JSON格式的系统状态信息
  528. """
  529. tools = _get_tools()
  530. result = tools['system'].get_system_status()
  531. return json.dumps(result, ensure_ascii=False, indent=2)
  532. @mcp.tool
  533. async def trigger_crawl(
  534. platforms: Optional[List[str]] = None,
  535. save_to_local: bool = False,
  536. include_url: bool = False
  537. ) -> str:
  538. """
  539. 手动触发一次爬取任务(可选持久化)
  540. Args:
  541. platforms: 指定平台ID列表,如 ['zhihu', 'weibo', 'douyin']
  542. - 不指定时:使用 config.yaml 中配置的所有平台
  543. - 支持的平台来自 config/config.yaml 的 platforms 配置
  544. - 每个平台都有对应的name字段(如"知乎"、"微博"),方便AI识别
  545. - 注意:失败的平台会在返回结果的 failed_platforms 字段中列出
  546. save_to_local: 是否保存到本地 output 目录,默认 False
  547. include_url: 是否包含URL链接,默认False(节省token)
  548. Returns:
  549. JSON格式的任务状态信息,包含:
  550. - platforms: 成功爬取的平台列表
  551. - failed_platforms: 失败的平台列表(如有)
  552. - total_news: 爬取的新闻总数
  553. - data: 新闻数据
  554. Examples:
  555. - 临时爬取: trigger_crawl(platforms=['zhihu'])
  556. - 爬取并保存: trigger_crawl(platforms=['weibo'], save_to_local=True)
  557. - 使用默认平台: trigger_crawl() # 爬取config.yaml中配置的所有平台
  558. """
  559. tools = _get_tools()
  560. result = tools['system'].trigger_crawl(platforms=platforms, save_to_local=save_to_local, include_url=include_url)
  561. return json.dumps(result, ensure_ascii=False, indent=2)
  562. # ==================== 存储同步工具 ====================
  563. @mcp.tool
  564. async def sync_from_remote(
  565. days: int = 7
  566. ) -> str:
  567. """
  568. 从远程存储拉取数据到本地
  569. 用于 MCP Server 等场景:爬虫存到远程云存储(如 Cloudflare R2),
  570. MCP Server 拉取到本地进行分析查询。
  571. Args:
  572. days: 拉取最近 N 天的数据,默认 7 天
  573. - 0: 不拉取
  574. - 7: 拉取最近一周的数据
  575. - 30: 拉取最近一个月的数据
  576. Returns:
  577. JSON格式的同步结果,包含:
  578. - success: 是否成功
  579. - synced_files: 成功同步的文件数量
  580. - synced_dates: 成功同步的日期列表
  581. - skipped_dates: 跳过的日期(本地已存在)
  582. - failed_dates: 失败的日期及错误信息
  583. - message: 操作结果描述
  584. Examples:
  585. - sync_from_remote() # 拉取最近7天
  586. - sync_from_remote(days=30) # 拉取最近30天
  587. Note:
  588. 需要在 config/config.yaml 中配置远程存储(storage.remote)或设置环境变量:
  589. - S3_ENDPOINT_URL: 服务端点
  590. - S3_BUCKET_NAME: 存储桶名称
  591. - S3_ACCESS_KEY_ID: 访问密钥 ID
  592. - S3_SECRET_ACCESS_KEY: 访问密钥
  593. """
  594. tools = _get_tools()
  595. result = tools['storage'].sync_from_remote(days=days)
  596. return json.dumps(result, ensure_ascii=False, indent=2)
  597. @mcp.tool
  598. async def get_storage_status() -> str:
  599. """
  600. 获取存储配置和状态
  601. 查看当前存储后端配置、本地和远程存储的状态信息。
  602. Returns:
  603. JSON格式的存储状态信息,包含:
  604. - backend: 当前使用的后端类型(local/remote/auto)
  605. - local: 本地存储状态
  606. - data_dir: 数据目录
  607. - retention_days: 保留天数
  608. - total_size: 总大小
  609. - date_count: 日期数量
  610. - earliest_date: 最早日期
  611. - latest_date: 最新日期
  612. - remote: 远程存储状态
  613. - configured: 是否已配置
  614. - endpoint_url: 服务端点
  615. - bucket_name: 存储桶名称
  616. - date_count: 远程日期数量
  617. - pull: 拉取配置
  618. - enabled: 是否启用自动拉取
  619. - days: 自动拉取天数
  620. Examples:
  621. - get_storage_status() # 查看所有存储状态
  622. """
  623. tools = _get_tools()
  624. result = tools['storage'].get_storage_status()
  625. return json.dumps(result, ensure_ascii=False, indent=2)
  626. @mcp.tool
  627. async def list_available_dates(
  628. source: str = "both"
  629. ) -> str:
  630. """
  631. 列出本地/远程可用的日期范围
  632. 查看本地和远程存储中有哪些日期的数据可用,
  633. 帮助了解数据覆盖范围和同步状态。
  634. Args:
  635. source: 数据来源,可选值:
  636. - "local": 仅列出本地可用日期
  637. - "remote": 仅列出远程可用日期
  638. - "both": 同时列出两者并进行对比(默认)
  639. Returns:
  640. JSON格式的日期列表,包含:
  641. - local: 本地日期信息(如果 source 包含 local)
  642. - dates: 日期列表(按时间倒序)
  643. - count: 日期数量
  644. - earliest: 最早日期
  645. - latest: 最新日期
  646. - remote: 远程日期信息(如果 source 包含 remote)
  647. - configured: 是否已配置远程存储
  648. - dates: 日期列表
  649. - count: 日期数量
  650. - earliest: 最早日期
  651. - latest: 最新日期
  652. - comparison: 对比结果(仅当 source="both" 时)
  653. - only_local: 仅本地存在的日期
  654. - only_remote: 仅远程存在的日期
  655. - both: 两边都存在的日期
  656. Examples:
  657. - list_available_dates() # 查看本地和远程的对比
  658. - list_available_dates(source="local") # 仅查看本地
  659. - list_available_dates(source="remote") # 仅查看远程
  660. """
  661. tools = _get_tools()
  662. result = tools['storage'].list_available_dates(source=source)
  663. return json.dumps(result, ensure_ascii=False, indent=2)
  664. # ==================== 启动入口 ====================
  665. def run_server(
  666. project_root: Optional[str] = None,
  667. transport: str = 'stdio',
  668. host: str = '0.0.0.0',
  669. port: int = 3333
  670. ):
  671. """
  672. 启动 MCP 服务器
  673. Args:
  674. project_root: 项目根目录路径
  675. transport: 传输模式,'stdio' 或 'http'
  676. host: HTTP模式的监听地址,默认 0.0.0.0
  677. port: HTTP模式的监听端口,默认 3333
  678. """
  679. # 初始化工具实例
  680. _get_tools(project_root)
  681. # 打印启动信息
  682. print()
  683. print("=" * 60)
  684. print(" TrendRadar MCP Server - FastMCP 2.0")
  685. print("=" * 60)
  686. print(f" 传输模式: {transport.upper()}")
  687. if transport == 'stdio':
  688. print(" 协议: MCP over stdio (标准输入输出)")
  689. print(" 说明: 通过标准输入输出与 MCP 客户端通信")
  690. elif transport == 'http':
  691. print(f" 协议: MCP over HTTP (生产环境)")
  692. print(f" 服务器监听: {host}:{port}")
  693. if project_root:
  694. print(f" 项目目录: {project_root}")
  695. else:
  696. print(" 项目目录: 当前目录")
  697. print()
  698. print(" 已注册的工具:")
  699. print(" === 日期解析工具(推荐优先调用)===")
  700. print(" 0. resolve_date_range - 解析自然语言日期为标准格式")
  701. print()
  702. print(" === 基础数据查询(P0核心)===")
  703. print(" 1. get_latest_news - 获取最新新闻")
  704. print(" 2. get_news_by_date - 按日期查询新闻(支持自然语言)")
  705. print(" 3. get_trending_topics - 获取趋势话题")
  706. print()
  707. print(" === 智能检索工具 ===")
  708. print(" 4. search_news - 统一新闻搜索(关键词/模糊/实体)")
  709. print(" 5. search_related_news_history - 历史相关新闻检索")
  710. print()
  711. print(" === 高级数据分析 ===")
  712. print(" 6. analyze_topic_trend - 统一话题趋势分析(热度/生命周期/爆火/预测)")
  713. print(" 7. analyze_data_insights - 统一数据洞察分析(平台对比/活跃度/关键词共现)")
  714. print(" 8. analyze_sentiment - 情感倾向分析")
  715. print(" 9. find_similar_news - 相似新闻查找")
  716. print(" 10. generate_summary_report - 每日/每周摘要生成")
  717. print()
  718. print(" === 配置与系统管理 ===")
  719. print(" 11. get_current_config - 获取当前系统配置")
  720. print(" 12. get_system_status - 获取系统运行状态")
  721. print(" 13. trigger_crawl - 手动触发爬取任务")
  722. print()
  723. print(" === 存储同步工具 ===")
  724. print(" 14. sync_from_remote - 从远程存储拉取数据到本地")
  725. print(" 15. get_storage_status - 获取存储配置和状态")
  726. print(" 16. list_available_dates - 列出本地/远程可用日期")
  727. print("=" * 60)
  728. print()
  729. # 根据传输模式运行服务器
  730. if transport == 'stdio':
  731. mcp.run(transport='stdio')
  732. elif transport == 'http':
  733. # HTTP 模式(生产推荐)
  734. mcp.run(
  735. transport='http',
  736. host=host,
  737. port=port,
  738. path='/mcp' # HTTP 端点路径
  739. )
  740. else:
  741. raise ValueError(f"不支持的传输模式: {transport}")
  742. if __name__ == '__main__':
  743. import argparse
  744. parser = argparse.ArgumentParser(
  745. description='TrendRadar MCP Server - 新闻热点聚合 MCP 工具服务器',
  746. formatter_class=argparse.RawDescriptionHelpFormatter,
  747. epilog="""
  748. 详细配置教程请查看: README-Cherry-Studio.md
  749. """
  750. )
  751. parser.add_argument(
  752. '--transport',
  753. choices=['stdio', 'http'],
  754. default='stdio',
  755. help='传输模式:stdio (默认) 或 http (生产环境)'
  756. )
  757. parser.add_argument(
  758. '--host',
  759. default='0.0.0.0',
  760. help='HTTP模式的监听地址,默认 0.0.0.0'
  761. )
  762. parser.add_argument(
  763. '--port',
  764. type=int,
  765. default=3333,
  766. help='HTTP模式的监听端口,默认 3333'
  767. )
  768. parser.add_argument(
  769. '--project-root',
  770. help='项目根目录路径'
  771. )
  772. args = parser.parse_args()
  773. run_server(
  774. project_root=args.project_root,
  775. transport=args.transport,
  776. host=args.host,
  777. port=args.port
  778. )