mcp_server_fastmcp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. from __future__ import annotations
  2. from fastapi import FastAPI
  3. from mcp.server.fastmcp import FastMCP
  4. from mcp.server.transport_security import TransportSecuritySettings
  5. from news_mcp.config import CLUSTERS_TTL_HOURS, DEFAULT_TOPICS, DB_PATH
  6. from news_mcp.config import NEWS_REFRESH_INTERVAL_SECONDS, NEWS_BACKGROUND_REFRESH_ENABLED, NEWS_BACKGROUND_REFRESH_ON_START
  7. from news_mcp.jobs.poller import refresh_clusters
  8. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  9. from news_mcp.enrichment.llm_enrich import summarize_cluster_groq
  10. from news_mcp.trends_resolution import resolve_entity_via_trends
  11. from news_mcp.llm import active_llm_config
  12. from news_mcp.entity_normalize import normalize_query
  13. from collections import Counter
  14. import logging
  15. mcp = FastMCP(
  16. "news-mcp",
  17. transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False),
  18. )
  19. def _cluster_entity_haystack(cluster: dict) -> list[str]:
  20. """Collect the normalized entity clues attached to a cluster."""
  21. values: list[str] = []
  22. for ent in cluster.get("entities", []) or []:
  23. values.append(str(ent).strip().lower())
  24. for res in cluster.get("entityResolutions", []) or []:
  25. if not isinstance(res, dict):
  26. continue
  27. for key in ("normalized", "canonical_label", "mid"):
  28. val = res.get(key)
  29. if val:
  30. values.append(str(val).strip().lower())
  31. return [v for v in values if v]
  32. @mcp.tool(description="What is happening right now? Return the latest deduplicated news clusters for a topic.")
  33. async def get_latest_events(topic: str = "crypto", limit: int = 5, include_articles: bool = False):
  34. limit = max(1, min(int(limit), 20))
  35. # If the caller passes an entity-like value, resolve it and use the canonical
  36. # entity as the query lens. Otherwise keep the original topic path.
  37. topic_norm = normalize_query(topic).lower()
  38. resolved = resolve_entity_via_trends(topic_norm)
  39. allowed = {t.lower() for t in DEFAULT_TOPICS}
  40. is_topic = topic_norm in allowed
  41. query_terms = {
  42. topic_norm,
  43. str(resolved.get("normalized") or "").strip().lower(),
  44. str(resolved.get("canonical_label") or "").strip().lower(),
  45. str(resolved.get("mid") or "").strip().lower(),
  46. }
  47. query_terms = {q for q in query_terms if q}
  48. store = SQLiteClusterStore(DB_PATH)
  49. if is_topic:
  50. # Cache-first: only refresh if we currently have no fresh clusters for this topic.
  51. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=CLUSTERS_TTL_HOURS, limit=limit)
  52. if not clusters:
  53. await refresh_clusters(topic=topic_norm, limit=200)
  54. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=CLUSTERS_TTL_HOURS, limit=limit)
  55. else:
  56. # Entity-aware mode: search recent clusters across all topics and match by
  57. # raw entity, canonical label, or MID.
  58. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=limit * 8)
  59. filtered = []
  60. for c in clusters:
  61. haystack = _cluster_entity_haystack(c)
  62. if any(any(term in item for item in haystack) for term in query_terms):
  63. filtered.append(c)
  64. if len(filtered) >= limit:
  65. break
  66. clusters = filtered
  67. # Ensure the response is compact and agent-friendly.
  68. clusters_sorted = sorted(clusters, key=lambda x: float(x.get("importance", 0.0)), reverse=True)
  69. out = []
  70. for c in clusters_sorted:
  71. item = {
  72. "cluster_id": c.get("cluster_id"),
  73. "headline": c.get("headline"),
  74. "summary": c.get("summary"),
  75. "entities": c.get("entities", []),
  76. "sentiment": c.get("sentiment", "neutral"),
  77. "importance": c.get("importance", 0.0),
  78. "sources": c.get("sources", []),
  79. "timestamp": c.get("timestamp"),
  80. }
  81. if include_articles:
  82. # Return minimal article fields to keep responses compact.
  83. arts = c.get("articles", []) or []
  84. item["articles"] = [
  85. {
  86. "title": a.get("title"),
  87. "url": a.get("url"),
  88. "source": a.get("source"),
  89. "timestamp": a.get("timestamp"),
  90. }
  91. for a in arts
  92. if isinstance(a, dict)
  93. ]
  94. out.append(item)
  95. return out
  96. @mcp.tool(description="What's happening with X? Filter latest clusters by extracted entity substring (case-insensitive).")
  97. async def get_events_for_entity(entity: str, limit: int = 10, include_articles: bool = False):
  98. limit = max(1, min(int(limit), 30))
  99. query = normalize_query(entity).strip().lower()
  100. if not query:
  101. return []
  102. resolved = resolve_entity_via_trends(query)
  103. query_terms = {
  104. query,
  105. str(resolved.get("normalized") or "").strip().lower(),
  106. str(resolved.get("canonical_label") or "").strip().lower(),
  107. str(resolved.get("mid") or "").strip().lower(),
  108. }
  109. query_terms = {q for q in query_terms if q}
  110. # Cache-first: search recent clusters across all topics.
  111. store = SQLiteClusterStore(DB_PATH)
  112. def _match_clusters(clusters: list[dict]) -> list[dict]:
  113. hits: list[dict] = []
  114. for c in clusters:
  115. haystack = _cluster_entity_haystack(c)
  116. if any(any(term in item for item in haystack) for term in query_terms):
  117. hits.append(c)
  118. if len(hits) >= limit:
  119. break
  120. return hits
  121. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=limit * 5)
  122. hits = _match_clusters(clusters)
  123. # If the recent slice misses, broaden the search window before giving up.
  124. if not hits:
  125. clusters = store.get_latest_clusters_all_topics(ttl_hours=24 * 7, limit=500)
  126. hits = _match_clusters(clusters)
  127. # Compress to tool response shape.
  128. out = []
  129. for c in hits:
  130. item = {
  131. "cluster_id": c.get("cluster_id"),
  132. "headline": c.get("headline"),
  133. "summary": c.get("summary"),
  134. "entities": c.get("entities", []),
  135. "sentiment": c.get("sentiment", "neutral"),
  136. "importance": c.get("importance", 0.0),
  137. "sources": c.get("sources", []),
  138. "timestamp": c.get("timestamp"),
  139. }
  140. if include_articles:
  141. arts = c.get("articles", []) or []
  142. item["articles"] = [
  143. {
  144. "title": a.get("title"),
  145. "url": a.get("url"),
  146. "source": a.get("source"),
  147. "timestamp": a.get("timestamp"),
  148. }
  149. for a in arts
  150. if isinstance(a, dict)
  151. ]
  152. out.append(item)
  153. return out
  154. @mcp.tool(description="Explain an event clearly by cluster_id (Groq summary).")
  155. async def get_event_summary(event_id: str, include_articles: bool = False):
  156. store = SQLiteClusterStore(DB_PATH)
  157. # Summary cache: reuse if present within TTL.
  158. cached_summary = store.get_cluster_summary(
  159. cluster_id=event_id,
  160. ttl_hours=CLUSTERS_TTL_HOURS,
  161. )
  162. if cached_summary:
  163. out = {
  164. "event_id": event_id,
  165. "headline": cached_summary.get("headline"),
  166. "mergedSummary": cached_summary.get("mergedSummary"),
  167. "keyFacts": cached_summary.get("keyFacts", []),
  168. "sources": cached_summary.get("sources", []),
  169. }
  170. if include_articles:
  171. cluster = store.get_cluster_by_id(event_id)
  172. arts = (cluster or {}).get("articles", []) or []
  173. out["articles"] = [
  174. {
  175. "title": a.get("title"),
  176. "url": a.get("url"),
  177. "source": a.get("source"),
  178. "timestamp": a.get("timestamp"),
  179. }
  180. for a in arts
  181. if isinstance(a, dict)
  182. ]
  183. return out
  184. cluster = store.get_cluster_by_id(event_id)
  185. if not cluster:
  186. return {
  187. "event_id": event_id,
  188. "error": "NOT_FOUND",
  189. }
  190. articles_out = None
  191. if include_articles:
  192. arts = cluster.get("articles", []) or []
  193. articles_out = [
  194. {
  195. "title": a.get("title"),
  196. "url": a.get("url"),
  197. "source": a.get("source"),
  198. "timestamp": a.get("timestamp"),
  199. }
  200. for a in arts
  201. if isinstance(a, dict)
  202. ]
  203. summary = await summarize_cluster_groq(cluster)
  204. store.upsert_cluster_summary(event_id, summary)
  205. out = {
  206. "event_id": event_id,
  207. "headline": summary.get("headline"),
  208. "mergedSummary": summary.get("mergedSummary"),
  209. "keyFacts": summary.get("keyFacts", []),
  210. "sources": summary.get("sources", []),
  211. }
  212. if include_articles:
  213. out["articles"] = articles_out or []
  214. return out
  215. @mcp.tool(description="Detect emerging topics/entities from recent cached news clusters.")
  216. async def detect_emerging_topics(limit: int = 10):
  217. limit = max(1, min(int(limit), 20))
  218. store = SQLiteClusterStore(DB_PATH)
  219. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=200)
  220. from collections import Counter
  221. import re
  222. entity_counts = Counter()
  223. phrase_counts = Counter()
  224. topic_counts = Counter()
  225. for c in clusters:
  226. topic_counts[c.get("topic", "other")] += 1
  227. for ent in c.get("entities", []) or []:
  228. key = str(ent).strip().lower()
  229. if key:
  230. entity_counts[key] += 1
  231. text = f"{c.get('headline','')} {c.get('summary','')}"
  232. words = [w for w in re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())]
  233. for i in range(len(words) - 1):
  234. phrase = f"{words[i]} {words[i+1]}"
  235. if len(phrase) > 6:
  236. phrase_counts[phrase] += 1
  237. emerging = []
  238. for ent, count in entity_counts.most_common(limit):
  239. emerging.append({
  240. "topic": ent,
  241. "trend_score": min(0.99, round(0.25 + 0.15 * count, 2)),
  242. "related_entities": [ent],
  243. "signal_type": "entity",
  244. "count": count,
  245. })
  246. for phrase, count in phrase_counts.most_common(limit * 2):
  247. if any(item["topic"] == phrase for item in emerging):
  248. continue
  249. emerging.append({
  250. "topic": phrase.title(),
  251. "trend_score": min(0.99, round(0.20 + 0.10 * count, 2)),
  252. "related_entities": [],
  253. "signal_type": "phrase",
  254. "count": count,
  255. })
  256. if len(emerging) >= limit:
  257. break
  258. return emerging[:limit]
  259. @mcp.tool(description="What's the overall sentiment around an entity within a timeframe?")
  260. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  261. store = SQLiteClusterStore(DB_PATH)
  262. ent = normalize_query(entity).strip().lower()
  263. resolved = resolve_entity_via_trends(ent)
  264. query_terms = {
  265. ent,
  266. str(resolved.get("normalized") or "").strip().lower(),
  267. str(resolved.get("canonical_label") or "").strip().lower(),
  268. str(resolved.get("mid") or "").strip().lower(),
  269. }
  270. query_terms = {q for q in query_terms if q}
  271. if not ent:
  272. return {
  273. "entity": entity,
  274. "sentiment": "neutral",
  275. "score": 0.0,
  276. "cluster_count": 0,
  277. }
  278. # timeframe: accept '24h' or '24'
  279. tf = str(timeframe).strip().lower()
  280. try:
  281. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  282. except Exception:
  283. hours = 24
  284. hours = max(1, min(int(hours), 168))
  285. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  286. matched = []
  287. for c in clusters:
  288. haystack = _cluster_entity_haystack(c)
  289. if any(any(term in item for item in haystack) for term in query_terms):
  290. matched.append(c)
  291. if not matched:
  292. return {
  293. "entity": entity,
  294. "sentiment": "neutral",
  295. "score": 0.0,
  296. "cluster_count": 0,
  297. }
  298. scores = []
  299. for c in matched:
  300. s = c.get("sentimentScore")
  301. if s is not None:
  302. try:
  303. scores.append(float(s))
  304. except Exception:
  305. pass
  306. avg_score = sum(scores) / len(scores) if scores else 0.0
  307. # Keep the label aligned with the numeric score.
  308. # Small magnitudes are treated as neutral to avoid noisy label flips.
  309. if avg_score >= 0.15:
  310. sentiment = "positive"
  311. elif avg_score <= -0.15:
  312. sentiment = "negative"
  313. else:
  314. sentiment = "neutral"
  315. return {
  316. "entity": entity,
  317. "sentiment": sentiment,
  318. "score": round(avg_score, 3),
  319. "cluster_count": len(matched),
  320. }
  321. app = FastAPI(title="News MCP Server")
  322. logger = logging.getLogger("news_mcp.startup")
  323. app.mount("/mcp", mcp.sse_app())
  324. _background_task_started = False
  325. @app.on_event("startup")
  326. async def _start_background_refresh():
  327. global _background_task_started
  328. if _background_task_started:
  329. return
  330. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  331. return
  332. _background_task_started = True
  333. logger.info("news-mcp llm config: %s", active_llm_config())
  334. async def _loop():
  335. if not NEWS_BACKGROUND_REFRESH_ON_START:
  336. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  337. while True:
  338. try:
  339. # Refresh all topics by passing topic=None
  340. await refresh_clusters(topic=None, limit=200)
  341. except Exception:
  342. # Avoid crashing the server on network errors.
  343. pass
  344. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  345. import asyncio
  346. asyncio.create_task(_loop())
  347. @app.get("/")
  348. def root():
  349. return {
  350. "status": "ok",
  351. "transport": "fastmcp+sse",
  352. "mount": "/mcp",
  353. "tools": ["get_latest_events", "get_events_for_entity", "get_event_summary", "detect_emerging_topics"],
  354. "refresh": {
  355. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  356. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  357. },
  358. }
  359. @app.get("/health")
  360. def health():
  361. store = SQLiteClusterStore(DB_PATH)
  362. return {
  363. "status": "ok",
  364. "ttl_hours": CLUSTERS_TTL_HOURS,
  365. "db": str(DB_PATH),
  366. "refresh": store.get_feed_state("breakingthenews"),
  367. }