mcp_server_fastmcp.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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.llm import active_llm_config
  11. from news_mcp.entity_normalize import normalize_query
  12. from collections import Counter
  13. import logging
  14. mcp = FastMCP(
  15. "news-mcp",
  16. transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False),
  17. )
  18. @mcp.tool(description="What is happening right now? Return the latest deduplicated news clusters for a topic.")
  19. async def get_latest_events(topic: str = "crypto", limit: int = 5):
  20. limit = max(1, min(int(limit), 20))
  21. # In v1, `topic` is a coarse category. If the caller passes an entity name
  22. # (e.g. "trump"/"iran"), gracefully fall back to `other`.
  23. topic_norm = normalize_query(topic).lower()
  24. allowed = {t.lower() for t in DEFAULT_TOPICS}
  25. if topic_norm not in allowed:
  26. topic_norm = "other"
  27. store = SQLiteClusterStore(DB_PATH)
  28. # Cache-first: only refresh if we currently have no fresh clusters for this topic.
  29. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=CLUSTERS_TTL_HOURS, limit=limit)
  30. if not clusters:
  31. await refresh_clusters(topic=topic_norm, limit=200)
  32. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=CLUSTERS_TTL_HOURS, limit=limit)
  33. # Ensure the response is compact and agent-friendly.
  34. clusters_sorted = sorted(clusters, key=lambda x: float(x.get("importance", 0.0)), reverse=True)
  35. out = []
  36. for c in clusters_sorted:
  37. out.append(
  38. {
  39. "cluster_id": c.get("cluster_id"),
  40. "headline": c.get("headline"),
  41. "summary": c.get("summary"),
  42. "entities": c.get("entities", []),
  43. "sentiment": c.get("sentiment", "neutral"),
  44. "importance": c.get("importance", 0.0),
  45. "sources": c.get("sources", []),
  46. "timestamp": c.get("timestamp"),
  47. }
  48. )
  49. return out
  50. @mcp.tool(description="What's happening with X? Filter latest clusters by extracted entity substring (case-insensitive).")
  51. async def get_events_for_entity(entity: str, limit: int = 10):
  52. limit = max(1, min(int(limit), 30))
  53. query = normalize_query(entity).strip().lower()
  54. if not query:
  55. return []
  56. # Cache-first: search recent clusters across all topics.
  57. store = SQLiteClusterStore(DB_PATH)
  58. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=limit * 5)
  59. hits = []
  60. for c in clusters:
  61. ents = c.get("entities") or []
  62. if any(query in str(e).lower() for e in ents):
  63. hits.append(c)
  64. if len(hits) >= limit:
  65. break
  66. # Compress to tool response shape.
  67. out = []
  68. for c in hits:
  69. out.append(
  70. {
  71. "cluster_id": c.get("cluster_id"),
  72. "headline": c.get("headline"),
  73. "summary": c.get("summary"),
  74. "entities": c.get("entities", []),
  75. "sentiment": c.get("sentiment", "neutral"),
  76. "importance": c.get("importance", 0.0),
  77. "sources": c.get("sources", []),
  78. "timestamp": c.get("timestamp"),
  79. }
  80. )
  81. return out
  82. @mcp.tool(description="Explain an event clearly by cluster_id (Groq summary).")
  83. async def get_event_summary(event_id: str):
  84. store = SQLiteClusterStore(DB_PATH)
  85. # Summary cache: reuse if present within TTL.
  86. cached_summary = store.get_cluster_summary(
  87. cluster_id=event_id,
  88. ttl_hours=CLUSTERS_TTL_HOURS,
  89. )
  90. if cached_summary:
  91. return {
  92. "event_id": event_id,
  93. "headline": cached_summary.get("headline"),
  94. "mergedSummary": cached_summary.get("mergedSummary"),
  95. "keyFacts": cached_summary.get("keyFacts", []),
  96. "sources": cached_summary.get("sources", []),
  97. }
  98. cluster = store.get_cluster_by_id(event_id)
  99. if not cluster:
  100. return {
  101. "event_id": event_id,
  102. "error": "NOT_FOUND",
  103. }
  104. summary = await summarize_cluster_groq(cluster)
  105. store.upsert_cluster_summary(event_id, summary)
  106. return {
  107. "event_id": event_id,
  108. "headline": summary.get("headline"),
  109. "mergedSummary": summary.get("mergedSummary"),
  110. "keyFacts": summary.get("keyFacts", []),
  111. "sources": summary.get("sources", []),
  112. }
  113. @mcp.tool(description="Detect emerging topics/entities from recent cached news clusters.")
  114. async def detect_emerging_topics(limit: int = 10):
  115. limit = max(1, min(int(limit), 20))
  116. store = SQLiteClusterStore(DB_PATH)
  117. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=200)
  118. from collections import Counter
  119. import re
  120. entity_counts = Counter()
  121. phrase_counts = Counter()
  122. topic_counts = Counter()
  123. for c in clusters:
  124. topic_counts[c.get("topic", "other")] += 1
  125. for ent in c.get("entities", []) or []:
  126. key = str(ent).strip().lower()
  127. if key:
  128. entity_counts[key] += 1
  129. text = f"{c.get('headline','')} {c.get('summary','')}"
  130. words = [w for w in re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())]
  131. for i in range(len(words) - 1):
  132. phrase = f"{words[i]} {words[i+1]}"
  133. if len(phrase) > 6:
  134. phrase_counts[phrase] += 1
  135. emerging = []
  136. for ent, count in entity_counts.most_common(limit):
  137. emerging.append({
  138. "topic": ent,
  139. "trend_score": min(0.99, round(0.25 + 0.15 * count, 2)),
  140. "related_entities": [ent],
  141. "signal_type": "entity",
  142. "count": count,
  143. })
  144. for phrase, count in phrase_counts.most_common(limit * 2):
  145. if any(item["topic"] == phrase for item in emerging):
  146. continue
  147. emerging.append({
  148. "topic": phrase.title(),
  149. "trend_score": min(0.99, round(0.20 + 0.10 * count, 2)),
  150. "related_entities": [],
  151. "signal_type": "phrase",
  152. "count": count,
  153. })
  154. if len(emerging) >= limit:
  155. break
  156. return emerging[:limit]
  157. @mcp.tool(description="What's the overall sentiment around an entity within a timeframe?")
  158. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  159. store = SQLiteClusterStore(DB_PATH)
  160. ent = normalize_query(entity).strip().lower()
  161. if not ent:
  162. return {
  163. "entity": entity,
  164. "sentiment": "neutral",
  165. "score": 0.0,
  166. "cluster_count": 0,
  167. }
  168. # timeframe: accept '24h' or '24'
  169. tf = str(timeframe).strip().lower()
  170. try:
  171. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  172. except Exception:
  173. hours = 24
  174. hours = max(1, min(int(hours), 168))
  175. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  176. matched = []
  177. for c in clusters:
  178. ents = c.get("entities") or []
  179. if any(ent in str(e).lower() for e in ents):
  180. matched.append(c)
  181. if not matched:
  182. return {
  183. "entity": entity,
  184. "sentiment": "neutral",
  185. "score": 0.0,
  186. "cluster_count": 0,
  187. }
  188. scores = []
  189. for c in matched:
  190. s = c.get("sentimentScore")
  191. if s is not None:
  192. try:
  193. scores.append(float(s))
  194. except Exception:
  195. pass
  196. avg_score = sum(scores) / len(scores) if scores else 0.0
  197. # Keep the label aligned with the numeric score.
  198. # Small magnitudes are treated as neutral to avoid noisy label flips.
  199. if avg_score >= 0.15:
  200. sentiment = "positive"
  201. elif avg_score <= -0.15:
  202. sentiment = "negative"
  203. else:
  204. sentiment = "neutral"
  205. return {
  206. "entity": entity,
  207. "sentiment": sentiment,
  208. "score": round(avg_score, 3),
  209. "cluster_count": len(matched),
  210. }
  211. app = FastAPI(title="News MCP Server")
  212. logger = logging.getLogger("news_mcp.startup")
  213. app.mount("/mcp", mcp.sse_app())
  214. _background_task_started = False
  215. @app.on_event("startup")
  216. async def _start_background_refresh():
  217. global _background_task_started
  218. if _background_task_started:
  219. return
  220. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  221. return
  222. _background_task_started = True
  223. logger.info("news-mcp llm config: %s", active_llm_config())
  224. async def _loop():
  225. if not NEWS_BACKGROUND_REFRESH_ON_START:
  226. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  227. while True:
  228. try:
  229. # Refresh all topics by passing topic=None
  230. await refresh_clusters(topic=None, limit=200)
  231. except Exception:
  232. # Avoid crashing the server on network errors.
  233. pass
  234. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  235. import asyncio
  236. asyncio.create_task(_loop())
  237. @app.get("/")
  238. def root():
  239. return {
  240. "status": "ok",
  241. "transport": "fastmcp+sse",
  242. "mount": "/mcp",
  243. "tools": ["get_latest_events", "get_events_for_entity", "get_event_summary", "detect_emerging_topics"],
  244. "refresh": {
  245. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  246. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  247. },
  248. }
  249. @app.get("/health")
  250. def health():
  251. store = SQLiteClusterStore(DB_PATH)
  252. return {
  253. "status": "ok",
  254. "ttl_hours": CLUSTERS_TTL_HOURS,
  255. "db": str(DB_PATH),
  256. "refresh": store.get_feed_state("breakingthenews"),
  257. }