mcp_server_fastmcp.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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):
  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. out.append(
  72. {
  73. "cluster_id": c.get("cluster_id"),
  74. "headline": c.get("headline"),
  75. "summary": c.get("summary"),
  76. "entities": c.get("entities", []),
  77. "sentiment": c.get("sentiment", "neutral"),
  78. "importance": c.get("importance", 0.0),
  79. "sources": c.get("sources", []),
  80. "timestamp": c.get("timestamp"),
  81. }
  82. )
  83. return out
  84. @mcp.tool(description="What's happening with X? Filter latest clusters by extracted entity substring (case-insensitive).")
  85. async def get_events_for_entity(entity: str, limit: int = 10):
  86. limit = max(1, min(int(limit), 30))
  87. query = normalize_query(entity).strip().lower()
  88. if not query:
  89. return []
  90. resolved = resolve_entity_via_trends(query)
  91. query_terms = {
  92. query,
  93. str(resolved.get("normalized") or "").strip().lower(),
  94. str(resolved.get("canonical_label") or "").strip().lower(),
  95. str(resolved.get("mid") or "").strip().lower(),
  96. }
  97. query_terms = {q for q in query_terms if q}
  98. # Cache-first: search recent clusters across all topics.
  99. store = SQLiteClusterStore(DB_PATH)
  100. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=limit * 5)
  101. hits = []
  102. for c in clusters:
  103. haystack = _cluster_entity_haystack(c)
  104. if any(any(term in item for item in haystack) for term in query_terms):
  105. hits.append(c)
  106. if len(hits) >= limit:
  107. break
  108. # Compress to tool response shape.
  109. out = []
  110. for c in hits:
  111. out.append(
  112. {
  113. "cluster_id": c.get("cluster_id"),
  114. "headline": c.get("headline"),
  115. "summary": c.get("summary"),
  116. "entities": c.get("entities", []),
  117. "sentiment": c.get("sentiment", "neutral"),
  118. "importance": c.get("importance", 0.0),
  119. "sources": c.get("sources", []),
  120. "timestamp": c.get("timestamp"),
  121. }
  122. )
  123. return out
  124. @mcp.tool(description="Explain an event clearly by cluster_id (Groq summary).")
  125. async def get_event_summary(event_id: str):
  126. store = SQLiteClusterStore(DB_PATH)
  127. # Summary cache: reuse if present within TTL.
  128. cached_summary = store.get_cluster_summary(
  129. cluster_id=event_id,
  130. ttl_hours=CLUSTERS_TTL_HOURS,
  131. )
  132. if cached_summary:
  133. return {
  134. "event_id": event_id,
  135. "headline": cached_summary.get("headline"),
  136. "mergedSummary": cached_summary.get("mergedSummary"),
  137. "keyFacts": cached_summary.get("keyFacts", []),
  138. "sources": cached_summary.get("sources", []),
  139. }
  140. cluster = store.get_cluster_by_id(event_id)
  141. if not cluster:
  142. return {
  143. "event_id": event_id,
  144. "error": "NOT_FOUND",
  145. }
  146. summary = await summarize_cluster_groq(cluster)
  147. store.upsert_cluster_summary(event_id, summary)
  148. return {
  149. "event_id": event_id,
  150. "headline": summary.get("headline"),
  151. "mergedSummary": summary.get("mergedSummary"),
  152. "keyFacts": summary.get("keyFacts", []),
  153. "sources": summary.get("sources", []),
  154. }
  155. @mcp.tool(description="Detect emerging topics/entities from recent cached news clusters.")
  156. async def detect_emerging_topics(limit: int = 10):
  157. limit = max(1, min(int(limit), 20))
  158. store = SQLiteClusterStore(DB_PATH)
  159. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=200)
  160. from collections import Counter
  161. import re
  162. entity_counts = Counter()
  163. phrase_counts = Counter()
  164. topic_counts = Counter()
  165. for c in clusters:
  166. topic_counts[c.get("topic", "other")] += 1
  167. for ent in c.get("entities", []) or []:
  168. key = str(ent).strip().lower()
  169. if key:
  170. entity_counts[key] += 1
  171. text = f"{c.get('headline','')} {c.get('summary','')}"
  172. words = [w for w in re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())]
  173. for i in range(len(words) - 1):
  174. phrase = f"{words[i]} {words[i+1]}"
  175. if len(phrase) > 6:
  176. phrase_counts[phrase] += 1
  177. emerging = []
  178. for ent, count in entity_counts.most_common(limit):
  179. emerging.append({
  180. "topic": ent,
  181. "trend_score": min(0.99, round(0.25 + 0.15 * count, 2)),
  182. "related_entities": [ent],
  183. "signal_type": "entity",
  184. "count": count,
  185. })
  186. for phrase, count in phrase_counts.most_common(limit * 2):
  187. if any(item["topic"] == phrase for item in emerging):
  188. continue
  189. emerging.append({
  190. "topic": phrase.title(),
  191. "trend_score": min(0.99, round(0.20 + 0.10 * count, 2)),
  192. "related_entities": [],
  193. "signal_type": "phrase",
  194. "count": count,
  195. })
  196. if len(emerging) >= limit:
  197. break
  198. return emerging[:limit]
  199. @mcp.tool(description="What's the overall sentiment around an entity within a timeframe?")
  200. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  201. store = SQLiteClusterStore(DB_PATH)
  202. ent = normalize_query(entity).strip().lower()
  203. resolved = resolve_entity_via_trends(ent)
  204. query_terms = {
  205. ent,
  206. str(resolved.get("normalized") or "").strip().lower(),
  207. str(resolved.get("canonical_label") or "").strip().lower(),
  208. str(resolved.get("mid") or "").strip().lower(),
  209. }
  210. query_terms = {q for q in query_terms if q}
  211. if not ent:
  212. return {
  213. "entity": entity,
  214. "sentiment": "neutral",
  215. "score": 0.0,
  216. "cluster_count": 0,
  217. }
  218. # timeframe: accept '24h' or '24'
  219. tf = str(timeframe).strip().lower()
  220. try:
  221. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  222. except Exception:
  223. hours = 24
  224. hours = max(1, min(int(hours), 168))
  225. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  226. matched = []
  227. for c in clusters:
  228. haystack = _cluster_entity_haystack(c)
  229. if any(any(term in item for item in haystack) for term in query_terms):
  230. matched.append(c)
  231. if not matched:
  232. return {
  233. "entity": entity,
  234. "sentiment": "neutral",
  235. "score": 0.0,
  236. "cluster_count": 0,
  237. }
  238. scores = []
  239. for c in matched:
  240. s = c.get("sentimentScore")
  241. if s is not None:
  242. try:
  243. scores.append(float(s))
  244. except Exception:
  245. pass
  246. avg_score = sum(scores) / len(scores) if scores else 0.0
  247. # Keep the label aligned with the numeric score.
  248. # Small magnitudes are treated as neutral to avoid noisy label flips.
  249. if avg_score >= 0.15:
  250. sentiment = "positive"
  251. elif avg_score <= -0.15:
  252. sentiment = "negative"
  253. else:
  254. sentiment = "neutral"
  255. return {
  256. "entity": entity,
  257. "sentiment": sentiment,
  258. "score": round(avg_score, 3),
  259. "cluster_count": len(matched),
  260. }
  261. app = FastAPI(title="News MCP Server")
  262. logger = logging.getLogger("news_mcp.startup")
  263. app.mount("/mcp", mcp.sse_app())
  264. _background_task_started = False
  265. @app.on_event("startup")
  266. async def _start_background_refresh():
  267. global _background_task_started
  268. if _background_task_started:
  269. return
  270. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  271. return
  272. _background_task_started = True
  273. logger.info("news-mcp llm config: %s", active_llm_config())
  274. async def _loop():
  275. if not NEWS_BACKGROUND_REFRESH_ON_START:
  276. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  277. while True:
  278. try:
  279. # Refresh all topics by passing topic=None
  280. await refresh_clusters(topic=None, limit=200)
  281. except Exception:
  282. # Avoid crashing the server on network errors.
  283. pass
  284. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  285. import asyncio
  286. asyncio.create_task(_loop())
  287. @app.get("/")
  288. def root():
  289. return {
  290. "status": "ok",
  291. "transport": "fastmcp+sse",
  292. "mount": "/mcp",
  293. "tools": ["get_latest_events", "get_events_for_entity", "get_event_summary", "detect_emerging_topics"],
  294. "refresh": {
  295. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  296. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  297. },
  298. }
  299. @app.get("/health")
  300. def health():
  301. store = SQLiteClusterStore(DB_PATH)
  302. return {
  303. "status": "ok",
  304. "ttl_hours": CLUSTERS_TTL_HOURS,
  305. "db": str(DB_PATH),
  306. "refresh": store.get_feed_state("breakingthenews"),
  307. }