mcp_server_fastmcp.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 clusters by extracted entity substring (case-insensitive) within a timeframe.")
  97. async def get_events_for_entity(entity: str, limit: int = 10, timeframe: str = "24h", 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. store = SQLiteClusterStore(DB_PATH)
  111. def _match_clusters(clusters: list[dict]) -> list[dict]:
  112. hits: list[dict] = []
  113. for c in clusters:
  114. haystack = _cluster_entity_haystack(c)
  115. if any(any(term in item for item in haystack) for term in query_terms):
  116. hits.append(c)
  117. if len(hits) >= limit:
  118. break
  119. return hits
  120. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=limit * 5)
  121. hits = _match_clusters(clusters)
  122. hours = _parse_timeframe_to_hours(timeframe)
  123. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=max(200, limit * 10))
  124. hits = _match_clusters(clusters)
  125. # Compress to tool response shape.
  126. out = []
  127. for c in hits:
  128. item = {
  129. "cluster_id": c.get("cluster_id"),
  130. "headline": c.get("headline"),
  131. "summary": c.get("summary"),
  132. "entities": c.get("entities", []),
  133. "sentiment": c.get("sentiment", "neutral"),
  134. "importance": c.get("importance", 0.0),
  135. "sources": c.get("sources", []),
  136. "timestamp": c.get("timestamp"),
  137. }
  138. if include_articles:
  139. arts = c.get("articles", []) or []
  140. item["articles"] = [
  141. {
  142. "title": a.get("title"),
  143. "url": a.get("url"),
  144. "source": a.get("source"),
  145. "timestamp": a.get("timestamp"),
  146. }
  147. for a in arts
  148. if isinstance(a, dict)
  149. ]
  150. out.append(item)
  151. return out
  152. @mcp.tool(description="Explain an event clearly by cluster_id (Groq summary).")
  153. async def get_event_summary(event_id: str, include_articles: bool = False):
  154. store = SQLiteClusterStore(DB_PATH)
  155. # Summary cache: reuse if present within TTL.
  156. cached_summary = store.get_cluster_summary(
  157. cluster_id=event_id,
  158. ttl_hours=CLUSTERS_TTL_HOURS,
  159. )
  160. if cached_summary:
  161. out = {
  162. "event_id": event_id,
  163. "headline": cached_summary.get("headline"),
  164. "mergedSummary": cached_summary.get("mergedSummary"),
  165. "keyFacts": cached_summary.get("keyFacts", []),
  166. "sources": cached_summary.get("sources", []),
  167. }
  168. if include_articles:
  169. cluster = store.get_cluster_by_id(event_id)
  170. arts = (cluster or {}).get("articles", []) or []
  171. out["articles"] = [
  172. {
  173. "title": a.get("title"),
  174. "url": a.get("url"),
  175. "source": a.get("source"),
  176. "timestamp": a.get("timestamp"),
  177. }
  178. for a in arts
  179. if isinstance(a, dict)
  180. ]
  181. return out
  182. cluster = store.get_cluster_by_id(event_id)
  183. if not cluster:
  184. return {
  185. "event_id": event_id,
  186. "error": "NOT_FOUND",
  187. }
  188. articles_out = None
  189. if include_articles:
  190. arts = cluster.get("articles", []) or []
  191. articles_out = [
  192. {
  193. "title": a.get("title"),
  194. "url": a.get("url"),
  195. "source": a.get("source"),
  196. "timestamp": a.get("timestamp"),
  197. }
  198. for a in arts
  199. if isinstance(a, dict)
  200. ]
  201. summary = await summarize_cluster_groq(cluster)
  202. store.upsert_cluster_summary(event_id, summary)
  203. out = {
  204. "event_id": event_id,
  205. "headline": summary.get("headline"),
  206. "mergedSummary": summary.get("mergedSummary"),
  207. "keyFacts": summary.get("keyFacts", []),
  208. "sources": summary.get("sources", []),
  209. }
  210. if include_articles:
  211. out["articles"] = articles_out or []
  212. return out
  213. @mcp.tool(description="Detect emerging topics/entities from recent cached news clusters.")
  214. async def detect_emerging_topics(limit: int = 10):
  215. limit = max(1, min(int(limit), 20))
  216. store = SQLiteClusterStore(DB_PATH)
  217. clusters = store.get_latest_clusters_all_topics(ttl_hours=CLUSTERS_TTL_HOURS, limit=200)
  218. from collections import Counter
  219. import re
  220. entity_counts = Counter()
  221. entity_importance_sum = Counter()
  222. # co-occurrence: ent -> other_ent -> count
  223. entity_cooccur = {}
  224. phrase_counts = Counter()
  225. topic_counts = Counter()
  226. # Very light heuristics to reduce “meta entities” dominating emerging topics.
  227. # Keep it conservative: only skip obvious boilerplate.
  228. def _is_generic_entity(ent: str) -> bool:
  229. e = str(ent).strip().lower()
  230. if not e:
  231. return True
  232. if len(e) < 4:
  233. return True
  234. # common outlet-ish / meta-ish tokens
  235. if e in {"news", "latest", "breaking"}:
  236. return True
  237. return False
  238. for c in clusters:
  239. topic_counts[c.get("topic", "other")] += 1
  240. ents_in_cluster = [e for e in (c.get("entities", []) or []) if not _is_generic_entity(e)]
  241. ents_in_cluster_norm = [str(e).strip().lower() for e in ents_in_cluster if str(e).strip()]
  242. for ent in ents_in_cluster_norm:
  243. if _is_generic_entity(ent):
  244. continue
  245. entity_counts[ent] += 1
  246. try:
  247. entity_importance_sum[ent] += float(c.get("importance", 0.0) or 0.0)
  248. except Exception:
  249. pass
  250. # update co-occurrence counts
  251. for i in range(len(ents_in_cluster_norm)):
  252. a = ents_in_cluster_norm[i]
  253. if not a:
  254. continue
  255. entity_cooccur.setdefault(a, Counter())
  256. for j in range(len(ents_in_cluster_norm)):
  257. if i == j:
  258. continue
  259. b = ents_in_cluster_norm[j]
  260. if not b:
  261. continue
  262. entity_cooccur[a][b] += 1
  263. text = f"{c.get('headline','')} {c.get('summary','')}"
  264. words = [w for w in re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())]
  265. for i in range(len(words) - 1):
  266. phrase = f"{words[i]} {words[i+1]}"
  267. if len(phrase) > 6:
  268. phrase_counts[phrase] += 1
  269. emerging = []
  270. # Combine frequency with average importance so “big signal” rises over pure repetition.
  271. for ent, count in entity_counts.most_common(limit):
  272. avg_imp = entity_importance_sum[ent] / max(1, count)
  273. # avg_imp is typically 0..~1; keep score bounded.
  274. trend_score = 0.25 + 0.40 * min(1.0, avg_imp) + 0.08 * min(6.0, float(count))
  275. related = []
  276. for other, _cnt in (entity_cooccur.get(ent) or Counter()).most_common(3):
  277. # avoid returning the entity itself (shouldn't happen, but be safe)
  278. if other != ent:
  279. related.append(other)
  280. emerging.append({
  281. "topic": ent,
  282. "trend_score": min(0.99, round(trend_score, 2)),
  283. "related_entities": related if related else [ent],
  284. "signal_type": "entity",
  285. "count": count,
  286. "avg_importance": round(avg_imp, 3),
  287. })
  288. for phrase, count in phrase_counts.most_common(limit * 2):
  289. if any(item["topic"] == phrase for item in emerging):
  290. continue
  291. emerging.append({
  292. "topic": phrase.title(),
  293. "trend_score": min(0.99, round(0.20 + 0.10 * count, 2)),
  294. "related_entities": [],
  295. "signal_type": "phrase",
  296. "count": count,
  297. })
  298. if len(emerging) >= limit:
  299. break
  300. return emerging[:limit]
  301. @mcp.tool(description="What's the overall sentiment around an entity within a timeframe?")
  302. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  303. store = SQLiteClusterStore(DB_PATH)
  304. ent = normalize_query(entity).strip().lower()
  305. resolved = resolve_entity_via_trends(ent)
  306. query_terms = {
  307. ent,
  308. str(resolved.get("normalized") or "").strip().lower(),
  309. str(resolved.get("canonical_label") or "").strip().lower(),
  310. str(resolved.get("mid") or "").strip().lower(),
  311. }
  312. query_terms = {q for q in query_terms if q}
  313. if not ent:
  314. return {
  315. "entity": entity,
  316. "sentiment": "neutral",
  317. "score": 0.0,
  318. "cluster_count": 0,
  319. }
  320. # timeframe: accept '24h' or '24'
  321. tf = str(timeframe).strip().lower()
  322. try:
  323. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  324. except Exception:
  325. hours = 24
  326. hours = max(1, min(int(hours), 168))
  327. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  328. matched = []
  329. for c in clusters:
  330. haystack = _cluster_entity_haystack(c)
  331. if any(any(term in item for item in haystack) for term in query_terms):
  332. matched.append(c)
  333. if not matched:
  334. return {
  335. "entity": entity,
  336. "sentiment": "neutral",
  337. "score": 0.0,
  338. "cluster_count": 0,
  339. }
  340. scores = []
  341. for c in matched:
  342. s = c.get("sentimentScore")
  343. if s is not None:
  344. try:
  345. scores.append(float(s))
  346. except Exception:
  347. pass
  348. avg_score = sum(scores) / len(scores) if scores else 0.0
  349. # Keep the label aligned with the numeric score.
  350. # Small magnitudes are treated as neutral to avoid noisy label flips.
  351. if avg_score >= 0.15:
  352. sentiment = "positive"
  353. elif avg_score <= -0.15:
  354. sentiment = "negative"
  355. else:
  356. sentiment = "neutral"
  357. return {
  358. "entity": entity,
  359. "sentiment": sentiment,
  360. "score": round(avg_score, 3),
  361. "cluster_count": len(matched),
  362. }
  363. def _parse_timeframe_to_hours(timeframe: str) -> int:
  364. tf = str(timeframe).strip().lower()
  365. try:
  366. if tf.endswith("d"):
  367. days = int(tf[:-1])
  368. return max(1, days * 24)
  369. if tf.endswith("h"):
  370. return max(1, int(tf[:-1]))
  371. return max(1, int(tf))
  372. except Exception:
  373. return 24
  374. @mcp.tool(
  375. description="Given a subject entity, find related entities via co-occurrence inside recent clusters (entity-only, no topic fallback)."
  376. )
  377. async def get_related_entities(subject: str, timeframe: str = "24h", limit: int = 10):
  378. store = SQLiteClusterStore(DB_PATH)
  379. limit = max(1, min(int(limit), 30))
  380. subj = normalize_query(subject).strip().lower()
  381. if not subj:
  382. return []
  383. resolved = resolve_entity_via_trends(subj)
  384. query_terms = {
  385. subj,
  386. str(resolved.get("normalized") or "").strip().lower(),
  387. str(resolved.get("canonical_label") or "").strip().lower(),
  388. str(resolved.get("mid") or "").strip().lower(),
  389. }
  390. query_terms = {q for q in query_terms if q}
  391. hours = _parse_timeframe_to_hours(timeframe)
  392. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  393. # Aggregate related metrics per entity.
  394. rel_count = Counter()
  395. rel_imp_sum = Counter()
  396. rel_sent_sum = Counter()
  397. rel_sent_n = Counter()
  398. for c in clusters:
  399. haystack = _cluster_entity_haystack(c)
  400. if not any(term in item for item in haystack for term in query_terms):
  401. continue
  402. ents = [str(e).strip().lower() for e in (c.get("entities", []) or []) if str(e).strip()]
  403. # remove generic/meta-ish short tokens conservatively
  404. ents = [e for e in ents if len(e) >= 4]
  405. for e in ents:
  406. if e in query_terms:
  407. continue
  408. rel_count[e] += 1
  409. try:
  410. rel_imp_sum[e] += float(c.get("importance", 0.0) or 0.0)
  411. except Exception:
  412. pass
  413. # sentiment aggregation based on sentimentScore if available.
  414. s = c.get("sentimentScore")
  415. if s is not None:
  416. try:
  417. rel_sent_sum[e] += float(s)
  418. rel_sent_n[e] += 1
  419. except Exception:
  420. pass
  421. # Sort by count, then avg importance.
  422. items = []
  423. for ent, cnt in rel_count.most_common():
  424. avg_imp = rel_imp_sum[ent] / max(1, cnt)
  425. avg_score = rel_sent_sum[ent] / max(1, rel_sent_n[ent]) if rel_sent_n[ent] else 0.0
  426. if avg_score >= 0.15:
  427. sentiment = "positive"
  428. elif avg_score <= -0.15:
  429. sentiment = "negative"
  430. else:
  431. sentiment = "neutral"
  432. items.append(
  433. {
  434. "entity": ent,
  435. "count": cnt,
  436. "avg_importance": round(avg_imp, 3),
  437. "sentiment": sentiment,
  438. "score": round(avg_score, 3),
  439. }
  440. )
  441. if len(items) >= limit:
  442. break
  443. return items
  444. app = FastAPI(title="News MCP Server")
  445. logger = logging.getLogger("news_mcp.startup")
  446. app.mount("/mcp", mcp.sse_app())
  447. _background_task_started = False
  448. @app.on_event("startup")
  449. async def _start_background_refresh():
  450. global _background_task_started
  451. if _background_task_started:
  452. return
  453. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  454. return
  455. _background_task_started = True
  456. logger.info("news-mcp llm config: %s", active_llm_config())
  457. async def _loop():
  458. if not NEWS_BACKGROUND_REFRESH_ON_START:
  459. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  460. while True:
  461. try:
  462. # Refresh all topics by passing topic=None
  463. await refresh_clusters(topic=None, limit=200)
  464. except Exception:
  465. # Avoid crashing the server on network errors.
  466. pass
  467. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  468. import asyncio
  469. asyncio.create_task(_loop())
  470. @app.get("/")
  471. def root():
  472. return {
  473. "status": "ok",
  474. "transport": "fastmcp+sse",
  475. "mount": "/mcp",
  476. "tools": ["get_latest_events", "get_events_for_entity", "get_event_summary", "detect_emerging_topics"],
  477. "refresh": {
  478. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  479. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  480. },
  481. }
  482. @app.get("/health")
  483. def health():
  484. store = SQLiteClusterStore(DB_PATH)
  485. return {
  486. "status": "ok",
  487. "ttl_hours": CLUSTERS_TTL_HOURS,
  488. "db": str(DB_PATH),
  489. "refresh": store.get_feed_state("breakingthenews"),
  490. }