mcp_server_fastmcp.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. from __future__ import annotations
  2. import asyncio
  3. import logging
  4. from collections import Counter
  5. from datetime import datetime, timezone
  6. from email.utils import parsedate_to_datetime
  7. from fastapi import FastAPI
  8. from mcp.server.fastmcp import FastMCP
  9. from mcp.server.transport_security import TransportSecuritySettings
  10. from news_mcp.config import DEFAULT_LOOKBACK_HOURS, DEFAULT_TOPICS, DB_PATH
  11. from news_mcp.config import (
  12. NEWS_PRUNE_INTERVAL_HOURS,
  13. NEWS_PRUNING_ENABLED,
  14. NEWS_REFRESH_INTERVAL_SECONDS,
  15. NEWS_BACKGROUND_REFRESH_ENABLED,
  16. NEWS_BACKGROUND_REFRESH_ON_START,
  17. NEWS_RETENTION_DAYS,
  18. )
  19. from news_mcp.jobs.poller import refresh_clusters
  20. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  21. from news_mcp.enrichment.llm_enrich import summarize_cluster_llm
  22. from news_mcp.trends_resolution import resolve_entity_via_trends
  23. from news_mcp.llm import active_llm_config
  24. from news_mcp.entity_normalize import normalize_query
  25. from news_mcp.related_entities import related_recent_entities
  26. mcp = FastMCP(
  27. "news-mcp",
  28. transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False),
  29. )
  30. def _cluster_entity_haystack(cluster: dict) -> list[str]:
  31. """Collect the normalized entity clues attached to a cluster."""
  32. values: list[str] = []
  33. for ent in cluster.get("entities", []) or []:
  34. values.append(str(ent).strip().lower())
  35. for res in cluster.get("entityResolutions", []) or []:
  36. if not isinstance(res, dict):
  37. continue
  38. for key in ("normalized", "canonical_label", "mid"):
  39. val = res.get(key)
  40. if val:
  41. values.append(str(val).strip().lower())
  42. return [v for v in values if v]
  43. def _parse_cluster_timestamp(value) -> datetime:
  44. if not value:
  45. return datetime.min.replace(tzinfo=timezone.utc)
  46. text = str(value).strip()
  47. if not text:
  48. return datetime.min.replace(tzinfo=timezone.utc)
  49. try:
  50. dt = datetime.fromisoformat(text.replace("Z", "+00:00"))
  51. if dt.tzinfo is None:
  52. dt = dt.replace(tzinfo=timezone.utc)
  53. return dt.astimezone(timezone.utc)
  54. except Exception:
  55. pass
  56. try:
  57. dt = parsedate_to_datetime(text)
  58. if dt.tzinfo is None:
  59. dt = dt.replace(tzinfo=timezone.utc)
  60. return dt.astimezone(timezone.utc)
  61. except Exception:
  62. return datetime.min.replace(tzinfo=timezone.utc)
  63. def _sort_clusters_by_recency(clusters: list[dict]) -> list[dict]:
  64. return sorted(
  65. clusters,
  66. key=lambda c: (
  67. _parse_cluster_timestamp(c.get("timestamp")),
  68. float(c.get("importance", 0.0) or 0.0),
  69. ),
  70. reverse=True,
  71. )
  72. def _tool_card(name: str, description: str, inputs: list[dict], outputs: list[str], notes: list[str] | None = None) -> dict:
  73. return {
  74. "name": name,
  75. "description": description,
  76. "inputs": inputs,
  77. "outputs": outputs,
  78. "notes": notes or [],
  79. }
  80. NEWS_TOOL_CARDS = [
  81. _tool_card(
  82. "get_latest_events",
  83. "Get the newest deduplicated clusters for a topic or resolved entity-like query.",
  84. [
  85. {"name": "topic", "type": "string", "default": "crypto", "meaning": "coarse category or entity-like topic"},
  86. {"name": "limit", "type": "integer", "default": 5, "range": "1-20"},
  87. {"name": "include_articles", "type": "boolean", "default": False},
  88. ],
  89. ["headline", "summary", "entities", "sentiment", "importance", "sources", "timestamp", "articles?"],
  90. ["Use when you want the freshest clusters and are willing to let the server decide topic vs entity mode."],
  91. ),
  92. _tool_card(
  93. "get_events_for_entity",
  94. "Search recent clusters for a person, place, company, or theme by entity matching.",
  95. [
  96. {"name": "entity", "type": "string", "meaning": "entity label or phrase"},
  97. {"name": "timeframe", "type": "string", "default": "24h", "examples": ["24h", "72h", "3d"]},
  98. {"name": "limit", "type": "integer", "default": 10, "range": "1-30"},
  99. {"name": "include_articles", "type": "boolean", "default": False},
  100. ],
  101. ["headline", "summary", "entities", "sentiment", "importance", "sources", "timestamp", "articles?"],
  102. ["Normalization is automatic; use this for an entity-centered deep dive."],
  103. ),
  104. _tool_card(
  105. "get_event_summary",
  106. "Produce a concise LLM-written explanation for one cluster and key facts.",
  107. [
  108. {"name": "event_id", "type": "string", "meaning": "cluster_id; do not surface in user-facing prose"},
  109. {"name": "include_articles", "type": "boolean", "default": False},
  110. ],
  111. ["headline", "mergedSummary", "keyFacts", "sources", "articles?"],
  112. ["Prefer this after you have already chosen a specific cluster to explain."],
  113. ),
  114. _tool_card(
  115. "detect_emerging_topics",
  116. "Surface entities and phrases starting to matter in the recent window.",
  117. [{"name": "limit", "type": "integer", "default": 10, "range": "1-20"}],
  118. ["topic", "trend_score", "related_entities", "signal_type", "count", "avg_importance"],
  119. ["Good for 'what is heating up?' style questions."],
  120. ),
  121. _tool_card(
  122. "get_news_sentiment",
  123. "Estimate sentiment around an entity over a lookback window.",
  124. [
  125. {"name": "entity", "type": "string"},
  126. {"name": "timeframe", "type": "string", "default": "24h"},
  127. ],
  128. ["entity", "sentiment", "score", "cluster_count"],
  129. ["Use after locating a cluster set or entity neighborhood."],
  130. ),
  131. _tool_card(
  132. "get_related_recent_entities",
  133. "Blend local co-occurrence with Google Trends related topics, while preserving mids where available.",
  134. [
  135. {"name": "subject", "type": "string", "meaning": "canonical entity or subject phrase"},
  136. {"name": "timeframe", "type": "string", "default": "72h"},
  137. {"name": "limit", "type": "integer", "default": 10, "range": "1-25"},
  138. {"name": "include_trends", "type": "boolean", "default": True},
  139. ],
  140. ["subject", "related[].normalized", "related[].canonical_label", "related[].mid", "related[].sources", "related[].scores"],
  141. ["Use this to drill from a subject into related entities, then feed those into get_events_for_entity."],
  142. ),
  143. ]
  144. NEWS_COMPOSITION_RECIPES = [
  145. {
  146. "name": "fresh-news-tail",
  147. "steps": [
  148. "get_latest_events(topic=...)",
  149. "optionally get_event_summary(event_id=...) for the strongest cluster",
  150. ],
  151. "notes": ["Best for a quick tail of what is happening now."]
  152. },
  153. {
  154. "name": "entity-deep-dive",
  155. "steps": [
  156. "get_events_for_entity(entity=...)",
  157. "get_event_summary(event_id=...)",
  158. "get_news_sentiment(entity=..., timeframe=...)",
  159. ],
  160. "notes": ["Prefer canonical entity labels when you have them; the server normalizes for you."],
  161. },
  162. {
  163. "name": "subject-neighborhood",
  164. "steps": [
  165. "get_related_recent_entities(subject=...)",
  166. "for each strong related entity, call get_events_for_entity(entity=...)",
  167. ],
  168. "notes": ["Use this when you want a graph-like expansion around a subject."]
  169. },
  170. {
  171. "name": "emerging-signal",
  172. "steps": [
  173. "detect_emerging_topics(limit=...)",
  174. "choose a topic/entity",
  175. "get_events_for_entity(entity=...)",
  176. "get_news_sentiment(entity=...)",
  177. ],
  178. "notes": ["Good for trend scouting and risk mapping."],
  179. },
  180. ]
  181. @mcp.tool(description="Investigate a topic and return the newest deduplicated news clusters, sorted by recency.")
  182. async def get_latest_events(topic: str = "crypto", limit: int = 5, include_articles: bool = False):
  183. limit = max(1, min(int(limit), 20))
  184. # If the caller passes an entity-like value, resolve it and use the canonical
  185. # entity as the query lens. Otherwise keep the original topic path.
  186. topic_norm = normalize_query(topic).lower()
  187. resolved = resolve_entity_via_trends(topic_norm)
  188. allowed = {t.lower() for t in DEFAULT_TOPICS}
  189. is_topic = topic_norm in allowed
  190. query_terms = {
  191. topic_norm,
  192. str(resolved.get("normalized") or "").strip().lower(),
  193. str(resolved.get("canonical_label") or "").strip().lower(),
  194. str(resolved.get("mid") or "").strip().lower(),
  195. }
  196. query_terms = {q for q in query_terms if q}
  197. store = SQLiteClusterStore(DB_PATH)
  198. if is_topic:
  199. # Cache-first: only refresh if we currently have no fresh clusters for this topic.
  200. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  201. if not clusters:
  202. await refresh_clusters(topic=topic_norm, limit=200)
  203. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  204. else:
  205. # Entity-aware mode: search recent clusters across all topics and match by
  206. # raw entity, canonical label, or MID.
  207. clusters = store.get_latest_clusters_all_topics(ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit * 8)
  208. filtered = []
  209. for c in clusters:
  210. haystack = _cluster_entity_haystack(c)
  211. if any(any(term in item for item in haystack) for term in query_terms):
  212. filtered.append(c)
  213. if len(filtered) >= limit:
  214. break
  215. clusters = filtered
  216. out = []
  217. for c in _sort_clusters_by_recency(clusters):
  218. item = {
  219. "cluster_id": c.get("cluster_id"),
  220. "headline": c.get("headline"),
  221. "summary": c.get("summary"),
  222. "entities": c.get("entities", []),
  223. "sentiment": c.get("sentiment", "neutral"),
  224. "importance": c.get("importance", 0.0),
  225. "sources": c.get("sources", []),
  226. "timestamp": c.get("timestamp"),
  227. }
  228. if include_articles:
  229. # Return minimal article fields to keep responses compact.
  230. arts = c.get("articles", []) or []
  231. item["articles"] = [
  232. {
  233. "title": a.get("title"),
  234. "url": a.get("url"),
  235. "source": a.get("source"),
  236. "timestamp": a.get("timestamp"),
  237. }
  238. for a in arts
  239. if isinstance(a, dict)
  240. ]
  241. out.append(item)
  242. return out
  243. @mcp.tool(description="Investigate a person, company, place, or theme by matching extracted entities within a time window.")
  244. async def get_events_for_entity(entity: str, limit: int = 10, timeframe: str = "24h", include_articles: bool = False):
  245. limit = max(1, min(int(limit), 30))
  246. query = normalize_query(entity).strip().lower()
  247. if not query:
  248. return []
  249. resolved = resolve_entity_via_trends(query)
  250. query_terms = {
  251. query,
  252. str(resolved.get("normalized") or "").strip().lower(),
  253. str(resolved.get("canonical_label") or "").strip().lower(),
  254. str(resolved.get("mid") or "").strip().lower(),
  255. }
  256. query_terms = {q for q in query_terms if q}
  257. store = SQLiteClusterStore(DB_PATH)
  258. def _match_clusters(clusters: list[dict]) -> list[dict]:
  259. hits: list[dict] = []
  260. for c in _sort_clusters_by_recency(clusters):
  261. haystack = _cluster_entity_haystack(c)
  262. if any(any(term in item for item in haystack) for term in query_terms):
  263. hits.append(c)
  264. if len(hits) >= limit:
  265. break
  266. return hits
  267. hours = _parse_timeframe_to_hours(timeframe)
  268. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=max(200, limit * 10))
  269. hits = _match_clusters(clusters)
  270. out = []
  271. for c in hits:
  272. item = {
  273. "cluster_id": c.get("cluster_id"),
  274. "headline": c.get("headline"),
  275. "summary": c.get("summary"),
  276. "entities": c.get("entities", []),
  277. "sentiment": c.get("sentiment", "neutral"),
  278. "importance": c.get("importance", 0.0),
  279. "sources": c.get("sources", []),
  280. "timestamp": c.get("timestamp"),
  281. }
  282. if include_articles:
  283. arts = c.get("articles", []) or []
  284. item["articles"] = [
  285. {
  286. "title": a.get("title"),
  287. "url": a.get("url"),
  288. "source": a.get("source"),
  289. "timestamp": a.get("timestamp"),
  290. }
  291. for a in arts
  292. if isinstance(a, dict)
  293. ]
  294. out.append(item)
  295. return out
  296. @mcp.tool(description="Return entities most commonly associated with the subject in recent clusters, optionally blended with Google Trends suggestions.")
  297. async def get_related_recent_entities(subject: str, timeframe: str = "72h", limit: int = 10, include_trends: bool = True):
  298. limit = max(1, min(int(limit), 25))
  299. hours = _parse_timeframe_to_hours(timeframe)
  300. include_trends_bool = str(include_trends).strip().lower() not in {"false", "0", "no"}
  301. store = SQLiteClusterStore(DB_PATH)
  302. result = related_recent_entities(
  303. store=store,
  304. subject=subject,
  305. timeframe_hours=hours,
  306. limit=limit,
  307. include_trends=include_trends_bool,
  308. )
  309. return result
  310. @mcp.tool(description="Investigate one cluster in depth and return a concise LLM-written explanation plus key facts.")
  311. async def get_event_summary(event_id: str, include_articles: bool = False):
  312. store = SQLiteClusterStore(DB_PATH)
  313. # Summary cache: reuse if present within TTL.
  314. cached_summary = store.get_cluster_summary(
  315. cluster_id=event_id,
  316. ttl_hours=DEFAULT_LOOKBACK_HOURS,
  317. )
  318. if cached_summary:
  319. out = {
  320. "event_id": event_id,
  321. "headline": cached_summary.get("headline"),
  322. "mergedSummary": cached_summary.get("mergedSummary"),
  323. "keyFacts": cached_summary.get("keyFacts", []),
  324. "sources": cached_summary.get("sources", []),
  325. }
  326. if include_articles:
  327. cluster = store.get_cluster_by_id(event_id)
  328. arts = (cluster or {}).get("articles", []) or []
  329. out["articles"] = [
  330. {
  331. "title": a.get("title"),
  332. "url": a.get("url"),
  333. "source": a.get("source"),
  334. "timestamp": a.get("timestamp"),
  335. }
  336. for a in arts
  337. if isinstance(a, dict)
  338. ]
  339. return out
  340. cluster = store.get_cluster_by_id(event_id)
  341. if not cluster:
  342. return {
  343. "event_id": event_id,
  344. "error": "NOT_FOUND",
  345. }
  346. articles_out = None
  347. if include_articles:
  348. arts = cluster.get("articles", []) or []
  349. articles_out = [
  350. {
  351. "title": a.get("title"),
  352. "url": a.get("url"),
  353. "source": a.get("source"),
  354. "timestamp": a.get("timestamp"),
  355. }
  356. for a in arts
  357. if isinstance(a, dict)
  358. ]
  359. summary = await summarize_cluster_llm(cluster)
  360. store.upsert_cluster_summary(event_id, summary)
  361. out = {
  362. "event_id": event_id,
  363. "headline": summary.get("headline"),
  364. "mergedSummary": summary.get("mergedSummary"),
  365. "keyFacts": summary.get("keyFacts", []),
  366. "sources": summary.get("sources", []),
  367. }
  368. if include_articles:
  369. out["articles"] = articles_out or []
  370. return out
  371. @mcp.tool(description="Explore what is starting to matter: surface emerging entities and phrases from recent clusters.")
  372. async def detect_emerging_topics(limit: int = 10):
  373. limit = max(1, min(int(limit), 20))
  374. store = SQLiteClusterStore(DB_PATH)
  375. clusters = store.get_latest_clusters_all_topics(ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=200)
  376. import re
  377. entity_counts = Counter()
  378. entity_importance_sum = Counter()
  379. # co-occurrence: ent -> other_ent -> count
  380. entity_cooccur = {}
  381. phrase_counts = Counter()
  382. topic_counts = Counter()
  383. # Very light heuristics to reduce “meta entities” dominating emerging topics.
  384. # Keep it conservative: only skip obvious boilerplate.
  385. def _is_generic_entity(ent: str) -> bool:
  386. e = str(ent).strip().lower()
  387. if not e:
  388. return True
  389. if len(e) < 4:
  390. return True
  391. # common outlet-ish / meta-ish tokens
  392. if e in {"news", "latest", "breaking"}:
  393. return True
  394. return False
  395. for c in clusters:
  396. topic_counts[c.get("topic", "other")] += 1
  397. ents_in_cluster = [e for e in (c.get("entities", []) or []) if not _is_generic_entity(e)]
  398. ents_in_cluster_norm = [str(e).strip().lower() for e in ents_in_cluster if str(e).strip()]
  399. for ent in ents_in_cluster_norm:
  400. if _is_generic_entity(ent):
  401. continue
  402. entity_counts[ent] += 1
  403. try:
  404. entity_importance_sum[ent] += float(c.get("importance", 0.0) or 0.0)
  405. except Exception:
  406. pass
  407. # update co-occurrence counts
  408. for i in range(len(ents_in_cluster_norm)):
  409. a = ents_in_cluster_norm[i]
  410. if not a:
  411. continue
  412. entity_cooccur.setdefault(a, Counter())
  413. for j in range(len(ents_in_cluster_norm)):
  414. if i == j:
  415. continue
  416. b = ents_in_cluster_norm[j]
  417. if not b:
  418. continue
  419. entity_cooccur[a][b] += 1
  420. text = f"{c.get('headline','')} {c.get('summary','')}"
  421. words = [w for w in re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())]
  422. for i in range(len(words) - 1):
  423. phrase = f"{words[i]} {words[i+1]}"
  424. if len(phrase) > 6:
  425. phrase_counts[phrase] += 1
  426. emerging = []
  427. # Combine frequency with average importance so “big signal” rises over pure repetition.
  428. for ent, count in entity_counts.most_common(limit):
  429. avg_imp = entity_importance_sum[ent] / max(1, count)
  430. # avg_imp is typically 0..~1; keep score bounded.
  431. trend_score = 0.25 + 0.40 * min(1.0, avg_imp) + 0.08 * min(6.0, float(count))
  432. related = []
  433. for other, _cnt in (entity_cooccur.get(ent) or Counter()).most_common(3):
  434. # avoid returning the entity itself (shouldn't happen, but be safe)
  435. if other != ent:
  436. related.append(other)
  437. emerging.append({
  438. "topic": ent,
  439. "trend_score": min(0.99, round(trend_score, 2)),
  440. "related_entities": related if related else [ent],
  441. "signal_type": "entity",
  442. "count": count,
  443. "avg_importance": round(avg_imp, 3),
  444. })
  445. for phrase, count in phrase_counts.most_common(limit * 2):
  446. if any(item["topic"] == phrase for item in emerging):
  447. continue
  448. emerging.append({
  449. "topic": phrase.title(),
  450. "trend_score": min(0.99, round(0.20 + 0.10 * count, 2)),
  451. "related_entities": [],
  452. "signal_type": "phrase",
  453. "count": count,
  454. })
  455. if len(emerging) >= limit:
  456. break
  457. return emerging[:limit]
  458. @mcp.tool(description="Investigate whether sentiment around an entity is positive, negative, or neutral over a chosen lookback window.")
  459. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  460. store = SQLiteClusterStore(DB_PATH)
  461. ent = normalize_query(entity).strip().lower()
  462. resolved = resolve_entity_via_trends(ent)
  463. query_terms = {
  464. ent,
  465. str(resolved.get("normalized") or "").strip().lower(),
  466. str(resolved.get("canonical_label") or "").strip().lower(),
  467. str(resolved.get("mid") or "").strip().lower(),
  468. }
  469. query_terms = {q for q in query_terms if q}
  470. if not ent:
  471. return {
  472. "entity": entity,
  473. "sentiment": "neutral",
  474. "score": 0.0,
  475. "cluster_count": 0,
  476. }
  477. # timeframe: accept '24h' or '24'
  478. tf = str(timeframe).strip().lower()
  479. try:
  480. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  481. except Exception:
  482. hours = 24
  483. hours = max(1, min(int(hours), 168))
  484. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  485. matched = []
  486. for c in clusters:
  487. haystack = _cluster_entity_haystack(c)
  488. if any(any(term in item for item in haystack) for term in query_terms):
  489. matched.append(c)
  490. if not matched:
  491. return {
  492. "entity": entity,
  493. "sentiment": "neutral",
  494. "score": 0.0,
  495. "cluster_count": 0,
  496. }
  497. scores = []
  498. for c in matched:
  499. s = c.get("sentimentScore")
  500. if s is not None:
  501. try:
  502. scores.append(float(s))
  503. except Exception:
  504. pass
  505. avg_score = sum(scores) / len(scores) if scores else 0.0
  506. # Keep the label aligned with the numeric score.
  507. # Small magnitudes are treated as neutral to avoid noisy label flips.
  508. if avg_score >= 0.15:
  509. sentiment = "positive"
  510. elif avg_score <= -0.15:
  511. sentiment = "negative"
  512. else:
  513. sentiment = "neutral"
  514. return {
  515. "entity": entity,
  516. "sentiment": sentiment,
  517. "score": round(avg_score, 3),
  518. "cluster_count": len(matched),
  519. }
  520. @mcp.tool(description="Describe the server tool surface, how tools fit together, and output conventions for downstream agents.")
  521. async def get_capabilities():
  522. return {
  523. "server": {
  524. "name": "news-mcp",
  525. "purpose": "Recent news clusters, entity drill-down, sentiment, emerging topics, and related-entity expansion.",
  526. "output_conventions": {
  527. "cluster_ids": "Do not surface cluster_id in user-facing prose unless explicitly requested; treat it as internal navigation metadata.",
  528. "sources": "Always preserve and display sources when summarizing a cluster or entity result.",
  529. "timestamps": "Mention timestamps consistently when comparing multiple clusters or when recency matters.",
  530. },
  531. },
  532. "tools": NEWS_TOOL_CARDS,
  533. "recipes": NEWS_COMPOSITION_RECIPES,
  534. "guidance": [
  535. "Use get_latest_events for a tail, get_events_for_entity for entity deep dives, and get_related_recent_entities for neighborhood expansion.",
  536. "Prefer normalized/canonical entities when possible, but the server will resolve common aliases and MIDs for you.",
  537. "When presenting results to users, summarize the cluster; avoid exposing internal IDs unless they are needed for follow-up tool calls.",
  538. ],
  539. }
  540. def _parse_timeframe_to_hours(timeframe: str) -> int:
  541. tf = str(timeframe).strip().lower()
  542. try:
  543. if tf.endswith("d"):
  544. days = int(tf[:-1])
  545. return max(1, days * 24)
  546. if tf.endswith("h"):
  547. return max(1, int(tf[:-1]))
  548. return max(1, int(tf))
  549. except Exception:
  550. return 24
  551. app = FastAPI(title="News MCP Server")
  552. logger = logging.getLogger("news_mcp.startup")
  553. app.mount("/mcp", mcp.sse_app())
  554. _background_task_started = False
  555. @app.on_event("startup")
  556. async def _start_background_refresh():
  557. global _background_task_started
  558. if _background_task_started:
  559. return
  560. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  561. return
  562. _background_task_started = True
  563. logger.info("news-mcp llm config: %s", active_llm_config())
  564. store = SQLiteClusterStore(DB_PATH)
  565. prune_result = store.prune_if_due(
  566. pruning_enabled=NEWS_PRUNING_ENABLED,
  567. retention_days=NEWS_RETENTION_DAYS,
  568. interval_hours=NEWS_PRUNE_INTERVAL_HOURS,
  569. )
  570. logger.info("startup prune_result=%s", prune_result)
  571. async def _loop():
  572. if not NEWS_BACKGROUND_REFRESH_ON_START:
  573. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  574. while True:
  575. try:
  576. # Refresh all topics by passing topic=None
  577. await refresh_clusters(topic=None, limit=200)
  578. except Exception:
  579. # Avoid crashing the server on network errors.
  580. pass
  581. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  582. asyncio.create_task(_loop())
  583. @app.get("/")
  584. def root():
  585. return {
  586. "status": "ok",
  587. "transport": "fastmcp+sse",
  588. "mount": "/mcp",
  589. "tools": [
  590. "get_latest_events",
  591. "get_events_for_entity",
  592. "get_event_summary",
  593. "detect_emerging_topics",
  594. "get_news_sentiment",
  595. "get_related_recent_entities",
  596. "get_capabilities",
  597. ],
  598. "refresh": {
  599. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  600. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  601. },
  602. "retention": {
  603. "lookback_hours": DEFAULT_LOOKBACK_HOURS,
  604. "retention_days": NEWS_RETENTION_DAYS,
  605. },
  606. "pruning": {
  607. "enabled": NEWS_PRUNING_ENABLED,
  608. "interval_hours": NEWS_PRUNE_INTERVAL_HOURS,
  609. },
  610. }
  611. @app.get("/health")
  612. def health():
  613. store = SQLiteClusterStore(DB_PATH)
  614. return {
  615. "status": "ok",
  616. "lookback_hours": DEFAULT_LOOKBACK_HOURS,
  617. "db": str(DB_PATH),
  618. "refresh": store.get_feed_state("breakingthenews"),
  619. "pruning": store.get_prune_state(
  620. pruning_enabled=NEWS_PRUNING_ENABLED,
  621. retention_days=NEWS_RETENTION_DAYS,
  622. interval_hours=NEWS_PRUNE_INTERVAL_HOURS,
  623. ),
  624. }