mcp_server_fastmcp.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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):
  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. return {
  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. cluster = store.get_cluster_by_id(event_id)
  171. if not cluster:
  172. return {
  173. "event_id": event_id,
  174. "error": "NOT_FOUND",
  175. }
  176. summary = await summarize_cluster_groq(cluster)
  177. store.upsert_cluster_summary(event_id, summary)
  178. return {
  179. "event_id": event_id,
  180. "headline": summary.get("headline"),
  181. "mergedSummary": summary.get("mergedSummary"),
  182. "keyFacts": summary.get("keyFacts", []),
  183. "sources": summary.get("sources", []),
  184. }
  185. @mcp.tool(description="Detect emerging topics/entities from recent cached news clusters.")
  186. async def detect_emerging_topics(limit: int = 10):
  187. limit = max(1, min(int(limit), 20))
  188. store = SQLiteClusterStore(DB_PATH)
  189. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=200)
  190. from collections import Counter
  191. import re
  192. entity_counts = Counter()
  193. phrase_counts = Counter()
  194. topic_counts = Counter()
  195. for c in clusters:
  196. topic_counts[c.get("topic", "other")] += 1
  197. for ent in c.get("entities", []) or []:
  198. key = str(ent).strip().lower()
  199. if key:
  200. entity_counts[key] += 1
  201. text = f"{c.get('headline','')} {c.get('summary','')}"
  202. words = [w for w in re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())]
  203. for i in range(len(words) - 1):
  204. phrase = f"{words[i]} {words[i+1]}"
  205. if len(phrase) > 6:
  206. phrase_counts[phrase] += 1
  207. emerging = []
  208. for ent, count in entity_counts.most_common(limit):
  209. emerging.append({
  210. "topic": ent,
  211. "trend_score": min(0.99, round(0.25 + 0.15 * count, 2)),
  212. "related_entities": [ent],
  213. "signal_type": "entity",
  214. "count": count,
  215. })
  216. for phrase, count in phrase_counts.most_common(limit * 2):
  217. if any(item["topic"] == phrase for item in emerging):
  218. continue
  219. emerging.append({
  220. "topic": phrase.title(),
  221. "trend_score": min(0.99, round(0.20 + 0.10 * count, 2)),
  222. "related_entities": [],
  223. "signal_type": "phrase",
  224. "count": count,
  225. })
  226. if len(emerging) >= limit:
  227. break
  228. return emerging[:limit]
  229. @mcp.tool(description="What's the overall sentiment around an entity within a timeframe?")
  230. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  231. store = SQLiteClusterStore(DB_PATH)
  232. ent = normalize_query(entity).strip().lower()
  233. resolved = resolve_entity_via_trends(ent)
  234. query_terms = {
  235. ent,
  236. str(resolved.get("normalized") or "").strip().lower(),
  237. str(resolved.get("canonical_label") or "").strip().lower(),
  238. str(resolved.get("mid") or "").strip().lower(),
  239. }
  240. query_terms = {q for q in query_terms if q}
  241. if not ent:
  242. return {
  243. "entity": entity,
  244. "sentiment": "neutral",
  245. "score": 0.0,
  246. "cluster_count": 0,
  247. }
  248. # timeframe: accept '24h' or '24'
  249. tf = str(timeframe).strip().lower()
  250. try:
  251. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  252. except Exception:
  253. hours = 24
  254. hours = max(1, min(int(hours), 168))
  255. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  256. matched = []
  257. for c in clusters:
  258. haystack = _cluster_entity_haystack(c)
  259. if any(any(term in item for item in haystack) for term in query_terms):
  260. matched.append(c)
  261. if not matched:
  262. return {
  263. "entity": entity,
  264. "sentiment": "neutral",
  265. "score": 0.0,
  266. "cluster_count": 0,
  267. }
  268. scores = []
  269. for c in matched:
  270. s = c.get("sentimentScore")
  271. if s is not None:
  272. try:
  273. scores.append(float(s))
  274. except Exception:
  275. pass
  276. avg_score = sum(scores) / len(scores) if scores else 0.0
  277. # Keep the label aligned with the numeric score.
  278. # Small magnitudes are treated as neutral to avoid noisy label flips.
  279. if avg_score >= 0.15:
  280. sentiment = "positive"
  281. elif avg_score <= -0.15:
  282. sentiment = "negative"
  283. else:
  284. sentiment = "neutral"
  285. return {
  286. "entity": entity,
  287. "sentiment": sentiment,
  288. "score": round(avg_score, 3),
  289. "cluster_count": len(matched),
  290. }
  291. app = FastAPI(title="News MCP Server")
  292. logger = logging.getLogger("news_mcp.startup")
  293. app.mount("/mcp", mcp.sse_app())
  294. _background_task_started = False
  295. @app.on_event("startup")
  296. async def _start_background_refresh():
  297. global _background_task_started
  298. if _background_task_started:
  299. return
  300. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  301. return
  302. _background_task_started = True
  303. logger.info("news-mcp llm config: %s", active_llm_config())
  304. async def _loop():
  305. if not NEWS_BACKGROUND_REFRESH_ON_START:
  306. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  307. while True:
  308. try:
  309. # Refresh all topics by passing topic=None
  310. await refresh_clusters(topic=None, limit=200)
  311. except Exception:
  312. # Avoid crashing the server on network errors.
  313. pass
  314. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  315. import asyncio
  316. asyncio.create_task(_loop())
  317. @app.get("/")
  318. def root():
  319. return {
  320. "status": "ok",
  321. "transport": "fastmcp+sse",
  322. "mount": "/mcp",
  323. "tools": ["get_latest_events", "get_events_for_entity", "get_event_summary", "detect_emerging_topics"],
  324. "refresh": {
  325. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  326. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  327. },
  328. }
  329. @app.get("/health")
  330. def health():
  331. store = SQLiteClusterStore(DB_PATH)
  332. return {
  333. "status": "ok",
  334. "ttl_hours": CLUSTERS_TTL_HOURS,
  335. "db": str(DB_PATH),
  336. "refresh": store.get_feed_state("breakingthenews"),
  337. }