mcp_server_fastmcp.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. from __future__ import annotations
  2. import asyncio
  3. import logging
  4. import time
  5. from collections import Counter
  6. from datetime import datetime, timezone
  7. from email.utils import parsedate_to_datetime
  8. from fastapi import FastAPI
  9. from mcp.server.fastmcp import FastMCP
  10. from mcp.server.transport_security import TransportSecuritySettings
  11. from news_mcp.config import DEFAULT_LOOKBACK_HOURS, DEFAULT_TOPICS, DB_PATH
  12. from news_mcp.config import (
  13. NEWS_PRUNE_INTERVAL_HOURS,
  14. NEWS_PRUNING_ENABLED,
  15. NEWS_REFRESH_INTERVAL_SECONDS,
  16. NEWS_BACKGROUND_REFRESH_ENABLED,
  17. NEWS_BACKGROUND_REFRESH_ON_START,
  18. NEWS_RETENTION_DAYS,
  19. )
  20. from news_mcp.jobs.poller import refresh_clusters
  21. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  22. from news_mcp.dashboard.dashboard_store import DashboardStore
  23. from news_mcp.enrichment.llm_enrich import summarize_cluster_llm
  24. from news_mcp.trends_resolution import resolve_entity_via_trends
  25. from news_mcp.llm import active_llm_config
  26. from news_mcp.entity_normalize import normalize_query
  27. from news_mcp.related_entities import related_recent_entities
  28. logging.basicConfig(
  29. level=logging.INFO,
  30. format="%(asctime)s %(levelname)s %(name)s: %(message)s",
  31. )
  32. _PROCESS_STARTED_AT = time.monotonic()
  33. mcp = FastMCP(
  34. "news-mcp",
  35. transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False),
  36. )
  37. def _cluster_entity_haystack(cluster: dict) -> list[str]:
  38. """Collect the normalized entity clues attached to a cluster."""
  39. values: list[str] = []
  40. for ent in cluster.get("entities", []) or []:
  41. values.append(str(ent).strip().lower())
  42. for res in cluster.get("entityResolutions", []) or []:
  43. if not isinstance(res, dict):
  44. continue
  45. for key in ("normalized", "canonical_label", "mid"):
  46. val = res.get(key)
  47. if val:
  48. values.append(str(val).strip().lower())
  49. return [v for v in values if v]
  50. def _parse_cluster_timestamp(value) -> datetime:
  51. if not value:
  52. return datetime.min.replace(tzinfo=timezone.utc)
  53. text = str(value).strip()
  54. if not text:
  55. return datetime.min.replace(tzinfo=timezone.utc)
  56. try:
  57. dt = datetime.fromisoformat(text.replace("Z", "+00:00"))
  58. if dt.tzinfo is None:
  59. dt = dt.replace(tzinfo=timezone.utc)
  60. return dt.astimezone(timezone.utc)
  61. except Exception:
  62. pass
  63. try:
  64. dt = parsedate_to_datetime(text)
  65. if dt.tzinfo is None:
  66. dt = dt.replace(tzinfo=timezone.utc)
  67. return dt.astimezone(timezone.utc)
  68. except Exception:
  69. return datetime.min.replace(tzinfo=timezone.utc)
  70. def _sort_clusters_by_recency(clusters: list[dict]) -> list[dict]:
  71. return sorted(
  72. clusters,
  73. key=lambda c: (
  74. _parse_cluster_timestamp(c.get("timestamp")),
  75. float(c.get("importance", 0.0) or 0.0),
  76. ),
  77. reverse=True,
  78. )
  79. def _tool_card(name: str, description: str, inputs: list[dict], outputs: list[str], notes: list[str] | None = None) -> dict:
  80. return {
  81. "name": name,
  82. "description": description,
  83. "inputs": inputs,
  84. "outputs": outputs,
  85. "notes": notes or [],
  86. }
  87. NEWS_TOOL_CARDS = [
  88. _tool_card(
  89. "get_latest_events",
  90. "Get the newest deduplicated clusters for a topic or resolved entity-like query.",
  91. [
  92. {"name": "topic", "type": "string", "default": "crypto", "meaning": "coarse category or entity-like topic"},
  93. {"name": "limit", "type": "integer", "default": 5, "range": "1-20"},
  94. {"name": "include_articles", "type": "boolean", "default": False},
  95. ],
  96. ["headline", "summary", "entities", "sentiment", "importance", "sources", "timestamp", "articles?"],
  97. ["Use when you want the freshest clusters and are willing to let the server decide topic vs entity mode."],
  98. ),
  99. _tool_card(
  100. "get_events_for_entity",
  101. "Search recent clusters for a person, place, company, or theme by entity matching.",
  102. [
  103. {"name": "entity", "type": "string", "meaning": "entity label or phrase"},
  104. {"name": "timeframe", "type": "string", "default": "24h", "examples": ["24h", "72h", "3d"]},
  105. {"name": "limit", "type": "integer", "default": 10, "range": "1-30"},
  106. {"name": "include_articles", "type": "boolean", "default": False},
  107. ],
  108. ["headline", "summary", "entities", "sentiment", "importance", "sources", "timestamp", "articles?"],
  109. ["Normalization is automatic; use this for an entity-centered deep dive."],
  110. ),
  111. _tool_card(
  112. "get_event_summary",
  113. "Produce a concise LLM-written explanation for one cluster and key facts.",
  114. [
  115. {"name": "event_id", "type": "string", "meaning": "cluster_id; do not surface in user-facing prose"},
  116. {"name": "include_articles", "type": "boolean", "default": False},
  117. ],
  118. ["headline", "mergedSummary", "keyFacts", "sources", "articles?"],
  119. ["Prefer this after you have already chosen a specific cluster to explain."],
  120. ),
  121. _tool_card(
  122. "detect_emerging_topics",
  123. "Surface entities and phrases starting to matter in the recent window.",
  124. [{"name": "limit", "type": "integer", "default": 10, "range": "1-20"}],
  125. ["topic", "trend_score", "related_entities", "signal_type", "count", "avg_importance"],
  126. ["Good for 'what is heating up?' style questions."],
  127. ),
  128. _tool_card(
  129. "get_news_sentiment",
  130. "Estimate sentiment around an entity over a lookback window.",
  131. [
  132. {"name": "entity", "type": "string"},
  133. {"name": "timeframe", "type": "string", "default": "24h"},
  134. ],
  135. ["entity", "sentiment", "score", "cluster_count"],
  136. ["Use after locating a cluster set or entity neighborhood."],
  137. ),
  138. _tool_card(
  139. "get_related_recent_entities",
  140. "Blend local co-occurrence with Google Trends related topics, while preserving mids where available.",
  141. [
  142. {"name": "subject", "type": "string", "meaning": "canonical entity or subject phrase"},
  143. {"name": "timeframe", "type": "string", "default": "72h"},
  144. {"name": "limit", "type": "integer", "default": 10, "range": "1-25"},
  145. {"name": "include_trends", "type": "boolean", "default": True},
  146. ],
  147. ["subject", "related[].normalized", "related[].canonical_label", "related[].mid", "related[].sources", "related[].scores"],
  148. ["Use this to drill from a subject into related entities, then feed those into get_events_for_entity."],
  149. ),
  150. ]
  151. NEWS_COMPOSITION_RECIPES = [
  152. {
  153. "name": "fresh-news-tail",
  154. "steps": [
  155. "get_latest_events(topic=...)",
  156. "optionally get_event_summary(event_id=...) for the strongest cluster",
  157. ],
  158. "notes": ["Best for a quick tail of what is happening now."]
  159. },
  160. {
  161. "name": "entity-deep-dive",
  162. "steps": [
  163. "get_events_for_entity(entity=...)",
  164. "get_event_summary(event_id=...)",
  165. "get_news_sentiment(entity=..., timeframe=...)",
  166. ],
  167. "notes": ["Prefer canonical entity labels when you have them; the server normalizes for you."],
  168. },
  169. {
  170. "name": "subject-neighborhood",
  171. "steps": [
  172. "get_related_recent_entities(subject=...)",
  173. "for each strong related entity, call get_events_for_entity(entity=...)",
  174. ],
  175. "notes": ["Use this when you want a graph-like expansion around a subject."]
  176. },
  177. {
  178. "name": "emerging-signal",
  179. "steps": [
  180. "detect_emerging_topics(limit=...)",
  181. "choose a topic/entity",
  182. "get_events_for_entity(entity=...)",
  183. "get_news_sentiment(entity=...)",
  184. ],
  185. "notes": ["Good for trend scouting and risk mapping."],
  186. },
  187. ]
  188. NEWS_AGENT_TIPS = [
  189. "If you need a fast answer, start with get_latest_events, then summarize the strongest cluster with get_event_summary.",
  190. "If a user asks about a person/place/company/theme, use get_events_for_entity before broadening to get_related_recent_entities.",
  191. "Treat cluster_id as an internal cursor, not user-facing output; use it only for follow-up tool calls.",
  192. "When describing clusters, keep sources and timestamps visible so the user can assess recency and provenance.",
  193. "Prefer a short chain of tools over many parallel calls unless you are building a neighborhood map or comparison table.",
  194. "For tricky names, rely on the server’s resolver instead of inventing alias rules in the client.",
  195. ]
  196. NEWS_EXAMPLE_CHAINS = [
  197. {
  198. "task": "What is happening now?",
  199. "chain": [
  200. "get_latest_events(topic=...)",
  201. "get_event_summary(event_id=...) if one cluster looks important",
  202. ],
  203. },
  204. {
  205. "task": "Deep dive on an entity",
  206. "chain": [
  207. "get_events_for_entity(entity=..., timeframe=...)",
  208. "get_news_sentiment(entity=..., timeframe=...)",
  209. "get_event_summary(event_id=...) for the strongest cluster",
  210. ],
  211. },
  212. {
  213. "task": "Broaden from a subject",
  214. "chain": [
  215. "get_related_recent_entities(subject=..., include_trends=true)",
  216. "get_events_for_entity(entity=...) for the strongest related entities",
  217. ],
  218. },
  219. {
  220. "task": "Find what is emerging",
  221. "chain": [
  222. "detect_emerging_topics(limit=...)",
  223. "get_events_for_entity(entity=...) on one or two emerging terms",
  224. ],
  225. },
  226. ]
  227. @mcp.tool(description="Investigate a topic and return the newest deduplicated news clusters, sorted by recency.")
  228. async def get_latest_events(topic: str = "crypto", limit: int = 5, include_articles: bool = False):
  229. limit = max(1, min(int(limit), 20))
  230. # If the caller passes an entity-like value, resolve it and use the canonical
  231. # entity as the query lens. Otherwise keep the original topic path.
  232. topic_norm = normalize_query(topic).lower()
  233. resolved = resolve_entity_via_trends(topic_norm)
  234. allowed = {t.lower() for t in DEFAULT_TOPICS}
  235. is_topic = topic_norm in allowed
  236. query_terms = {
  237. topic_norm,
  238. str(resolved.get("normalized") or "").strip().lower(),
  239. str(resolved.get("canonical_label") or "").strip().lower(),
  240. str(resolved.get("mid") or "").strip().lower(),
  241. }
  242. query_terms = {q for q in query_terms if q}
  243. store = SQLiteClusterStore(DB_PATH)
  244. if is_topic:
  245. # Cache-first: only refresh if we currently have no fresh clusters for this topic.
  246. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  247. if not clusters:
  248. await refresh_clusters(topic=topic_norm, limit=200)
  249. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  250. else:
  251. # Entity-aware mode: search recent clusters across all topics and match by
  252. # raw entity, canonical label, or MID.
  253. clusters = store.get_latest_clusters_all_topics(ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit * 8)
  254. filtered = []
  255. for c in clusters:
  256. haystack = _cluster_entity_haystack(c)
  257. if any(any(term in item for item in haystack) for term in query_terms):
  258. filtered.append(c)
  259. if len(filtered) >= limit:
  260. break
  261. clusters = filtered
  262. out = []
  263. for c in _sort_clusters_by_recency(clusters):
  264. item = {
  265. "cluster_id": c.get("cluster_id"),
  266. "headline": c.get("headline"),
  267. "summary": c.get("summary"),
  268. "entities": c.get("entities", []),
  269. "sentiment": c.get("sentiment", "neutral"),
  270. "importance": c.get("importance", 0.0),
  271. "sources": c.get("sources", []),
  272. "timestamp": c.get("timestamp"),
  273. }
  274. if include_articles:
  275. # Return minimal article fields to keep responses compact.
  276. arts = c.get("articles", []) or []
  277. item["articles"] = [
  278. {
  279. "title": a.get("title"),
  280. "url": a.get("url"),
  281. "source": a.get("source"),
  282. "timestamp": a.get("timestamp"),
  283. }
  284. for a in arts
  285. if isinstance(a, dict)
  286. ]
  287. out.append(item)
  288. return out
  289. @mcp.tool(description="Investigate a person, company, place, or theme by matching extracted entities within a time window.")
  290. async def get_events_for_entity(entity: str, limit: int = 10, timeframe: str = "24h", include_articles: bool = False):
  291. limit = max(1, min(int(limit), 30))
  292. query = normalize_query(entity).strip().lower()
  293. if not query:
  294. return []
  295. resolved = resolve_entity_via_trends(query)
  296. query_terms = {
  297. query,
  298. str(resolved.get("normalized") or "").strip().lower(),
  299. str(resolved.get("canonical_label") or "").strip().lower(),
  300. str(resolved.get("mid") or "").strip().lower(),
  301. }
  302. query_terms = {q for q in query_terms if q}
  303. store = SQLiteClusterStore(DB_PATH)
  304. def _match_clusters(clusters: list[dict]) -> list[dict]:
  305. hits: list[dict] = []
  306. for c in _sort_clusters_by_recency(clusters):
  307. haystack = _cluster_entity_haystack(c)
  308. if any(any(term in item for item in haystack) for term in query_terms):
  309. hits.append(c)
  310. if len(hits) >= limit:
  311. break
  312. return hits
  313. hours = _parse_timeframe_to_hours(timeframe)
  314. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=max(200, limit * 10))
  315. hits = _match_clusters(clusters)
  316. out = []
  317. for c in hits:
  318. item = {
  319. "cluster_id": c.get("cluster_id"),
  320. "headline": c.get("headline"),
  321. "summary": c.get("summary"),
  322. "entities": c.get("entities", []),
  323. "sentiment": c.get("sentiment", "neutral"),
  324. "importance": c.get("importance", 0.0),
  325. "sources": c.get("sources", []),
  326. "timestamp": c.get("timestamp"),
  327. }
  328. if include_articles:
  329. arts = c.get("articles", []) or []
  330. item["articles"] = [
  331. {
  332. "title": a.get("title"),
  333. "url": a.get("url"),
  334. "source": a.get("source"),
  335. "timestamp": a.get("timestamp"),
  336. }
  337. for a in arts
  338. if isinstance(a, dict)
  339. ]
  340. out.append(item)
  341. return out
  342. @mcp.tool(description="Return entities most commonly associated with the subject in recent clusters, optionally blended with Google Trends suggestions.")
  343. async def get_related_recent_entities(subject: str, timeframe: str = "72h", limit: int = 10, include_trends: bool = True):
  344. limit = max(1, min(int(limit), 25))
  345. hours = _parse_timeframe_to_hours(timeframe)
  346. include_trends_bool = str(include_trends).strip().lower() not in {"false", "0", "no"}
  347. store = SQLiteClusterStore(DB_PATH)
  348. result = related_recent_entities(
  349. store=store,
  350. subject=subject,
  351. timeframe_hours=hours,
  352. limit=limit,
  353. include_trends=include_trends_bool,
  354. )
  355. return result
  356. @mcp.tool(description="Investigate one cluster in depth and return a concise LLM-written explanation plus key facts.")
  357. async def get_event_summary(event_id: str, include_articles: bool = False):
  358. store = SQLiteClusterStore(DB_PATH)
  359. # Summary cache: reuse if present within TTL.
  360. cached_summary = store.get_cluster_summary(
  361. cluster_id=event_id,
  362. ttl_hours=DEFAULT_LOOKBACK_HOURS,
  363. )
  364. if cached_summary:
  365. out = {
  366. "event_id": event_id,
  367. "headline": cached_summary.get("headline"),
  368. "mergedSummary": cached_summary.get("mergedSummary"),
  369. "keyFacts": cached_summary.get("keyFacts", []),
  370. "sources": cached_summary.get("sources", []),
  371. }
  372. if include_articles:
  373. cluster = store.get_cluster_by_id(event_id)
  374. arts = (cluster or {}).get("articles", []) or []
  375. out["articles"] = [
  376. {
  377. "title": a.get("title"),
  378. "url": a.get("url"),
  379. "source": a.get("source"),
  380. "timestamp": a.get("timestamp"),
  381. }
  382. for a in arts
  383. if isinstance(a, dict)
  384. ]
  385. return out
  386. cluster = store.get_cluster_by_id(event_id)
  387. if not cluster:
  388. return {
  389. "event_id": event_id,
  390. "error": "NOT_FOUND",
  391. }
  392. articles_out = None
  393. if include_articles:
  394. arts = cluster.get("articles", []) or []
  395. articles_out = [
  396. {
  397. "title": a.get("title"),
  398. "url": a.get("url"),
  399. "source": a.get("source"),
  400. "timestamp": a.get("timestamp"),
  401. }
  402. for a in arts
  403. if isinstance(a, dict)
  404. ]
  405. summary = await summarize_cluster_llm(cluster)
  406. store.upsert_cluster_summary(event_id, summary)
  407. out = {
  408. "event_id": event_id,
  409. "headline": summary.get("headline"),
  410. "mergedSummary": summary.get("mergedSummary"),
  411. "keyFacts": summary.get("keyFacts", []),
  412. "sources": summary.get("sources", []),
  413. }
  414. if include_articles:
  415. out["articles"] = articles_out or []
  416. return out
  417. @mcp.tool(description="Explore what is starting to matter: surface emerging entities and phrases from recent clusters.")
  418. async def detect_emerging_topics(limit: int = 10):
  419. limit = max(1, min(int(limit), 20))
  420. store = SQLiteClusterStore(DB_PATH)
  421. clusters = store.get_latest_clusters_all_topics(ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=200)
  422. import re
  423. entity_counts = Counter()
  424. entity_importance_sum = Counter()
  425. # co-occurrence: ent -> other_ent -> count
  426. entity_cooccur = {}
  427. phrase_counts = Counter()
  428. topic_counts = Counter()
  429. # Very light heuristics to reduce “meta entities” dominating emerging topics.
  430. # Keep it conservative: only skip obvious boilerplate.
  431. def _is_generic_entity(ent: str) -> bool:
  432. e = str(ent).strip().lower()
  433. if not e:
  434. return True
  435. if len(e) < 4:
  436. return True
  437. # common outlet-ish / meta-ish tokens
  438. if e in {"news", "latest", "breaking"}:
  439. return True
  440. return False
  441. for c in clusters:
  442. topic_counts[c.get("topic", "other")] += 1
  443. ents_in_cluster = [e for e in (c.get("entities", []) or []) if not _is_generic_entity(e)]
  444. ents_in_cluster_norm = [str(e).strip().lower() for e in ents_in_cluster if str(e).strip()]
  445. for ent in ents_in_cluster_norm:
  446. if _is_generic_entity(ent):
  447. continue
  448. entity_counts[ent] += 1
  449. try:
  450. entity_importance_sum[ent] += float(c.get("importance", 0.0) or 0.0)
  451. except Exception:
  452. pass
  453. # update co-occurrence counts
  454. for i in range(len(ents_in_cluster_norm)):
  455. a = ents_in_cluster_norm[i]
  456. if not a:
  457. continue
  458. entity_cooccur.setdefault(a, Counter())
  459. for j in range(len(ents_in_cluster_norm)):
  460. if i == j:
  461. continue
  462. b = ents_in_cluster_norm[j]
  463. if not b:
  464. continue
  465. entity_cooccur[a][b] += 1
  466. text = f"{c.get('headline','')} {c.get('summary','')}"
  467. words = [w for w in re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())]
  468. for i in range(len(words) - 1):
  469. phrase = f"{words[i]} {words[i+1]}"
  470. if len(phrase) > 6:
  471. phrase_counts[phrase] += 1
  472. emerging = []
  473. # Combine frequency with average importance so “big signal” rises over pure repetition.
  474. for ent, count in entity_counts.most_common(limit):
  475. avg_imp = entity_importance_sum[ent] / max(1, count)
  476. # avg_imp is typically 0..~1; keep score bounded.
  477. trend_score = 0.25 + 0.40 * min(1.0, avg_imp) + 0.08 * min(6.0, float(count))
  478. related = []
  479. for other, _cnt in (entity_cooccur.get(ent) or Counter()).most_common(3):
  480. # avoid returning the entity itself (shouldn't happen, but be safe)
  481. if other != ent:
  482. related.append(other)
  483. emerging.append({
  484. "topic": ent,
  485. "trend_score": min(0.99, round(trend_score, 2)),
  486. "related_entities": related if related else [ent],
  487. "signal_type": "entity",
  488. "count": count,
  489. "avg_importance": round(avg_imp, 3),
  490. })
  491. for phrase, count in phrase_counts.most_common(limit * 2):
  492. if any(item["topic"] == phrase for item in emerging):
  493. continue
  494. emerging.append({
  495. "topic": phrase.title(),
  496. "trend_score": min(0.99, round(0.20 + 0.10 * count, 2)),
  497. "related_entities": [],
  498. "signal_type": "phrase",
  499. "count": count,
  500. })
  501. if len(emerging) >= limit:
  502. break
  503. return emerging[:limit]
  504. @mcp.tool(description="Investigate whether sentiment around an entity is positive, negative, or neutral over a chosen lookback window.")
  505. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  506. store = SQLiteClusterStore(DB_PATH)
  507. ent = normalize_query(entity).strip().lower()
  508. resolved = resolve_entity_via_trends(ent)
  509. query_terms = {
  510. ent,
  511. str(resolved.get("normalized") or "").strip().lower(),
  512. str(resolved.get("canonical_label") or "").strip().lower(),
  513. str(resolved.get("mid") or "").strip().lower(),
  514. }
  515. query_terms = {q for q in query_terms if q}
  516. if not ent:
  517. return {
  518. "entity": entity,
  519. "sentiment": "neutral",
  520. "score": 0.0,
  521. "cluster_count": 0,
  522. }
  523. # timeframe: accept '24h' or '24'
  524. tf = str(timeframe).strip().lower()
  525. try:
  526. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  527. except Exception:
  528. hours = 24
  529. hours = max(1, min(int(hours), 168))
  530. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  531. matched = []
  532. for c in clusters:
  533. haystack = _cluster_entity_haystack(c)
  534. if any(any(term in item for item in haystack) for term in query_terms):
  535. matched.append(c)
  536. if not matched:
  537. return {
  538. "entity": entity,
  539. "sentiment": "neutral",
  540. "score": 0.0,
  541. "cluster_count": 0,
  542. }
  543. scores = []
  544. for c in matched:
  545. s = c.get("sentimentScore")
  546. if s is not None:
  547. try:
  548. scores.append(float(s))
  549. except Exception:
  550. pass
  551. avg_score = sum(scores) / len(scores) if scores else 0.0
  552. # Keep the label aligned with the numeric score.
  553. # Small magnitudes are treated as neutral to avoid noisy label flips.
  554. if avg_score >= 0.15:
  555. sentiment = "positive"
  556. elif avg_score <= -0.15:
  557. sentiment = "negative"
  558. else:
  559. sentiment = "neutral"
  560. return {
  561. "entity": entity,
  562. "sentiment": sentiment,
  563. "score": round(avg_score, 3),
  564. "cluster_count": len(matched),
  565. }
  566. @mcp.tool(description="Describe the server tool surface, how tools fit together, and output conventions for downstream agents.")
  567. async def get_capabilities():
  568. return {
  569. "server": {
  570. "name": "news-mcp",
  571. "purpose": "Recent news clusters, entity drill-down, sentiment, emerging topics, and related-entity expansion.",
  572. "output_conventions": {
  573. "cluster_ids": "Do not surface cluster_id in user-facing prose unless explicitly requested; treat it as internal navigation metadata.",
  574. "sources": "Always preserve and display sources when summarizing a cluster or entity result.",
  575. "timestamps": "Mention timestamps consistently when comparing multiple clusters or when recency matters.",
  576. },
  577. },
  578. "tools": NEWS_TOOL_CARDS,
  579. "recipes": NEWS_COMPOSITION_RECIPES,
  580. "example_chains": NEWS_EXAMPLE_CHAINS,
  581. "agent_tips": NEWS_AGENT_TIPS,
  582. "guidance": [
  583. "Use get_latest_events for a tail, get_events_for_entity for entity deep dives, and get_related_recent_entities for neighborhood expansion.",
  584. "Prefer normalized/canonical entities when possible, but the server will resolve common aliases and MIDs for you.",
  585. "When presenting results to users, summarize the cluster; avoid exposing internal IDs unless they are needed for follow-up tool calls.",
  586. ],
  587. }
  588. def _parse_timeframe_to_hours(timeframe: str) -> int:
  589. tf = str(timeframe).strip().lower()
  590. try:
  591. if tf.endswith("d"):
  592. days = int(tf[:-1])
  593. return max(1, days * 24)
  594. if tf.endswith("h"):
  595. return max(1, int(tf[:-1]))
  596. return max(1, int(tf))
  597. except Exception:
  598. return 24
  599. from contextlib import asynccontextmanager
  600. @asynccontextmanager
  601. async def _lifespan(app: FastAPI):
  602. asyncio.ensure_future(_background_refresh_loop())
  603. yield
  604. app = FastAPI(title="News MCP Server", lifespan=_lifespan)
  605. logger = logging.getLogger("news_mcp.startup")
  606. app.mount("/mcp", mcp.sse_app())
  607. # Shared store — single connection pool
  608. _shared_store = SQLiteClusterStore(DB_PATH)
  609. _refresh_lock = asyncio.Lock()
  610. _refresh_started = False
  611. async def _background_refresh_loop():
  612. """Non-blocking background refresher: prune then poll.
  613. Protected by an async lock so a second event-loop wake-up cannot
  614. start a parallel ingestion cycle.
  615. """
  616. global _refresh_started
  617. async with _refresh_lock:
  618. if _refresh_started:
  619. return
  620. _refresh_started = True
  621. logger.info("news-mcp llm config: %s", active_llm_config())
  622. # Prune off-thread so we do not block the event loop
  623. prune_result = await asyncio.to_thread(
  624. _shared_store.prune_if_due,
  625. NEWS_PRUNING_ENABLED,
  626. NEWS_RETENTION_DAYS,
  627. NEWS_PRUNE_INTERVAL_HOURS,
  628. )
  629. logger.info("startup prune_result=%s", prune_result)
  630. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  631. return
  632. async def _loop():
  633. if not NEWS_BACKGROUND_REFRESH_ON_START:
  634. logger.info("background refresh delayed start interval_seconds=%s", NEWS_REFRESH_INTERVAL_SECONDS)
  635. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  636. while True:
  637. try:
  638. logger.info("background refresh tick start")
  639. await refresh_clusters(topic=None, limit=200)
  640. logger.info("background refresh tick complete")
  641. except Exception:
  642. logger.exception("background refresh tick failed")
  643. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  644. asyncio.create_task(_loop())
  645. @app.get("/")
  646. def root():
  647. return {
  648. "status": "ok",
  649. "transport": "fastmcp+sse",
  650. "mount": "/mcp",
  651. "tools": [
  652. "get_latest_events",
  653. "get_events_for_entity",
  654. "get_event_summary",
  655. "detect_emerging_topics",
  656. "get_news_sentiment",
  657. "get_related_recent_entities",
  658. "get_capabilities",
  659. ],
  660. "refresh": {
  661. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  662. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  663. },
  664. "retention": {
  665. "lookback_hours": DEFAULT_LOOKBACK_HOURS,
  666. "retention_days": NEWS_RETENTION_DAYS,
  667. },
  668. "pruning": {
  669. "enabled": NEWS_PRUNING_ENABLED,
  670. "interval_hours": NEWS_PRUNE_INTERVAL_HOURS,
  671. },
  672. }
  673. # ------------------------------------------------------------------
  674. # Dashboard REST API endpoints
  675. # ------------------------------------------------------------------
  676. from fastapi.staticfiles import StaticFiles
  677. from fastapi.responses import JSONResponse
  678. app.mount("/dashboard", StaticFiles(directory="dashboard", html=True), name="dashboard")
  679. import logging as _log
  680. API_LOG = _log.getLogger("news_mcp.api")
  681. def _api_ok(data: dict) -> dict:
  682. return data
  683. def _api_err(exc: Exception, ctx: str) -> JSONResponse:
  684. API_LOG.exception(f"API error in {ctx}")
  685. return JSONResponse(status_code=500, content={"error": str(exc), "ctx": ctx})
  686. @app.get("/api/v1/health")
  687. def api_health():
  688. """Extended health + dashboard stats."""
  689. try:
  690. store = DashboardStore(_shared_store)
  691. return store.get_dashboard_stats()
  692. except Exception as e:
  693. return _api_err(e, "health")
  694. @app.get("/api/v1/clusters")
  695. def api_clusters(
  696. topic: str | None = None,
  697. hours: int = 24,
  698. limit: int = 50,
  699. offset: int = 0,
  700. ):
  701. """Paginated cluster listing."""
  702. try:
  703. store = DashboardStore(_shared_store)
  704. clusters = store.get_clusters_page(topic=topic, hours=hours, limit=limit, offset=offset)
  705. with store._store._conn() as conn:
  706. if topic and topic != "all":
  707. count_row = conn.execute(
  708. "SELECT COUNT(*) FROM clusters WHERE updated_at >= datetime('now', ? || ' hours') AND topic = ?",
  709. (-hours, topic),
  710. ).fetchone()
  711. else:
  712. count_row = conn.execute(
  713. "SELECT COUNT(*) FROM clusters WHERE updated_at >= datetime('now', ? || ' hours')",
  714. (-hours,),
  715. ).fetchone()
  716. total = count_row[0] if count_row else 0
  717. return {"clusters": clusters, "total": total, "topic": topic or "all", "hours": hours}
  718. except Exception as e:
  719. return _api_err(e, f"clusters(topic={topic},hours={hours})")
  720. @app.get("/api/v1/sentiment-series")
  721. def api_sentiment_series(
  722. topic: str | None = None,
  723. hours: int = 24,
  724. bucket_hours: float = 1.0,
  725. ):
  726. """Sentiment time-series for Chart.js."""
  727. try:
  728. store = DashboardStore(_shared_store)
  729. series = store.get_sentiment_series(topic=topic, hours=hours, bucket_hours=bucket_hours)
  730. return {"series": series, "topic": topic or "all"}
  731. except Exception as e:
  732. return _api_err(e, f"sentiment(topic={topic})")
  733. @app.get("/api/v1/entities")
  734. def api_entities(
  735. hours: int = 24,
  736. limit: int = 30,
  737. ):
  738. """Top entity frequencies."""
  739. try:
  740. store = DashboardStore(_shared_store)
  741. entities = store.get_entity_frequencies(hours=hours, limit=limit)
  742. return {"entities": entities, "hours": hours}
  743. except Exception as e:
  744. return _api_err(e, f"entities(hours={hours})")
  745. @app.get("/api/v1/cluster/{cluster_id}")
  746. def api_cluster_detail(cluster_id: str):
  747. """Full cluster detail for drill-down."""
  748. try:
  749. store = DashboardStore(_shared_store)
  750. detail = store.get_cluster_detail(cluster_id)
  751. if not detail:
  752. return JSONResponse(status_code=404, content={"error": "Cluster not found", "id": cluster_id})
  753. return detail
  754. except Exception as e:
  755. return _api_err(e, f"detail({cluster_id})")
  756. @app.get("/health")
  757. def health():
  758. return {
  759. "status": "ok",
  760. "uptime": round(time.monotonic() - _PROCESS_STARTED_AT, 3),
  761. }