mcp_server_fastmcp.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. from __future__ import annotations
  2. import asyncio
  3. import logging
  4. import subprocess
  5. import math
  6. import re
  7. import time
  8. from collections import Counter
  9. from datetime import datetime, timezone
  10. from pathlib import Path
  11. from fastapi import FastAPI, Form
  12. from mcp.server.fastmcp import FastMCP
  13. from mcp.server.transport_security import TransportSecuritySettings
  14. from news_mcp.config import DEFAULT_LOOKBACK_HOURS, DEFAULT_TOPICS, DB_PATH
  15. from news_mcp.config import (
  16. NEWS_FEED_URL,
  17. NEWS_FEED_URLS,
  18. NEWS_PRUNE_INTERVAL_HOURS,
  19. NEWS_PRUNING_ENABLED,
  20. NEWS_REFRESH_INTERVAL_SECONDS,
  21. NEWS_BACKGROUND_REFRESH_ENABLED,
  22. NEWS_BACKGROUND_REFRESH_ON_START,
  23. NEWS_RETENTION_DAYS,
  24. )
  25. from news_mcp.jobs.poller import refresh_clusters
  26. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  27. from news_mcp.dashboard.dashboard_store import DashboardStore
  28. from news_mcp.enrichment.llm_enrich import summarize_cluster_llm
  29. from news_mcp.trends_resolution import resolve_entity_via_trends
  30. from news_mcp.llm import active_llm_config
  31. from news_mcp.entity_normalize import normalize_query
  32. from news_mcp.related_entities import related_recent_entities
  33. logging.basicConfig(
  34. level=logging.INFO,
  35. format="%(asctime)s %(levelname)s %(name)s: %(message)s",
  36. )
  37. _PROCESS_STARTED_AT = time.monotonic()
  38. _REPO_ROOT = Path(__file__).resolve().parent
  39. try:
  40. _VERSION_HASH = (
  41. subprocess.check_output(
  42. ["git", "rev-parse", "--short=9", "HEAD"],
  43. cwd=str(_REPO_ROOT),
  44. stderr=subprocess.DEVNULL,
  45. )
  46. .decode()
  47. .strip()
  48. )
  49. except Exception:
  50. _VERSION_HASH = "unknown"
  51. mcp = FastMCP(
  52. "news-mcp",
  53. transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False),
  54. )
  55. def _cluster_entity_haystack(cluster: dict) -> list[str]:
  56. """Collect the normalized entity + keyword clues attached to a cluster."""
  57. values: list[str] = []
  58. for ent in cluster.get("entities", []) or []:
  59. values.append(str(ent).strip().lower())
  60. for res in cluster.get("entityResolutions", []) or []:
  61. if not isinstance(res, dict):
  62. continue
  63. for key in ("normalized", "canonical_label", "mid"):
  64. val = res.get(key)
  65. if val:
  66. values.append(str(val).strip().lower())
  67. # Keywords are LLM-curated thematic descriptors — include them in the
  68. # searchable haystack so entity/theme queries match on subject-matter
  69. # signals, not just named entities.
  70. for kw in cluster.get("keywords", []) or []:
  71. values.append(str(kw).strip().lower())
  72. return [v for v in values if v]
  73. def _parse_cluster_timestamp(value) -> datetime:
  74. """Parse a stored cluster timestamp.
  75. payload.timestamp is guaranteed ISO 8601 UTC (YYYY-MM-DDTHH:MM:SS+00:00)
  76. at write time. Only datetime.fromisoformat is needed — no RFC 2822 fallback.
  77. """
  78. if not value:
  79. return datetime.min.replace(tzinfo=timezone.utc)
  80. text = str(value).strip()
  81. if not text:
  82. return datetime.min.replace(tzinfo=timezone.utc)
  83. try:
  84. dt = datetime.fromisoformat(text)
  85. if dt.tzinfo is None:
  86. dt = dt.replace(tzinfo=timezone.utc)
  87. return dt.astimezone(timezone.utc)
  88. except Exception:
  89. return datetime.min.replace(tzinfo=timezone.utc)
  90. def _sort_clusters_by_recency(clusters: list[dict]) -> list[dict]:
  91. return sorted(
  92. clusters,
  93. key=lambda c: (
  94. _parse_cluster_timestamp(c.get("timestamp")),
  95. float(c.get("importance", 0.0) or 0.0),
  96. ),
  97. reverse=True,
  98. )
  99. def _tool_card(name: str, description: str, inputs: list[dict], outputs: list[str], notes: list[str] | None = None) -> dict:
  100. return {
  101. "name": name,
  102. "description": description,
  103. "inputs": inputs,
  104. "outputs": outputs,
  105. "notes": notes or [],
  106. }
  107. NEWS_TOOL_CARDS = [
  108. _tool_card(
  109. "get_feeds",
  110. "List all configured RSS feeds with their enabled/disabled status.",
  111. [],
  112. ["feeds[]: {feed_key, enabled, last_hash, last_item_count, updated_at}"],
  113. ["Use this to see which feeds are currently active or disabled."],
  114. ),
  115. _tool_card(
  116. "toggle_feed",
  117. "Enable or disable a specific RSS feed by URL.",
  118. [
  119. {"name": "feed_url", "type": "string", "meaning": "the feed URL to toggle"},
  120. {"name": "enabled", "type": "boolean", "meaning": "true to enable, false to disable"},
  121. ],
  122. ["ok", "feed_key", "enabled"],
  123. ["Changes take effect on the next refresh cycle."],
  124. ),
  125. _tool_card(
  126. "get_latest_events",
  127. "Get the newest deduplicated clusters for a topic or resolved entity-like query.",
  128. [
  129. {"name": "topic", "type": "string", "default": "all topics", "meaning": "coarse category (crypto, macro, regulation, ai, other), entity-like topic, or omit for all topics"},
  130. {"name": "limit", "type": "integer", "default": 5, "range": "1-20"},
  131. {"name": "include_articles", "type": "boolean", "default": False},
  132. ],
  133. ["headline", "summary", "entities", "keywords", "sentiment", "importance", "sources", "timestamp", "articles?"],
  134. ["Use when you want the freshest clusters. Each cluster includes both named entities and LLM-curated thematic keywords describing what the story is about."],
  135. ),
  136. _tool_card(
  137. "get_events_for_entity",
  138. "Search recent clusters for a person, place, company, theme, or keyword by matching entities and thematic keywords.",
  139. [
  140. {"name": "entity", "type": "string", "meaning": "entity label, phrase, or keyword to search for"},
  141. {"name": "timeframe", "type": "string", "default": "24h", "examples": ["24h", "72h", "3d"]},
  142. {"name": "limit", "type": "integer", "default": 10, "range": "1-30"},
  143. {"name": "include_articles", "type": "boolean", "default": False},
  144. ],
  145. ["headline", "summary", "entities", "keywords", "sentiment", "importance", "sources", "timestamp", "articles?"],
  146. ["Matches against both named entities and thematic keywords. Use this for an entity-centered or theme-centered deep dive."],
  147. ),
  148. _tool_card(
  149. "get_event_summary",
  150. "Produce a concise LLM-written explanation for one cluster and key facts.",
  151. [
  152. {"name": "event_id", "type": "string", "meaning": "cluster_id; do not surface in user-facing prose"},
  153. {"name": "include_articles", "type": "boolean", "default": False},
  154. ],
  155. ["headline", "mergedSummary", "keyFacts", "sources", "articles?"],
  156. ["Prefer this after you have already chosen a specific cluster to explain."],
  157. ),
  158. _tool_card(
  159. "detect_emerging_topics",
  160. "Surface emerging entities, thematic keywords, and phrases that are accelerating in the recent window.",
  161. [
  162. {"name": "limit", "type": "integer", "default": 10, "range": "1-20"},
  163. {"name": "timeframe", "type": "string", "default": "24h", "examples": ["4h", "24h", "3d"]},
  164. {"name": "topic", "type": "string", "default": "all topics", "examples": ["crypto", "macro", "regulation", "ai", "other"]},
  165. {"name": "around", "type": "string", "default": "none", "meaning": "entity to scope results to its neighborhood (e.g. \"Bitcoin\")"},
  166. ],
  167. ["topic", "trend_score", "velocity", "recent_count", "prior_count", "source_count", "related_entities", "signal_type"],
  168. ["Use timeframe to control lookback, topic to scope to a category, around to find what's emerging near a specific entity. Signal types: entity (named entity), keyword (thematic descriptor), phrase (headline bigram). Check velocity and source_count to distinguish real spikes from noise."],
  169. ),
  170. _tool_card(
  171. "get_news_sentiment",
  172. "Estimate sentiment around an entity or keyword over a lookback window.",
  173. [
  174. {"name": "entity", "type": "string", "meaning": "entity label, phrase, or keyword to analyze"},
  175. {"name": "timeframe", "type": "string", "default": "24h"},
  176. ],
  177. ["entity", "sentiment", "score", "cluster_count"],
  178. ["Matches clusters by entities and keywords. Use after locating a cluster set or entity neighborhood."],
  179. ),
  180. _tool_card(
  181. "get_related_recent_entities",
  182. "Find entities and thematic keywords commonly co-occurring with a subject in recent clusters, optionally blended with Google Trends suggestions.",
  183. [
  184. {"name": "subject", "type": "string", "meaning": "canonical entity or subject phrase"},
  185. {"name": "timeframe", "type": "string", "default": "72h"},
  186. {"name": "limit", "type": "integer", "default": 10, "range": "1-25"},
  187. {"name": "include_trends", "type": "boolean", "default": True},
  188. ],
  189. ["subject", "related[].normalized", "related[].canonical_label", "related[].mid", "related[].sources", "related[].scores"],
  190. ["Use this to drill from a subject into related entities and themes, then feed results into get_events_for_entity."],
  191. ),
  192. ]
  193. NEWS_COMPOSITION_RECIPES = [
  194. {
  195. "name": "fresh-news-tail",
  196. "steps": [
  197. "get_latest_events(topic=...)",
  198. "optionally get_event_summary(event_id=...) for the strongest cluster",
  199. ],
  200. "notes": ["Best for a quick tail of what is happening now. Omit topic for all topics, or pass crypto/macro/regulation/ai/other to filter."]
  201. },
  202. {
  203. "name": "entity-deep-dive",
  204. "steps": [
  205. "get_events_for_entity(entity=...)",
  206. "get_event_summary(event_id=...)",
  207. "get_news_sentiment(entity=..., timeframe=...)",
  208. ],
  209. "notes": ["Prefer canonical entity labels when you have them; the server normalizes for you."],
  210. },
  211. {
  212. "name": "subject-neighborhood",
  213. "steps": [
  214. "get_related_recent_entities(subject=...)",
  215. "for each strong related entity, call get_events_for_entity(entity=...)",
  216. ],
  217. "notes": ["Use this when you want a graph-like expansion around a subject."]
  218. },
  219. {
  220. "name": "emerging-signal",
  221. "steps": [
  222. "detect_emerging_topics(limit=..., timeframe=..., topic=..., around=...)",
  223. "choose a topic/entity from the results",
  224. "get_events_for_entity(entity=...)",
  225. "get_news_sentiment(entity=...)",
  226. ],
  227. "notes": ["Use timeframe to control lookback (e.g. \"4h\" for what's hot right now, \"3d\" for weekly trends), topic to scope to a category, around to find what's emerging near a specific entity. Check velocity and source_count to distinguish real spikes from noise."],
  228. },
  229. ]
  230. NEWS_AGENT_TIPS = [
  231. "If you need a fast answer, start with get_latest_events, then summarize the strongest cluster with get_event_summary.",
  232. "If a user asks about a person/place/company/theme, use get_events_for_entity before broadening to get_related_recent_entities.",
  233. "Treat cluster_id as an internal cursor, not user-facing output; use it only for follow-up tool calls.",
  234. "When describing clusters, keep sources and timestamps visible so the user can assess recency and provenance.",
  235. "Prefer a short chain of tools over many parallel calls unless you are building a neighborhood map or comparison table.",
  236. "For tricky names, rely on the server's resolver instead of inventing alias rules in the client.",
  237. "Use detect_emerging_topics with timeframe=\"4h\" for what's hot right now, timeframe=\"3d\" for weekly trends. Use topic= to scope to a category, around= to find what's emerging near a specific entity. Check velocity to distinguish accelerating signals from steady-state ones. Filter by signal_type to focus on entities, keywords, or phrases.",
  238. "Each cluster contains both entities (named entities with identity resolution) and keywords (thematic descriptors). Use keywords to understand what a story is about beyond the named entities.",
  239. ]
  240. NEWS_EXAMPLE_CHAINS = [
  241. {
  242. "task": "What is happening now?",
  243. "chain": [
  244. "get_latest_events(topic=...)",
  245. "get_event_summary(event_id=...) if one cluster looks important",
  246. ],
  247. },
  248. {
  249. "task": "Deep dive on an entity",
  250. "chain": [
  251. "get_events_for_entity(entity=..., timeframe=...)",
  252. "get_news_sentiment(entity=..., timeframe=...)",
  253. "get_event_summary(event_id=...) for the strongest cluster",
  254. ],
  255. },
  256. {
  257. "task": "Broaden from a subject",
  258. "chain": [
  259. "get_related_recent_entities(subject=..., include_trends=true)",
  260. "get_events_for_entity(entity=...) for the strongest related entities",
  261. ],
  262. },
  263. {
  264. "task": "Find what is emerging",
  265. "chain": [
  266. "detect_emerging_topics(limit=..., timeframe=..., topic=..., around=...) with optional scoping",
  267. "get_events_for_entity(entity=...) on one or two emerging terms",
  268. ],
  269. },
  270. {
  271. "task": "What's heating up around a specific entity",
  272. "chain": [
  273. "detect_emerging_topics(around=\"<entity>\", timeframe=\"4h\")",
  274. "get_events_for_entity(entity=...) on the top emerging neighbor",
  275. ],
  276. },
  277. ]
  278. def _configured_feed_urls() -> list[str]:
  279. """Return the configured feed URLs from environment variables."""
  280. urls = [u.strip() for u in NEWS_FEED_URLS.split(",") if u.strip()]
  281. if not urls:
  282. urls = [NEWS_FEED_URL]
  283. return urls
  284. @mcp.tool(description="List all configured RSS feeds with their current enabled/disabled status.")
  285. async def get_feeds() -> list[dict]:
  286. """Return each feed URL with its enabled flag, last fetch stats, and timestamps."""
  287. store = SQLiteClusterStore(DB_PATH)
  288. return store.get_feed_state_list()
  289. @mcp.tool(description="Enable or disable a specific RSS feed by URL.")
  290. async def toggle_feed(feed_url: str, enabled: bool) -> dict:
  291. """Toggle a feed's active/inactive state.
  292. Changes take effect on the next background refresh cycle.
  293. Returns the updated feed state.
  294. """
  295. store = SQLiteClusterStore(DB_PATH)
  296. store.set_feed_enabled(feed_url.strip(), enabled)
  297. updated = store.get_feed_state(feed_url.strip())
  298. return {"ok": True, "feed_key": feed_url.strip(), "enabled": enabled, "details": updated}
  299. @mcp.tool(description="Investigate a topic and return the newest deduplicated news clusters with entities and thematic keywords, sorted by recency.")
  300. async def get_latest_events(topic: str | None = None, limit: int = 5, include_articles: bool = False):
  301. limit = max(1, min(int(limit), 20))
  302. # When topic is omitted, search across all topics (no topic filter).
  303. # When topic is provided and matches a known topic, filter by that topic.
  304. # Otherwise treat the value as an entity-like query.
  305. topic_norm = normalize_query(topic).lower() if topic else ""
  306. resolved = resolve_entity_via_trends(topic_norm) if topic_norm else {}
  307. allowed = {t.lower() for t in DEFAULT_TOPICS}
  308. is_topic = topic_norm in allowed
  309. is_all_topics = not topic_norm
  310. query_terms = {
  311. topic_norm,
  312. str(resolved.get("normalized") or "").strip().lower(),
  313. str(resolved.get("canonical_label") or "").strip().lower(),
  314. str(resolved.get("mid") or "").strip().lower(),
  315. }
  316. query_terms = {q for q in query_terms if q}
  317. store = SQLiteClusterStore(DB_PATH)
  318. if is_all_topics:
  319. # No topic specified: return freshest clusters across all topics.
  320. clusters = store.get_latest_clusters_all_topics(ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  321. elif is_topic:
  322. # Cache-first: only refresh if we currently have no fresh clusters for this topic.
  323. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  324. if not clusters:
  325. await refresh_clusters(topic=topic_norm, limit=200)
  326. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  327. else:
  328. # Entity-aware mode: search recent clusters across all topics and match by
  329. # raw entity, canonical label, or MID.
  330. clusters = store.get_latest_clusters_all_topics(ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit * 8)
  331. filtered = []
  332. for c in clusters:
  333. haystack = _cluster_entity_haystack(c)
  334. if any(any(term in item for item in haystack) for term in query_terms):
  335. filtered.append(c)
  336. if len(filtered) >= limit:
  337. break
  338. clusters = filtered
  339. out = []
  340. for c in _sort_clusters_by_recency(clusters):
  341. item = {
  342. "cluster_id": c.get("cluster_id"),
  343. "headline": c.get("headline"),
  344. "summary": c.get("summary"),
  345. "entities": c.get("entities", []),
  346. "keywords": c.get("keywords", []),
  347. "sentiment": c.get("sentiment", "neutral"),
  348. "importance": c.get("importance", 0.0),
  349. "sources": c.get("sources", []),
  350. "timestamp": c.get("timestamp"),
  351. }
  352. if include_articles:
  353. # Return minimal article fields to keep responses compact.
  354. arts = c.get("articles", []) or []
  355. item["articles"] = [
  356. {
  357. "title": a.get("title"),
  358. "url": a.get("url"),
  359. "source": a.get("source"),
  360. "timestamp": a.get("timestamp"),
  361. }
  362. for a in arts
  363. if isinstance(a, dict)
  364. ]
  365. out.append(item)
  366. return out
  367. @mcp.tool(description="Investigate a person, company, place, theme, or keyword by matching entities and thematic keywords within a time window.")
  368. async def get_events_for_entity(entity: str, limit: int = 10, timeframe: str = "24h", include_articles: bool = False):
  369. limit = max(1, min(int(limit), 30))
  370. query = normalize_query(entity).strip().lower()
  371. if not query:
  372. return []
  373. resolved = resolve_entity_via_trends(query)
  374. query_terms = {
  375. query,
  376. str(resolved.get("normalized") or "").strip().lower(),
  377. str(resolved.get("canonical_label") or "").strip().lower(),
  378. str(resolved.get("mid") or "").strip().lower(),
  379. }
  380. query_terms = {q for q in query_terms if q}
  381. store = SQLiteClusterStore(DB_PATH)
  382. def _match_clusters(clusters: list[dict]) -> list[dict]:
  383. hits: list[dict] = []
  384. for c in _sort_clusters_by_recency(clusters):
  385. haystack = _cluster_entity_haystack(c)
  386. if any(any(term in item for item in haystack) for term in query_terms):
  387. hits.append(c)
  388. if len(hits) >= limit:
  389. break
  390. return hits
  391. hours = _parse_timeframe_to_hours(timeframe)
  392. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=max(200, limit * 10))
  393. hits = _match_clusters(clusters)
  394. out = []
  395. for c in hits:
  396. item = {
  397. "cluster_id": c.get("cluster_id"),
  398. "headline": c.get("headline"),
  399. "summary": c.get("summary"),
  400. "entities": c.get("entities", []),
  401. "keywords": c.get("keywords", []),
  402. "sentiment": c.get("sentiment", "neutral"),
  403. "importance": c.get("importance", 0.0),
  404. "sources": c.get("sources", []),
  405. "timestamp": c.get("timestamp"),
  406. }
  407. if include_articles:
  408. arts = c.get("articles", []) or []
  409. item["articles"] = [
  410. {
  411. "title": a.get("title"),
  412. "url": a.get("url"),
  413. "source": a.get("source"),
  414. "timestamp": a.get("timestamp"),
  415. }
  416. for a in arts
  417. if isinstance(a, dict)
  418. ]
  419. out.append(item)
  420. return out
  421. @mcp.tool(description="Return entities and thematic keywords commonly co-occurring with the subject in recent clusters, optionally blended with Google Trends suggestions.")
  422. async def get_related_recent_entities(subject: str, timeframe: str = "72h", limit: int = 10, include_trends: bool = True):
  423. limit = max(1, min(int(limit), 25))
  424. hours = _parse_timeframe_to_hours(timeframe)
  425. include_trends_bool = str(include_trends).strip().lower() not in {"false", "0", "no"}
  426. store = SQLiteClusterStore(DB_PATH)
  427. result = related_recent_entities(
  428. store=store,
  429. subject=subject,
  430. timeframe_hours=hours,
  431. limit=limit,
  432. include_trends=include_trends_bool,
  433. )
  434. return result
  435. @mcp.tool(description="Investigate one cluster in depth and return a concise LLM-written explanation plus key facts.")
  436. async def get_event_summary(event_id: str, include_articles: bool = False):
  437. store = SQLiteClusterStore(DB_PATH)
  438. # Summary cache: reuse if present within TTL.
  439. cached_summary = store.get_cluster_summary(
  440. cluster_id=event_id,
  441. ttl_hours=DEFAULT_LOOKBACK_HOURS,
  442. )
  443. if cached_summary:
  444. out = {
  445. "event_id": event_id,
  446. "headline": cached_summary.get("headline"),
  447. "mergedSummary": cached_summary.get("mergedSummary"),
  448. "keyFacts": cached_summary.get("keyFacts", []),
  449. "sources": cached_summary.get("sources", []),
  450. }
  451. if include_articles:
  452. cluster = store.get_cluster_by_id(event_id)
  453. arts = (cluster or {}).get("articles", []) or []
  454. out["articles"] = [
  455. {
  456. "title": a.get("title"),
  457. "url": a.get("url"),
  458. "source": a.get("source"),
  459. "timestamp": a.get("timestamp"),
  460. }
  461. for a in arts
  462. if isinstance(a, dict)
  463. ]
  464. return out
  465. cluster = store.get_cluster_by_id(event_id)
  466. if not cluster:
  467. return {
  468. "event_id": event_id,
  469. "error": "NOT_FOUND",
  470. }
  471. articles_out = None
  472. if include_articles:
  473. arts = cluster.get("articles", []) or []
  474. articles_out = [
  475. {
  476. "title": a.get("title"),
  477. "url": a.get("url"),
  478. "source": a.get("source"),
  479. "timestamp": a.get("timestamp"),
  480. }
  481. for a in arts
  482. if isinstance(a, dict)
  483. ]
  484. summary = await summarize_cluster_llm(cluster)
  485. store.upsert_cluster_summary(event_id, summary)
  486. out = {
  487. "event_id": event_id,
  488. "headline": summary.get("headline"),
  489. "mergedSummary": summary.get("mergedSummary"),
  490. "keyFacts": summary.get("keyFacts", []),
  491. "sources": summary.get("sources", []),
  492. }
  493. if include_articles:
  494. out["articles"] = articles_out or []
  495. return out
  496. @mcp.tool(description="Explore what is starting to matter: surface emerging entities, thematic keywords, and phrases from recent clusters. "
  497. "Use timeframe to control the lookback window, topic to scope to a category, and around to find what's emerging near a specific entity. "
  498. "Results include signal_type (entity / keyword / phrase) for downstream filtering.")
  499. async def detect_emerging_topics(limit: int = 10, timeframe: str = "24h", topic: str | None = None, around: str | None = None):
  500. """Surface entities and phrases that are accelerating in recent clusters.
  501. Args:
  502. limit: max results to return (1-20, default 10).
  503. timeframe: lookback window like "4h", "24h", "3d" (default "24h").
  504. topic: optional coarse topic filter ("crypto", "macro", "regulation", "ai", "other").
  505. around: optional entity — only return entities that co-occur with this entity
  506. in the recent window (e.g. "Bitcoin" to find what's emerging in Bitcoin's neighborhood).
  507. """
  508. limit = max(1, min(int(limit), 20))
  509. hours = _parse_timeframe_to_hours(timeframe)
  510. half_hours = hours / 2.0
  511. store = SQLiteClusterStore(DB_PATH)
  512. # Fetch more clusters than needed so velocity stats are meaningful even for short windows.
  513. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  514. # --- optional topic filter ---
  515. if topic:
  516. topic_norm = normalize_query(topic).strip().lower()
  517. if topic_norm:
  518. clusters = [c for c in clusters if (c.get("topic") or "other").strip().lower() == topic_norm]
  519. # --- resolve the 'around' entity ---
  520. around_terms: set[str] = set()
  521. if around:
  522. around_norm = normalize_query(around).strip().lower()
  523. if around_norm:
  524. resolved = resolve_entity_via_trends(around_norm)
  525. around_terms = {
  526. around_norm,
  527. str(resolved.get("normalized") or "").strip().lower(),
  528. str(resolved.get("canonical_label") or "").strip().lower(),
  529. }
  530. around_terms.discard("")
  531. # split clusters into first-half vs second-half by timestamp
  532. # clusters are already sorted most-recent-first from the store
  533. now = datetime.now(timezone.utc)
  534. def _cluster_age_hours(c: dict) -> float:
  535. """Return the cluster's age in hours. payload.timestamp is ISO 8601 UTC guaranteed."""
  536. ts = c.get("timestamp") or c.get("last_updated")
  537. if not ts:
  538. return 0.0
  539. try:
  540. dt = datetime.fromisoformat(str(ts).strip())
  541. if dt.tzinfo is None:
  542. dt = dt.replace(tzinfo=timezone.utc)
  543. return max(0.0, (now - dt.astimezone(timezone.utc)).total_seconds() / 3600.0)
  544. except Exception:
  545. return 0.0
  546. # Generic entity filter
  547. _generic_tokens = {"news", "latest", "breaking", "update", "updates", "report", "reports"}
  548. def _is_generic_entity(ent: str) -> bool:
  549. e = str(ent).strip().lower()
  550. if not e or len(e) < 4:
  551. return True
  552. if e in _generic_tokens:
  553. return True
  554. return False
  555. # --- accumulate signals ---
  556. # recent = second half of timeframe (newer), prior = first half (older)
  557. entity_counts_recent = Counter()
  558. entity_counts_prior = Counter()
  559. entity_importance_recent = Counter()
  560. entity_sources: dict[str, set] = {} # ent -> set of source names
  561. entity_buckets: dict[str, set] = {} # ent -> set of time-bucket indices (for sustained-spike detection)
  562. entity_cooccur: dict[str, Counter] = {}
  563. phrase_counts_recent = Counter()
  564. # Keyword accumulators — same scoring pipeline as entities, but tracking
  565. # LLM-curated thematic descriptors instead of named entities.
  566. kw_counts_recent = Counter()
  567. kw_counts_prior = Counter()
  568. kw_importance_recent = Counter()
  569. kw_sources: dict[str, set] = {}
  570. kw_buckets: dict[str, set] = {}
  571. bucket_size_hours = max(1.0, hours / 6.0) # split window into ~6 buckets
  572. for c in clusters:
  573. ents_in_cluster = [e for e in (c.get("entities", []) or []) if not _is_generic_entity(e)]
  574. ents_norm = [str(e).strip().lower() for e in ents_in_cluster if str(e).strip()]
  575. # Keywords: deduplicate per cluster so a cluster with the same keyword
  576. # listed twice doesn't inflate counts.
  577. kws_in_cluster = list(dict.fromkeys(
  578. str(k).strip().lower()
  579. for k in (c.get("keywords", []) or [])
  580. if str(k).strip() and not _is_generic_entity(k)
  581. ))
  582. age_h = _cluster_age_hours(c)
  583. is_recent = age_h <= half_hours
  584. bucket_idx = int(age_h / bucket_size_hours)
  585. # --- around filter: only count clusters that mention the target entity ---
  586. if around_terms:
  587. haystack = set(ents_norm)
  588. for res in c.get("entityResolutions", []) or []:
  589. if isinstance(res, dict):
  590. for key in ("normalized", "canonical_label"):
  591. val = res.get(key)
  592. if val:
  593. haystack.add(str(val).strip().lower())
  594. if not (haystack & around_terms):
  595. continue
  596. counts = entity_counts_recent if is_recent else entity_counts_prior
  597. imp_acc = entity_importance_recent if is_recent else None # only importance from recent window
  598. for ent in ents_norm:
  599. if _is_generic_entity(ent):
  600. continue
  601. counts[ent] += 1
  602. if ent not in entity_sources:
  603. entity_sources[ent] = set()
  604. src = c.get("source") or c.get("headline", "").split(" - ")[-1] if c.get("headline") else ""
  605. if src:
  606. entity_sources[ent].add(str(src))
  607. if ent not in entity_buckets:
  608. entity_buckets[ent] = set()
  609. entity_buckets[ent].add(bucket_idx)
  610. if imp_acc is not None:
  611. try:
  612. imp_acc[ent] += float(c.get("importance", 0.0) or 0.0)
  613. except Exception:
  614. pass
  615. # --- keyword counting (same recent/prior split as entities) ---
  616. kw_counts = kw_counts_recent if is_recent else kw_counts_prior
  617. kw_imp_acc = kw_importance_recent if is_recent else None
  618. for kw in kws_in_cluster:
  619. kw_counts[kw] += 1
  620. if kw not in kw_sources:
  621. kw_sources[kw] = set()
  622. src = c.get("source") or c.get("headline", "").split(" - ")[-1] if c.get("headline") else ""
  623. if src:
  624. kw_sources[kw].add(str(src))
  625. if kw not in kw_buckets:
  626. kw_buckets[kw] = set()
  627. kw_buckets[kw].add(bucket_idx)
  628. if kw_imp_acc is not None:
  629. try:
  630. kw_imp_acc[kw] += float(c.get("importance", 0.0) or 0.0) # type: ignore[assignment]
  631. except Exception:
  632. pass
  633. # co-occurrence (only for clusters matching the around filter, if any)
  634. for i in range(len(ents_norm)):
  635. a = ents_norm[i]
  636. if _is_generic_entity(a):
  637. continue
  638. if a not in entity_cooccur:
  639. entity_cooccur[a] = Counter()
  640. for j in range(len(ents_norm)):
  641. if i == j:
  642. continue
  643. b = ents_norm[j]
  644. if _is_generic_entity(b):
  645. continue
  646. entity_cooccur[a][b] += 1
  647. # bigram phrases (recent only)
  648. if is_recent:
  649. text = f"{c.get('headline', '')} {c.get('summary', '')}"
  650. words = re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())
  651. for i in range(len(words) - 1):
  652. phrase = f"{words[i]} {words[i+1]}"
  653. if len(phrase) > 6:
  654. phrase_counts_recent[phrase] += 1
  655. # --- score entities ---
  656. all_entities = set(entity_counts_recent.keys()) | set(entity_counts_prior.keys())
  657. scored = []
  658. for ent in all_entities:
  659. recent_n = entity_counts_recent.get(ent, 0)
  660. prior_n = entity_counts_prior.get(ent, 0)
  661. total_n = recent_n + prior_n
  662. if total_n < 1:
  663. continue
  664. # velocity: ratio of recent vs prior (smoothed to avoid division noise)
  665. # 0 prior → velocity = recent_n (pure emergence)
  666. # equal → velocity = 1.0 (steady)
  667. velocity = (recent_n + 0.5) / (prior_n + 0.5)
  668. # recency weight: what fraction of total hits are in the recent window
  669. recency_ratio = recent_n / total_n
  670. # source diversity: how many distinct outlets
  671. n_sources = len(entity_sources.get(ent, set()))
  672. # sustained: how many distinct time buckets did it appear in (max ~6)
  673. n_buckets = len(entity_buckets.get(ent, set()))
  674. # average importance (recent window only)
  675. avg_imp = (entity_importance_recent.get(ent, 0.0) / max(1, recent_n)) if recent_n > 0 else 0.0
  676. composed_score = (
  677. 0.35 * min(1.0, math.log1p(velocity) / math.log1p(4.0)) + # velocity (0..1, 4x = max)
  678. 0.25 * recency_ratio + # recency concentration
  679. 0.15 * min(1.0, n_sources / 5.0) + # source diversity
  680. 0.10 * min(1.0, n_buckets / 4.0) + # sustained (>1 bucket)
  681. 0.15 * min(1.0, avg_imp) # importance
  682. )
  683. related = []
  684. if ent in entity_cooccur:
  685. for other, _cnt in entity_cooccur[ent].most_common(5):
  686. if other != ent:
  687. related.append(other)
  688. scored.append({
  689. "topic": ent,
  690. "trend_score": min(0.99, round(composed_score, 3)),
  691. "related_entities": related[:3] if related else [ent],
  692. "velocity": round(velocity, 2),
  693. "recent_count": recent_n,
  694. "prior_count": prior_n,
  695. "source_count": n_sources,
  696. "avg_importance": round(avg_imp, 3),
  697. "signal_type": "entity",
  698. })
  699. # --- score keywords (same velocity/recency/source/sustained/importance formula) ---
  700. all_keywords = set(kw_counts_recent.keys()) | set(kw_counts_prior.keys())
  701. kw_scored = []
  702. for kw in all_keywords:
  703. # Skip keywords that are already scored as entities — entity signal is
  704. # higher quality (proper nouns, resolved identities).
  705. if kw in all_entities:
  706. continue
  707. recent_n = kw_counts_recent.get(kw, 0)
  708. prior_n = kw_counts_prior.get(kw, 0)
  709. total_n = recent_n + prior_n
  710. if total_n < 1:
  711. continue
  712. velocity = (recent_n + 0.5) / (prior_n + 0.5)
  713. recency_ratio = recent_n / total_n
  714. n_sources = len(kw_sources.get(kw, set()))
  715. n_buckets = len(kw_buckets.get(kw, set()))
  716. avg_imp = (kw_importance_recent.get(kw, 0.0) / max(1, recent_n)) if recent_n > 0 else 0.0
  717. composed_score = (
  718. 0.35 * min(1.0, math.log1p(velocity) / math.log1p(4.0)) +
  719. 0.25 * recency_ratio +
  720. 0.15 * min(1.0, n_sources / 5.0) +
  721. 0.10 * min(1.0, n_buckets / 4.0) +
  722. 0.15 * min(1.0, avg_imp)
  723. )
  724. kw_scored.append({
  725. "topic": kw,
  726. "trend_score": min(0.99, round(composed_score, 3)),
  727. "related_entities": [],
  728. "velocity": round(velocity, 2),
  729. "recent_count": recent_n,
  730. "prior_count": prior_n,
  731. "source_count": n_sources,
  732. "avg_importance": round(avg_imp, 3),
  733. "signal_type": "keyword",
  734. })
  735. # sort keywords by score descending
  736. kw_scored.sort(key=lambda x: (-x["trend_score"], -x["velocity"], x["topic"]))
  737. # sort by composed score descending
  738. scored.sort(key=lambda x: (-x["trend_score"], -x["velocity"], x["topic"]))
  739. # --- merge: entities first, then keywords, then phrases ---
  740. emerging = list(scored) # start with entities
  741. seen_topics = {item["topic"] for item in emerging}
  742. for kw_item in kw_scored:
  743. if kw_item["topic"] not in seen_topics:
  744. emerging.append(kw_item)
  745. seen_topics.add(kw_item["topic"])
  746. # --- add phrase signals (only from recent window) ---
  747. for phrase, count in phrase_counts_recent.most_common(limit * 2):
  748. if phrase in seen_topics:
  749. continue
  750. emerging.append({
  751. "topic": phrase.title(),
  752. "trend_score": min(0.99, round(0.30 + 0.15 * min(count, 5), 2)),
  753. "related_entities": [],
  754. "velocity": None,
  755. "recent_count": count,
  756. "prior_count": 0,
  757. "source_count": 0,
  758. "avg_importance": 0.0,
  759. "signal_type": "phrase",
  760. })
  761. seen_topics.add(phrase)
  762. if len(emerging) >= limit:
  763. break
  764. return emerging[:limit]
  765. @mcp.tool(description="Investigate whether sentiment around an entity or keyword is positive, negative, or neutral over a chosen lookback window. "
  766. "Matches clusters by both named entities and thematic keywords.")
  767. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  768. store = SQLiteClusterStore(DB_PATH)
  769. ent = normalize_query(entity).strip().lower()
  770. resolved = resolve_entity_via_trends(ent)
  771. query_terms = {
  772. ent,
  773. str(resolved.get("normalized") or "").strip().lower(),
  774. str(resolved.get("canonical_label") or "").strip().lower(),
  775. str(resolved.get("mid") or "").strip().lower(),
  776. }
  777. query_terms = {q for q in query_terms if q}
  778. if not ent:
  779. return {
  780. "entity": entity,
  781. "sentiment": "neutral",
  782. "score": 0.0,
  783. "cluster_count": 0,
  784. }
  785. # timeframe: accept '24h' or '24'
  786. tf = str(timeframe).strip().lower()
  787. try:
  788. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  789. except Exception:
  790. hours = 24
  791. hours = max(1, min(int(hours), 168))
  792. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  793. matched = []
  794. for c in clusters:
  795. haystack = _cluster_entity_haystack(c)
  796. if any(any(term in item for item in haystack) for term in query_terms):
  797. matched.append(c)
  798. if not matched:
  799. return {
  800. "entity": entity,
  801. "sentiment": "neutral",
  802. "score": 0.0,
  803. "cluster_count": 0,
  804. }
  805. scores = []
  806. for c in matched:
  807. s = c.get("sentimentScore")
  808. if s is not None:
  809. try:
  810. scores.append(float(s))
  811. except Exception:
  812. pass
  813. avg_score = sum(scores) / len(scores) if scores else 0.0
  814. # Keep the label aligned with the numeric score.
  815. # Small magnitudes are treated as neutral to avoid noisy label flips.
  816. if avg_score >= 0.15:
  817. sentiment = "positive"
  818. elif avg_score <= -0.15:
  819. sentiment = "negative"
  820. else:
  821. sentiment = "neutral"
  822. return {
  823. "entity": entity,
  824. "sentiment": sentiment,
  825. "score": round(avg_score, 3),
  826. "cluster_count": len(matched),
  827. }
  828. @mcp.tool(description="Describe the server tool surface, how tools fit together, and output conventions for downstream agents.")
  829. async def get_capabilities():
  830. return {
  831. "server": {
  832. "name": "news-mcp",
  833. "purpose": "Recent news clusters with entities and thematic keywords, entity/keyword drill-down, sentiment, emerging topics, and related-entity expansion.",
  834. "output_conventions": {
  835. "cluster_ids": "Do not surface cluster_id in user-facing prose unless explicitly requested; treat it as internal navigation metadata.",
  836. "sources": "Always preserve and display sources when summarizing a cluster or entity result.",
  837. "timestamps": "Mention timestamps consistently when comparing multiple clusters or when recency matters.",
  838. "clusters": "Each cluster includes entities (named entities with optional MID/canonical_label) and keywords (thematic descriptors). Both are searchable; entities are higher-signal, keywords capture subject-matter themes.",
  839. },
  840. },
  841. "tools": NEWS_TOOL_CARDS,
  842. "recipes": NEWS_COMPOSITION_RECIPES,
  843. "example_chains": NEWS_EXAMPLE_CHAINS,
  844. "agent_tips": NEWS_AGENT_TIPS,
  845. "guidance": [
  846. "Use get_latest_events for a tail, get_events_for_entity for entity/keyword deep dives, and get_related_recent_entities for neighborhood expansion.",
  847. "Prefer normalized/canonical entities when possible, but the server will resolve common aliases and MIDs for you.",
  848. "When presenting results to users, summarize the cluster; avoid exposing internal IDs unless they are needed for follow-up tool calls.",
  849. "For emerging topics, use detect_emerging_topics with timeframe and around parameters. Signal types: entity (named entity, highest quality), keyword (thematic descriptor), phrase (headline bigram). High velocity + high source_count = strong signal.",
  850. "get_events_for_entity and get_news_sentiment match both entities and thematic keywords — use keywords when the subject is a theme rather than a named entity.",
  851. ],
  852. }
  853. def _parse_timeframe_to_hours(timeframe: str) -> int:
  854. tf = str(timeframe).strip().lower()
  855. try:
  856. if tf.endswith("d"):
  857. days = int(tf[:-1])
  858. return max(1, days * 24)
  859. if tf.endswith("h"):
  860. return max(1, int(tf[:-1]))
  861. return max(1, int(tf))
  862. except Exception:
  863. return 24
  864. from contextlib import asynccontextmanager
  865. @asynccontextmanager
  866. async def _lifespan(app: FastAPI):
  867. asyncio.ensure_future(_background_refresh_loop())
  868. yield
  869. app = FastAPI(title="News MCP Server", lifespan=_lifespan)
  870. logger = logging.getLogger("news_mcp.startup")
  871. app.mount("/mcp", mcp.sse_app())
  872. # Shared store — single connection pool
  873. _shared_store = SQLiteClusterStore(DB_PATH)
  874. _refresh_lock = asyncio.Lock()
  875. _refresh_started = False
  876. async def _background_refresh_loop():
  877. """Non-blocking background refresher: prune then poll.
  878. Protected by an async lock so a second event-loop wake-up cannot
  879. start a parallel ingestion cycle.
  880. """
  881. global _refresh_started
  882. async with _refresh_lock:
  883. if _refresh_started:
  884. return
  885. _refresh_started = True
  886. logger.info("news-mcp llm config: %s", active_llm_config())
  887. # Prune off-thread so we do not block the event loop
  888. prune_result = await asyncio.to_thread(
  889. _shared_store.prune_if_due,
  890. NEWS_PRUNING_ENABLED,
  891. NEWS_RETENTION_DAYS,
  892. NEWS_PRUNE_INTERVAL_HOURS,
  893. )
  894. logger.info("startup prune_result=%s", prune_result)
  895. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  896. return
  897. async def _loop():
  898. if not NEWS_BACKGROUND_REFRESH_ON_START:
  899. logger.info("background refresh delayed start interval_seconds=%s", NEWS_REFRESH_INTERVAL_SECONDS)
  900. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  901. while True:
  902. try:
  903. logger.info("background refresh tick start")
  904. await refresh_clusters(topic=None, limit=200)
  905. logger.info("background refresh tick complete")
  906. except Exception:
  907. logger.exception("background refresh tick failed")
  908. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  909. asyncio.create_task(_loop())
  910. @app.get("/")
  911. def root():
  912. return {
  913. "status": "ok",
  914. "transport": "fastmcp+sse",
  915. "mount": "/mcp",
  916. "tools": [
  917. "get_latest_events",
  918. "get_events_for_entity",
  919. "get_event_summary",
  920. "detect_emerging_topics",
  921. "get_news_sentiment",
  922. "get_related_recent_entities",
  923. "get_capabilities",
  924. ],
  925. "refresh": {
  926. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  927. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  928. },
  929. "retention": {
  930. "lookback_hours": DEFAULT_LOOKBACK_HOURS,
  931. "retention_days": NEWS_RETENTION_DAYS,
  932. },
  933. "pruning": {
  934. "enabled": NEWS_PRUNING_ENABLED,
  935. "interval_hours": NEWS_PRUNE_INTERVAL_HOURS,
  936. },
  937. }
  938. # ------------------------------------------------------------------
  939. # Dashboard REST API endpoints
  940. # ------------------------------------------------------------------
  941. from fastapi.staticfiles import StaticFiles
  942. from fastapi.responses import JSONResponse
  943. app.mount("/dashboard", StaticFiles(directory="dashboard", html=True), name="dashboard")
  944. import logging as _log
  945. API_LOG = _log.getLogger("news_mcp.api")
  946. def _api_ok(data: dict) -> dict:
  947. return data
  948. def _api_err(exc: Exception, ctx: str) -> JSONResponse:
  949. API_LOG.exception(f"API error in {ctx}")
  950. return JSONResponse(status_code=500, content={"error": str(exc), "ctx": ctx})
  951. @app.get("/api/v1/health")
  952. def api_health():
  953. """Extended health + dashboard stats."""
  954. try:
  955. store = DashboardStore(_shared_store)
  956. stats = store.get_dashboard_stats()
  957. stats["version"] = _VERSION_HASH
  958. return stats
  959. except Exception as e:
  960. return _api_err(e, "health")
  961. @app.get("/api/v1/clusters")
  962. def api_clusters(
  963. topic: str | None = None,
  964. hours: int = 24,
  965. limit: int = 50,
  966. offset: int = 0,
  967. ):
  968. """Paginated cluster listing."""
  969. try:
  970. store = DashboardStore(_shared_store)
  971. result = store.get_clusters_page(topic=topic, hours=hours, limit=limit, offset=offset)
  972. return {"clusters": result["clusters"], "total": result["total"], "topic": topic or "all", "hours": hours}
  973. except Exception as e:
  974. return _api_err(e, f"clusters(topic={topic},hours={hours})")
  975. @app.get("/api/v1/sentiment-series")
  976. def api_sentiment_series(
  977. topic: str | None = None,
  978. hours: int = 24,
  979. bucket_hours: float = 1.0,
  980. ):
  981. """Sentiment time-series for Chart.js."""
  982. try:
  983. store = DashboardStore(_shared_store)
  984. series = store.get_sentiment_series(topic=topic, hours=hours, bucket_hours=bucket_hours)
  985. return {"series": series, "topic": topic or "all"}
  986. except Exception as e:
  987. return _api_err(e, f"sentiment(topic={topic})")
  988. @app.get("/api/v1/entities")
  989. def api_entities(
  990. hours: int = 24,
  991. limit: int = 30,
  992. ):
  993. """Top entity frequencies."""
  994. try:
  995. store = DashboardStore(_shared_store)
  996. entities = store.get_entity_frequencies(hours=hours, limit=limit)
  997. return {"entities": entities, "hours": hours}
  998. except Exception as e:
  999. return _api_err(e, f"entities(hours={hours})")
  1000. @app.get("/api/v1/keywords")
  1001. def api_keywords(
  1002. hours: int = 24,
  1003. limit: int = 30,
  1004. ):
  1005. """Top keyword frequencies (thematic descriptors, excluding terms already counted as entities)."""
  1006. try:
  1007. store = DashboardStore(_shared_store)
  1008. keywords = store.get_keyword_frequencies(hours=hours, limit=limit)
  1009. return {"keywords": keywords, "hours": hours}
  1010. except Exception as e:
  1011. return _api_err(e, f"keywords(hours={hours})")
  1012. @app.get("/api/v1/cluster/{cluster_id}")
  1013. def api_cluster_detail(cluster_id: str):
  1014. """Full cluster detail for drill-down."""
  1015. try:
  1016. store = DashboardStore(_shared_store)
  1017. detail = store.get_cluster_detail(cluster_id)
  1018. if not detail:
  1019. return JSONResponse(status_code=404, content={"error": "Cluster not found", "id": cluster_id})
  1020. return detail
  1021. except Exception as e:
  1022. return _api_err(e, f"detail({cluster_id})")
  1023. # ------------------------------------------------------------------
  1024. # Feed management endpoints (toggle on/off from dashboard)
  1025. # ------------------------------------------------------------------
  1026. @app.get("/api/v1/feeds")
  1027. def api_feeds():
  1028. """List all configured feeds with enabled/disabled status."""
  1029. try:
  1030. store = SQLiteClusterStore(DB_PATH)
  1031. feed_list = store.get_feed_state_list()
  1032. configured = _configured_feed_urls()
  1033. return {
  1034. "feeds": feed_list,
  1035. "configured_urls": configured,
  1036. }
  1037. except Exception as e:
  1038. return _api_err(e, "feeds")
  1039. @app.post("/api/v1/feeds/toggle")
  1040. async def api_feed_toggle(feed_url: str = Form(), enabled: bool = Form()):
  1041. """Toggle a feed's enabled state."""
  1042. try:
  1043. store = SQLiteClusterStore(DB_PATH)
  1044. ok = store.set_feed_enabled(feed_url.strip(), enabled)
  1045. if not ok:
  1046. return JSONResponse(
  1047. status_code=404,
  1048. content={"error": f"Feed not found: {feed_url}"},
  1049. )
  1050. return {"ok": True, "feed_url": feed_url.strip(), "enabled": enabled}
  1051. except Exception as e:
  1052. return _api_err(e, f"toggle({feed_url})")
  1053. @app.get("/health")
  1054. def health():
  1055. return {
  1056. "status": "ok",
  1057. "uptime": round(time.monotonic() - _PROCESS_STARTED_AT, 3),
  1058. "version": _VERSION_HASH,
  1059. }