mcp_server_fastmcp.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. from __future__ import annotations
  2. import asyncio
  3. import hashlib
  4. import json
  5. import logging
  6. import math
  7. import re
  8. import time
  9. from collections import Counter
  10. from datetime import datetime, timezone
  11. from pathlib import Path
  12. from fastapi import FastAPI, Form
  13. from mcp.server.fastmcp import FastMCP
  14. from mcp.server.transport_security import TransportSecuritySettings
  15. from news_mcp.config import DEFAULT_LOOKBACK_HOURS, DEFAULT_TOPICS, DB_PATH
  16. from news_mcp.config import (
  17. NEWS_FEED_URL,
  18. NEWS_FEED_URLS,
  19. NEWS_PRUNE_INTERVAL_HOURS,
  20. NEWS_PRUNING_ENABLED,
  21. NEWS_REFRESH_INTERVAL_SECONDS,
  22. NEWS_BACKGROUND_REFRESH_ENABLED,
  23. NEWS_BACKGROUND_REFRESH_ON_START,
  24. NEWS_RETENTION_DAYS,
  25. )
  26. from news_mcp.jobs.poller import refresh_clusters
  27. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  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. _PACKAGE_DIR = Path(__file__).resolve().parent
  39. def _compute_version_hash() -> str:
  40. """SHA-256 of all .py files under news_mcp/, sorted by relative path.
  41. Deterministic across machines and environments — no git dependency.
  42. Works identically in Docker and native runs.
  43. """
  44. hasher = hashlib.sha256()
  45. for f in sorted(_PACKAGE_DIR.rglob("*.py")):
  46. try:
  47. hasher.update(f.read_bytes())
  48. except OSError:
  49. continue
  50. return hasher.hexdigest()[:9]
  51. _VERSION_HASH = _compute_version_hash()
  52. mcp = FastMCP(
  53. "news-mcp",
  54. transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False),
  55. )
  56. def _cluster_entity_haystack(cluster: dict) -> list[str]:
  57. """Collect the normalized entity + keyword clues attached to a cluster."""
  58. values: list[str] = []
  59. for ent in cluster.get("entities", []) or []:
  60. values.append(str(ent).strip().lower())
  61. for res in cluster.get("entityResolutions", []) or []:
  62. if not isinstance(res, dict):
  63. continue
  64. for key in ("normalized", "canonical_label", "mid"):
  65. val = res.get(key)
  66. if val:
  67. values.append(str(val).strip().lower())
  68. # Keywords are LLM-curated thematic descriptors — include them in the
  69. # searchable haystack so entity/theme queries match on subject-matter
  70. # signals, not just named entities.
  71. for kw in cluster.get("keywords", []) or []:
  72. values.append(str(kw).strip().lower())
  73. return [v for v in values if v]
  74. def _parse_cluster_timestamp(value) -> datetime:
  75. """Parse a stored cluster timestamp.
  76. payload.timestamp is guaranteed ISO 8601 UTC (YYYY-MM-DDTHH:MM:SS+00:00)
  77. at write time. Only datetime.fromisoformat is needed — no RFC 2822 fallback.
  78. """
  79. if not value:
  80. return datetime.min.replace(tzinfo=timezone.utc)
  81. text = str(value).strip()
  82. if not text:
  83. return datetime.min.replace(tzinfo=timezone.utc)
  84. try:
  85. dt = datetime.fromisoformat(text)
  86. if dt.tzinfo is None:
  87. dt = dt.replace(tzinfo=timezone.utc)
  88. return dt.astimezone(timezone.utc)
  89. except Exception:
  90. return datetime.min.replace(tzinfo=timezone.utc)
  91. def _sort_clusters_by_recency(clusters: list[dict]) -> list[dict]:
  92. return sorted(
  93. clusters,
  94. key=lambda c: (
  95. _parse_cluster_timestamp(c.get("timestamp")),
  96. float(c.get("importance", 0.0) or 0.0),
  97. ),
  98. reverse=True,
  99. )
  100. def _tool_card(name: str, description: str, inputs: list[dict], outputs: list[str], notes: list[str] | None = None) -> dict:
  101. return {
  102. "name": name,
  103. "description": description,
  104. "inputs": inputs,
  105. "outputs": outputs,
  106. "notes": notes or [],
  107. }
  108. NEWS_TOOL_CARDS = [
  109. _tool_card(
  110. "get_feeds",
  111. "List all configured RSS feeds with their enabled/disabled status.",
  112. [],
  113. ["feeds[]: {feed_key, enabled, last_hash, last_item_count, updated_at}"],
  114. ["Use this to see which feeds are currently active or disabled."],
  115. ),
  116. _tool_card(
  117. "toggle_feed",
  118. "Enable or disable a specific RSS feed by URL.",
  119. [
  120. {"name": "feed_url", "type": "string", "meaning": "the feed URL to toggle"},
  121. {"name": "enabled", "type": "boolean", "meaning": "true to enable, false to disable"},
  122. ],
  123. ["ok", "feed_key", "enabled"],
  124. ["Changes take effect on the next refresh cycle."],
  125. ),
  126. _tool_card(
  127. "get_latest_events",
  128. "Get the newest deduplicated clusters for a topic or resolved entity-like query.",
  129. [
  130. {"name": "topic", "type": "string", "default": "all topics", "meaning": "coarse category (crypto, macro, regulation, ai, other), entity-like topic, or omit for all topics"},
  131. {"name": "limit", "type": "integer", "default": 5, "range": "1-20"},
  132. {"name": "include_articles", "type": "boolean", "default": False},
  133. ],
  134. ["headline", "summary", "entities", "keywords", "sentiment", "importance", "sources", "timestamp", "articles?"],
  135. ["Use when you want the freshest clusters. Each cluster includes both named entities and LLM-curated thematic keywords describing what the story is about."],
  136. ),
  137. _tool_card(
  138. "get_events_for_entity",
  139. "Search recent clusters for a person, place, company, theme, or keyword by matching entities and thematic keywords.",
  140. [
  141. {"name": "entity", "type": "string", "meaning": "entity label, phrase, or keyword to search for"},
  142. {"name": "timeframe", "type": "string", "default": "24h", "examples": ["24h", "72h", "3d"]},
  143. {"name": "limit", "type": "integer", "default": 10, "range": "1-30"},
  144. {"name": "include_articles", "type": "boolean", "default": False},
  145. ],
  146. ["headline", "summary", "entities", "keywords", "sentiment", "importance", "sources", "timestamp", "articles?"],
  147. ["Matches against both named entities and thematic keywords. Use this for an entity-centered or theme-centered deep dive."],
  148. ),
  149. _tool_card(
  150. "get_event_summary",
  151. "Produce a concise LLM-written explanation for one cluster and key facts.",
  152. [
  153. {"name": "event_id", "type": "string", "meaning": "cluster_id; do not surface in user-facing prose"},
  154. {"name": "include_articles", "type": "boolean", "default": True},
  155. ],
  156. ["headline", "mergedSummary", "keyFacts", "sources", "entities", "keywords", "related_entities", "related_keywords", "topic", "sentiment", "importance", "articles"],
  157. ["Rich cluster drill-down. Returns LLM summary + cluster metadata + articles. Defaults to include articles."],
  158. ),
  159. _tool_card(
  160. "detect_emerging_topics",
  161. "Surface emerging entities, thematic keywords, and phrases that are accelerating in the recent window.",
  162. [
  163. {"name": "limit", "type": "integer", "default": 10, "range": "1-20"},
  164. {"name": "timeframe", "type": "string", "default": "24h", "examples": ["4h", "24h", "3d"]},
  165. {"name": "topic", "type": "string", "default": "all topics", "examples": ["crypto", "macro", "regulation", "ai", "other"]},
  166. {"name": "around", "type": "string", "default": "none", "meaning": "entity to scope results to its neighborhood (e.g. \"Bitcoin\")"},
  167. ],
  168. ["topic", "trend_score", "velocity", "recent_count", "prior_count", "source_count", "related_entities", "related_keywords", "signal_type"],
  169. ["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."],
  170. ),
  171. _tool_card(
  172. "get_news_sentiment",
  173. "Estimate sentiment around an entity or keyword over a lookback window.",
  174. [
  175. {"name": "entity", "type": "string", "meaning": "entity label, phrase, or keyword to analyze"},
  176. {"name": "timeframe", "type": "string", "default": "24h"},
  177. ],
  178. ["entity", "sentiment", "score", "cluster_count"],
  179. ["Matches clusters by entities and keywords. Use after locating a cluster set or entity neighborhood."],
  180. ),
  181. _tool_card(
  182. "get_related_recent_entities",
  183. "Find entities and thematic keywords commonly co-occurring with a subject in recent clusters, optionally blended with Google Trends suggestions.",
  184. [
  185. {"name": "subject", "type": "string", "meaning": "canonical entity or subject phrase"},
  186. {"name": "timeframe", "type": "string", "default": "72h"},
  187. {"name": "limit", "type": "integer", "default": 10, "range": "1-25"},
  188. {"name": "include_trends", "type": "boolean", "default": True},
  189. ],
  190. ["subject", "related[].normalized", "related[].canonical_label", "related[].mid", "related[].sources", "related[].scores"],
  191. ["Use this to drill from a subject into related entities and themes, then feed results into get_events_for_entity."],
  192. ),
  193. ]
  194. NEWS_COMPOSITION_RECIPES = [
  195. {
  196. "name": "fresh-news-tail",
  197. "steps": [
  198. "get_latest_events(topic=...)",
  199. "optionally get_event_summary(event_id=...) for the strongest cluster",
  200. ],
  201. "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."]
  202. },
  203. {
  204. "name": "entity-deep-dive",
  205. "steps": [
  206. "get_events_for_entity(entity=...)",
  207. "get_event_summary(event_id=...)",
  208. "get_news_sentiment(entity=..., timeframe=...)",
  209. ],
  210. "notes": ["Prefer canonical entity labels when you have them; the server normalizes for you."],
  211. },
  212. {
  213. "name": "subject-neighborhood",
  214. "steps": [
  215. "get_related_recent_entities(subject=...)",
  216. "for each strong related entity, call get_events_for_entity(entity=...)",
  217. ],
  218. "notes": ["Use this when you want a graph-like expansion around a subject."]
  219. },
  220. {
  221. "name": "emerging-signal",
  222. "steps": [
  223. "detect_emerging_topics(limit=..., timeframe=..., topic=..., around=...)",
  224. "choose a topic/entity from the results",
  225. "get_events_for_entity(entity=...)",
  226. "get_news_sentiment(entity=...)",
  227. ],
  228. "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."],
  229. },
  230. ]
  231. NEWS_AGENT_TIPS = [
  232. "If you need a fast answer, start with get_latest_events, then summarize the strongest cluster with get_event_summary.",
  233. "If a user asks about a person/place/company/theme, use get_events_for_entity before broadening to get_related_recent_entities.",
  234. "Treat cluster_id as an internal cursor, not user-facing output; use it only for follow-up tool calls.",
  235. "When describing clusters, keep sources and timestamps visible so the user can assess recency and provenance.",
  236. "Prefer a short chain of tools over many parallel calls unless you are building a neighborhood map or comparison table.",
  237. "For tricky names, rely on the server's resolver instead of inventing alias rules in the client.",
  238. "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. Each result also includes related_keywords for thematic context.",
  239. "get_event_summary returns a rich result: headline, mergedSummary, keyFacts, entities, keywords, related_entities, related_keywords, topic, sentiment, importance, and articles (included by default). Use it for full cluster drill-down.",
  240. "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.",
  241. "Use detect_emerging_topics with multiple timeframes (e.g. 4h vs 3d) and compare results to distinguish what's hot right now vs what's persistently trending. related_keywords help identify thematic neighborhoods.",
  242. ]
  243. NEWS_EXAMPLE_CHAINS = [
  244. {
  245. "task": "What is happening now?",
  246. "chain": [
  247. "get_latest_events(topic=...)",
  248. "get_event_summary(event_id=...) if one cluster looks important",
  249. ],
  250. },
  251. {
  252. "task": "Deep dive on an entity",
  253. "chain": [
  254. "get_events_for_entity(entity=..., timeframe=...)",
  255. "get_news_sentiment(entity=..., timeframe=...)",
  256. "get_event_summary(event_id=...) for the strongest cluster",
  257. ],
  258. },
  259. {
  260. "task": "Broaden from a subject",
  261. "chain": [
  262. "get_related_recent_entities(subject=..., include_trends=true)",
  263. "get_events_for_entity(entity=...) for the strongest related entities",
  264. ],
  265. },
  266. {
  267. "task": "Find what is emerging",
  268. "chain": [
  269. "detect_emerging_topics(limit=..., timeframe=..., topic=..., around=...) with optional scoping",
  270. "get_events_for_entity(entity=...) on one or two emerging terms",
  271. ],
  272. },
  273. {
  274. "task": "What's heating up around a specific entity",
  275. "chain": [
  276. "detect_emerging_topics(around=\"<entity>\", timeframe=\"4h\")",
  277. "get_events_for_entity(entity=...) on the top emerging neighbor",
  278. ],
  279. },
  280. {
  281. "task": "Full investigation pipeline",
  282. "chain": [
  283. "detect_emerging_topics(limit=20, timeframe=\"3d\")",
  284. "pick an emerging entity/keyword and note its related_entities and related_keywords",
  285. "get_event_summary(event_id=...) on the top cluster for full context including articles",
  286. "get_news_sentiment(entity=...) to gauge tone around the emerging topic",
  287. "detect_emerging_topics(around=<entity>, timeframe=\"4h\") to scout its neighborhood",
  288. ],
  289. },
  290. ]
  291. def _configured_feed_urls() -> list[str]:
  292. """Return the configured feed URLs from environment variables."""
  293. urls = [u.strip() for u in NEWS_FEED_URLS.split(",") if u.strip()]
  294. if not urls:
  295. urls = [NEWS_FEED_URL]
  296. return urls
  297. @mcp.tool(description="List all configured RSS feeds with their current enabled/disabled status.")
  298. async def get_feeds() -> list[dict]:
  299. """Return each feed URL with its enabled flag, last fetch stats, and timestamps."""
  300. store = SQLiteClusterStore(DB_PATH)
  301. return store.get_feed_state_list()
  302. @mcp.tool(description="Enable or disable a specific RSS feed by URL.")
  303. async def toggle_feed(feed_url: str, enabled: bool) -> dict:
  304. """Toggle a feed's active/inactive state.
  305. Changes take effect on the next background refresh cycle.
  306. Returns the updated feed state.
  307. """
  308. store = SQLiteClusterStore(DB_PATH)
  309. store.set_feed_enabled(feed_url.strip(), enabled)
  310. updated = store.get_feed_state(feed_url.strip())
  311. return {"ok": True, "feed_key": feed_url.strip(), "enabled": enabled, "details": updated}
  312. @mcp.tool(description="Debug dedup: inspect whether an article URL was already processed, which cluster it belongs to, and what similarity signals it would produce against existing clusters.")
  313. async def debug_dedup(url: str, title: str | None = None) -> dict:
  314. """Given an article URL (and optional title), report dedup status.
  315. Returns:
  316. - seen: whether the article_key is in seen_articles
  317. - article_key: the identity key derived from the URL
  318. - cluster_id: which cluster it belongs to (if seen)
  319. - similarity_signals: if title is provided, compute signals against
  320. the top-N most similar existing clusters
  321. """
  322. from news_mcp.article_identity import article_key, article_content_hash
  323. from news_mcp.dedup.cluster import _title_similarity, _normalize_title, _signals, _is_match
  324. from news_mcp.config import NEWS_EMBEDDINGS_ENABLED
  325. art = {"url": url, "title": title or ""}
  326. akey = article_key(art)
  327. result = {"url": url, "article_key": akey}
  328. store = SQLiteClusterStore(DB_PATH)
  329. with store._conn() as conn:
  330. # Check seen_articles
  331. row = conn.execute(
  332. "SELECT cluster_id, first_seen, url FROM seen_articles WHERE article_key=?",
  333. (akey,),
  334. ).fetchone()
  335. if row:
  336. result["seen"] = True
  337. result["cluster_id"] = row[0]
  338. result["first_seen"] = row[1]
  339. result["stored_url"] = row[2]
  340. else:
  341. result["seen"] = False
  342. # If title provided, compute similarity against top clusters
  343. if title:
  344. # Get recent clusters for comparison
  345. recent = store.get_latest_clusters_all_topics(ttl_hours=24, limit=20)
  346. signals_list = []
  347. for c in recent:
  348. c_title = c.get("headline", "")
  349. sigs = _signals(art, c)
  350. matched, signal_name, signal_value = _is_match(
  351. sigs, embeddings_enabled=NEWS_EMBEDDINGS_ENABLED,
  352. )
  353. signals_list.append({
  354. "cluster_id": c.get("cluster_id", "")[:12],
  355. "headline": c_title[:60],
  356. "title_sim": round(sigs["title"], 3),
  357. "jaccard": round(sigs["jaccard"], 3),
  358. "cosine": round(sigs["cosine"], 3) if sigs["cosine"] else None,
  359. "matched": matched,
  360. "match_signal": signal_name,
  361. "match_value": round(signal_value, 3) if signal_value else None,
  362. })
  363. # Sort by best title similarity
  364. signals_list.sort(key=lambda x: x["title_sim"], reverse=True)
  365. result["similarity_signals"] = signals_list[:10]
  366. result["title_threshold"] = 0.75 # DEFAULT_TITLE_THRESHOLD
  367. result["jaccard_threshold"] = 0.55 # DEFAULT_JACCARD_THRESHOLD
  368. return result
  369. @mcp.tool(description="Investigate a topic and return the newest deduplicated news clusters with entities and thematic keywords, sorted by recency.")
  370. async def get_latest_events(topic: str | None = None, limit: int = 5, include_articles: bool = False):
  371. limit = max(1, min(int(limit), 20))
  372. # When topic is omitted, search across all topics (no topic filter).
  373. # When topic is provided and matches a known topic, filter by that topic.
  374. # Otherwise treat the value as an entity-like query.
  375. topic_norm = normalize_query(topic).lower() if topic else ""
  376. resolved = resolve_entity_via_trends(topic_norm) if topic_norm else {}
  377. allowed = {t.lower() for t in DEFAULT_TOPICS}
  378. is_topic = topic_norm in allowed
  379. is_all_topics = not topic_norm
  380. query_terms = {
  381. topic_norm,
  382. str(resolved.get("normalized") or "").strip().lower(),
  383. str(resolved.get("canonical_label") or "").strip().lower(),
  384. str(resolved.get("mid") or "").strip().lower(),
  385. }
  386. query_terms = {q for q in query_terms if q}
  387. store = SQLiteClusterStore(DB_PATH)
  388. if is_all_topics:
  389. # No topic specified: return freshest clusters across all topics.
  390. clusters = store.get_latest_clusters_all_topics(ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  391. elif is_topic:
  392. # Cache-first: only refresh if we currently have no fresh clusters for this topic.
  393. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  394. if not clusters:
  395. await refresh_clusters(topic=topic_norm, limit=200)
  396. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  397. else:
  398. # Entity-aware mode: search recent clusters across all topics and match by
  399. # raw entity, canonical label, or MID using SQL-level junction table search.
  400. clusters = store.get_clusters_by_entity_or_keyword(
  401. query_terms=query_terms, hours=DEFAULT_LOOKBACK_HOURS, limit=limit
  402. )
  403. out = []
  404. for c in _sort_clusters_by_recency(clusters):
  405. item = {
  406. "cluster_id": c.get("cluster_id"),
  407. "headline": c.get("headline"),
  408. "summary": c.get("summary"),
  409. "entities": c.get("entities", []),
  410. "keywords": c.get("keywords", []),
  411. "sentiment": c.get("sentiment", "neutral"),
  412. "importance": c.get("importance", 0.0),
  413. "sources": c.get("sources", []),
  414. "timestamp": c.get("timestamp"),
  415. }
  416. if include_articles:
  417. # Return minimal article fields to keep responses compact.
  418. arts = c.get("articles", []) or []
  419. item["articles"] = [
  420. {
  421. "title": a.get("title"),
  422. "url": a.get("url"),
  423. "source": a.get("source"),
  424. "timestamp": a.get("timestamp"),
  425. }
  426. for a in arts
  427. if isinstance(a, dict)
  428. ]
  429. out.append(item)
  430. return out
  431. @mcp.tool(description="Investigate a person, company, place, theme, or keyword by matching entities and thematic keywords within a time window.")
  432. async def get_events_for_entity(entity: str, limit: int = 10, timeframe: str = "24h", include_articles: bool = False):
  433. limit = max(1, min(int(limit), 30))
  434. query = normalize_query(entity).strip().lower()
  435. if not query:
  436. return []
  437. resolved = resolve_entity_via_trends(query)
  438. query_terms = {
  439. query,
  440. str(resolved.get("normalized") or "").strip().lower(),
  441. str(resolved.get("canonical_label") or "").strip().lower(),
  442. str(resolved.get("mid") or "").strip().lower(),
  443. }
  444. query_terms = {q for q in query_terms if q}
  445. store = SQLiteClusterStore(DB_PATH)
  446. hours = _parse_timeframe_to_hours(timeframe)
  447. hits = store.get_clusters_by_entity_or_keyword(query_terms=query_terms, hours=hours, limit=limit)
  448. out = []
  449. for c in hits:
  450. item = {
  451. "cluster_id": c.get("cluster_id"),
  452. "headline": c.get("headline"),
  453. "summary": c.get("summary"),
  454. "entities": c.get("entities", []),
  455. "keywords": c.get("keywords", []),
  456. "sentiment": c.get("sentiment", "neutral"),
  457. "importance": c.get("importance", 0.0),
  458. "sources": c.get("sources", []),
  459. "timestamp": c.get("timestamp"),
  460. }
  461. if include_articles:
  462. arts = c.get("articles", []) or []
  463. item["articles"] = [
  464. {
  465. "title": a.get("title"),
  466. "url": a.get("url"),
  467. "source": a.get("source"),
  468. "timestamp": a.get("timestamp"),
  469. }
  470. for a in arts
  471. if isinstance(a, dict)
  472. ]
  473. out.append(item)
  474. return out
  475. @mcp.tool(description="Return entities and thematic keywords commonly co-occurring with the subject in recent clusters, optionally blended with Google Trends suggestions.")
  476. async def get_related_recent_entities(subject: str, timeframe: str = "72h", limit: int = 10, include_trends: bool = True):
  477. limit = max(1, min(int(limit), 25))
  478. hours = _parse_timeframe_to_hours(timeframe)
  479. include_trends_bool = str(include_trends).strip().lower() not in {"false", "0", "no"}
  480. store = SQLiteClusterStore(DB_PATH)
  481. result = related_recent_entities(
  482. store=store,
  483. subject=subject,
  484. timeframe_hours=hours,
  485. limit=limit,
  486. include_trends=include_trends_bool,
  487. )
  488. return result
  489. @mcp.tool(description="Investigate one cluster in depth and return a concise LLM-written explanation plus key facts, "
  490. "entities, keywords, related entities and keywords, sentiment, importance, and articles.")
  491. async def get_event_summary(event_id: str, include_articles: bool = True):
  492. store = SQLiteClusterStore(DB_PATH)
  493. # Summary cache: reuse if present within TTL.
  494. cluster = store.get_cluster_by_id(event_id)
  495. if not cluster:
  496. return {
  497. "event_id": event_id,
  498. "error": "NOT_FOUND",
  499. }
  500. cached_summary = store.get_cluster_summary(
  501. cluster_id=event_id,
  502. ttl_hours=DEFAULT_LOOKBACK_HOURS,
  503. )
  504. def _enrich(base: dict, src_cluster: dict) -> dict:
  505. base["entities"] = src_cluster.get("entities", [])
  506. base["keywords"] = src_cluster.get("keywords", [])
  507. base["topic"] = src_cluster.get("topic", "other")
  508. base["sentiment"] = src_cluster.get("sentiment", "neutral")
  509. base["sentimentScore"] = src_cluster.get("sentimentScore")
  510. base["importance"] = src_cluster.get("importance", 0.0)
  511. # Related entities: from co-occurrence in this cluster's article set
  512. resolved = src_cluster.get("entityResolutions", []) or []
  513. related_ents = []
  514. seen_ents = {str(e).strip().lower() for e in (src_cluster.get("entities", []) or [])}
  515. for res in resolved:
  516. if isinstance(res, dict):
  517. label = str(res.get("canonical_label") or res.get("normalized") or "").strip()
  518. if label and label.lower() not in seen_ents:
  519. related_ents.append(label)
  520. seen_ents.add(label.lower())
  521. base["related_entities"] = related_ents[:10]
  522. # Related keywords: from the cluster's own keywords (thematic descriptors)
  523. # plus any co-occurring keywords from recent related clusters
  524. base["related_keywords"] = _fetch_related_keywords(store, src_cluster, event_id)
  525. if include_articles:
  526. arts = src_cluster.get("articles", []) or []
  527. base["articles"] = [
  528. {
  529. "title": a.get("title"),
  530. "url": a.get("url"),
  531. "source": a.get("source"),
  532. "timestamp": a.get("timestamp"),
  533. }
  534. for a in arts
  535. if isinstance(a, dict)
  536. ]
  537. return base
  538. if cached_summary:
  539. out = {
  540. "event_id": event_id,
  541. "headline": cached_summary.get("headline"),
  542. "mergedSummary": cached_summary.get("mergedSummary"),
  543. "keyFacts": cached_summary.get("keyFacts", []),
  544. "sources": cached_summary.get("sources", []),
  545. }
  546. out = _enrich(out, cluster)
  547. return out
  548. summary = await summarize_cluster_llm(cluster)
  549. store.upsert_cluster_summary(event_id, summary)
  550. out = {
  551. "event_id": event_id,
  552. "headline": summary.get("headline"),
  553. "mergedSummary": summary.get("mergedSummary"),
  554. "keyFacts": summary.get("keyFacts", []),
  555. "sources": summary.get("sources", []),
  556. }
  557. out = _enrich(out, cluster)
  558. return out
  559. def _fetch_related_keywords(store: SQLiteClusterStore, cluster: dict, event_id: str) -> list[str]:
  560. """Find keywords that co-occur with this cluster's entities in recent clusters.
  561. This gives agents thematic context: what else was being discussed alongside
  562. the entities in this cluster during the same window.
  563. """
  564. entities = cluster.get("entities", []) or []
  565. if not entities:
  566. return []
  567. # Build a set of entity terms to search with
  568. entity_terms = set()
  569. for e in entities:
  570. entity_terms.add(str(e).strip().lower())
  571. for res in (cluster.get("entityResolutions", []) or []):
  572. if isinstance(res, dict):
  573. for key in ("normalized", "canonical_label"):
  574. val = res.get(key)
  575. if val:
  576. entity_terms.add(str(val).strip().lower())
  577. entity_terms.discard("")
  578. if not entity_terms:
  579. return []
  580. # Find recent clusters that share any entity, collect their keywords
  581. # Use payload_ts lookback of 48h for co-occurrence window
  582. from datetime import timedelta
  583. cutoff = (datetime.now(timezone.utc) - timedelta(hours=48)).isoformat()
  584. placeholders = ",".join("?" for _ in entity_terms)
  585. try:
  586. rows = store._conn().execute(
  587. f"SELECT DISTINCT c.payload FROM clusters c "
  588. f"JOIN cluster_entities ce ON c.cluster_id = ce.cluster_id "
  589. f"WHERE c.payload_ts >= ? AND c.cluster_id != ? "
  590. f"AND ce.entity IN ({placeholders}) "
  591. f"ORDER BY c.payload_ts DESC LIMIT 20",
  592. (cutoff, event_id, *entity_terms),
  593. ).fetchall()
  594. except Exception:
  595. return []
  596. kw_counter: dict[str, int] = {}
  597. cluster_kws = {str(k).strip().lower() for k in (cluster.get("keywords", []) or []) if str(k).strip()}
  598. for (payload_text,) in rows:
  599. try:
  600. c = json.loads(payload_text)
  601. except Exception:
  602. continue
  603. for kw in (c.get("keywords", []) or []):
  604. kw_norm = str(kw).strip()
  605. if not kw_norm:
  606. continue
  607. kw_key = kw_norm.lower()
  608. # Skip keywords that already appear in this cluster
  609. if kw_key in cluster_kws:
  610. continue
  611. kw_counter[kw_norm] = kw_counter.get(kw_norm, 0) + 1
  612. # Return top keywords by co-occurrence count
  613. sorted_kws = sorted(kw_counter.items(), key=lambda x: -x[1])
  614. return [kw for kw, _ in sorted_kws[:10]]
  615. @mcp.tool(description="Explore what is starting to matter: surface emerging entities, thematic keywords, and phrases from recent clusters. "
  616. "Use timeframe to control the lookback window, topic to scope to a category, and around to find what's emerging near a specific entity. "
  617. "Results include signal_type (entity / keyword / phrase) for downstream filtering.")
  618. async def detect_emerging_topics(limit: int = 10, timeframe: str = "24h", topic: str | None = None, around: str | None = None):
  619. """Surface entities and phrases that are accelerating in recent clusters.
  620. Args:
  621. limit: max results to return (1-20, default 10).
  622. timeframe: lookback window like "4h", "24h", "3d" (default "24h").
  623. topic: optional coarse topic filter ("crypto", "macro", "regulation", "ai", "other").
  624. around: optional entity — only return entities that co-occur with this entity
  625. in the recent window (e.g. "Bitcoin" to find what's emerging in Bitcoin's neighborhood).
  626. """
  627. limit = max(1, min(int(limit), 20))
  628. hours = _parse_timeframe_to_hours(timeframe)
  629. half_hours = hours / 2.0
  630. store = SQLiteClusterStore(DB_PATH)
  631. # Fetch more clusters than needed so velocity stats are meaningful even for short windows.
  632. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  633. # --- optional topic filter ---
  634. if topic:
  635. topic_norm = normalize_query(topic).strip().lower()
  636. if topic_norm:
  637. clusters = [c for c in clusters if (c.get("topic") or "other").strip().lower() == topic_norm]
  638. # --- resolve the 'around' entity ---
  639. around_terms: set[str] = set()
  640. if around:
  641. around_norm = normalize_query(around).strip().lower()
  642. if around_norm:
  643. resolved = resolve_entity_via_trends(around_norm)
  644. around_terms = {
  645. around_norm,
  646. str(resolved.get("normalized") or "").strip().lower(),
  647. str(resolved.get("canonical_label") or "").strip().lower(),
  648. }
  649. around_terms.discard("")
  650. # split clusters into first-half vs second-half by timestamp
  651. # clusters are already sorted most-recent-first from the store
  652. now = datetime.now(timezone.utc)
  653. def _cluster_age_hours(c: dict) -> float:
  654. """Return the cluster's age in hours. payload.timestamp is ISO 8601 UTC guaranteed."""
  655. ts = c.get("timestamp") or c.get("last_updated")
  656. if not ts:
  657. return 0.0
  658. try:
  659. dt = datetime.fromisoformat(str(ts).strip())
  660. if dt.tzinfo is None:
  661. dt = dt.replace(tzinfo=timezone.utc)
  662. return max(0.0, (now - dt.astimezone(timezone.utc)).total_seconds() / 3600.0)
  663. except Exception:
  664. return 0.0
  665. # Generic entity filter
  666. _generic_tokens = {"news", "latest", "breaking", "update", "updates", "report", "reports"}
  667. def _is_generic_entity(ent: str) -> bool:
  668. e = str(ent).strip().lower()
  669. if not e or len(e) < 4:
  670. return True
  671. if e in _generic_tokens:
  672. return True
  673. return False
  674. # --- accumulate signals ---
  675. # recent = second half of timeframe (newer), prior = first half (older)
  676. entity_counts_recent = Counter()
  677. entity_counts_prior = Counter()
  678. entity_importance_recent = Counter()
  679. entity_sources: dict[str, set] = {} # ent -> set of source names
  680. entity_buckets: dict[str, set] = {} # ent -> set of time-bucket indices (for sustained-spike detection)
  681. entity_cooccur: dict[str, Counter] = {}
  682. phrase_counts_recent = Counter()
  683. # Keyword accumulators — same scoring pipeline as entities, but tracking
  684. # LLM-curated thematic descriptors instead of named entities.
  685. kw_counts_recent = Counter()
  686. kw_counts_prior = Counter()
  687. kw_importance_recent = Counter()
  688. kw_sources: dict[str, set] = {}
  689. kw_buckets: dict[str, set] = {}
  690. kw_cooccur: dict[str, Counter] = {}
  691. entity_kw_cooccur: dict[str, Counter] = {} # entity -> Counter of co-occurring keywords
  692. bucket_size_hours = max(1.0, hours / 6.0) # split window into ~6 buckets
  693. for c in clusters:
  694. ents_in_cluster = [e for e in (c.get("entities", []) or []) if not _is_generic_entity(e)]
  695. ents_norm = [str(e).strip().lower() for e in ents_in_cluster if str(e).strip()]
  696. # Keywords: deduplicate per cluster so a cluster with the same keyword
  697. # listed twice doesn't inflate counts.
  698. kws_in_cluster = list(dict.fromkeys(
  699. str(k).strip().lower()
  700. for k in (c.get("keywords", []) or [])
  701. if str(k).strip() and not _is_generic_entity(k)
  702. ))
  703. age_h = _cluster_age_hours(c)
  704. is_recent = age_h <= half_hours
  705. bucket_idx = int(age_h / bucket_size_hours)
  706. # --- around filter: only count clusters that mention the target entity ---
  707. if around_terms:
  708. haystack = set(ents_norm)
  709. for res in c.get("entityResolutions", []) or []:
  710. if isinstance(res, dict):
  711. for key in ("normalized", "canonical_label"):
  712. val = res.get(key)
  713. if val:
  714. haystack.add(str(val).strip().lower())
  715. if not (haystack & around_terms):
  716. continue
  717. counts = entity_counts_recent if is_recent else entity_counts_prior
  718. imp_acc = entity_importance_recent if is_recent else None # only importance from recent window
  719. for ent in ents_norm:
  720. if _is_generic_entity(ent):
  721. continue
  722. counts[ent] += 1
  723. if ent not in entity_sources:
  724. entity_sources[ent] = set()
  725. src = c.get("source") or c.get("headline", "").split(" - ")[-1] if c.get("headline") else ""
  726. if src:
  727. entity_sources[ent].add(str(src))
  728. if ent not in entity_buckets:
  729. entity_buckets[ent] = set()
  730. entity_buckets[ent].add(bucket_idx)
  731. if imp_acc is not None:
  732. try:
  733. imp_acc[ent] += float(c.get("importance", 0.0) or 0.0)
  734. except Exception:
  735. pass
  736. # --- keyword counting (same recent/prior split as entities) ---
  737. kw_counts = kw_counts_recent if is_recent else kw_counts_prior
  738. kw_imp_acc = kw_importance_recent if is_recent else None
  739. for kw in kws_in_cluster:
  740. kw_counts[kw] += 1
  741. if kw not in kw_sources:
  742. kw_sources[kw] = set()
  743. src = c.get("source") or c.get("headline", "").split(" - ")[-1] if c.get("headline") else ""
  744. if src:
  745. kw_sources[kw].add(str(src))
  746. if kw not in kw_buckets:
  747. kw_buckets[kw] = set()
  748. kw_buckets[kw].add(bucket_idx)
  749. if kw_imp_acc is not None:
  750. try:
  751. kw_imp_acc[kw] += float(c.get("importance", 0.0) or 0.0) # type: ignore[assignment]
  752. except Exception:
  753. pass
  754. # co-occurrence (only for clusters matching the around filter, if any)
  755. for i in range(len(ents_norm)):
  756. a = ents_norm[i]
  757. if _is_generic_entity(a):
  758. continue
  759. if a not in entity_cooccur:
  760. entity_cooccur[a] = Counter()
  761. for j in range(len(ents_norm)):
  762. if i == j:
  763. continue
  764. b = ents_norm[j]
  765. if _is_generic_entity(b):
  766. continue
  767. entity_cooccur[a][b] += 1
  768. # keyword co-occurrence: which keywords appear together in the same clusters
  769. for i in range(len(kws_in_cluster)):
  770. ka = kws_in_cluster[i]
  771. if ka not in kw_cooccur:
  772. kw_cooccur[ka] = Counter()
  773. for j in range(len(kws_in_cluster)):
  774. if i == j:
  775. continue
  776. kb = kws_in_cluster[j]
  777. kw_cooccur[ka][kb] += 1
  778. # also track entity<->keyword co-occurrence (bidirectional)
  779. for ent in ents_norm:
  780. if _is_generic_entity(ent):
  781. continue
  782. kw_cooccur[ka][ent] += 1
  783. # and the reverse: entity -> keyword
  784. if ent not in entity_kw_cooccur:
  785. entity_kw_cooccur[ent] = Counter()
  786. entity_kw_cooccur[ent][ka] += 1
  787. # bigram phrases (recent only)
  788. if is_recent:
  789. text = f"{c.get('headline', '')} {c.get('summary', '')}"
  790. words = re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())
  791. for i in range(len(words) - 1):
  792. phrase = f"{words[i]} {words[i+1]}"
  793. if len(phrase) > 6:
  794. phrase_counts_recent[phrase] += 1
  795. # --- score entities ---
  796. all_entities = set(entity_counts_recent.keys()) | set(entity_counts_prior.keys())
  797. scored = []
  798. for ent in all_entities:
  799. recent_n = entity_counts_recent.get(ent, 0)
  800. prior_n = entity_counts_prior.get(ent, 0)
  801. total_n = recent_n + prior_n
  802. if total_n < 1:
  803. continue
  804. # velocity: ratio of recent vs prior (smoothed to avoid division noise)
  805. # 0 prior → velocity = recent_n (pure emergence)
  806. # equal → velocity = 1.0 (steady)
  807. velocity = (recent_n + 0.5) / (prior_n + 0.5)
  808. # recency weight: what fraction of total hits are in the recent window
  809. recency_ratio = recent_n / total_n
  810. # source diversity: how many distinct outlets
  811. n_sources = len(entity_sources.get(ent, set()))
  812. # sustained: how many distinct time buckets did it appear in (max ~6)
  813. n_buckets = len(entity_buckets.get(ent, set()))
  814. # average importance (recent window only)
  815. avg_imp = (entity_importance_recent.get(ent, 0.0) / max(1, recent_n)) if recent_n > 0 else 0.0
  816. composed_score = (
  817. 0.35 * min(1.0, math.log1p(velocity) / math.log1p(4.0)) + # velocity (0..1, 4x = max)
  818. 0.25 * recency_ratio + # recency concentration
  819. 0.15 * min(1.0, n_sources / 5.0) + # source diversity
  820. 0.10 * min(1.0, n_buckets / 4.0) + # sustained (>1 bucket)
  821. 0.15 * min(1.0, avg_imp) # importance
  822. )
  823. related = []
  824. if ent in entity_cooccur:
  825. for other, _cnt in entity_cooccur[ent].most_common(10):
  826. if other != ent:
  827. related.append(other)
  828. related_kws = []
  829. if ent in entity_kw_cooccur:
  830. # Build a set of related entity names (lowercased) to deduplicate
  831. # keywords that are already represented in related_entities
  832. related_ent_names = {e.strip().lower() for e in related}
  833. # Also include the entity itself and its common aliases
  834. related_ent_names.add(ent.strip().lower())
  835. for kw, _cnt in entity_kw_cooccur[ent].most_common(10):
  836. kw_lower = kw.strip().lower()
  837. # Skip keywords that are just a related entity name (substring match)
  838. if any(kw_lower in ent_name or ent_name in kw_lower
  839. for ent_name in related_ent_names):
  840. continue
  841. related_kws.append(kw)
  842. if len(related_kws) >= 5:
  843. break
  844. scored.append({
  845. "topic": ent,
  846. "trend_score": min(0.99, round(composed_score, 3)),
  847. "related_entities": related[:5] if related else [ent],
  848. "related_keywords": related_kws[:5],
  849. "velocity": round(velocity, 2),
  850. "recent_count": recent_n,
  851. "prior_count": prior_n,
  852. "source_count": n_sources,
  853. "avg_importance": round(avg_imp, 3),
  854. "signal_type": "entity",
  855. })
  856. # --- score keywords (same velocity/recency/source/sustained/importance formula) ---
  857. all_keywords = set(kw_counts_recent.keys()) | set(kw_counts_prior.keys())
  858. kw_scored = []
  859. for kw in all_keywords:
  860. # Skip keywords that are already scored as entities — entity signal is
  861. # higher quality (proper nouns, resolved identities).
  862. if kw in all_entities:
  863. continue
  864. recent_n = kw_counts_recent.get(kw, 0)
  865. prior_n = kw_counts_prior.get(kw, 0)
  866. total_n = recent_n + prior_n
  867. if total_n < 1:
  868. continue
  869. velocity = (recent_n + 0.5) / (prior_n + 0.5)
  870. recency_ratio = recent_n / total_n
  871. n_sources = len(kw_sources.get(kw, set()))
  872. n_buckets = len(kw_buckets.get(kw, set()))
  873. avg_imp = (kw_importance_recent.get(kw, 0.0) / max(1, recent_n)) if recent_n > 0 else 0.0
  874. composed_score = (
  875. 0.35 * min(1.0, math.log1p(velocity) / math.log1p(4.0)) +
  876. 0.25 * recency_ratio +
  877. 0.15 * min(1.0, n_sources / 5.0) +
  878. 0.10 * min(1.0, n_buckets / 4.0) +
  879. 0.15 * min(1.0, avg_imp)
  880. )
  881. kw_related_kws = []
  882. kw_related_ents = []
  883. if kw in kw_cooccur:
  884. for other, _cnt in kw_cooccur[kw].most_common(10):
  885. if other == kw:
  886. continue
  887. # If this co-occurring term is a known entity, route to related_entities
  888. if other in all_entities:
  889. kw_related_ents.append(other)
  890. else:
  891. kw_related_kws.append(other)
  892. if len(kw_related_kws) >= 5 and len(kw_related_ents) >= 5:
  893. break
  894. kw_scored.append({
  895. "topic": kw,
  896. "trend_score": min(0.99, round(composed_score, 3)),
  897. "related_entities": kw_related_ents[:5],
  898. "related_keywords": kw_related_kws[:5],
  899. "velocity": round(velocity, 2),
  900. "recent_count": recent_n,
  901. "prior_count": prior_n,
  902. "source_count": n_sources,
  903. "avg_importance": round(avg_imp, 3),
  904. "signal_type": "keyword",
  905. })
  906. # sort keywords by score descending
  907. kw_scored.sort(key=lambda x: (-x["trend_score"], -x["velocity"], x["topic"]))
  908. # sort by composed score descending
  909. scored.sort(key=lambda x: (-x["trend_score"], -x["velocity"], x["topic"]))
  910. # --- merge: entities first, then keywords, then phrases ---
  911. emerging = list(scored) # start with entities
  912. seen_topics = {item["topic"] for item in emerging}
  913. for kw_item in kw_scored:
  914. if kw_item["topic"] not in seen_topics:
  915. emerging.append(kw_item)
  916. seen_topics.add(kw_item["topic"])
  917. # --- add phrase signals (only from recent window) ---
  918. for phrase, count in phrase_counts_recent.most_common(limit * 2):
  919. if phrase in seen_topics:
  920. continue
  921. emerging.append({
  922. "topic": phrase.title(),
  923. "trend_score": min(0.99, round(0.30 + 0.15 * min(count, 5), 2)),
  924. "related_entities": [],
  925. "related_keywords": [],
  926. "velocity": None,
  927. "recent_count": count,
  928. "prior_count": 0,
  929. "source_count": 0,
  930. "avg_importance": 0.0,
  931. "signal_type": "phrase",
  932. })
  933. seen_topics.add(phrase)
  934. if len(emerging) >= limit:
  935. break
  936. return emerging[:limit]
  937. @mcp.tool(description="Investigate whether sentiment around an entity or keyword is positive, negative, or neutral over a chosen lookback window. "
  938. "Matches clusters by both named entities and thematic keywords.")
  939. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  940. store = SQLiteClusterStore(DB_PATH)
  941. ent = normalize_query(entity).strip().lower()
  942. resolved = resolve_entity_via_trends(ent)
  943. query_terms = {
  944. ent,
  945. str(resolved.get("normalized") or "").strip().lower(),
  946. str(resolved.get("canonical_label") or "").strip().lower(),
  947. str(resolved.get("mid") or "").strip().lower(),
  948. }
  949. query_terms = {q for q in query_terms if q}
  950. if not ent:
  951. return {
  952. "entity": entity,
  953. "sentiment": "neutral",
  954. "score": 0.0,
  955. "cluster_count": 0,
  956. }
  957. # timeframe: accept '24h' or '24'
  958. tf = str(timeframe).strip().lower()
  959. try:
  960. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  961. except Exception:
  962. hours = 24
  963. hours = max(1, min(int(hours), 168))
  964. clusters = store.get_clusters_by_entity_or_keyword(query_terms=query_terms, hours=hours, limit=500)
  965. matched = clusters
  966. if not matched:
  967. return {
  968. "entity": entity,
  969. "sentiment": "neutral",
  970. "score": 0.0,
  971. "cluster_count": 0,
  972. }
  973. scores = []
  974. for c in matched:
  975. s = c.get("sentimentScore")
  976. if s is not None:
  977. try:
  978. scores.append(float(s))
  979. except Exception:
  980. pass
  981. avg_score = sum(scores) / len(scores) if scores else 0.0
  982. # Keep the label aligned with the numeric score.
  983. # Small magnitudes are treated as neutral to avoid noisy label flips.
  984. if avg_score >= 0.15:
  985. sentiment = "positive"
  986. elif avg_score <= -0.15:
  987. sentiment = "negative"
  988. else:
  989. sentiment = "neutral"
  990. return {
  991. "entity": entity,
  992. "sentiment": sentiment,
  993. "score": round(avg_score, 3),
  994. "cluster_count": len(matched),
  995. }
  996. @mcp.tool(description="Describe the server tool surface, how tools fit together, and output conventions for downstream agents.")
  997. async def get_capabilities():
  998. return {
  999. "server": {
  1000. "name": "news-mcp",
  1001. "purpose": "Recent news clusters with entities and thematic keywords, entity/keyword drill-down, sentiment, emerging topics, and related-entity expansion.",
  1002. "output_conventions": {
  1003. "cluster_ids": "Do not surface cluster_id in user-facing prose unless explicitly requested; treat it as internal navigation metadata.",
  1004. "sources": "Always preserve and display sources when summarizing a cluster or entity result.",
  1005. "timestamps": "Mention timestamps consistently when comparing multiple clusters or when recency matters.",
  1006. "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.",
  1007. },
  1008. },
  1009. "tools": NEWS_TOOL_CARDS,
  1010. "recipes": NEWS_COMPOSITION_RECIPES,
  1011. "example_chains": NEWS_EXAMPLE_CHAINS,
  1012. "agent_tips": NEWS_AGENT_TIPS,
  1013. "guidance": [
  1014. "Use get_latest_events for a tail, get_events_for_entity for entity/keyword deep dives, and get_related_recent_entities for neighborhood expansion.",
  1015. "Prefer normalized/canonical entities when possible, but the server will resolve common aliases and MIDs for you.",
  1016. "When presenting results to users, summarize the cluster; avoid exposing internal IDs unless they are needed for follow-up tool calls.",
  1017. "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.",
  1018. "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.",
  1019. ],
  1020. }
  1021. def _parse_timeframe_to_hours(timeframe: str) -> int:
  1022. tf = str(timeframe).strip().lower()
  1023. try:
  1024. if tf.endswith("d"):
  1025. days = int(tf[:-1])
  1026. return max(1, days * 24)
  1027. if tf.endswith("h"):
  1028. return max(1, int(tf[:-1]))
  1029. return max(1, int(tf))
  1030. except Exception:
  1031. return 24
  1032. from contextlib import asynccontextmanager
  1033. @asynccontextmanager
  1034. async def _lifespan(app: FastAPI):
  1035. asyncio.ensure_future(_background_refresh_loop())
  1036. yield
  1037. app = FastAPI(title="News MCP Server", lifespan=_lifespan)
  1038. logger = logging.getLogger("news_mcp.startup")
  1039. app.mount("/mcp", mcp.sse_app())
  1040. # Shared store — single connection pool
  1041. _shared_store = SQLiteClusterStore(DB_PATH)
  1042. _refresh_lock = asyncio.Lock()
  1043. _refresh_started = False
  1044. async def _background_refresh_loop():
  1045. """Non-blocking background refresher: prune then poll.
  1046. Protected by an async lock so a second event-loop wake-up cannot
  1047. start a parallel ingestion cycle.
  1048. """
  1049. global _refresh_started
  1050. async with _refresh_lock:
  1051. if _refresh_started:
  1052. return
  1053. _refresh_started = True
  1054. logger.info("news-mcp llm config: %s", active_llm_config())
  1055. # Prune off-thread so we do not block the event loop
  1056. prune_result = await asyncio.to_thread(
  1057. _shared_store.prune_if_due,
  1058. NEWS_PRUNING_ENABLED,
  1059. NEWS_RETENTION_DAYS,
  1060. NEWS_PRUNE_INTERVAL_HOURS,
  1061. )
  1062. logger.info("startup prune_result=%s", prune_result)
  1063. # Seed feed_state from .env — insert missing feeds, leave existing alone
  1064. feed_urls = [u.strip() for u in NEWS_FEED_URLS.split(",") if u.strip()]
  1065. if not feed_urls and NEWS_FEED_URL:
  1066. feed_urls = [NEWS_FEED_URL]
  1067. with _shared_store._conn() as conn:
  1068. for url in feed_urls:
  1069. conn.execute(
  1070. "INSERT OR IGNORE INTO feed_state(feed_key, last_hash, last_item_count, enabled, updated_at) VALUES(?, '', 0, 1, '')",
  1071. (url,),
  1072. )
  1073. logger.info("startup seeded %d feeds into feed_state", len(feed_urls))
  1074. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  1075. return
  1076. async def _loop():
  1077. if not NEWS_BACKGROUND_REFRESH_ON_START:
  1078. logger.info("background refresh delayed start interval_seconds=%s", NEWS_REFRESH_INTERVAL_SECONDS)
  1079. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  1080. while True:
  1081. try:
  1082. logger.info("background refresh tick start")
  1083. await refresh_clusters(topic=None, limit=200)
  1084. logger.info("background refresh tick complete")
  1085. except Exception:
  1086. logger.exception("background refresh tick failed")
  1087. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  1088. asyncio.create_task(_loop())
  1089. @app.get("/")
  1090. def root():
  1091. return {
  1092. "status": "ok",
  1093. "transport": "fastmcp+sse",
  1094. "mount": "/mcp",
  1095. "tools": [
  1096. "get_latest_events",
  1097. "get_events_for_entity",
  1098. "get_event_summary",
  1099. "detect_emerging_topics",
  1100. "get_news_sentiment",
  1101. "get_related_recent_entities",
  1102. "get_capabilities",
  1103. ],
  1104. "refresh": {
  1105. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  1106. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  1107. },
  1108. "retention": {
  1109. "lookback_hours": DEFAULT_LOOKBACK_HOURS,
  1110. "retention_days": NEWS_RETENTION_DAYS,
  1111. },
  1112. "pruning": {
  1113. "enabled": NEWS_PRUNING_ENABLED,
  1114. "interval_hours": NEWS_PRUNE_INTERVAL_HOURS,
  1115. },
  1116. }
  1117. # ------------------------------------------------------------------
  1118. # Dashboard REST API endpoints
  1119. # ------------------------------------------------------------------
  1120. from fastapi.staticfiles import StaticFiles
  1121. from fastapi.responses import JSONResponse
  1122. app.mount("/dashboard", StaticFiles(directory="dashboard", html=True), name="dashboard")
  1123. import logging as _log
  1124. API_LOG = _log.getLogger("news_mcp.api")
  1125. def _api_ok(data: dict) -> dict:
  1126. return data
  1127. def _api_err(exc: Exception, ctx: str) -> JSONResponse:
  1128. API_LOG.exception(f"API error in {ctx}")
  1129. return JSONResponse(status_code=500, content={"error": str(exc), "ctx": ctx})
  1130. @app.get("/api/v1/health")
  1131. def api_health():
  1132. """Extended health + dashboard stats."""
  1133. try:
  1134. store = _shared_store
  1135. stats = store.get_dashboard_stats()
  1136. stats["version"] = _VERSION_HASH
  1137. return stats
  1138. except Exception as e:
  1139. return _api_err(e, "health")
  1140. @app.get("/api/v1/clusters")
  1141. def api_clusters(
  1142. topic: str | None = None,
  1143. hours: int = 24,
  1144. limit: int = 50,
  1145. offset: int = 0,
  1146. ):
  1147. """Paginated cluster listing."""
  1148. try:
  1149. store = _shared_store
  1150. result = store.get_clusters_page(topic=topic, hours=hours, limit=limit, offset=offset)
  1151. return {"clusters": result["clusters"], "total": result["total"], "topic": topic or "all", "hours": hours}
  1152. except Exception as e:
  1153. return _api_err(e, f"clusters(topic={topic},hours={hours})")
  1154. @app.get("/api/v1/sentiment-series")
  1155. def api_sentiment_series(
  1156. topic: str | None = None,
  1157. hours: int = 24,
  1158. bucket_hours: float = 1.0,
  1159. ):
  1160. """Sentiment time-series for Chart.js."""
  1161. try:
  1162. store = _shared_store
  1163. series = store.get_sentiment_series(topic=topic, hours=hours, bucket_hours=bucket_hours)
  1164. return {"series": series, "topic": topic or "all"}
  1165. except Exception as e:
  1166. return _api_err(e, f"sentiment(topic={topic})")
  1167. @app.get("/api/v1/entities")
  1168. def api_entities(
  1169. hours: int = 24,
  1170. limit: int = 30,
  1171. ):
  1172. """Top entity frequencies."""
  1173. try:
  1174. store = _shared_store
  1175. entities = store.get_entity_frequencies(hours=hours, limit=limit)
  1176. return {"entities": entities, "hours": hours}
  1177. except Exception as e:
  1178. return _api_err(e, f"entities(hours={hours})")
  1179. @app.get("/api/v1/keywords")
  1180. def api_keywords(
  1181. hours: int = 24,
  1182. limit: int = 30,
  1183. ):
  1184. """Top keyword frequencies (thematic descriptors, excluding terms already counted as entities)."""
  1185. try:
  1186. store = _shared_store
  1187. keywords = store.get_keyword_frequencies(hours=hours, limit=limit)
  1188. return {"keywords": keywords, "hours": hours}
  1189. except Exception as e:
  1190. return _api_err(e, f"keywords(hours={hours})")
  1191. @app.get("/api/v1/clusters/by-entity")
  1192. def api_clusters_by_entity(
  1193. entity: str,
  1194. hours: int = 168,
  1195. limit: int = 50,
  1196. offset: int = 0,
  1197. ):
  1198. """Return clusters matching an entity, filtered by event time via SQL junction table."""
  1199. try:
  1200. store = _shared_store
  1201. return store.get_clusters_by_entity(
  1202. entity=entity.strip().lower(),
  1203. hours=hours,
  1204. limit=limit,
  1205. offset=offset,
  1206. )
  1207. except Exception as e:
  1208. return _api_err(e, f"by-entity(entity={entity},hours={hours})")
  1209. @app.get("/api/v1/clusters/by-keyword")
  1210. def api_clusters_by_keyword(
  1211. keyword: str,
  1212. hours: int = 168,
  1213. limit: int = 50,
  1214. offset: int = 0,
  1215. ):
  1216. """Return clusters matching a keyword, filtered by event time via SQL junction table."""
  1217. try:
  1218. store = _shared_store
  1219. return store.get_clusters_by_keyword(
  1220. keyword=keyword.strip().lower(),
  1221. hours=hours,
  1222. limit=limit,
  1223. offset=offset,
  1224. )
  1225. except Exception as e:
  1226. return _api_err(e, f"by-keyword(keyword={keyword},hours={hours})")
  1227. @app.get("/api/v1/cluster/{cluster_id}")
  1228. def api_cluster_detail(cluster_id: str):
  1229. """Full cluster detail for drill-down."""
  1230. try:
  1231. store = _shared_store
  1232. detail = store.get_cluster_detail(cluster_id)
  1233. if not detail:
  1234. return JSONResponse(status_code=404, content={"error": "Cluster not found", "id": cluster_id})
  1235. return detail
  1236. except Exception as e:
  1237. return _api_err(e, f"detail({cluster_id})")
  1238. # ------------------------------------------------------------------
  1239. # Feed management endpoints (toggle on/off from dashboard)
  1240. # ------------------------------------------------------------------
  1241. @app.get("/api/v1/feeds")
  1242. def api_feeds():
  1243. """List all configured feeds with enabled/disabled status."""
  1244. try:
  1245. store = SQLiteClusterStore(DB_PATH)
  1246. feed_list = store.get_feed_state_list()
  1247. configured = _configured_feed_urls()
  1248. return {
  1249. "feeds": feed_list,
  1250. "configured_urls": configured,
  1251. }
  1252. except Exception as e:
  1253. return _api_err(e, "feeds")
  1254. @app.post("/api/v1/feeds/toggle")
  1255. async def api_feed_toggle(feed_url: str = Form(), enabled: bool = Form()):
  1256. """Toggle a feed's enabled state."""
  1257. try:
  1258. store = SQLiteClusterStore(DB_PATH)
  1259. ok = store.set_feed_enabled(feed_url.strip(), enabled)
  1260. if not ok:
  1261. return JSONResponse(
  1262. status_code=404,
  1263. content={"error": f"Feed not found: {feed_url}"},
  1264. )
  1265. return {"ok": True, "feed_url": feed_url.strip(), "enabled": enabled}
  1266. except Exception as e:
  1267. return _api_err(e, f"toggle({feed_url})")
  1268. # ------------------------------------------------------------------ #
  1269. # Site config (dashboard-tuneable parameters)
  1270. # ------------------------------------------------------------------ #
  1271. @app.get("/api/v1/config")
  1272. def api_config():
  1273. """All site config parameters (seeded from .env/defaults)."""
  1274. try:
  1275. from news_mcp.site_config import get_site_config
  1276. with _shared_store._conn() as conn:
  1277. rows = get_site_config(conn)
  1278. return {"config": rows}
  1279. except Exception as e:
  1280. return _api_err(e, "config")
  1281. @app.post("/api/v1/config/update")
  1282. async def api_config_update(key: str = Form(), value: str = Form()):
  1283. """Update a single config parameter at runtime."""
  1284. try:
  1285. from news_mcp.site_config import set_config_value
  1286. with _shared_store._conn() as conn:
  1287. ok = set_config_value(conn, key.strip(), value.strip())
  1288. conn.commit()
  1289. if not ok:
  1290. return JSONResponse(status_code=404, content={"error": f"Config key not found: {key}"})
  1291. return {"ok": True, "key": key.strip(), "value": value.strip()}
  1292. except Exception as e:
  1293. return _api_err(e, f"config/update({key})")
  1294. @app.post("/api/v1/config/reset")
  1295. async def api_config_reset():
  1296. """Reset all config to .env/defaults (drops and re-seeds site_config)."""
  1297. try:
  1298. from news_mcp.site_config import seed_site_config
  1299. with _shared_store._conn() as conn:
  1300. conn.execute("DELETE FROM site_config")
  1301. seeded = seed_site_config(conn)
  1302. conn.commit()
  1303. return {"ok": True, "seeded": seeded}
  1304. except Exception as e:
  1305. return _api_err(e, "config/reset")
  1306. @app.get("/health")
  1307. def health():
  1308. return {
  1309. "status": "ok",
  1310. "uptime": round(time.monotonic() - _PROCESS_STARTED_AT, 3),
  1311. "version": _VERSION_HASH,
  1312. }