Skip to content

160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.

Word-boundary entity and classifier matching (kills the substring false-positive class)

Phoenix Agent (Marcs-Mac-Studio)ae4051c83ace
diff --git a/src/world_intel_mcp/analysis/classifier.py b/src/world_intel_mcp/analysis/classifier.py
index a3b88ee..82184d9 100644
--- a/src/world_intel_mcp/analysis/classifier.py
+++ b/src/world_intel_mcp/analysis/classifier.py
@@ -140,6 +140,61 @@ _MODERATE_SEVERITY: list[str] = [
"attack", "strike", "explosion", "breach", "violation",
]
+# ---------------------------------------------------------------------------
+# Keyword compilation
+#
+# Default semantics: boundary-anchored prefix (\b + keyword + \w*), so stems
+# keep matching their inflections ("launch" → "launched", "protest" →
+# "protesters") but nothing fires mid-word ("riot" no longer matches inside
+# "patriotic", "strike" inside "airstrike", "ied" inside "denied").
+# ---------------------------------------------------------------------------
+
+# Keywords that are themselves prefixes of unrelated words match only as a
+# standalone word (plus plural): "port" must not fire on "portfolio", "coup"
+# on "couple", "regime" on "regimen", "carbon" on "carbonated".
+_WORD_ONLY_KEYWORDS: frozenset[str] = frozenset({"coup", "port", "regime", "carbon"})
+
+# Keywords whose valid suffixes are narrower than \w*: "apt" only as APT or
+# a numbered group id (never "aptitude"), "dead" only bare or "deadly"
+# (never "deadline").
+_PATTERN_OVERRIDES: dict[str, str] = {
+ "apt": r"\bapt\d*\b",
+ "dead": r"\bdead(?:ly)?\b",
+}
+
+
+def _compile_keyword(kw: str) -> re.Pattern[str]:
+ override = _PATTERN_OVERRIDES.get(kw)
+ if override is not None:
+ return re.compile(override)
+ if kw in _WORD_ONLY_KEYWORDS:
+ return re.compile(r"\b" + re.escape(kw) + r"s?\b")
+ return re.compile(r"\b" + re.escape(kw) + r"\w*")
+
+
+def _matched_keywords(
+ patterns: list[tuple[str, re.Pattern[str]]], text_lower: str
+) -> list[str]:
+ """Keywords whose boundary pattern matches, in table order.
+
+ Every pattern requires its literal keyword as a substring (overrides
+ included), so the C-speed `in` check gates the regex and keeps
+ classification at roughly substring-scan cost.
+ """
+ return [kw for kw, pat in patterns if kw in text_lower and pat.search(text_lower)]
+
+
+_CATEGORY_PATTERNS: dict[str, list[tuple[str, re.Pattern[str]]]] = {
+ name: [(kw, _compile_keyword(kw)) for kw in info["keywords"]]
+ for name, info in CATEGORIES.items()
+}
+_HIGH_SEVERITY_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
+ (kw, _compile_keyword(kw)) for kw in _HIGH_SEVERITY
+]
+_MODERATE_SEVERITY_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
+ (kw, _compile_keyword(kw)) for kw in _MODERATE_SEVERITY
+]
+
def classify_event(text: str) -> dict:
"""Classify text into threat categories with severity scoring.
@@ -151,25 +206,27 @@ def classify_event(text: str) -> dict:
matches: list[dict] = []
for cat_name, cat_info in CATEGORIES.items():
- matched_kw = [kw for kw in cat_info["keywords"] if kw in text_lower]
+ matched_kw = _matched_keywords(_CATEGORY_PATTERNS[cat_name], text_lower)
if matched_kw:
# Confidence scales with number of keyword hits
confidence = min(1.0, len(matched_kw) * 0.2 + 0.3)
- matches.append({
- "category": cat_name,
- "keywords_matched": matched_kw,
- "keyword_count": len(matched_kw),
- "severity_base": cat_info["severity_base"],
- "confidence": round(confidence, 2),
- })
+ matches.append(
+ {
+ "category": cat_name,
+ "keywords_matched": matched_kw,
+ "keyword_count": len(matched_kw),
+ "severity_base": cat_info["severity_base"],
+ "confidence": round(confidence, 2),
+ }
+ )
# Sort by keyword count (most specific match first)
matches.sort(key=lambda m: m["keyword_count"], reverse=True)
# Compute severity modifier
severity_mod = 0
- high_hits = [kw for kw in _HIGH_SEVERITY if kw in text_lower]
- mod_hits = [kw for kw in _MODERATE_SEVERITY if kw in text_lower]
+ high_hits = _matched_keywords(_HIGH_SEVERITY_PATTERNS, text_lower)
+ mod_hits = _matched_keywords(_MODERATE_SEVERITY_PATTERNS, text_lower)
if high_hits:
severity_mod = 2
elif mod_hits:
@@ -183,7 +240,11 @@ def classify_event(text: str) -> dict:
"severity": severity,
"confidence": primary["confidence"] if primary else 0.0,
"all_categories": [
- {"category": m["category"], "confidence": m["confidence"], "keywords": m["keywords_matched"]}
+ {
+ "category": m["category"],
+ "confidence": m["confidence"],
+ "keywords": m["keywords_matched"],
+ }
for m in matches
],
"category_count": len(matches),
diff --git a/src/world_intel_mcp/analysis/entities.py b/src/world_intel_mcp/analysis/entities.py
index 1549689..90f4713 100644
--- a/src/world_intel_mcp/analysis/entities.py
+++ b/src/world_intel_mcp/analysis/entities.py
@@ -13,10 +13,32 @@ from ..config.countries import TIER1_COUNTRIES
from ..config.entities import LEADERS, ORGANIZATIONS, COMPANIES, APT_GROUPS
+def _compile_keywords(
+ keywords, *, plural_min_len: int | None = None
+) -> re.Pattern[str]:
+ """Compile keywords into one word-boundary-anchored alternation.
+
+ Longest-first ordering makes multi-word variants win over their prefixes
+ ("united nations" before "un"). With plural_min_len set, alphabetic
+ keywords at least that long also match a trailing "s" ("americans",
+ "houthis"); shorter abbreviations stay exact so "usa" never matches
+ inside "thousand" or "usable".
+ """
+ parts = []
+ for kw in sorted(keywords, key=len, reverse=True):
+ esc = re.escape(kw)
+ if plural_min_len is not None and len(kw) >= plural_min_len and kw.isalpha():
+ esc += "s?"
+ parts.append(esc)
+ return re.compile(r"\b(?:" + "|".join(parts) + r")\b")
+
+
# Pre-compile patterns
_CVE_RE = re.compile(r"CVE-\d{4}-\d{4,}", re.IGNORECASE)
_APT_RE = re.compile(
- r"\b(?:" + "|".join(re.escape(a) for a in sorted(APT_GROUPS, key=len, reverse=True)) + r")\b",
+ r"\b(?:"
+ + "|".join(re.escape(a) for a in sorted(APT_GROUPS, key=len, reverse=True))
+ + r")\b",
re.IGNORECASE,
)
@@ -37,6 +59,13 @@ _ORG_KW: dict[str, dict] = {k.lower(): v for k, v in ORGANIZATIONS.items()}
# Build company lookup (lowercase)
_COMPANY_KW: dict[str, dict] = {k.lower(): v for k, v in COMPANIES.items()}
+# Demonyms pluralize in headlines ("Americans", "Houthis"); leader, org, and
+# company names must stay exact — "apples" is not Apple Inc.
+_COUNTRY_RE = _compile_keywords(_COUNTRY_KW, plural_min_len=5)
+_LEADER_RE = _compile_keywords(_LEADER_KW)
+_ORG_RE = _compile_keywords(_ORG_KW)
+_COMPANY_RE = _compile_keywords(_COMPANY_KW)
+
def extract_entities(text: str) -> dict:
"""Extract named entities from text.
@@ -44,7 +73,6 @@ def extract_entities(text: str) -> dict:
Returns dict with entities grouped by type, plus counts and metadata.
"""
text_lower = text.lower()
- words_set = set(text_lower.split())
countries: list[dict] = []
leaders: list[dict] = []
@@ -58,64 +86,65 @@ def extract_entities(text: str) -> dict:
seen_orgs: set[str] = set()
seen_companies: set[str] = set()
- # Countries (keyword search in text)
- for kw, iso3 in _COUNTRY_KW.items():
- if iso3 in seen_countries:
+ # Countries (word-boundary match; the regex may add a plural "s" that
+ # is not itself a lookup key, so fall back to the singular)
+ for match in _COUNTRY_RE.finditer(text_lower):
+ kw = match.group(0)
+ iso3 = _COUNTRY_KW.get(kw) or _COUNTRY_KW.get(kw[:-1])
+ if iso3 is None or iso3 in seen_countries:
continue
- if kw in text_lower:
- seen_countries.add(iso3)
- info = TIER1_COUNTRIES[iso3]
- countries.append({
+ seen_countries.add(iso3)
+ info = TIER1_COUNTRIES[iso3]
+ countries.append(
+ {
"iso3": iso3,
"name": info["name"],
"baseline_risk": info["baseline_risk"],
- })
+ }
+ )
- # Leaders (match longest first to avoid partial matches)
- for kw in sorted(_LEADER_KW.keys(), key=len, reverse=True):
- info = _LEADER_KW[kw]
+ # Leaders (longest alternative wins, so "vladimir putin" never also
+ # emits a second entry via "putin")
+ for match in _LEADER_RE.finditer(text_lower):
+ info = _LEADER_KW[match.group(0)]
if info["name"] in seen_leaders:
continue
- if kw in text_lower:
- seen_leaders.add(info["name"])
- leaders.append({
+ seen_leaders.add(info["name"])
+ leaders.append(
+ {
"name": info["name"],
"title": info["title"],
"country": info["country"],
- })
+ }
+ )
# Organizations
- for kw in sorted(_ORG_KW.keys(), key=len, reverse=True):
- info = _ORG_KW[kw]
+ for match in _ORG_RE.finditer(text_lower):
+ info = _ORG_KW[match.group(0)]
if info["abbrev"] in seen_orgs:
continue
- # For short abbreviations (2-4 chars), require word boundary
- if len(kw) <= 4:
- if kw in words_set:
- seen_orgs.add(info["abbrev"])
- organizations.append({
- "name": info["abbrev"],
- "type": info["type"],
- })
- elif kw in text_lower:
- seen_orgs.add(info["abbrev"])
- organizations.append({
+ seen_orgs.add(info["abbrev"])
+ organizations.append(
+ {
"name": info["abbrev"],
"type": info["type"],
- })
+ }
+ )
# Companies
- for kw in sorted(_COMPANY_KW.keys(), key=len, reverse=True):
- info = _COMPANY_KW[kw]
+ for match in _COMPANY_RE.finditer(text_lower):
+ kw = match.group(0)
if kw in seen_companies:
continue
- if kw in text_lower:
- seen_companies.add(kw)
- companies.append({
+ info = _COMPANY_KW[kw]
+ seen_companies.add(kw)
+ companies.append(
+ {
"name": kw.title(),
"ticker": info["ticker"],
"sector": info["sector"],
- })
+ }
+ )
# CVEs
cves = list(set(_CVE_RE.findall(text)))
diff --git a/src/world_intel_mcp/tests/test_classifier.py b/src/world_intel_mcp/tests/test_classifier.py
index 3bc9ccc..094c699 100644
--- a/src/world_intel_mcp/tests/test_classifier.py
+++ b/src/world_intel_mcp/tests/test_classifier.py
@@ -106,3 +106,70 @@ async def test_fetch_classify_event_wraps_sync_classifier() -> None:
assert result["primary_category"] == direct["primary_category"]
assert result["severity"] == direct["severity"]
assert result["confidence"] == direct["confidence"]
+
+
+# ---------------------------------------------------------------------------
+# Word-boundary regressions (Phase 24.5): substring matching fired categories
+# and severity bumps from the inside of unrelated words — "port" in "report",
+# "coup" in "couple". Verb stems must still match their inflections.
+# ---------------------------------------------------------------------------
+
+
+def test_keywords_inside_unrelated_words_do_not_fire() -> None:
+ # Pre-fix this fired maritime ("port" in "report"), political ("coup" in
+ # "couple"), social_unrest ("riot" in "patriotic"), and cyber ("apt" in
+ # "captured").
+ result = classify_event(
+ "The report said a couple of patriotic films were captured on camera"
+ )
+ assert result["primary_category"] == "unclassified"
+ assert result["all_categories"] == []
+ assert result["severity"] == 0
+
+
+def test_airstrike_is_military_not_labor_strike() -> None:
+ result = classify_event("Airstrike hits depot near the frontline")
+ assert result["primary_category"] == "military"
+ cats = {c["category"] for c in result["all_categories"]}
+ assert "social_unrest" not in cats
+ # "strike" inside "airstrike" must not bump severity either.
+ assert result["severity_modifiers"] == []
+ assert result["severity"] == CATEGORIES["military"]["severity_base"]
+
+
+def test_labor_strike_still_fires_social_unrest() -> None:
+ result = classify_event("General strike and labor dispute paralyze the capital")
+ assert result["primary_category"] == "social_unrest"
+
+
+def test_verb_stems_still_match_inflected_forms() -> None:
+ result = classify_event("SpaceX launched a rocket into orbit")
+ assert result["primary_category"] == "space"
+ matched = result["all_categories"][0]["keywords"]
+ assert {"launch", "rocket", "orbit"} <= set(matched)
+
+
+def test_protest_stem_matches_protesters() -> None:
+ result = classify_event("A thousand protesters marched on parliament")
+ assert result["primary_category"] == "political"
+
+
+def test_deadline_does_not_bump_severity() -> None:
+ # "deadline" contains "dead" (a high-severity modifier).
+ result = classify_event("Sanctions deadline nears for the regime")
+ assert result["primary_category"] == "political"
+ assert result["severity_modifiers"] == []
+ assert result["severity"] == CATEGORIES["political"]["severity_base"]
+
+
+def test_deadly_still_bumps_severity() -> None:
+ result = classify_event("Deadly explosion reported at the port")
+ assert result["primary_category"] == "maritime"
+ assert "dead" in result["severity_modifiers"]
+ assert result["severity"] == CATEGORIES["maritime"]["severity_base"] + 2
+
+
+def test_apt_matches_group_ids_as_words() -> None:
+ result = classify_event("APT29 exploited a zero-day in the wild")
+ assert result["primary_category"] == "cyber"
+ assert "apt" in result["all_categories"][0]["keywords"]
diff --git a/src/world_intel_mcp/tests/test_entities.py b/src/world_intel_mcp/tests/test_entities.py
index 1c76c31..fe85958 100644
--- a/src/world_intel_mcp/tests/test_entities.py
+++ b/src/world_intel_mcp/tests/test_entities.py
@@ -137,3 +137,58 @@ async def test_fetch_entity_extraction_from_news_feed(
async def test_fetch_entity_extraction_no_text_no_news(fetcher) -> None:
result = await fetch_entity_extraction(fetcher, text=None, use_news=False)
assert result["total_entities"] == 0
+
+
+# ---------------------------------------------------------------------------
+# Word-boundary regressions (Phase 24.5): substring matching tagged entities
+# from the inside of unrelated words — "usa" in "thousand", "bp" in "subplot".
+# Each false-positive test is paired with a real-mention test so the fix
+# cannot pass by simply matching less.
+# ---------------------------------------------------------------------------
+
+
+def test_country_keyword_inside_word_not_tagged() -> None:
+ # "thousand" and "usable" both contain "usa"; neither mentions the USA.
+ result = extract_entities("A thousand protesters filled the square")
+ assert _iso3s(result) == set()
+
+ result = extract_entities("The bridge is no longer usable after the storm")
+ assert _iso3s(result) == set()
+
+
+def test_country_word_and_plural_demonym_still_tagged() -> None:
+ result = extract_entities("Americans voted as the USA prepared for midterms")
+ assert _iso3s(result) == {"USA"}
+
+
+def test_company_names_inside_words_not_tagged() -> None:
+ # "metadata" contains "meta", "bombshell" contains "shell",
+ # "subplot" contains "bp".
+ result = extract_entities("The metadata revealed a bombshell subplot")
+ assert result["entities"]["companies"] == []
+
+
+def test_company_short_names_still_match_as_words() -> None:
+ result = extract_entities("BP and Shell posted profits while Meta hired")
+ names = {c["name"] for c in result["entities"]["companies"]}
+ assert names == {"Bp", "Shell", "Meta"}
+
+
+def test_leader_names_inside_words_not_tagged() -> None:
+ # Same bug class: "taxi" contains "xi", "commodity" contains "modi",
+ # "trumpet" contains "trump".
+ result = extract_entities("The taxi passed commodity traders at the trumpet parade")
+ assert result["entities"]["leaders"] == []
+
+
+def test_leader_short_names_still_match_as_words() -> None:
+ result = extract_entities("Xi and Modi met at the summit")
+ names = {ldr["name"] for ldr in result["entities"]["leaders"]}
+ assert names == {"Xi Jinping", "Narendra Modi"}
+
+
+def test_long_org_name_inside_word_not_tagged() -> None:
+ # The pre-fix boundary guard only covered keywords of <=4 chars, so
+ # "hamas" matched inside "bahamas".
+ result = extract_entities("Storm damage reported across the Bahamas")
+ assert result["entities"]["organizations"] == []