mcp_server_fastmcp.py 9.9 KB

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