mcp_server_fastmcp.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  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="Investigate a topic and return the newest deduplicated news clusters with entities and thematic keywords, sorted by recency.")
  313. async def get_latest_events(topic: str | None = None, limit: int = 5, include_articles: bool = False):
  314. limit = max(1, min(int(limit), 20))
  315. # When topic is omitted, search across all topics (no topic filter).
  316. # When topic is provided and matches a known topic, filter by that topic.
  317. # Otherwise treat the value as an entity-like query.
  318. topic_norm = normalize_query(topic).lower() if topic else ""
  319. resolved = resolve_entity_via_trends(topic_norm) if topic_norm else {}
  320. allowed = {t.lower() for t in DEFAULT_TOPICS}
  321. is_topic = topic_norm in allowed
  322. is_all_topics = not topic_norm
  323. query_terms = {
  324. topic_norm,
  325. str(resolved.get("normalized") or "").strip().lower(),
  326. str(resolved.get("canonical_label") or "").strip().lower(),
  327. str(resolved.get("mid") or "").strip().lower(),
  328. }
  329. query_terms = {q for q in query_terms if q}
  330. store = SQLiteClusterStore(DB_PATH)
  331. if is_all_topics:
  332. # No topic specified: return freshest clusters across all topics.
  333. clusters = store.get_latest_clusters_all_topics(ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  334. elif is_topic:
  335. # Cache-first: only refresh if we currently have no fresh clusters for this topic.
  336. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  337. if not clusters:
  338. await refresh_clusters(topic=topic_norm, limit=200)
  339. clusters = store.get_latest_clusters(topic=topic_norm, ttl_hours=DEFAULT_LOOKBACK_HOURS, limit=limit)
  340. else:
  341. # Entity-aware mode: search recent clusters across all topics and match by
  342. # raw entity, canonical label, or MID using SQL-level junction table search.
  343. clusters = store.get_clusters_by_entity_or_keyword(
  344. query_terms=query_terms, hours=DEFAULT_LOOKBACK_HOURS, limit=limit
  345. )
  346. out = []
  347. for c in _sort_clusters_by_recency(clusters):
  348. item = {
  349. "cluster_id": c.get("cluster_id"),
  350. "headline": c.get("headline"),
  351. "summary": c.get("summary"),
  352. "entities": c.get("entities", []),
  353. "keywords": c.get("keywords", []),
  354. "sentiment": c.get("sentiment", "neutral"),
  355. "importance": c.get("importance", 0.0),
  356. "sources": c.get("sources", []),
  357. "timestamp": c.get("timestamp"),
  358. }
  359. if include_articles:
  360. # Return minimal article fields to keep responses compact.
  361. arts = c.get("articles", []) or []
  362. item["articles"] = [
  363. {
  364. "title": a.get("title"),
  365. "url": a.get("url"),
  366. "source": a.get("source"),
  367. "timestamp": a.get("timestamp"),
  368. }
  369. for a in arts
  370. if isinstance(a, dict)
  371. ]
  372. out.append(item)
  373. return out
  374. @mcp.tool(description="Investigate a person, company, place, theme, or keyword by matching entities and thematic keywords within a time window.")
  375. async def get_events_for_entity(entity: str, limit: int = 10, timeframe: str = "24h", include_articles: bool = False):
  376. limit = max(1, min(int(limit), 30))
  377. query = normalize_query(entity).strip().lower()
  378. if not query:
  379. return []
  380. resolved = resolve_entity_via_trends(query)
  381. query_terms = {
  382. query,
  383. str(resolved.get("normalized") or "").strip().lower(),
  384. str(resolved.get("canonical_label") or "").strip().lower(),
  385. str(resolved.get("mid") or "").strip().lower(),
  386. }
  387. query_terms = {q for q in query_terms if q}
  388. store = SQLiteClusterStore(DB_PATH)
  389. hours = _parse_timeframe_to_hours(timeframe)
  390. hits = store.get_clusters_by_entity_or_keyword(query_terms=query_terms, hours=hours, limit=limit)
  391. out = []
  392. for c in hits:
  393. item = {
  394. "cluster_id": c.get("cluster_id"),
  395. "headline": c.get("headline"),
  396. "summary": c.get("summary"),
  397. "entities": c.get("entities", []),
  398. "keywords": c.get("keywords", []),
  399. "sentiment": c.get("sentiment", "neutral"),
  400. "importance": c.get("importance", 0.0),
  401. "sources": c.get("sources", []),
  402. "timestamp": c.get("timestamp"),
  403. }
  404. if include_articles:
  405. arts = c.get("articles", []) or []
  406. item["articles"] = [
  407. {
  408. "title": a.get("title"),
  409. "url": a.get("url"),
  410. "source": a.get("source"),
  411. "timestamp": a.get("timestamp"),
  412. }
  413. for a in arts
  414. if isinstance(a, dict)
  415. ]
  416. out.append(item)
  417. return out
  418. @mcp.tool(description="Return entities and thematic keywords commonly co-occurring with the subject in recent clusters, optionally blended with Google Trends suggestions.")
  419. async def get_related_recent_entities(subject: str, timeframe: str = "72h", limit: int = 10, include_trends: bool = True):
  420. limit = max(1, min(int(limit), 25))
  421. hours = _parse_timeframe_to_hours(timeframe)
  422. include_trends_bool = str(include_trends).strip().lower() not in {"false", "0", "no"}
  423. store = SQLiteClusterStore(DB_PATH)
  424. result = related_recent_entities(
  425. store=store,
  426. subject=subject,
  427. timeframe_hours=hours,
  428. limit=limit,
  429. include_trends=include_trends_bool,
  430. )
  431. return result
  432. @mcp.tool(description="Investigate one cluster in depth and return a concise LLM-written explanation plus key facts, "
  433. "entities, keywords, related entities and keywords, sentiment, importance, and articles.")
  434. async def get_event_summary(event_id: str, include_articles: bool = True):
  435. store = SQLiteClusterStore(DB_PATH)
  436. # Summary cache: reuse if present within TTL.
  437. cluster = store.get_cluster_by_id(event_id)
  438. if not cluster:
  439. return {
  440. "event_id": event_id,
  441. "error": "NOT_FOUND",
  442. }
  443. cached_summary = store.get_cluster_summary(
  444. cluster_id=event_id,
  445. ttl_hours=DEFAULT_LOOKBACK_HOURS,
  446. )
  447. def _enrich(base: dict, src_cluster: dict) -> dict:
  448. base["entities"] = src_cluster.get("entities", [])
  449. base["keywords"] = src_cluster.get("keywords", [])
  450. base["topic"] = src_cluster.get("topic", "other")
  451. base["sentiment"] = src_cluster.get("sentiment", "neutral")
  452. base["sentimentScore"] = src_cluster.get("sentimentScore")
  453. base["importance"] = src_cluster.get("importance", 0.0)
  454. # Related entities: from co-occurrence in this cluster's article set
  455. resolved = src_cluster.get("entityResolutions", []) or []
  456. related_ents = []
  457. seen_ents = {str(e).strip().lower() for e in (src_cluster.get("entities", []) or [])}
  458. for res in resolved:
  459. if isinstance(res, dict):
  460. label = str(res.get("canonical_label") or res.get("normalized") or "").strip()
  461. if label and label.lower() not in seen_ents:
  462. related_ents.append(label)
  463. seen_ents.add(label.lower())
  464. base["related_entities"] = related_ents[:10]
  465. # Related keywords: from the cluster's own keywords (thematic descriptors)
  466. # plus any co-occurring keywords from recent related clusters
  467. base["related_keywords"] = _fetch_related_keywords(store, src_cluster, event_id)
  468. if include_articles:
  469. arts = src_cluster.get("articles", []) or []
  470. base["articles"] = [
  471. {
  472. "title": a.get("title"),
  473. "url": a.get("url"),
  474. "source": a.get("source"),
  475. "timestamp": a.get("timestamp"),
  476. }
  477. for a in arts
  478. if isinstance(a, dict)
  479. ]
  480. return base
  481. if cached_summary:
  482. out = {
  483. "event_id": event_id,
  484. "headline": cached_summary.get("headline"),
  485. "mergedSummary": cached_summary.get("mergedSummary"),
  486. "keyFacts": cached_summary.get("keyFacts", []),
  487. "sources": cached_summary.get("sources", []),
  488. }
  489. out = _enrich(out, cluster)
  490. return out
  491. summary = await summarize_cluster_llm(cluster)
  492. store.upsert_cluster_summary(event_id, summary)
  493. out = {
  494. "event_id": event_id,
  495. "headline": summary.get("headline"),
  496. "mergedSummary": summary.get("mergedSummary"),
  497. "keyFacts": summary.get("keyFacts", []),
  498. "sources": summary.get("sources", []),
  499. }
  500. out = _enrich(out, cluster)
  501. return out
  502. def _fetch_related_keywords(store: SQLiteClusterStore, cluster: dict, event_id: str) -> list[str]:
  503. """Find keywords that co-occur with this cluster's entities in recent clusters.
  504. This gives agents thematic context: what else was being discussed alongside
  505. the entities in this cluster during the same window.
  506. """
  507. entities = cluster.get("entities", []) or []
  508. if not entities:
  509. return []
  510. # Build a set of entity terms to search with
  511. entity_terms = set()
  512. for e in entities:
  513. entity_terms.add(str(e).strip().lower())
  514. for res in (cluster.get("entityResolutions", []) or []):
  515. if isinstance(res, dict):
  516. for key in ("normalized", "canonical_label"):
  517. val = res.get(key)
  518. if val:
  519. entity_terms.add(str(val).strip().lower())
  520. entity_terms.discard("")
  521. if not entity_terms:
  522. return []
  523. # Find recent clusters that share any entity, collect their keywords
  524. # Use payload_ts lookback of 48h for co-occurrence window
  525. from datetime import timedelta
  526. cutoff = (datetime.now(timezone.utc) - timedelta(hours=48)).isoformat()
  527. placeholders = ",".join("?" for _ in entity_terms)
  528. try:
  529. rows = store._conn().execute(
  530. f"SELECT DISTINCT c.payload FROM clusters c "
  531. f"JOIN cluster_entities ce ON c.cluster_id = ce.cluster_id "
  532. f"WHERE c.payload_ts >= ? AND c.cluster_id != ? "
  533. f"AND ce.entity IN ({placeholders}) "
  534. f"ORDER BY c.payload_ts DESC LIMIT 20",
  535. (cutoff, event_id, *entity_terms),
  536. ).fetchall()
  537. except Exception:
  538. return []
  539. kw_counter: dict[str, int] = {}
  540. cluster_kws = {str(k).strip().lower() for k in (cluster.get("keywords", []) or []) if str(k).strip()}
  541. for (payload_text,) in rows:
  542. try:
  543. c = json.loads(payload_text)
  544. except Exception:
  545. continue
  546. for kw in (c.get("keywords", []) or []):
  547. kw_norm = str(kw).strip()
  548. if not kw_norm:
  549. continue
  550. kw_key = kw_norm.lower()
  551. # Skip keywords that already appear in this cluster
  552. if kw_key in cluster_kws:
  553. continue
  554. kw_counter[kw_norm] = kw_counter.get(kw_norm, 0) + 1
  555. # Return top keywords by co-occurrence count
  556. sorted_kws = sorted(kw_counter.items(), key=lambda x: -x[1])
  557. return [kw for kw, _ in sorted_kws[:10]]
  558. @mcp.tool(description="Explore what is starting to matter: surface emerging entities, thematic keywords, and phrases from recent clusters. "
  559. "Use timeframe to control the lookback window, topic to scope to a category, and around to find what's emerging near a specific entity. "
  560. "Results include signal_type (entity / keyword / phrase) for downstream filtering.")
  561. async def detect_emerging_topics(limit: int = 10, timeframe: str = "24h", topic: str | None = None, around: str | None = None):
  562. """Surface entities and phrases that are accelerating in recent clusters.
  563. Args:
  564. limit: max results to return (1-20, default 10).
  565. timeframe: lookback window like "4h", "24h", "3d" (default "24h").
  566. topic: optional coarse topic filter ("crypto", "macro", "regulation", "ai", "other").
  567. around: optional entity — only return entities that co-occur with this entity
  568. in the recent window (e.g. "Bitcoin" to find what's emerging in Bitcoin's neighborhood).
  569. """
  570. limit = max(1, min(int(limit), 20))
  571. hours = _parse_timeframe_to_hours(timeframe)
  572. half_hours = hours / 2.0
  573. store = SQLiteClusterStore(DB_PATH)
  574. # Fetch more clusters than needed so velocity stats are meaningful even for short windows.
  575. clusters = store.get_latest_clusters_all_topics(ttl_hours=hours, limit=500)
  576. # --- optional topic filter ---
  577. if topic:
  578. topic_norm = normalize_query(topic).strip().lower()
  579. if topic_norm:
  580. clusters = [c for c in clusters if (c.get("topic") or "other").strip().lower() == topic_norm]
  581. # --- resolve the 'around' entity ---
  582. around_terms: set[str] = set()
  583. if around:
  584. around_norm = normalize_query(around).strip().lower()
  585. if around_norm:
  586. resolved = resolve_entity_via_trends(around_norm)
  587. around_terms = {
  588. around_norm,
  589. str(resolved.get("normalized") or "").strip().lower(),
  590. str(resolved.get("canonical_label") or "").strip().lower(),
  591. }
  592. around_terms.discard("")
  593. # split clusters into first-half vs second-half by timestamp
  594. # clusters are already sorted most-recent-first from the store
  595. now = datetime.now(timezone.utc)
  596. def _cluster_age_hours(c: dict) -> float:
  597. """Return the cluster's age in hours. payload.timestamp is ISO 8601 UTC guaranteed."""
  598. ts = c.get("timestamp") or c.get("last_updated")
  599. if not ts:
  600. return 0.0
  601. try:
  602. dt = datetime.fromisoformat(str(ts).strip())
  603. if dt.tzinfo is None:
  604. dt = dt.replace(tzinfo=timezone.utc)
  605. return max(0.0, (now - dt.astimezone(timezone.utc)).total_seconds() / 3600.0)
  606. except Exception:
  607. return 0.0
  608. # Generic entity filter
  609. _generic_tokens = {"news", "latest", "breaking", "update", "updates", "report", "reports"}
  610. def _is_generic_entity(ent: str) -> bool:
  611. e = str(ent).strip().lower()
  612. if not e or len(e) < 4:
  613. return True
  614. if e in _generic_tokens:
  615. return True
  616. return False
  617. # --- accumulate signals ---
  618. # recent = second half of timeframe (newer), prior = first half (older)
  619. entity_counts_recent = Counter()
  620. entity_counts_prior = Counter()
  621. entity_importance_recent = Counter()
  622. entity_sources: dict[str, set] = {} # ent -> set of source names
  623. entity_buckets: dict[str, set] = {} # ent -> set of time-bucket indices (for sustained-spike detection)
  624. entity_cooccur: dict[str, Counter] = {}
  625. phrase_counts_recent = Counter()
  626. # Keyword accumulators — same scoring pipeline as entities, but tracking
  627. # LLM-curated thematic descriptors instead of named entities.
  628. kw_counts_recent = Counter()
  629. kw_counts_prior = Counter()
  630. kw_importance_recent = Counter()
  631. kw_sources: dict[str, set] = {}
  632. kw_buckets: dict[str, set] = {}
  633. kw_cooccur: dict[str, Counter] = {}
  634. entity_kw_cooccur: dict[str, Counter] = {} # entity -> Counter of co-occurring keywords
  635. bucket_size_hours = max(1.0, hours / 6.0) # split window into ~6 buckets
  636. for c in clusters:
  637. ents_in_cluster = [e for e in (c.get("entities", []) or []) if not _is_generic_entity(e)]
  638. ents_norm = [str(e).strip().lower() for e in ents_in_cluster if str(e).strip()]
  639. # Keywords: deduplicate per cluster so a cluster with the same keyword
  640. # listed twice doesn't inflate counts.
  641. kws_in_cluster = list(dict.fromkeys(
  642. str(k).strip().lower()
  643. for k in (c.get("keywords", []) or [])
  644. if str(k).strip() and not _is_generic_entity(k)
  645. ))
  646. age_h = _cluster_age_hours(c)
  647. is_recent = age_h <= half_hours
  648. bucket_idx = int(age_h / bucket_size_hours)
  649. # --- around filter: only count clusters that mention the target entity ---
  650. if around_terms:
  651. haystack = set(ents_norm)
  652. for res in c.get("entityResolutions", []) or []:
  653. if isinstance(res, dict):
  654. for key in ("normalized", "canonical_label"):
  655. val = res.get(key)
  656. if val:
  657. haystack.add(str(val).strip().lower())
  658. if not (haystack & around_terms):
  659. continue
  660. counts = entity_counts_recent if is_recent else entity_counts_prior
  661. imp_acc = entity_importance_recent if is_recent else None # only importance from recent window
  662. for ent in ents_norm:
  663. if _is_generic_entity(ent):
  664. continue
  665. counts[ent] += 1
  666. if ent not in entity_sources:
  667. entity_sources[ent] = set()
  668. src = c.get("source") or c.get("headline", "").split(" - ")[-1] if c.get("headline") else ""
  669. if src:
  670. entity_sources[ent].add(str(src))
  671. if ent not in entity_buckets:
  672. entity_buckets[ent] = set()
  673. entity_buckets[ent].add(bucket_idx)
  674. if imp_acc is not None:
  675. try:
  676. imp_acc[ent] += float(c.get("importance", 0.0) or 0.0)
  677. except Exception:
  678. pass
  679. # --- keyword counting (same recent/prior split as entities) ---
  680. kw_counts = kw_counts_recent if is_recent else kw_counts_prior
  681. kw_imp_acc = kw_importance_recent if is_recent else None
  682. for kw in kws_in_cluster:
  683. kw_counts[kw] += 1
  684. if kw not in kw_sources:
  685. kw_sources[kw] = set()
  686. src = c.get("source") or c.get("headline", "").split(" - ")[-1] if c.get("headline") else ""
  687. if src:
  688. kw_sources[kw].add(str(src))
  689. if kw not in kw_buckets:
  690. kw_buckets[kw] = set()
  691. kw_buckets[kw].add(bucket_idx)
  692. if kw_imp_acc is not None:
  693. try:
  694. kw_imp_acc[kw] += float(c.get("importance", 0.0) or 0.0) # type: ignore[assignment]
  695. except Exception:
  696. pass
  697. # co-occurrence (only for clusters matching the around filter, if any)
  698. for i in range(len(ents_norm)):
  699. a = ents_norm[i]
  700. if _is_generic_entity(a):
  701. continue
  702. if a not in entity_cooccur:
  703. entity_cooccur[a] = Counter()
  704. for j in range(len(ents_norm)):
  705. if i == j:
  706. continue
  707. b = ents_norm[j]
  708. if _is_generic_entity(b):
  709. continue
  710. entity_cooccur[a][b] += 1
  711. # keyword co-occurrence: which keywords appear together in the same clusters
  712. for i in range(len(kws_in_cluster)):
  713. ka = kws_in_cluster[i]
  714. if ka not in kw_cooccur:
  715. kw_cooccur[ka] = Counter()
  716. for j in range(len(kws_in_cluster)):
  717. if i == j:
  718. continue
  719. kb = kws_in_cluster[j]
  720. kw_cooccur[ka][kb] += 1
  721. # also track entity<->keyword co-occurrence (bidirectional)
  722. for ent in ents_norm:
  723. if _is_generic_entity(ent):
  724. continue
  725. kw_cooccur[ka][ent] += 1
  726. # and the reverse: entity -> keyword
  727. if ent not in entity_kw_cooccur:
  728. entity_kw_cooccur[ent] = Counter()
  729. entity_kw_cooccur[ent][ka] += 1
  730. # bigram phrases (recent only)
  731. if is_recent:
  732. text = f"{c.get('headline', '')} {c.get('summary', '')}"
  733. words = re.findall(r"[A-Za-z][A-Za-z0-9\-]{2,}", text.lower())
  734. for i in range(len(words) - 1):
  735. phrase = f"{words[i]} {words[i+1]}"
  736. if len(phrase) > 6:
  737. phrase_counts_recent[phrase] += 1
  738. # --- score entities ---
  739. all_entities = set(entity_counts_recent.keys()) | set(entity_counts_prior.keys())
  740. scored = []
  741. for ent in all_entities:
  742. recent_n = entity_counts_recent.get(ent, 0)
  743. prior_n = entity_counts_prior.get(ent, 0)
  744. total_n = recent_n + prior_n
  745. if total_n < 1:
  746. continue
  747. # velocity: ratio of recent vs prior (smoothed to avoid division noise)
  748. # 0 prior → velocity = recent_n (pure emergence)
  749. # equal → velocity = 1.0 (steady)
  750. velocity = (recent_n + 0.5) / (prior_n + 0.5)
  751. # recency weight: what fraction of total hits are in the recent window
  752. recency_ratio = recent_n / total_n
  753. # source diversity: how many distinct outlets
  754. n_sources = len(entity_sources.get(ent, set()))
  755. # sustained: how many distinct time buckets did it appear in (max ~6)
  756. n_buckets = len(entity_buckets.get(ent, set()))
  757. # average importance (recent window only)
  758. avg_imp = (entity_importance_recent.get(ent, 0.0) / max(1, recent_n)) if recent_n > 0 else 0.0
  759. composed_score = (
  760. 0.35 * min(1.0, math.log1p(velocity) / math.log1p(4.0)) + # velocity (0..1, 4x = max)
  761. 0.25 * recency_ratio + # recency concentration
  762. 0.15 * min(1.0, n_sources / 5.0) + # source diversity
  763. 0.10 * min(1.0, n_buckets / 4.0) + # sustained (>1 bucket)
  764. 0.15 * min(1.0, avg_imp) # importance
  765. )
  766. related = []
  767. if ent in entity_cooccur:
  768. for other, _cnt in entity_cooccur[ent].most_common(10):
  769. if other != ent:
  770. related.append(other)
  771. related_kws = []
  772. if ent in entity_kw_cooccur:
  773. # Build a set of related entity names (lowercased) to deduplicate
  774. # keywords that are already represented in related_entities
  775. related_ent_names = {e.strip().lower() for e in related}
  776. # Also include the entity itself and its common aliases
  777. related_ent_names.add(ent.strip().lower())
  778. for kw, _cnt in entity_kw_cooccur[ent].most_common(10):
  779. kw_lower = kw.strip().lower()
  780. # Skip keywords that are just a related entity name (substring match)
  781. if any(kw_lower in ent_name or ent_name in kw_lower
  782. for ent_name in related_ent_names):
  783. continue
  784. related_kws.append(kw)
  785. if len(related_kws) >= 5:
  786. break
  787. scored.append({
  788. "topic": ent,
  789. "trend_score": min(0.99, round(composed_score, 3)),
  790. "related_entities": related[:5] if related else [ent],
  791. "related_keywords": related_kws[:5],
  792. "velocity": round(velocity, 2),
  793. "recent_count": recent_n,
  794. "prior_count": prior_n,
  795. "source_count": n_sources,
  796. "avg_importance": round(avg_imp, 3),
  797. "signal_type": "entity",
  798. })
  799. # --- score keywords (same velocity/recency/source/sustained/importance formula) ---
  800. all_keywords = set(kw_counts_recent.keys()) | set(kw_counts_prior.keys())
  801. kw_scored = []
  802. for kw in all_keywords:
  803. # Skip keywords that are already scored as entities — entity signal is
  804. # higher quality (proper nouns, resolved identities).
  805. if kw in all_entities:
  806. continue
  807. recent_n = kw_counts_recent.get(kw, 0)
  808. prior_n = kw_counts_prior.get(kw, 0)
  809. total_n = recent_n + prior_n
  810. if total_n < 1:
  811. continue
  812. velocity = (recent_n + 0.5) / (prior_n + 0.5)
  813. recency_ratio = recent_n / total_n
  814. n_sources = len(kw_sources.get(kw, set()))
  815. n_buckets = len(kw_buckets.get(kw, set()))
  816. avg_imp = (kw_importance_recent.get(kw, 0.0) / max(1, recent_n)) if recent_n > 0 else 0.0
  817. composed_score = (
  818. 0.35 * min(1.0, math.log1p(velocity) / math.log1p(4.0)) +
  819. 0.25 * recency_ratio +
  820. 0.15 * min(1.0, n_sources / 5.0) +
  821. 0.10 * min(1.0, n_buckets / 4.0) +
  822. 0.15 * min(1.0, avg_imp)
  823. )
  824. kw_related_kws = []
  825. kw_related_ents = []
  826. if kw in kw_cooccur:
  827. for other, _cnt in kw_cooccur[kw].most_common(10):
  828. if other == kw:
  829. continue
  830. # If this co-occurring term is a known entity, route to related_entities
  831. if other in all_entities:
  832. kw_related_ents.append(other)
  833. else:
  834. kw_related_kws.append(other)
  835. if len(kw_related_kws) >= 5 and len(kw_related_ents) >= 5:
  836. break
  837. kw_scored.append({
  838. "topic": kw,
  839. "trend_score": min(0.99, round(composed_score, 3)),
  840. "related_entities": kw_related_ents[:5],
  841. "related_keywords": kw_related_kws[:5],
  842. "velocity": round(velocity, 2),
  843. "recent_count": recent_n,
  844. "prior_count": prior_n,
  845. "source_count": n_sources,
  846. "avg_importance": round(avg_imp, 3),
  847. "signal_type": "keyword",
  848. })
  849. # sort keywords by score descending
  850. kw_scored.sort(key=lambda x: (-x["trend_score"], -x["velocity"], x["topic"]))
  851. # sort by composed score descending
  852. scored.sort(key=lambda x: (-x["trend_score"], -x["velocity"], x["topic"]))
  853. # --- merge: entities first, then keywords, then phrases ---
  854. emerging = list(scored) # start with entities
  855. seen_topics = {item["topic"] for item in emerging}
  856. for kw_item in kw_scored:
  857. if kw_item["topic"] not in seen_topics:
  858. emerging.append(kw_item)
  859. seen_topics.add(kw_item["topic"])
  860. # --- add phrase signals (only from recent window) ---
  861. for phrase, count in phrase_counts_recent.most_common(limit * 2):
  862. if phrase in seen_topics:
  863. continue
  864. emerging.append({
  865. "topic": phrase.title(),
  866. "trend_score": min(0.99, round(0.30 + 0.15 * min(count, 5), 2)),
  867. "related_entities": [],
  868. "related_keywords": [],
  869. "velocity": None,
  870. "recent_count": count,
  871. "prior_count": 0,
  872. "source_count": 0,
  873. "avg_importance": 0.0,
  874. "signal_type": "phrase",
  875. })
  876. seen_topics.add(phrase)
  877. if len(emerging) >= limit:
  878. break
  879. return emerging[:limit]
  880. @mcp.tool(description="Investigate whether sentiment around an entity or keyword is positive, negative, or neutral over a chosen lookback window. "
  881. "Matches clusters by both named entities and thematic keywords.")
  882. async def get_news_sentiment(entity: str, timeframe: str = "24h"):
  883. store = SQLiteClusterStore(DB_PATH)
  884. ent = normalize_query(entity).strip().lower()
  885. resolved = resolve_entity_via_trends(ent)
  886. query_terms = {
  887. ent,
  888. str(resolved.get("normalized") or "").strip().lower(),
  889. str(resolved.get("canonical_label") or "").strip().lower(),
  890. str(resolved.get("mid") or "").strip().lower(),
  891. }
  892. query_terms = {q for q in query_terms if q}
  893. if not ent:
  894. return {
  895. "entity": entity,
  896. "sentiment": "neutral",
  897. "score": 0.0,
  898. "cluster_count": 0,
  899. }
  900. # timeframe: accept '24h' or '24'
  901. tf = str(timeframe).strip().lower()
  902. try:
  903. hours = int(tf[:-1]) if tf.endswith("h") else int(tf)
  904. except Exception:
  905. hours = 24
  906. hours = max(1, min(int(hours), 168))
  907. clusters = store.get_clusters_by_entity_or_keyword(query_terms=query_terms, hours=hours, limit=500)
  908. matched = clusters
  909. if not matched:
  910. return {
  911. "entity": entity,
  912. "sentiment": "neutral",
  913. "score": 0.0,
  914. "cluster_count": 0,
  915. }
  916. scores = []
  917. for c in matched:
  918. s = c.get("sentimentScore")
  919. if s is not None:
  920. try:
  921. scores.append(float(s))
  922. except Exception:
  923. pass
  924. avg_score = sum(scores) / len(scores) if scores else 0.0
  925. # Keep the label aligned with the numeric score.
  926. # Small magnitudes are treated as neutral to avoid noisy label flips.
  927. if avg_score >= 0.15:
  928. sentiment = "positive"
  929. elif avg_score <= -0.15:
  930. sentiment = "negative"
  931. else:
  932. sentiment = "neutral"
  933. return {
  934. "entity": entity,
  935. "sentiment": sentiment,
  936. "score": round(avg_score, 3),
  937. "cluster_count": len(matched),
  938. }
  939. @mcp.tool(description="Describe the server tool surface, how tools fit together, and output conventions for downstream agents.")
  940. async def get_capabilities():
  941. return {
  942. "server": {
  943. "name": "news-mcp",
  944. "purpose": "Recent news clusters with entities and thematic keywords, entity/keyword drill-down, sentiment, emerging topics, and related-entity expansion.",
  945. "output_conventions": {
  946. "cluster_ids": "Do not surface cluster_id in user-facing prose unless explicitly requested; treat it as internal navigation metadata.",
  947. "sources": "Always preserve and display sources when summarizing a cluster or entity result.",
  948. "timestamps": "Mention timestamps consistently when comparing multiple clusters or when recency matters.",
  949. "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.",
  950. },
  951. },
  952. "tools": NEWS_TOOL_CARDS,
  953. "recipes": NEWS_COMPOSITION_RECIPES,
  954. "example_chains": NEWS_EXAMPLE_CHAINS,
  955. "agent_tips": NEWS_AGENT_TIPS,
  956. "guidance": [
  957. "Use get_latest_events for a tail, get_events_for_entity for entity/keyword deep dives, and get_related_recent_entities for neighborhood expansion.",
  958. "Prefer normalized/canonical entities when possible, but the server will resolve common aliases and MIDs for you.",
  959. "When presenting results to users, summarize the cluster; avoid exposing internal IDs unless they are needed for follow-up tool calls.",
  960. "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.",
  961. "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.",
  962. ],
  963. }
  964. def _parse_timeframe_to_hours(timeframe: str) -> int:
  965. tf = str(timeframe).strip().lower()
  966. try:
  967. if tf.endswith("d"):
  968. days = int(tf[:-1])
  969. return max(1, days * 24)
  970. if tf.endswith("h"):
  971. return max(1, int(tf[:-1]))
  972. return max(1, int(tf))
  973. except Exception:
  974. return 24
  975. from contextlib import asynccontextmanager
  976. @asynccontextmanager
  977. async def _lifespan(app: FastAPI):
  978. asyncio.ensure_future(_background_refresh_loop())
  979. yield
  980. app = FastAPI(title="News MCP Server", lifespan=_lifespan)
  981. logger = logging.getLogger("news_mcp.startup")
  982. app.mount("/mcp", mcp.sse_app())
  983. # Shared store — single connection pool
  984. _shared_store = SQLiteClusterStore(DB_PATH)
  985. _refresh_lock = asyncio.Lock()
  986. _refresh_started = False
  987. async def _background_refresh_loop():
  988. """Non-blocking background refresher: prune then poll.
  989. Protected by an async lock so a second event-loop wake-up cannot
  990. start a parallel ingestion cycle.
  991. """
  992. global _refresh_started
  993. async with _refresh_lock:
  994. if _refresh_started:
  995. return
  996. _refresh_started = True
  997. logger.info("news-mcp llm config: %s", active_llm_config())
  998. # Prune off-thread so we do not block the event loop
  999. prune_result = await asyncio.to_thread(
  1000. _shared_store.prune_if_due,
  1001. NEWS_PRUNING_ENABLED,
  1002. NEWS_RETENTION_DAYS,
  1003. NEWS_PRUNE_INTERVAL_HOURS,
  1004. )
  1005. logger.info("startup prune_result=%s", prune_result)
  1006. # Seed feed_state from .env — insert missing feeds, leave existing alone
  1007. feed_urls = [u.strip() for u in NEWS_FEED_URLS.split(",") if u.strip()]
  1008. if not feed_urls and NEWS_FEED_URL:
  1009. feed_urls = [NEWS_FEED_URL]
  1010. with _shared_store._conn() as conn:
  1011. for url in feed_urls:
  1012. conn.execute(
  1013. "INSERT OR IGNORE INTO feed_state(feed_key, last_hash, last_item_count, enabled, updated_at) VALUES(?, '', 0, 1, '')",
  1014. (url,),
  1015. )
  1016. logger.info("startup seeded %d feeds into feed_state", len(feed_urls))
  1017. if not NEWS_BACKGROUND_REFRESH_ENABLED:
  1018. return
  1019. async def _loop():
  1020. if not NEWS_BACKGROUND_REFRESH_ON_START:
  1021. logger.info("background refresh delayed start interval_seconds=%s", NEWS_REFRESH_INTERVAL_SECONDS)
  1022. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  1023. while True:
  1024. try:
  1025. logger.info("background refresh tick start")
  1026. await refresh_clusters(topic=None, limit=200)
  1027. logger.info("background refresh tick complete")
  1028. except Exception:
  1029. logger.exception("background refresh tick failed")
  1030. await asyncio.sleep(float(NEWS_REFRESH_INTERVAL_SECONDS))
  1031. asyncio.create_task(_loop())
  1032. @app.get("/")
  1033. def root():
  1034. return {
  1035. "status": "ok",
  1036. "transport": "fastmcp+sse",
  1037. "mount": "/mcp",
  1038. "tools": [
  1039. "get_latest_events",
  1040. "get_events_for_entity",
  1041. "get_event_summary",
  1042. "detect_emerging_topics",
  1043. "get_news_sentiment",
  1044. "get_related_recent_entities",
  1045. "get_capabilities",
  1046. ],
  1047. "refresh": {
  1048. "enabled": NEWS_BACKGROUND_REFRESH_ENABLED,
  1049. "interval_seconds": NEWS_REFRESH_INTERVAL_SECONDS,
  1050. },
  1051. "retention": {
  1052. "lookback_hours": DEFAULT_LOOKBACK_HOURS,
  1053. "retention_days": NEWS_RETENTION_DAYS,
  1054. },
  1055. "pruning": {
  1056. "enabled": NEWS_PRUNING_ENABLED,
  1057. "interval_hours": NEWS_PRUNE_INTERVAL_HOURS,
  1058. },
  1059. }
  1060. # ------------------------------------------------------------------
  1061. # Dashboard REST API endpoints
  1062. # ------------------------------------------------------------------
  1063. from fastapi.staticfiles import StaticFiles
  1064. from fastapi.responses import JSONResponse
  1065. app.mount("/dashboard", StaticFiles(directory="dashboard", html=True), name="dashboard")
  1066. import logging as _log
  1067. API_LOG = _log.getLogger("news_mcp.api")
  1068. def _api_ok(data: dict) -> dict:
  1069. return data
  1070. def _api_err(exc: Exception, ctx: str) -> JSONResponse:
  1071. API_LOG.exception(f"API error in {ctx}")
  1072. return JSONResponse(status_code=500, content={"error": str(exc), "ctx": ctx})
  1073. @app.get("/api/v1/health")
  1074. def api_health():
  1075. """Extended health + dashboard stats."""
  1076. try:
  1077. store = _shared_store
  1078. stats = store.get_dashboard_stats()
  1079. stats["version"] = _VERSION_HASH
  1080. return stats
  1081. except Exception as e:
  1082. return _api_err(e, "health")
  1083. @app.get("/api/v1/clusters")
  1084. def api_clusters(
  1085. topic: str | None = None,
  1086. hours: int = 24,
  1087. limit: int = 50,
  1088. offset: int = 0,
  1089. ):
  1090. """Paginated cluster listing."""
  1091. try:
  1092. store = _shared_store
  1093. result = store.get_clusters_page(topic=topic, hours=hours, limit=limit, offset=offset)
  1094. return {"clusters": result["clusters"], "total": result["total"], "topic": topic or "all", "hours": hours}
  1095. except Exception as e:
  1096. return _api_err(e, f"clusters(topic={topic},hours={hours})")
  1097. @app.get("/api/v1/sentiment-series")
  1098. def api_sentiment_series(
  1099. topic: str | None = None,
  1100. hours: int = 24,
  1101. bucket_hours: float = 1.0,
  1102. ):
  1103. """Sentiment time-series for Chart.js."""
  1104. try:
  1105. store = _shared_store
  1106. series = store.get_sentiment_series(topic=topic, hours=hours, bucket_hours=bucket_hours)
  1107. return {"series": series, "topic": topic or "all"}
  1108. except Exception as e:
  1109. return _api_err(e, f"sentiment(topic={topic})")
  1110. @app.get("/api/v1/entities")
  1111. def api_entities(
  1112. hours: int = 24,
  1113. limit: int = 30,
  1114. ):
  1115. """Top entity frequencies."""
  1116. try:
  1117. store = _shared_store
  1118. entities = store.get_entity_frequencies(hours=hours, limit=limit)
  1119. return {"entities": entities, "hours": hours}
  1120. except Exception as e:
  1121. return _api_err(e, f"entities(hours={hours})")
  1122. @app.get("/api/v1/keywords")
  1123. def api_keywords(
  1124. hours: int = 24,
  1125. limit: int = 30,
  1126. ):
  1127. """Top keyword frequencies (thematic descriptors, excluding terms already counted as entities)."""
  1128. try:
  1129. store = _shared_store
  1130. keywords = store.get_keyword_frequencies(hours=hours, limit=limit)
  1131. return {"keywords": keywords, "hours": hours}
  1132. except Exception as e:
  1133. return _api_err(e, f"keywords(hours={hours})")
  1134. @app.get("/api/v1/clusters/by-entity")
  1135. def api_clusters_by_entity(
  1136. entity: str,
  1137. hours: int = 168,
  1138. limit: int = 50,
  1139. offset: int = 0,
  1140. ):
  1141. """Return clusters matching an entity, filtered by event time via SQL junction table."""
  1142. try:
  1143. store = _shared_store
  1144. return store.get_clusters_by_entity(
  1145. entity=entity.strip().lower(),
  1146. hours=hours,
  1147. limit=limit,
  1148. offset=offset,
  1149. )
  1150. except Exception as e:
  1151. return _api_err(e, f"by-entity(entity={entity},hours={hours})")
  1152. @app.get("/api/v1/clusters/by-keyword")
  1153. def api_clusters_by_keyword(
  1154. keyword: str,
  1155. hours: int = 168,
  1156. limit: int = 50,
  1157. offset: int = 0,
  1158. ):
  1159. """Return clusters matching a keyword, filtered by event time via SQL junction table."""
  1160. try:
  1161. store = _shared_store
  1162. return store.get_clusters_by_keyword(
  1163. keyword=keyword.strip().lower(),
  1164. hours=hours,
  1165. limit=limit,
  1166. offset=offset,
  1167. )
  1168. except Exception as e:
  1169. return _api_err(e, f"by-keyword(keyword={keyword},hours={hours})")
  1170. @app.get("/api/v1/cluster/{cluster_id}")
  1171. def api_cluster_detail(cluster_id: str):
  1172. """Full cluster detail for drill-down."""
  1173. try:
  1174. store = _shared_store
  1175. detail = store.get_cluster_detail(cluster_id)
  1176. if not detail:
  1177. return JSONResponse(status_code=404, content={"error": "Cluster not found", "id": cluster_id})
  1178. return detail
  1179. except Exception as e:
  1180. return _api_err(e, f"detail({cluster_id})")
  1181. # ------------------------------------------------------------------
  1182. # Feed management endpoints (toggle on/off from dashboard)
  1183. # ------------------------------------------------------------------
  1184. @app.get("/api/v1/feeds")
  1185. def api_feeds():
  1186. """List all configured feeds with enabled/disabled status."""
  1187. try:
  1188. store = SQLiteClusterStore(DB_PATH)
  1189. feed_list = store.get_feed_state_list()
  1190. configured = _configured_feed_urls()
  1191. return {
  1192. "feeds": feed_list,
  1193. "configured_urls": configured,
  1194. }
  1195. except Exception as e:
  1196. return _api_err(e, "feeds")
  1197. @app.post("/api/v1/feeds/toggle")
  1198. async def api_feed_toggle(feed_url: str = Form(), enabled: bool = Form()):
  1199. """Toggle a feed's enabled state."""
  1200. try:
  1201. store = SQLiteClusterStore(DB_PATH)
  1202. ok = store.set_feed_enabled(feed_url.strip(), enabled)
  1203. if not ok:
  1204. return JSONResponse(
  1205. status_code=404,
  1206. content={"error": f"Feed not found: {feed_url}"},
  1207. )
  1208. return {"ok": True, "feed_url": feed_url.strip(), "enabled": enabled}
  1209. except Exception as e:
  1210. return _api_err(e, f"toggle({feed_url})")
  1211. @app.get("/health")
  1212. def health():
  1213. return {
  1214. "status": "ok",
  1215. "uptime": round(time.monotonic() - _PROCESS_STARTED_AT, 3),
  1216. "version": _VERSION_HASH,
  1217. }