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.

Research guide over MCP: resources, prompts and intel guide

Phoenix Agent (mac-studio)efa1cd1b020d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6311734..92dd0b1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,40 @@
# Changelog
+## Unreleased
+
+### Added: research guide over MCP (prompts and resources)
+- The server now answers `resources/list`, `resources/read`, `prompts/list`
+ and `prompts/get`, and advertises the resources and prompts capabilities
+ at initialize. Before this it exposed tools only. No tools were added or
+ changed.
+- `intel://guide` (markdown): how to ask a strong question (period,
+ comparison, measure, place), what an answer contains, what this server
+ will not do, the worked prompts, and every registered tool grouped by
+ domain module. Built from the live registry on every read; a test fails
+ if a registered tool is missing or listed twice.
+- `intel://guide/source-health` (JSON): open circuit breakers, stale
+ serves, stale cache prefixes, cache freshness, and which keyed sources
+ have their variables set (names only, never values). Reads in-process
+ state and the cache database only; reading it starts no fetch. It says
+ that breaker state covers this server process only. The keyed-source
+ list is checked against the credentials `sources/*.py` actually read.
+- `intel://guide/measures` (markdown): stock versus flow, growth versus
+ acceleration, percentage points, seasonal adjustment, the three dates
+ (observation, publication, collection), revisions, correlation and
+ timing offsets, composite scores, missing data versus zero.
+- 29 prompts across conflict, markets, hazards, migration, aviation, cyber,
+ infrastructure, maritime, areas of interest, news, politics, sanctions,
+ health, stored history and country views. Each names the tools to call
+ and the limits to respect; arguments (country, topic, period and so on)
+ are validated, and a missing, unknown or invalid one is an
+ `invalid params` error. A test fails if any prompt names a tool that is
+ not registered.
+- `intel guide` prints the guide markdown; `intel guide --measures` prints
+ the glossary.
+- A test spawns the installed `world-intel-mcp` console script and drives
+ initialize, resources/list, resources/read, prompts/list, prompts/get
+ and tools/list over stdio.
+
## 0.11.0 - 2026-10-12
Cross-border migration (MCP tools, CLI, collector and a dashboard
diff --git a/README.md b/README.md
index 77f7474..436b1c5 100644
--- a/README.md
+++ b/README.md
@@ -130,6 +130,7 @@ intel earthquakes --min-mag 5.0
intel migration-surges # year-over-year displacement jumps (UNHCR)
intel migration-flows -o Sudan
intel status # cache + circuit breaker health
+intel guide # the research guide (also served as intel://guide)
```
---
@@ -154,6 +155,57 @@ collector.py (daemon) ─┘
---
+## Research Guide: MCP Prompts and Resources
+
+Besides its tools, the server answers the MCP `resources` and `prompts`
+requests and advertises both capabilities at initialize. A connecting
+model can read which tool answers which question, and what the data
+cannot support, before it calls anything.
+
+| Resource | Type | What it holds |
+|----------|------|---------------|
+| `intel://guide` | Markdown | How to ask a strong question (name the period, the comparison, the measure and the place), what an answer contains, what this server will not do, the worked prompts, and every tool grouped by domain. Built from the live tool registry on each read, so it always matches `tools/list`. |
+| `intel://guide/source-health` | JSON | Open circuit breakers, stale serves, cache freshness per source prefix, and which keyed sources have their variables set (names only, never values). Reading it starts no fetch. Breaker state covers this server process only; the collector keeps its own. |
+| `intel://guide/measures` | Markdown | Amount outstanding versus flow, growth versus acceleration, percentage points, seasonal adjustment, observation versus publication versus collection dates, revisions, correlation and timing offsets, composite scores, and why missing data is not zero. |
+
+**29 prompts**, each a worked research question that names the tools to
+call and the limits an honest answer respects (arguments marked * are
+required):
+
+| Domain | Prompts |
+|--------|---------|
+| conflict | `conflict-trend` (country*, days), `hotspot-escalation` |
+| markets | `market-risk-snapshot`, `yield-curve-check`, `central-bank-compare`, `fx-move` (symbol*, base, days), `company-events` (ticker*), `energy-pressure`, `crypto-structure` |
+| hazards | `earthquake-exposure` (min_magnitude, hours), `severe-weather` (us_area, europe_country), `wildfire-situation` (region), `space-weather-impact` |
+| migration | `displacement-history` (country*, role), `migration-surges` (year) |
+| aviation | `airspace-anomaly` (cohort, region), `airport-disruption` |
+| cyber | `cyber-landscape` |
+| infrastructure | `internet-disruption` (country*, resource), `cloud-incidents` |
+| maritime | `maritime-chokepoints` |
+| aoi | `aoi-watch-setup` (name*, lat*, lon*, radius_km*), `aoi-review` (name*) |
+| news | `story-breadth` (topic*) |
+| politics | `election-watch` (country) |
+| finance | `sanctions-screen` (query*) |
+| health | `disease-watch` |
+| history | `history-recall` (topic*, hours) |
+| country | `country-overview` (country*) |
+
+`prompts/get` with `conflict-trend` and `{"country": "Sudan"}` returns one
+user message: the question with Sudan and the default 30-day window
+filled in, the numbered tools (`intel_ucdp_events`, `intel_acled_events`,
+`intel_unrest_events`) with what each call is for, the limits (recent
+days are the least complete; count events and fatalities separately;
+compare each source only with itself), and the shape of a complete
+answer. A missing required argument, an unknown argument or an unknown
+prompt is an `invalid params` error, never a guess. The tests fail if a
+prompt names a tool that is not registered, or if the guide leaves out a
+registered tool.
+
+From the shell, `intel guide` prints the same guide markdown and
+`intel guide --measures` prints the glossary.
+
+---
+
## MCP Tools Reference
### Financial Markets (7)
diff --git a/ROADMAP.md b/ROADMAP.md
index 7249537..dee68a3 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -574,7 +574,7 @@ dashboard.
| 1 | Observation history store | Every collector capture saved with `observed_at` (period the data describe), `published_at` (publisher release, when known) and `collected_at` (when we saved it); unchanged payloads stored once; bounded retention; backfill for sources that serve history (FRED CSV) | :red_circle: |
| 1 | Capture history and revisions | Earlier saved copies of a source, and values a later copy revised | :red_circle: |
| 1 | Collection health | Per-source expected cadence; overdue / failing / never-run per source, measured from the run log, not inferred from cache freshness. Says what it cannot prove | :red_circle: |
-| 1 | Research guide over MCP | MCP resources (guide generated from the live registry and source health, measures glossary, "what this server will not do") and MCP prompts (worked research questions, each naming the tools it needs and the limit to respect). Server exposed no prompts or resources before | :red_circle: |
+| 1 | Research guide over MCP | MCP resources (guide generated from the live registry and source health, measures glossary, "what this server will not do") and MCP prompts (worked research questions, each naming the tools it needs and the limit to respect). Server exposed no prompts or resources before | :white_check_mark: Built 2026-10-17, unreleased: 3 resources (`intel://guide`, `intel://guide/source-health`, `intel://guide/measures`), 29 prompts, `intel guide`; verified over a live stdio session |
| 1 | Hostility timeline | Per country pair or country, daily counts of threat / sanction / force / criticism coverage plus tone; sortable by most covered, most hostile, biggest change | :red_circle: |
| 1 | Story breadth | News clusters carry a distinct-outlet count; a top-stories view ranks by how many outlets carry a story | :red_circle: |
| 1 | Liquidity and flows | Fed balance sheet, Treasury General Account, reverse repo and net liquidity (FRED keyless CSV), money supply (US M2, euro area M1/M2/M3, never summed), ECB, ICI fund flows and ETF net issuance, FINRA margin statistics, BLS series; amounts kept separate from flows | :red_circle: |
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index af3204c..033e745 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -2186,6 +2186,27 @@ def status(ctx: click.Context) -> None:
console.print("\n[dim]No circuit breaker data yet (no requests made)[/dim]")
[email protected](name="guide")
+ "--measures", is_flag=True, help="Print the measures glossary instead of the guide"
+)
+def guide_cmd(ctx: click.Context, measures: bool) -> None:
+ """Print the research guide the MCP server serves as intel://guide."""
+ from . import guide
+
+ if measures:
+ uri, text = guide.MEASURES_URI, guide.MEASURES
+ else:
+ uri, text = guide.GUIDE_URI, guide.render_guide()
+ if ctx.obj.get("json"):
+ _print_json({"uri": uri, "mime_type": "text/markdown", "text": text})
+ return
+ # click.echo, not console.print: tool descriptions contain brackets
+ # that Rich would parse as markup, and the output is meant to pipe.
+ click.echo(text, nl=False)
+
+
@main.command(name="sync")
@click.argument("source", required=False)
def sync_cmd(source: str | None) -> None:
diff --git a/src/world_intel_mcp/guide.py b/src/world_intel_mcp/guide.py
new file mode 100644
index 0000000..935b447
--- /dev/null
+++ b/src/world_intel_mcp/guide.py
@@ -0,0 +1,513 @@
+"""Research guide served over MCP as resources and prompts.
+
+A model connecting to this server sees 139 tools and, before this module,
+nothing else: no map of which tool answers which question, and no
+statement of what the data cannot support. The guide fills that gap with
+three read-only resources and a set of worked research prompts
+(``guide_prompts.py``):
+
+- ``intel://guide``: how to ask a strong question, what an answer
+ contains, what this server will not do, the prompts, and every
+ registered tool grouped by its domain module. The tool list is built
+ from the live registry (``tools._MODULES``) on every read, so it cannot
+ drift from what ``tools/list`` serves.
+- ``intel://guide/source-health``: circuit breakers, cache freshness and
+ which keyed sources have their environment variables set. It reads
+ in-process state and the cache database only; reading it never starts
+ a fetch.
+- ``intel://guide/measures``: a glossary of the measures the tools
+ return and the mistakes they invite.
+
+Gaps / not covered:
+- Source health cannot see the collector's run log or schedule, nor the
+ breaker state of other processes (collector, dashboard, CLI); it says
+ so in its ``scope`` field.
+- ``keyed_sources`` reports whether a variable is set, not whether the
+ key is valid or within quota.
+"""
+
+import json
+import os
+import re
+import time
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, Mapping
+
+from mcp.server.lowlevel.helper_types import ReadResourceContents
+from mcp.shared.exceptions import McpError
+from mcp.types import (
+ INVALID_PARAMS,
+ ErrorData,
+ GetPromptResult,
+ Prompt,
+ PromptArgument,
+ PromptMessage,
+ Resource,
+ TextContent,
+)
+
+from . import guide_prompts
+from .guide_prompts import PROMPTS, PromptArgumentError
+
+GUIDE_URI = "intel://guide"
+HEALTH_URI = "intel://guide/source-health"
+MEASURES_URI = "intel://guide/measures"
+
+# Display names for the domain modules under tools/. A module missing
+# here still appears in the guide, titled from its module name.
+_DOMAIN_TITLES = {
+ "markets": "Markets and economy",
+ "hazards": "Natural hazards and space",
+ "conflict": "Conflict and military",
+ "infrastructure": "Infrastructure and transport",
+ "society": "News, society and migration",
+ "intelligence": "Intelligence analysis",
+ "geospatial": "Static geospatial datasets",
+ "synthesis": "NLP and strategic synthesis",
+ "finance": "Business finance",
+ "vector": "Stored history (vector store)",
+ "aoi": "Areas of interest, briefs and reports",
+ "system": "System",
+}
+
+
+@dataclass(frozen=True)
+class KeyedSource:
+ source: str
+ env: tuple[str, ...]
+ without_key: str
+
+
+# Every credential-like variable the source modules read. A test scans
+# sources/*.py and fails when a variable is read there but missing here,
+# or listed here but no longer read.
+KEYED_SOURCES: tuple[KeyedSource, ...] = (
+ KeyedSource(
+ "ACLED",
+ ("ACLED_EMAIL", "ACLED_PASSWORD"),
+ "ACLED event, unrest and risk tools return an error naming the missing credentials.",
+ ),
+ KeyedSource(
+ "UCDP",
+ ("UCDP_ACCESS_TOKEN",),
+ "Requests go out without a token. The UCDP source module notes the API "
+ "has required one since 2026, so expect errors.",
+ ),
+ KeyedSource(
+ "NASA FIRMS",
+ ("NASA_FIRMS_API_KEY",),
+ "intel_wildfires returns an error.",
+ ),
+ KeyedSource(
+ "EIA",
+ ("EIA_API_KEY",),
+ "Energy prices, residential natural gas and electricity rates return an error.",
+ ),
+ KeyedSource(
+ "FRED",
+ ("FRED_API_KEY",),
+ "intel_fred_series returns an error; the yield curve falls back to four Yahoo "
+ "maturities (no 2s10s spread); central bank rates use a curated table.",
+ ),
+ KeyedSource(
+ "Cloudflare Radar",
+ ("CLOUDFLARE_API_TOKEN",),
+ "Internet outages fall back to the IODA public API.",
+ ),
+ KeyedSource(
+ "OpenSky",
+ ("OPENSKY_CLIENT_ID", "OPENSKY_CLIENT_SECRET", "OPENSKY_USERNAME", "OPENSKY_PASSWORD"),
+ "Requests are anonymous, with OpenSky's lower anonymous limits.",
+ ),
+ KeyedSource(
+ "TomTom",
+ ("TOMTOM_API_KEY",),
+ "Traffic flow and incident tools return an error.",
+ ),
+ KeyedSource(
+ "Windy Webcams",
+ ("WINDY_API_KEY",),
+ "intel_webcams returns an error.",
+ ),
+)
+
+
+@dataclass(frozen=True)
+class Domain:
+ key: str
+ title: str
+ summary: str
+ tools: tuple[Any, ...]
+
+
+def _module_summary(module: Any) -> str:
+ doc = (module.__doc__ or "").strip()
+ first_paragraph = doc.split("\n\n", 1)[0]
+ return " ".join(first_paragraph.split())
+
+
+def domains(modules: list | None = None) -> list[Domain]:
+ """The live registry grouped by domain module, in list_tools order."""
+ if modules is None:
+ from . import tools as tools_pkg
+
+ modules = tools_pkg._MODULES
+ out = []
+ for module in modules:
+ key = module.__name__.rsplit(".", 1)[-1]
+ title = _DOMAIN_TITLES.get(key, key.replace("_", " ").capitalize())
+ out.append(Domain(key, title, _module_summary(module), tuple(module.TOOLS)))
+ return out
+
+
+_SENTENCE_END = re.compile(r"(?<=[.!?])\s+(?=[A-Z(])")
+
+
+def _one_line(description: str) -> str:
+ first = _SENTENCE_END.split(" ".join(description.split()), 1)[0]
+ # Em dashes in tool descriptions become hyphens: the guide is
+ # published text.
+ return first.replace(" — ", " - ").replace("—", "-")
+
+
+def _arg_list(tool: Any) -> str:
+ schema = tool.inputSchema or {}
+ required = set(schema.get("required", []))
+ names = [
+ f"{name} (required)" if name in required else name
+ for name in schema.get("properties", {})
+ ]
+ return ", ".join(names)
+
+
+def tool_line(tool: Any) -> str:
+ args = _arg_list(tool)
+ args_part = f" [{args}]" if args else ""
+ return f"- `{tool.name}`{args_part}: {_one_line(tool.description or '')}"
+
+
+_GUIDE_INTRO = """\
+# World Intelligence MCP: research guide
+
+This server answers questions about the world with live public data:
+markets, conflict, hazards, migration, aviation, cyber, infrastructure,
+news and more. This guide is generated from the running server: {tools}
+tools in {domains} domains, and {prompts} worked research prompts.
+
+Other resources: `intel://guide/source-health` (which sources are
+failing, stale or missing keys right now) and `intel://guide/measures`
+(what the numbers mean and how they mislead).
+
+## How to ask a strong question
+
+- Name the period: "the last 30 days against the 30 days before", not
+ "recently".
+- Name the comparison: an earlier period, another place, or a stated
+ baseline.
+- Name the measure: event count or fatalities, price level or percentage
+ change, people displaced at year end or arrivals during the year.
+- Name the place: a country (many tools take an ISO-3 code), a region, a
+ bounding box, or a saved area of interest.
+
+A question with all four can be answered from tool output. A question
+with none of them invites a story.
+
+## What an answer from this server contains
+
+- Values as the sources published them. Most responses name their source
+ and carry a fetch timestamp; the date a value describes is often earlier
+ than the fetch, so give both.
+- Failures as failures. A source that is down or not configured returns
+ an `error` field; composite tools list each domain they could not
+ measure in `data_gaps`. Neither is ever an empty success.
+- Citations. Briefs and digests number their sources.
+- Old copies marked as old where the shape allows. When a live fetch fails
+ and an older cached copy exists, dictionary responses carry `_stale` and
+ `_stale_age_seconds`. Tools that reshape a response do not always pass
+ that marker through, so check stale serves in the source-health
+ resource.
+
+## What this server will not do
+
+- Trade, place orders, or say what to buy or sell.
+- Forecast prices, elections or wars. Escalation, instability, risk and
+ composite scores are weighted summaries of current readings against
+ stated baselines, not probabilities.
+- Prove causation. Series that move together, or one shortly after the
+ other, may share a cause or be coincidence.
+- Show history it did not record. Stored history (semantic search,
+ timelines, baselines, area change detection) exists only for the time
+ the collector or server was running and storing.
+- Use keyed sources without their keys. Those tools return an error
+ naming the variable; `intel://guide/source-health` shows which are set.
+- See what its sources do not publish. Aircraft without a broadcast
+ position, unlisted outlets, and regions outside a feed's coverage are
+ absent, which is not the same as quiet.
+- Confirm identities. A sanctions or entity name match is a text match.
+"""
+
+
+def render_guide(modules: list | None = None, prompts: tuple = PROMPTS) -> str:
+ """The guide markdown, built from the live registry."""
+ groups = domains(modules)
+ total = sum(len(d.tools) for d in groups)
+ parts = [
+ _GUIDE_INTRO.format(tools=total, domains=len(groups), prompts=len(prompts)),
+ "## Worked research prompts\n",
+ "Each prompt names the tools to call and the limits to respect. "
+ "Fetch one with prompts/get.\n",
+ ]
+ for p in prompts:
+ args = ", ".join(
+ f"{a.name} (required)" if a.required else a.name for a in p.arguments
+ )
+ args_part = f" [{args}]" if args else ""
+ parts.append(f"- `{p.name}`{args_part}: {p.title}.")
+ parts.append("\n## Tools by domain\n")
+ for d in groups:
+ parts.append(f"### {d.title} ({len(d.tools)})\n")
+ if d.summary:
+ parts.append(f"{d.summary}\n")
+ parts.extend(tool_line(t) for t in d.tools)
+ parts.append("")
+ return "\n".join(parts).rstrip() + "\n"
+
+
+MEASURES = """\
+# Measures glossary
+
+What the numbers returned by this server's tools mean, and the mistakes
+they invite.
+
+## Amount outstanding versus flow
+
+An amount outstanding (a stock) is a level at one moment: people
+displaced at the end of a year, a central bank's balance sheet, money
+supply. A flow is what happened during a period: arrivals during a year,
+fund inflows in a week, fatalities in a month. Never add a stock to a
+flow. A change in a stock is a net figure: a displaced population that
+grew by 100,000 may have had 300,000 arrivals and 200,000 returns.
+
+## Growth versus acceleration
+
+Growth is how fast a level changes (prices 3 percent higher than a year
+earlier). Acceleration is how fast the growth rate itself changes
+(growth up from 2 to 3 percent). Slower growth is still growth: inflation
+falling from 4 to 3 percent means prices are still rising, only more
+slowly.
+
+## Percent versus percentage points
+
+A rate that moves from 4 percent to 5 percent rose by 1 percentage
+point, which is a 25 percent increase in the rate itself. Yields,
+spreads, policy rates and shares are compared in points; one point is
+100 basis points.
+
+## Seasonally adjusted
+
+Many series repeat a calendar pattern: holiday spending, winter heating,
+summer travel. A seasonally adjusted series has the expected pattern
+removed, so one month can be compared with the month before. An
+unadjusted series should be compared with the same period a year
+earlier. Never compare an adjusted figure with an unadjusted one; check
+which a series is before comparing.
+
+## Observation, publication and collection dates
+
+- Observation date: the period a value describes (March unemployment,
+ the day an event took place).
+- Publication date: when the publisher released it, often weeks after
+ the observation, with revisions later still.
+- Collection date: when this server fetched or saved it.
+
+A value fetched today can describe last month or last year; annual
+datasets such as World Bank indicators often trail by a year or more.
+Report the observation date. The fetch time only tells you how fresh the
+copy is.
+
+## Revisions
+
+First releases are estimates. Economic series, event datasets and
+displacement figures are revised after publication, sometimes by more
+than the change being discussed. Say which release you used.
+
+## Correlation and timing offsets
+
+Two series that move together, or where one tends to move a few days
+before the other, may share a cause, may be linked in either direction,
+or may be coincidence. Coincidence becomes likely when many pairs or
+many offsets are tried and only the best is reported. A lead or lag found
+in one sample describes that sample. None of this shows that one thing
+caused the other.
+
+## Composite scores
+
+Escalation, instability, risk, macro composite and stress scores are
+weighted combinations of current inputs against stated baselines. They
+summarize their inputs, they are not probabilities, and they hold no
+information their inputs do not. Report the components with the score.
+
+## Missing data is not zero
+
+A source that failed, is not configured, or does not cover a place
+returns an error, a note or a `data_gaps` entry. That means unknown, not
+none. Zero events in a region a source covers is a measurement; zero
+events in a region it does not cover is nothing at all.
+"""
+
+
+_HEALTH_SCOPE = (
+ "circuit_breakers covers requests made by this server process since it "
+ "started; the collector, dashboard and CLI keep their own. An empty map "
+ "means no requests yet, not that every source is healthy.",
+ "cache_freshness reads the shared cache database: the newest entry per "
+ "key prefix, written by whichever process fetched it. A fresh entry shows "
+ "a recent successful fetch, not that the collector is on schedule.",
+ "keyed_sources says whether each variable is set in this server's "
+ "environment. It never shows values and does not check that a key works.",
+ "Not read here: vector store statistics (intel_vector_stats) and the "
+ "collector's run history. Reading this resource starts no fetches.",
+)
+
+
+def source_health(
+ breaker: Any,
+ cache: Any,
+ environ: Mapping[str, str] | None = None,
+ now: float | None = None,
+) -> dict[str, Any]:
+ """Read-only health snapshot from in-process state and the cache DB."""
+ env = os.environ if environ is None else environ
+ breakers = breaker.status()
+ freshness = cache.freshness()
+ keyed = []
+ for ks in KEYED_SOURCES:
+ set_vars = [name for name in ks.env if env.get(name)]
+ keyed.append(
+ {
+ "source": ks.source,
+ "env": list(ks.env),
+ "configured": [name for name in ks.env if name in set_vars],
+ "missing": [name for name in ks.env if name not in set_vars],
+ "without_key": ks.without_key,
+ }
+ )
+ generated = datetime.fromtimestamp(time.time() if now is None else now, timezone.utc)
+ return {
+ "generated_at": generated.isoformat(),
+ "scope": list(_HEALTH_SCOPE),
+ "open_breakers": sorted(
+ name for name, info in breakers.items() if info.get("status") != "closed"
+ ),
+ "stale_serves": {
+ name: info["total_stale_serves"]
+ for name, info in sorted(breakers.items())
+ if info.get("total_stale_serves")
+ },
+ "stale_cache_prefixes": sorted(
+ prefix for prefix, info in freshness.items() if info.get("is_stale")
+ ),
+ "circuit_breakers": breakers,
+ "cache": cache.stats(),
+ "cache_freshness": freshness,
+ "keyed_sources": keyed,
+ }
+
+
+# ---------------------------------------------------------------------------
+# MCP glue: server.py's handlers delegate here.
+# ---------------------------------------------------------------------------
+
+RESOURCES: tuple[Resource, ...] = (
+ Resource(
+ uri=GUIDE_URI,
+ name="research-guide",
+ title="Research guide",
+ description=(
+ "How to ask this server a strong question, what an answer contains, "
+ "what it will not do, the worked prompts, and every tool by domain "
+ "(generated from the live registry)."
+ ),
+ mimeType="text/markdown",
+ ),
+ Resource(
+ uri=HEALTH_URI,
+ name="source-health",
+ title="Source health",
+ description=(
+ "Circuit breakers, cache freshness, stale serves and which keyed "
+ "sources are configured. Read-only; starts no fetches."
+ ),
+ mimeType="application/json",
+ ),
+ Resource(
+ uri=MEASURES_URI,
+ name="measures-glossary",
+ title="Measures glossary",
+ description=(
+ "Stock versus flow, growth versus acceleration, percentage points, "
+ "seasonal adjustment, the three dates, correlation versus causation, "
+ "missing data versus zero."
+ ),
+ mimeType="text/markdown",
+ ),
+)
+
+
+def list_resources() -> list[Resource]:
+ return list(RESOURCES)
+
+
+def read_resource(uri: str) -> list[ReadResourceContents]:
+ uri = str(uri)
+ if uri == GUIDE_URI:
+ return [ReadResourceContents(content=render_guide(), mime_type="text/markdown")]
+ if uri == MEASURES_URI:
+ return [ReadResourceContents(content=MEASURES, mime_type="text/markdown")]
+ if uri == HEALTH_URI:
+ from . import runtime
+
+ health = source_health(runtime.breaker, runtime.cache)
+ return [
+ ReadResourceContents(
+ content=json.dumps(health, indent=2, default=str),
+ mime_type="application/json",
+ )
+ ]
+ known = ", ".join(str(r.uri) for r in RESOURCES)
+ raise McpError(
+ ErrorData(code=INVALID_PARAMS, message=f"Unknown resource {uri}; available: {known}")
+ )
+
+
+def list_prompts() -> list[Prompt]:
+ return [
+ Prompt(
+ name=p.name,
+ title=p.title,
+ description=p.description,
+ arguments=[
+ PromptArgument(name=a.name, description=a.description, required=a.required)
+ for a in p.arguments
+ ],
+ )
+ for p in PROMPTS
+ ]
+
+
+def get_prompt(name: str, arguments: dict[str, str] | None) -> GetPromptResult:
+ prompt = guide_prompts.get(name)
+ if prompt is None:
+ known = ", ".join(p.name for p in PROMPTS)
+ raise McpError(
+ ErrorData(code=INVALID_PARAMS, message=f"Unknown prompt '{name}'; available: {known}")
+ )
+ try:
+ text = guide_prompts.render(prompt, arguments)
+ except PromptArgumentError as exc:
+ raise McpError(ErrorData(code=INVALID_PARAMS, message=str(exc))) from exc
+ return GetPromptResult(
+ description=prompt.description,
+ messages=[PromptMessage(role="user", content=TextContent(type="text", text=text))],
+ )
diff --git a/src/world_intel_mcp/guide_prompts.py b/src/world_intel_mcp/guide_prompts.py
new file mode 100644
index 0000000..2884289
--- /dev/null
+++ b/src/world_intel_mcp/guide_prompts.py
@@ -0,0 +1,806 @@
+"""Worked research questions served as MCP prompts.
+
+Each prompt is a research question a model can run against this server:
+the tools to call (named exactly as registered), what each call is for,
+and the limits an honest answer has to respect. ``guide.py`` turns these
+into MCP ``Prompt`` / ``GetPromptResult`` objects; this module holds the
+data and the text rendering only.
+
+Every tool named here must exist in the live registry, and every
+``intel_*`` name that appears anywhere in a rendered prompt must be one
+of that prompt's listed tools. ``tests/test_guide.py`` pins both, so a
+renamed or removed tool fails the suite instead of leaving a prompt that
+sends a model to a tool that is not there.
+"""
+
+import re
+from dataclasses import dataclass
+
+# Rendered into every prompt after its own limits.
+COMMON_LIMITS: tuple[str, ...] = (
+ "A tool that returns an error, a note or a data_gaps entry has told you "
+ "what is missing: report it as missing. Missing data is never zero, calm "
+ "or peace.",
+ "Give each figure the date it describes (the observation date) as well "
+ "as when it was fetched; they are often different.",
+ "Describe what the data show. This server does not forecast prices, "
+ "give trading advice or prove causation.",
+)
+
+ANSWER_SHAPE = (
+ "Answer with: the place, period and measure you used; each number with "
+ "its unit and date; the comparison you were asked for; every data gap; "
+ "and one line on what this data cannot tell."
+)
+
+_MAX_ARG_CHARS = 200
+_PLACEHOLDER = re.compile(r"\{([a-z_]+)\}")
+TOOL_NAME = re.compile(r"\bintel_[a-z0-9_]+\b")
+
+
+@dataclass(frozen=True)
+class PromptArg:
+ name: str
+ description: str
+ required: bool = False
+ default: str | None = None
+ choices: tuple[str, ...] = ()
+
+
+@dataclass(frozen=True)
+class ResearchPrompt:
+ name: str
+ title: str
+ domain: str
+ question: str
+ steps: tuple[tuple[str, str], ...]
+ limits: tuple[str, ...]
+ arguments: tuple[PromptArg, ...] = ()
+
+ @property
+ def tools(self) -> tuple[str, ...]:
+ return tuple(tool for tool, _ in self.steps)
+
+ @property
+ def description(self) -> str:
+ return f"{self.title}. Uses {', '.join(self.tools)}."
+
+
+class PromptArgumentError(ValueError):
+ """A prompt was requested with missing, unknown or invalid arguments."""
+
+
+def _resolve_args(prompt: ResearchPrompt, given: dict[str, str] | None) -> dict[str, str]:
+ given = dict(given or {})
+ known = {a.name for a in prompt.arguments}
+ unknown = sorted(set(given) - known)
+ if unknown:
+ accepted = ", ".join(sorted(known)) or "none"
+ raise PromptArgumentError(
+ f"Prompt '{prompt.name}' does not take {', '.join(unknown)} "
+ f"(accepted: {accepted})"
+ )
+ values: dict[str, str] = {}
+ for arg in prompt.arguments:
+ raw = given.get(arg.name)
+ value = str(raw).strip()[:_MAX_ARG_CHARS] if raw is not None else ""
+ if not value:
+ if arg.required:
+ raise PromptArgumentError(
+ f"Prompt '{prompt.name}' needs argument '{arg.name}': "
+ f"{arg.description}"
+ )
+ value = arg.default or ""
+ if arg.choices and value not in arg.choices:
+ raise PromptArgumentError(
+ f"Prompt '{prompt.name}' argument '{arg.name}' must be one of "
+ f"{', '.join(arg.choices)} (got '{value}')"
+ )
+ values[arg.name] = value
+ return values
+
+
+def render(prompt: ResearchPrompt, arguments: dict[str, str] | None = None) -> str:
+ """The prompt's user-message text with its arguments filled in."""
+ values = _resolve_args(prompt, arguments)
+
+ def fill(text: str) -> str:
+ return _PLACEHOLDER.sub(lambda m: values[m.group(1)], text)
+
+ lines = [f"Research question: {fill(prompt.question)}", "", "Tools to call:"]
+ for i, (tool, purpose) in enumerate(prompt.steps, 1):
+ lines.append(f"{i}. {tool}: {fill(purpose)}")
+ lines += ["", "Limits to respect:"]
+ lines += [f"- {fill(limit)}" for limit in prompt.limits]
+ lines += [f"- {limit}" for limit in COMMON_LIMITS]
+ lines += ["", ANSWER_SHAPE]
+ return "\n".join(lines)
+
+
+_COUNTRY = PromptArg("country", "Country name, e.g. Sudan", required=True)
+_ISO3 = PromptArg("country", "ISO alpha-3 country code, e.g. UKR", required=True)
+
+
+PROMPTS: tuple[ResearchPrompt, ...] = (
+ # --- conflict -------------------------------------------------------
+ ResearchPrompt(
+ name="conflict-trend",
+ title="Conflict trend in one country against the previous period",
+ domain="conflict",
+ question=(
+ "How has organized violence in {country} changed over the last "
+ "{days} days, and is it more or less intense than the {days} days "
+ "before that?"
+ ),
+ arguments=(
+ _COUNTRY,
+ PromptArg("days", "Length of each comparison window in days", default="30"),
+ ),
+ steps=(
+ (
+ "intel_ucdp_events",
+ "state-based violence events. It has no country filter, so ask "
+ "for twice the window with a high limit (it caps results), keep "
+ "the events in {country} yourself, split them at the midpoint "
+ "and say that you filtered",
+ ),
+ (
+ "intel_acled_events",
+ "events for {country} over both windows (needs ACLED_EMAIL and "
+ "ACLED_PASSWORD; without them it returns an error)",
+ ),
+ ("intel_unrest_events", "protests and riots in {country} (also ACLED), kept apart from armed violence"),
+ ),
+ limits=(
+ "Event datasets are revised and arrive late, so the most recent "
+ "days are the least complete. A quiet final week is not proof of calm.",
+ "Count events and fatalities separately: fewer events with more "
+ "deaths is not de-escalation.",
+ "ACLED and UCDP define an event differently. Compare each source "
+ "with itself across the two windows, never one source's count "
+ "against the other's.",
+ ),
+ ),
+ ResearchPrompt(
+ name="hotspot-escalation",
+ title="Which hotspots are escalating and why",
+ domain="conflict",
+ question=(
+ "Which of the built-in hotspots score highest for escalation right "
+ "now, and which measured component drives each score?"
+ ),
+ steps=(
+ ("intel_hotspot_escalation", "scores and their components for the 22 hotspots"),
+ ("intel_military_surge", "foreign military aircraft concentrations against baseline"),
+ ("intel_theater_posture", "military aircraft presence by theater"),
+ ),
+ limits=(
+ "Escalation scores are weighted heuristics against fixed "
+ "baselines, renormalized over the components actually measured. "
+ "They are not probabilities of war. List the unavailable_components.",
+ "Aircraft tracking sees only aircraft that broadcast a position, "
+ "and many military flights do not, so counts are a floor.",
+ ),
+ ),
+ # --- markets and economy ---------------------------------------------
+ ResearchPrompt(
+ name="market-risk-snapshot",
+ title="Cross-asset risk picture today",
+ domain="markets",
+ question=(
+ "What does the current risk picture look like across equities, "
+ "volatility, the dollar, rates and crypto?"
+ ),
+ steps=(
+ ("intel_macro_signals", "Fear and Greed, VIX, DXY, gold, 10-year yield, BTC dominance"),
+ ("intel_sector_heatmap", "which US equity sectors are leading and lagging"),
+ ("intel_yield_curve", "curve shape and spreads"),
+ ("intel_macro_composite", "the composite score and the inputs it weighs"),
+ ),
+ limits=(
+ "Report current readings and their recent change only. Quote the "
+ "composite score next to its inputs, since it is a weighted summary "
+ "of them.",
+ ),
+ ),
+ ResearchPrompt(
+ name="yield-curve-check",
+ title="Is the Treasury curve inverted, and by how much",
+ domain="markets",
+ question=(
+ "Is the US Treasury yield curve inverted today, by how much, and "
+ "how has the 10-year minus 2-year spread moved recently?"
+ ),
+ steps=(
+ ("intel_yield_curve", "maturities, the 2s10s and 3m10y spreads and the inversion flag"),
+ ("intel_fred_series", "series T10Y2Y for the spread's recent history (needs FRED_API_KEY)"),
+ ("intel_central_bank_rates", "the policy rate the short end is anchored to"),
+ ),
+ limits=(
+ "Spreads are in percentage points. A move from 0.10 to 0.30 is "
+ "0.20 points, not a 200 percent rise.",
+ "Without FRED_API_KEY the curve falls back to four Yahoo "
+ "maturities (3M, 5Y, 10Y, 30Y), so spread_2s10s comes back null. "
+ "Say so; do not swap in another spread without saying which.",
+ "An inverted curve describes today's yields. It is not a "
+ "recession forecast.",
+ ),
+ ),
+ ResearchPrompt(
+ name="central-bank-compare",
+ title="Where major central bank policy rates stand",
+ domain="markets",
+ question=(
+ "Where do the major central banks' policy rates stand, and which "
+ "of them changed most recently?"
+ ),
+ steps=(
+ ("intel_central_bank_rates", "policy rates for 15 central banks with their source"),
+ ("intel_fred_series", "series DFF for the US effective federal funds rate history (needs FRED_API_KEY)"),
+ ("intel_major_crosses", "how the major currencies sit against each other today"),
+ ),
+ limits=(
+ "Without FRED_API_KEY some rates come from a curated table. Give "
+ "each rate's as-of date and source, and never present a curated "
+ "value as live.",
+ "Rate changes are in percentage points or basis points (one point "
+ "is 100 basis points), not percent of the rate.",
+ ),
+ ),
+ ResearchPrompt(
+ name="fx-move",
+ title="A currency pair's move and the coverage around it",
+ domain="markets",
+ question=(
+ "How has {symbol} moved against {base} over the last {days} days, "
+ "and what news coverage ran alongside the largest daily moves?"
+ ),
+ arguments=(
+ PromptArg("symbol", "Quote currency, ISO code such as EUR", required=True),
+ PromptArg("base", "Base currency, ISO code", default="USD"),
+ PromptArg("days", "Days of history", default="30"),
+ ),
+ steps=(
+ ("intel_forex_timeseries", "base {base}, symbol {symbol}, days {days}"),
+ ("intel_major_crosses", "where the pair sits among the majors today"),
+ ("intel_gdelt_search", "articles about the currency around the dates of the largest moves"),
+ ),
+ limits=(
+ "ECB reference rates are published once per business day. A "
+ "weekend or holiday has no observation, which is not a zero change.",
+ "News published alongside a move is context. Timing alone does "
+ "not show that the news caused the move.",
+ ),
+ ),
+ ResearchPrompt(
+ name="company-events",
+ title="A company's recent disclosures and results",
+ domain="markets",
+ question=(
+ "What material events has {ticker} disclosed recently, and how did "
+ "its reported results compare with estimates?"
+ ),
+ arguments=(PromptArg("ticker", "Stock ticker, e.g. AAPL", required=True),),
+ steps=(
+ ("intel_company_profile", "quote, sector and recent news for {ticker}"),
+ ("intel_company_filings", "recent 10-K, 10-Q and 8-K filings for {ticker}"),
+ ("intel_earnings_surprise", "actual against estimated earnings for {ticker}"),
+ ),
+ limits=(
+ "A filing date is when the company filed, not when the event "
+ "happened; give both when the filing states the event date.",
+ "No buy, sell or hold view: describe what was disclosed.",
+ ),
+ ),
+ ResearchPrompt(
+ name="energy-pressure",
+ title="Energy prices from futures to the pump",
+ domain="markets",
+ question=(
+ "Are energy prices rising for producers and for consumers, and is "
+ "any chokepoint exposure relevant to the move?"
+ ),
+ steps=(
+ ("intel_commodity_quotes", "crude oil and natural gas futures"),
+ ("intel_energy_prices", "EIA crude and gas prices (needs EIA_API_KEY)"),
+ ("intel_gas_prices", "AAA US retail gasoline and diesel averages"),
+ ("intel_trade_routes", "oil flows through the major chokepoints"),
+ ),
+ limits=(
+ "Futures, wholesale and retail pump prices are different measures "
+ "with different dates. Never join them into one series.",
+ "Chokepoint oil flows are curated reference values, not live "
+ "tanker counts.",
+ ),
+ ),
+ ResearchPrompt(
+ name="crypto-structure",
+ title="Crypto market structure today",
+ domain="markets",
+ question=(
+ "What is the state of the crypto market today: prices, stablecoin "
+ "pegs, spot ETF trading and Bitcoin's trend indicators?"
+ ),
+ steps=(
+ ("intel_crypto_quotes", "prices and market caps of the largest coins"),
+ ("intel_stablecoin_status", "whether the major stablecoins hold their peg"),
+ ("intel_etf_flows", "Bitcoin spot ETF prices and trading volume"),
+ ("intel_btc_technicals", "moving averages, Mayer Multiple and distance from the high"),
+ ),
+ limits=(
+ "intel_etf_flows reports prices and trading volume, not creations "
+ "or redemptions. Volume is not net flow.",
+ "Technical indicators summarize past prices; they do not predict "
+ "the next move.",
+ ),
+ ),
+ # --- hazards ----------------------------------------------------------
+ ResearchPrompt(
+ name="earthquake-exposure",
+ title="Recent strong earthquakes near people",
+ domain="hazards",
+ question=(
+ "Which earthquakes of magnitude {min_magnitude} or more in the "
+ "last {hours} hours struck near large populations, and did any "
+ "raise a disaster alert?"
+ ),
+ arguments=(
+ PromptArg("min_magnitude", "Smallest magnitude to include", default="5.5"),
+ PromptArg("hours", "Lookback in hours", default="48"),
+ ),
+ steps=(
+ ("intel_earthquakes", "min_magnitude {min_magnitude}, hours {hours}"),
+ ("intel_population_exposure", "event_types earthquake, for people near each event"),
+ ("intel_disaster_alerts", "event_type EQ, for the GDACS alert level of the same events"),
+ ),
+ limits=(
+ "Exposure adds up the population of major cities inside the "
+ "radius. It is not a casualty estimate and misses rural people.",
+ "Magnitudes and locations are revised in the first hours after an "
+ "event; say when you read them.",
+ ),
+ ),
+ ResearchPrompt(
+ name="severe-weather",
+ title="Severe weather warnings in the covered regions",
+ domain="hazards",
+ question=(
+ "What severe weather warnings are active in {us_area} and in "
+ "{europe_country}, and are any tropical cyclones active?"
+ ),
+ arguments=(
+ PromptArg("us_area", "Two-letter US state code, e.g. TX", default="the United States"),
+ PromptArg("europe_country", "Meteoalarm country, e.g. france", default="Europe"),
+ ),
+ steps=(
+ ("intel_weather_alerts", "US National Weather Service alerts (pass area when a state was given)"),
+ ("intel_meteoalarm_alerts", "European warnings (one country per call; without country it lists the countries)"),
+ ("intel_cyclones", "Atlantic and eastern and central Pacific storms from the National Hurricane Center"),
+ ("intel_jtwc_cyclones", "western Pacific, Indian Ocean and Southern Hemisphere storms from JTWC"),
+ ),
+ limits=(
+ "NWS covers the US and Meteoalarm covers its participating "
+ "European countries only. No alert outside those areas says "
+ "nothing about the weather there.",
+ "NHC and JTWC cover different basins and can label the same storm "
+ "differently. Match storms by position and time before counting.",
+ ),
+ ),
+ ResearchPrompt(
+ name="wildfire-situation",
+ title="Wildfire activity and the conditions around it",
+ domain="hazards",
+ question="How active are wildfires in {region} now, and are temperatures or rainfall abnormal there?",
+ arguments=(
+ PromptArg(
+ "region",
+ "FIRMS region: north_america, south_america, europe, africa, "
+ "middle_east, south_asia, east_asia, southeast_asia or oceania",
+ default="all FIRMS regions",
+ ),
+ ),
+ steps=(
+ ("intel_wildfires", "satellite fire detections (needs NASA_FIRMS_API_KEY)"),
+ ("intel_environmental_events", "category wildfires, for named fires NASA EONET tracks"),
+ ("intel_climate_anomalies", "temperature and precipitation against the prior year"),
+ ),
+ limits=(
+ "FIRMS detections are satellite heat signatures, not mapped fire "
+ "perimeters; one large fire produces many detections.",
+ "Without NASA_FIRMS_API_KEY the fire tool returns an error. Report "
+ "that, not zero fires.",
+ "Climate anomalies are measured against the prior year, not a "
+ "long-term normal.",
+ ),
+ ),
+ ResearchPrompt(
+ name="space-weather-impact",
+ title="Space weather and coincident outages",
+ domain="hazards",
+ question=(
+ "How strong is current geomagnetic and solar activity, and are "
+ "internet or cloud outages being reported at the same time?"
+ ),
+ steps=(
+ ("intel_space_weather", "Kp index, flare class, solar wind and SWPC alerts"),
+ ("intel_internet_outages", "internet outages reported over the last 7 days"),
+ ("intel_service_status", "active incidents at the major cloud providers"),
+ ),
+ limits=(
+ "An outage at the same time as a storm does not show the storm "
+ "caused it; most outages have local causes.",
+ "Kp runs 0 to 9 on a quasi-logarithmic scale: Kp 8 is far more "
+ "than twice Kp 4.",
+ ),
+ ),
+ # --- migration --------------------------------------------------------
+ ResearchPrompt(
+ name="displacement-history",
+ title="A country's displacement record since 1951",
+ domain="migration",
+ question=(
+ "How has displacement linked to {country} as {role} changed since "
+ "records began, and which years saw the largest waves?"
+ ),
+ arguments=(
+ _COUNTRY,
+ PromptArg(
+ "role",
+ "origin (its people abroad, plus IDPs) or host (people it hosts)",
+ default="origin",
+ choices=("origin", "host"),
+ ),
+ ),
+ steps=(
+ ("intel_migration_history", "country {country}, role {role}"),
+ ("intel_migration_flows", "the latest year's corridors with {country} as origin or destination"),
+ ("intel_displacement_summary", "the global totals for context"),
+ ),
+ limits=(
+ "UNHCR figures are year-end stocks (people displaced at the end of "
+ "each year), not arrivals during the year. A change between two "
+ "years is a net change in the stock.",
+ "UNHCR revises past years. Say which reporting year you used.",
+ ),
+ ),
+ ResearchPrompt(
+ name="migration-surges",
+ title="The largest year-over-year displacement changes",
+ domain="migration",
+ question=(
+ "Which origins and corridors had the largest year-over-year change "
+ "in displacement in {year}, and how does that compare with net "
+ "migration from all causes?"
+ ),
+ arguments=(PromptArg("year", "Reporting year", default="the latest year with data"),),
+ steps=(
+ ("intel_migration_surges", "largest increases and decreases (pass year if one was given)"),
+ ("intel_net_migration", "World Bank net migration for the leading countries"),
+ ("intel_humanitarian_summary", "HDX crisis datasets for the leading origins"),
+ ),
+ limits=(
+ "World Bank net migration counts every reason, work included; "
+ "UNHCR counts forcibly displaced people. Show them side by side "
+ "and never add them together.",
+ "The mass, major and notable levels are the tool's stated "
+ "thresholds, not official designations.",
+ ),
+ ),
+ # --- aviation ---------------------------------------------------------
+ ResearchPrompt(
+ name="airspace-anomaly",
+ title="Unusual business jet or military air activity",
+ domain="aviation",
+ question=(
+ "Is {cohort} air activity over {region} unusual for this time of "
+ "the week, and if so, where did the extra aircraft come from?"
+ ),
+ arguments=(
+ PromptArg("cohort", "bizjet or military", default="bizjet", choices=("bizjet", "military")),
+ PromptArg(
+ "region",
+ "global, conus, north_america, europe, middle_east or east_asia",
+ default="global",
+ ),
+ ),
+ steps=(
+ ("intel_jet_cohort_snapshot", "cohort {cohort}, region {region}; also builds the tracked cohort"),
+ ("intel_jet_activity_anomaly", "the latest half-hour against the same slot on earlier weeks"),
+ ("intel_jet_excess_origins", "only if an excess is flagged: where the extra departures came from"),
+ ("intel_military_flights", "for the military cohort, a second source of positions"),
+ ),
+ limits=(
+ "ADS-B shows only aircraft whose transponders volunteer receivers "
+ "pick up; many military and some private aircraft do not broadcast "
+ "a usable position, so counts are a floor.",
+ "An anomaly is a deviation from the same slot on earlier weeks. "
+ "It is not evidence of anyone's intent.",
+ "The anomaly check needs a learned cohort; a fresh install reports "
+ "that gap first.",
+ ),
+ ),
+ ResearchPrompt(
+ name="airport-disruption",
+ title="US airport delays and their likely weather context",
+ domain="aviation",
+ question="Which major US airports have delays now, and is severe weather active near them?",
+ steps=(
+ ("intel_airport_delays", "FAA delays at 20 major US airports"),
+ ("intel_aviation_domestic", "the airborne traffic snapshot for scale"),
+ ("intel_weather_alerts", "NWS alerts for the states of the delayed airports"),
+ ),
+ limits=(
+ "FAA data covers major US airports only.",
+ "The airborne total is a snapshot of aircraft OpenSky receives, "
+ "not a count of all flights.",
+ ),
+ ),
+ # --- cyber and infrastructure ----------------------------------------
+ ResearchPrompt(
+ name="cyber-landscape",
+ title="Current cyber threat landscape",
+ domain="cyber",
+ question=(
+ "What does the current cyber threat picture look like: newly "
+ "known-exploited vulnerabilities, active malware infrastructure, "
+ "and which threat actors are in the headlines?"
+ ),
+ steps=(
+ ("intel_cyber_threats", "Feodo, CISA KEV, SANS and URLhaus indicators"),
+ ("intel_keyword_spikes", "CVE and APT names rising in headlines against baseline"),
+ ("intel_extract_entities", "CVEs, APT groups and organizations in recent headlines"),
+ ),
+ limits=(
+ "Feeds list reported indicators and known-exploited "
+ "vulnerabilities. A listing is not attribution and does not show "
+ "that any particular organization was hit.",
+ "Keyword spikes measure mentions in headlines, not attack volume.",
+ ),
+ ),
+ ResearchPrompt(
+ name="internet-disruption",
+ title="Internet disruption in one country",
+ domain="infrastructure",
+ question=(
+ "Is internet connectivity in {country} disrupted now, and could a "
+ "cable corridor failure explain it?"
+ ),
+ arguments=(
+ _COUNTRY,
+ PromptArg(
+ "resource",
+ "An ASN or prefix to check, e.g. AS3333",
+ default="none given (skip the BGP check)",
+ ),
+ ),
+ steps=(
+ ("intel_internet_outages", "outages over the last 7 days; keep those in {country}"),
+ ("intel_bgp_status", "routing visibility for resource {resource}"),
+ ("intel_cable_health", "the condition of the cable corridors"),
+ ("intel_cascade_analysis", "which countries depend on an at-risk corridor"),
+ ),
+ limits=(
+ "An empty outage list can mean the sources returned nothing. "
+ "Check for a note field and the source health resource before "
+ "calling {country} connected.",
+ "Cascade analysis is a simulation over curated cable "
+ "dependencies, not a measurement of a real outage.",
+ "BGP status checks one ASN or prefix at a time; it is not a "
+ "global hijack detector.",
+ ),
+ ),
+ ResearchPrompt(
+ name="cloud-incidents",
+ title="Cloud provider incidents and the regions involved",
+ domain="infrastructure",
+ question="Which cloud providers report active incidents, and which of their regions are involved?",
+ steps=(
+ ("intel_service_status", "active incidents at AWS, Azure, GCP, Cloudflare and GitHub"),
+ ("intel_cloud_regions", "where the named regions are"),
+ ),
+ limits=(
+ "Status pages are published by the providers themselves and can "
+ "lag or understate an incident.",
+ ),
+ ),
+ ResearchPrompt(
+ name="maritime-chokepoints",
+ title="Pressure on maritime chokepoints",
+ domain="maritime",
+ question=(
+ "Are navigational warnings building at the strategic waterways, "
+ "and is shipping stress rising in markets?"
+ ),
+ steps=(
+ ("intel_vessel_snapshot", "warning-based scores for 9 strategic waterways"),
+ ("intel_nav_warnings", "the warning texts behind the scores"),
+ ("intel_trade_routes", "what share of oil and trade each chokepoint carries"),
+ ("intel_shipping_index", "a stress score from shipping-linked ETF and equity prices"),
+ ),
+ limits=(
+ "The vessel snapshot scores navigational warnings; it does not "
+ "count ships. Warnings are not yet filtered by distance to each "
+ "waterway, so read the warnings themselves before naming one.",
+ "The shipping stress score is a market proxy, not a freight rate.",
+ ),
+ ),
+ # --- areas of interest --------------------------------------------------
+ ResearchPrompt(
+ name="aoi-watch-setup",
+ title="Start watching an area of interest",
+ domain="aoi",
+ question=(
+ "Set up a watch on {name} (centre {lat}, {lon}, radius {radius_km} "
+ "km): what is inside it now, and what should later checks compare against?"
+ ),
+ arguments=(
+ PromptArg("name", "A name for the area", required=True),
+ PromptArg("lat", "Centre latitude in degrees", required=True),
+ PromptArg("lon", "Centre longitude in degrees", required=True),
+ PromptArg("radius_km", "Radius in kilometres", required=True),
+ ),
+ steps=(
+ ("intel_aoi_define", "name {name}, lat {lat}, lon {lon}, radius_km {radius_km}"),
+ ("intel_aoi_brief", "the cited picture inside {name} today"),
+ ("intel_aoi_changes", "the first run records a baseline for {name}"),
+ ),
+ limits=(
+ "The first change check records a baseline and claims nothing "
+ "entered or left.",
+ "A domain that fails is listed in data_gaps and left out of the "
+ "diff. Never read it as everything leaving.",
+ "Change history between your own calls exists only while the "
+ "collector daemon runs its AOI sweeps.",
+ ),
+ ),
+ ResearchPrompt(
+ name="aoi-review",
+ title="What changed in a watched area",
+ domain="aoi",
+ question="What entered or left {name} since the last sweep, and is the area escalating?",
+ arguments=(PromptArg("name", "The AOI name", required=True),),
+ steps=(
+ ("intel_aoi_list", "confirm {name} exists and see its shape"),
+ ("intel_aoi_changes", "new, departed and unchanged items since the last sweep"),
+ ("intel_aoi_escalation", "the escalation score and its components for {name}"),
+ ("intel_aoi_brief", "cited detail behind any change worth reporting"),
+ ),
+ limits=(
+ "Changes are relative to the previous sweep, whenever that ran; "
+ "give its time.",
+ "News for an AOI is found by place name near its centre, so a "
+ "nearby place with the same name can leak in.",
+ ),
+ ),
+ # --- news, politics, health ---------------------------------------------
+ ResearchPrompt(
+ name="story-breadth",
+ title="How widely a story is covered and how that changed",
+ domain="news",
+ question=(
+ "How much coverage has {topic} received, how has that changed over "
+ "time, and which story clusters carry it?"
+ ),
+ arguments=(PromptArg("topic", "Search terms for the story", required=True),),
+ steps=(
+ ("intel_gdelt_search", "query {topic}, mode timelinevol for volume over time, then artlist for articles"),
+ ("intel_news_clusters", "the clusters of related stories in the RSS set"),
+ ("intel_news_feed", "the latest items from the RSS feeds"),
+ ),
+ limits=(
+ "Coverage volume measures attention, not truth or importance.",
+ "The RSS set is a fixed list of feeds. A story missing there may "
+ "still be covered elsewhere.",
+ ),
+ ),
+ ResearchPrompt(
+ name="election-watch",
+ title="Upcoming elections and the signals around them",
+ domain="politics",
+ question="Which elections are coming up in {country}, and what do current signals show around them?",
+ arguments=(PromptArg("country", "ISO-3 code or country name", default="all countries"),),
+ steps=(
+ ("intel_election_calendar", "upcoming elections and their proximity risk"),
+ ("intel_country_dossier", "economy, sanctions, news and conflict context for a named country"),
+ ("intel_social_signals", "discussion velocity on the tracked subreddits"),
+ ("intel_prediction_markets", "active Polymarket questions; keep the ones about this election"),
+ ),
+ limits=(
+ "Proximity risk rises as an election nears; it is a stated "
+ "heuristic, not a forecast of unrest or of the result.",
+ "Reddit and prediction markets reflect their own participants, "
+ "not the electorate.",
+ ),
+ ),
+ ResearchPrompt(
+ name="sanctions-screen",
+ title="Search the OFAC sanctions list for a name",
+ domain="finance",
+ question="Does {query} appear on the US Treasury OFAC SDN list, and under which programs?",
+ arguments=(PromptArg("query", "Name to search for", required=True),),
+ steps=(
+ ("intel_sanctions_search", "query {query}"),
+ ("intel_company_profile", "only if the name is a listed company: who it is"),
+ ),
+ limits=(
+ "Matching is by substring on names. A name match is not an "
+ "identity match, and this is not a compliance screening service.",
+ "The SDN list changes. Say when you searched.",
+ ),
+ ),
+ ResearchPrompt(
+ name="disease-watch",
+ title="Disease outbreak reports",
+ domain="health",
+ question="Which disease outbreaks are being reported now, and which involve high-concern pathogens?",
+ steps=(
+ ("intel_disease_outbreaks", "WHO, ProMED and CIDRAP outbreak reports"),
+ ("intel_humanitarian_summary", "crisis datasets for the affected countries"),
+ ("intel_news_feed", "recent coverage, for context only"),
+ ),
+ limits=(
+ "Outbreak reports arrive after cases occur and case counts are "
+ "revised. Give each report's date.",
+ "Reporting is uneven across countries. Fewer reports does not "
+ "mean fewer cases.",
+ ),
+ ),
+ # --- history and country views ------------------------------------------
+ ResearchPrompt(
+ name="history-recall",
+ title="What the stored history says about a topic",
+ domain="history",
+ question=(
+ "What has this server stored about {topic} over the last {hours} "
+ "hours, and has anything similar been recorded before?"
+ ),
+ arguments=(
+ PromptArg("topic", "Natural language topic", required=True),
+ PromptArg("hours", "How far back to search, in hours", default="168"),
+ ),
+ steps=(
+ ("intel_domain_summary", "hours {hours}: what is stored, per category, with the earliest timestamp"),
+ ("intel_semantic_search", "query {topic}, hours {hours}"),
+ ("intel_timeline", "the stored entries in time order for the matching domain"),
+ ("intel_similar_events", "earlier stored entries that resemble the strongest match"),
+ ),
+ limits=(
+ "History exists only for what the collector stored while it was "
+ "running. Before calling anything the first or the largest, check "
+ "the earliest stored timestamp.",
+ "Semantic search ranks by similarity of wording. A high score is "
+ "not a factual match.",
+ "If the vector store is not available these tools return an "
+ "error; say that history could not be read.",
+ ),
+ ),
+ ResearchPrompt(
+ name="country-overview",
+ title="One country across economy, stability and markets",
+ domain="country",
+ question=(
+ "What is the current picture in {country} across economy, "
+ "stability, active signals and its stock market?"
+ ),
+ arguments=(_ISO3,),
+ steps=(
+ ("intel_country_dossier", "country {country}"),
+ ("intel_instability_index", "country_code {country}, with its four components"),
+ ("intel_signal_summary", "signals for the country (this tool takes the country name)"),
+ ("intel_country_stocks", "country {country}, its main index"),
+ ),
+ limits=(
+ "The instability index is a weighted composite with country "
+ "multipliers. Quote its components, not only the total.",
+ "World Bank figures in the dossier are annual and often a year or "
+ "more old. Give the year of each.",
+ ),
+ ),
+)
+
+
+def get(name: str) -> ResearchPrompt | None:
+ for prompt in PROMPTS:
+ if prompt.name == name:
+ return prompt
+ return None
diff --git a/src/world_intel_mcp/server.py b/src/world_intel_mcp/server.py
index e620d38..33eb879 100644
--- a/src/world_intel_mcp/server.py
+++ b/src/world_intel_mcp/server.py
@@ -71,8 +71,10 @@ import os
from typing import Any
from mcp.server import Server
+from mcp.server.lowlevel.helper_types import ReadResourceContents
from mcp.server.stdio import stdio_server
-from mcp.types import Tool, TextContent
+from mcp.types import GetPromptResult, Prompt, Resource, Tool, TextContent
+from pydantic import AnyUrl
logging.basicConfig(
level=os.environ.get("WORLD_INTEL_LOG_LEVEL", "INFO"),
@@ -86,6 +88,7 @@ server = Server("world-intel-mcp")
# aliases remain as the module's public face — external readers (and the
# registry tests) reach the live cache and vector store as server.cache,
# server._vector_store, etc.
+from . import guide as _guide # noqa: E402
from . import runtime as _runtime # noqa: E402
from . import tools as _tools_pkg # noqa: E402
@@ -135,6 +138,32 @@ async def call_tool(name: str, arguments: dict[str, Any] | None) -> list[TextCon
return [TextContent(type="text", text=json.dumps(result, indent=2, default=str))]
+# Research guide (Phase 29): read-only resources and worked prompts. The
+# content lives in guide.py / guide_prompts.py; registering these handlers
+# is what makes the server advertise the resources and prompts
+# capabilities at initialize.
+
+
[email protected]_resources()
+async def list_resources() -> list[Resource]:
+ return _guide.list_resources()
+
+
+async def read_resource(uri: AnyUrl) -> list[ReadResourceContents]:
+ return _guide.read_resource(str(uri))
+
+
+async def list_prompts() -> list[Prompt]:
+ return _guide.list_prompts()
+
+
+async def get_prompt(name: str, arguments: dict[str, str] | None) -> GetPromptResult:
+ return _guide.get_prompt(name, arguments)
+
+
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
diff --git a/src/world_intel_mcp/tests/test_guide.py b/src/world_intel_mcp/tests/test_guide.py
new file mode 100644
index 0000000..a8281e8
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_guide.py
@@ -0,0 +1,483 @@
+"""Tests for the research guide: MCP resources, prompts and ``intel guide``.
+
+The registry is imported under test_server_registry's temp cache path
+(the shared override every registry-importing test file uses), so
+nothing here opens the developer's real cache database. The live stdio
+test spawns the installed console script with its own temp cache.
+"""
+
+import importlib
+import json
+import os
+import re
+import sys
+import types
+from pathlib import Path
+
+import anyio
+import pytest
+from click.testing import CliRunner
+from mcp import ClientSession, StdioServerParameters
+from mcp.client.stdio import stdio_client
+from mcp.server.lowlevel import NotificationOptions
+from mcp.shared.exceptions import McpError
+from mcp.types import Tool
+
+from world_intel_mcp import guide, guide_prompts
+from world_intel_mcp.cache import Cache
+from world_intel_mcp.circuit_breaker import CircuitBreaker
+
+from .test_server_registry import _TMP_CACHE
+
+_SOURCES_DIR = Path(guide.__file__).resolve().parent / "sources"
+_TOOL_LINE = re.compile(r"^- `(intel_[a-z0-9_]+)`", re.M)
+
+
+def _import_under_temp_cache(name: str):
+ prior = os.environ.get("WORLD_INTEL_CACHE_DB")
+ os.environ["WORLD_INTEL_CACHE_DB"] = str(_TMP_CACHE)
+ try:
+ return importlib.import_module(name)
+ finally:
+ if prior is None:
+ os.environ.pop("WORLD_INTEL_CACHE_DB", None)
+ else:
+ os.environ["WORLD_INTEL_CACHE_DB"] = prior
+
+
[email protected](scope="module")
+def tools_pkg():
+ return _import_under_temp_cache("world_intel_mcp.tools")
+
+
[email protected](scope="module")
+def server():
+ return _import_under_temp_cache("world_intel_mcp.server")
+
+
[email protected](scope="module")
+def registered(tools_pkg) -> set[str]:
+ return {t.name for t in tools_pkg.ALL_TOOLS}
+
+
+def _tools_section(markdown: str) -> str:
+ return markdown.split("## Tools by domain", 1)[1]
+
+
+def _sample_args(prompt: guide_prompts.ResearchPrompt) -> dict[str, str]:
+ return {a.name: (a.choices[0] if a.choices else "Sudan") for a in prompt.arguments if a.required}
+
+
+def _prompt_problems(prompt: guide_prompts.ResearchPrompt, registered: set[str]) -> list[str]:
+ """Every way a prompt can send a model to a tool that is not there."""
+ problems = [f"lists unregistered {t}" for t in prompt.tools if t not in registered]
+ text = guide_prompts.render(prompt, _sample_args(prompt))
+ if "{" in text or "}" in text:
+ problems.append("text keeps an unfilled placeholder")
+ for name in set(guide_prompts.TOOL_NAME.findall(text)):
+ if name not in prompt.tools:
+ problems.append(f"text names {name}, which is not in its tool list")
+ if name not in registered:
+ problems.append(f"text names unregistered {name}")
+ return problems
+
+
+# ---------------------------------------------------------------------------
+# Guide resource: generated from the live registry
+# ---------------------------------------------------------------------------
+
+
+def test_guide_lists_every_registered_tool_exactly_once(tools_pkg, registered) -> None:
+ text = guide.render_guide()
+ listed = _TOOL_LINE.findall(_tools_section(text))
+ assert len(listed) == len(set(listed)), "a tool is listed twice"
+ assert set(listed) == registered, {
+ "missing_from_guide": sorted(registered - set(listed)),
+ "not_registered": sorted(set(listed) - registered),
+ }
+ n_tools, n_domains = len(tools_pkg.ALL_TOOLS), len(tools_pkg._MODULES)
+ assert f"server: {n_tools}\ntools in {n_domains} domains" in text
+
+
+def test_guide_groups_tools_under_their_own_module(tools_pkg) -> None:
+ section = _tools_section(guide.render_guide())
+ blocks = re.split(r"^### ", section, flags=re.M)[1:]
+ assert len(blocks) == len(tools_pkg._MODULES)
+ for module, block in zip(tools_pkg._MODULES, blocks):
+ header = block.split("\n", 1)[0]
+ names = _TOOL_LINE.findall(block)
+ assert names == [t.name for t in module.TOOLS], module.__name__
+ assert header.endswith(f"({len(module.TOOLS)})"), header
+
+
+def test_guide_follows_the_registry_it_is_given() -> None:
+ """A tool added to a module shows up and a removed one disappears:
+ the list is computed, never hand-kept."""
+ fake = types.SimpleNamespace(
+ __name__="world_intel_mcp.tools.newdomain",
+ __doc__="New domain tools: one probe.\n\nDetail paragraph.",
+ TOOLS=[
+ Tool(
+ name="intel_probe",
+ description="Probe something — carefully. Second sentence.",
+ inputSchema={
+ "type": "object",
+ "properties": {"where": {}, "when": {}},
+ "required": ["where"],
+ },
+ )
+ ],
+ )
+ text = guide.render_guide([fake], prompts=())
+ assert "### Newdomain (1)" in text
+ assert "New domain tools: one probe." in text
+ assert "Detail paragraph" not in text
+ assert "- `intel_probe` [where (required), when]: Probe something - carefully." in text
+ assert "Second sentence" not in text
+ assert "1\ntools in 1 domains" in text
+ assert _TOOL_LINE.findall(_tools_section(guide.render_guide([], prompts=()))) == []
+
+
+def test_guide_states_how_to_ask_what_answers_hold_and_limits() -> None:
+ text = guide.render_guide()
+ for heading in (
+ "## How to ask a strong question",
+ "## What an answer from this server contains",
+ "## What this server will not do",
+ "## Worked research prompts",
+ ):
+ assert heading in text
+ for phrase in ("Name the period", "Name the comparison", "Name the measure", "Name the place"):
+ assert phrase in text
+ for phrase in ("Trade, place orders", "Forecast prices", "Prove causation", "Show history it did not record"):
+ assert phrase in text
+ for resource in guide.RESOURCES:
+ if str(resource.uri) != guide.GUIDE_URI:
+ assert str(resource.uri) in text
+ for prompt in guide_prompts.PROMPTS:
+ assert f"- `{prompt.name}`" in text
+
+
+def test_published_guide_text_has_no_em_dashes() -> None:
+ assert "—" not in guide.render_guide()
+ assert "—" not in guide.MEASURES
+ for prompt in guide_prompts.PROMPTS:
+ assert "—" not in guide_prompts.render(prompt, _sample_args(prompt)), prompt.name
+
+
+def test_measures_glossary_covers_the_named_measures() -> None:
+ for heading in (
+ "## Amount outstanding versus flow",
+ "## Growth versus acceleration",
+ "## Percent versus percentage points",
+ "## Seasonally adjusted",
+ "## Observation, publication and collection dates",
+ "## Correlation and timing offsets",
+ "## Missing data is not zero",
+ ):
+ assert heading in guide.MEASURES
+ assert "None of this shows that one thing\ncaused the other" in guide.MEASURES
+
+
+# ---------------------------------------------------------------------------
+# Prompts
+# ---------------------------------------------------------------------------
+
+
+def test_prompt_set_size_names_and_domain_coverage() -> None:
+ prompts = guide_prompts.PROMPTS
+ assert len(prompts) >= 20
+ names = [p.name for p in prompts]
+ assert len(names) == len(set(names))
+ assert all(re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", n) for n in names), names
+ domains = {p.domain for p in prompts}
+ assert {"conflict", "markets", "hazards", "migration", "aviation", "cyber", "aoi"} <= domains
+ for p in prompts:
+ assert p.steps and p.limits, p.name
+
+
+def test_every_prompt_names_only_registered_tools(registered) -> None:
+ problems = {p.name: _prompt_problems(p, registered) for p in guide_prompts.PROMPTS}
+ assert {k: v for k, v in problems.items() if v} == {}
+
+
+def test_prompt_check_catches_a_nonexistent_tool(registered) -> None:
+ """The check above has to be able to fail."""
+ bad = guide_prompts.ResearchPrompt(
+ name="bad",
+ title="Bad",
+ domain="test",
+ question="Use intel_status and also intel_no_such_tool in {Country}.",
+ steps=(("intel_status", "health"), ("intel_gone_tool", "was renamed")),
+ limits=("none",),
+ )
+ problems = _prompt_problems(bad, registered)
+ assert "lists unregistered intel_gone_tool" in problems
+ assert "text names unregistered intel_no_such_tool" in problems
+ assert "text names intel_no_such_tool, which is not in its tool list" in problems
+ assert "text keeps an unfilled placeholder" in problems
+
+
+def test_prompt_text_names_tools_limits_and_arguments() -> None:
+ prompt = guide_prompts.get("conflict-trend")
+ text = guide_prompts.render(prompt, {"country": "Sudan", "days": "14"})
+ assert "How has organized violence in Sudan changed over the last 14 days" in text
+ assert "1. intel_ucdp_events:" in text
+ assert "2. intel_acled_events:" in text
+ assert "Limits to respect:" in text
+ assert "Missing data is never zero" in text
+ assert "{" not in text and "}" not in text
+
+
+def test_prompt_defaults_fill_optional_arguments() -> None:
+ prompt = guide_prompts.get("conflict-trend")
+ text = guide_prompts.render(prompt, {"country": "Sudan", "days": " "})
+ assert "over the last 30 days" in text
+
+
+def test_prompt_argument_errors() -> None:
+ prompt = guide_prompts.get("displacement-history")
+ with pytest.raises(guide_prompts.PromptArgumentError, match="needs argument 'country'"):
+ guide_prompts.render(prompt, {})
+ with pytest.raises(guide_prompts.PromptArgumentError, match="does not take colour"):
+ guide_prompts.render(prompt, {"country": "Syria", "colour": "red"})
+ with pytest.raises(guide_prompts.PromptArgumentError, match="must be one of origin, host"):
+ guide_prompts.render(prompt, {"country": "Syria", "role": "both"})
+ long_value = "x" * 1000
+ text = guide_prompts.render(prompt, {"country": long_value})
+ assert "x" * 200 in text and "x" * 201 not in text
+
+
+def test_prompt_without_arguments_rejects_any() -> None:
+ with pytest.raises(guide_prompts.PromptArgumentError, match="accepted: none"):
+ guide_prompts.render(guide_prompts.get("hotspot-escalation"), {"country": "x"})
+
+
+def test_readme_documents_every_prompt_and_resource() -> None:
+ readme = (Path(__file__).resolve().parents[3] / "README.md").read_text()
+ section = readme.split("## Research Guide: MCP Prompts and Resources", 1)[1].split("\n## ", 1)[0]
+ documented = set(re.findall(r"`([a-z0-9]+(?:-[a-z0-9]+)+)`", section))
+ names = {p.name for p in guide_prompts.PROMPTS}
+ assert names <= documented, sorted(names - documented)
+ assert f"**{len(guide_prompts.PROMPTS)} prompts**" in section
+ for resource in guide.RESOURCES:
+ assert f"`{resource.uri}`" in section
+
+
+def test_list_prompts_mirrors_prompt_data() -> None:
+ listed = guide.list_prompts()
+ assert [p.name for p in listed] == [p.name for p in guide_prompts.PROMPTS]
+ by_name = {p.name: p for p in listed}
+ aoi = by_name["aoi-watch-setup"]
+ assert {a.name: a.required for a in aoi.arguments} == {
+ "name": True,
+ "lat": True,
+ "lon": True,
+ "radius_km": True,
+ }
+ assert "intel_aoi_define" in aoi.description
+
+
+def test_get_prompt_returns_one_user_message() -> None:
+ result = guide.get_prompt("fx-move", {"symbol": "JPY"})
+ assert len(result.messages) == 1
+ msg = result.messages[0]
+ assert msg.role == "user"
+ assert "How has JPY moved against USD over the last 30 days" in msg.content.text
+
+
+def test_get_prompt_errors_are_mcp_errors() -> None:
+ with pytest.raises(McpError, match="Unknown prompt 'nope'"):
+ guide.get_prompt("nope", None)
+ with pytest.raises(McpError, match="needs argument 'ticker'"):
+ guide.get_prompt("company-events", {})
+
+
+# ---------------------------------------------------------------------------
+# Source health resource
+# ---------------------------------------------------------------------------
+
+
+def test_source_health_reports_breakers_freshness_and_keys(tmp_path) -> None:
+ cache = Cache(db_path=tmp_path / "health.db")
+ cache.set("markets:quotes:^GSPC", {"v": 1}, ttl_seconds=300)
+ cache.set("seismology:usgs:24", {"v": 2}, ttl_seconds=-10)
+ breaker = CircuitBreaker(failure_threshold=2, cooldown_seconds=300)
+ breaker.record_failure("gdelt")
+ breaker.record_failure("gdelt")
+ breaker.record_failure("ucdp")
+ breaker.record_stale_serve("ucdp")
+ env = {"FRED_API_KEY": "secret-fred-value", "OPENSKY_CLIENT_ID": "id-value"}
+
+ try:
+ health = guide.source_health(breaker, cache, environ=env, now=0)
+ finally:
+ cache.close()
+
+ assert health["generated_at"] == "1970-01-01T00:00:00+00:00"
+ assert health["open_breakers"] == ["gdelt"]
+ assert health["stale_serves"] == {"ucdp": 1}
+ assert health["circuit_breakers"]["ucdp"]["failures"] == 1
+ assert health["stale_cache_prefixes"] == ["seismology"]
+ assert set(health["cache_freshness"]) == {"markets", "seismology"}
+ assert health["cache"]["total_entries"] == 2
+ keyed = {k["source"]: k for k in health["keyed_sources"]}
+ assert keyed["FRED"]["configured"] == ["FRED_API_KEY"]
+ assert keyed["FRED"]["missing"] == []
+ assert keyed["OpenSky"]["configured"] == ["OPENSKY_CLIENT_ID"]
+ assert "OPENSKY_CLIENT_SECRET" in keyed["OpenSky"]["missing"]
+ assert keyed["ACLED"]["configured"] == []
+ dumped = json.dumps(health)
+ assert "secret-fred-value" not in dumped and "id-value" not in dumped
+ assert any("not that every source is healthy" in s for s in health["scope"])
+
+
+def test_keyed_sources_match_what_the_source_modules_read() -> None:
+ """A source that starts reading a new credential, or stops reading
+ one, must change the health resource in the same commit."""
+ pattern = re.compile(
+ r"os\.(?:environ\.get|getenv)\(\s*[\"']([A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|EMAIL|USERNAME|CLIENT_ID))[\"']"
+ )
+ read = set()
+ for path in _SOURCES_DIR.glob("*.py"):
+ read |= set(pattern.findall(path.read_text()))
+ listed = {name for ks in guide.KEYED_SOURCES for name in ks.env}
+ assert read, "scan found no credential reads at all; the pattern is broken"
+ assert listed == read, {
+ "read_but_not_listed": sorted(read - listed),
+ "listed_but_not_read": sorted(listed - read),
+ }
+
+
+def test_reading_health_resource_never_fetches(server, monkeypatch) -> None:
+ import httpx
+
+ def _no_network(*args, **kwargs):
+ raise AssertionError("reading source health made an HTTP request")
+
+ monkeypatch.setattr(httpx.AsyncClient, "send", _no_network)
+ monkeypatch.setattr(httpx.Client, "send", _no_network)
+ # A copy of the shared breaker's state, so the seeded failure does
+ # not outlive this test.
+ monkeypatch.setattr(server.breaker, "_states", dict(server.breaker._states))
+ server.breaker.record_failure("guide-test-source")
+ (content,) = guide.read_resource(guide.HEALTH_URI)
+ assert content.mime_type == "application/json"
+ health = json.loads(content.content)
+ assert "guide-test-source" in health["circuit_breakers"]
+ assert Path(health["cache"]["db_path"]) == _TMP_CACHE
+
+
+def test_unknown_resource_is_an_mcp_error() -> None:
+ with pytest.raises(McpError, match="Unknown resource intel://nope"):
+ guide.read_resource("intel://nope")
+
+
+# ---------------------------------------------------------------------------
+# Server wiring (in process)
+# ---------------------------------------------------------------------------
+
+
+def test_server_advertises_prompts_and_resources(server) -> None:
+ caps = server.server.get_capabilities(NotificationOptions(), {})
+ assert caps.prompts is not None
+ assert caps.resources is not None
+ assert caps.tools is not None
+
+
+async def test_server_handlers_delegate_to_guide(server) -> None:
+ resources = await server.list_resources()
+ assert [str(r.uri) for r in resources] == [guide.GUIDE_URI, guide.HEALTH_URI, guide.MEASURES_URI]
+ (content,) = await server.read_resource(guide.MEASURES_URI)
+ assert content.content == guide.MEASURES
+ (content,) = await server.read_resource(guide.GUIDE_URI)
+ assert content.mime_type == "text/markdown"
+ assert content.content == guide.render_guide()
+ prompts = await server.list_prompts()
+ assert len(prompts) == len(guide_prompts.PROMPTS)
+ result = await server.get_prompt("story-breadth", {"topic": "Red Sea shipping"})
+ assert "query Red Sea shipping" in result.messages[0].content.text
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+
+def test_cli_guide_prints_registry_generated_markdown(tools_pkg, monkeypatch, tmp_path) -> None:
+ from world_intel_mcp import cli
+
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli.db"))
+ result = CliRunner().invoke(cli.main, ["guide"], catch_exceptions=False)
+ assert result.exit_code == 0
+ assert result.output.startswith("# World Intelligence MCP: research guide")
+ assert set(_TOOL_LINE.findall(_tools_section(result.output))) == {
+ t.name for t in tools_pkg.ALL_TOOLS
+ }
+
+
+def test_cli_guide_measures_and_json(tools_pkg) -> None:
+ from world_intel_mcp import cli
+
+ result = CliRunner().invoke(cli.main, ["guide", "--measures"], catch_exceptions=False)
+ assert result.exit_code == 0
+ assert result.output == guide.MEASURES
+ result = CliRunner().invoke(cli.main, ["--json-output", "guide"], catch_exceptions=False)
+ assert result.exit_code == 0
+ payload = json.loads(result.output)
+ assert payload["uri"] == guide.GUIDE_URI
+ assert payload["text"] == guide.render_guide()
+
+
+# ---------------------------------------------------------------------------
+# Live stdio session against the installed console script
+# ---------------------------------------------------------------------------
+
+_CONSOLE_SCRIPT = Path(sys.executable).with_name("world-intel-mcp")
+
+
[email protected](not _CONSOLE_SCRIPT.exists(), reason="console script not installed in this env")
+async def test_live_stdio_session_serves_resources_and_prompts(tmp_path, registered) -> None:
+ env = dict(os.environ)
+ env.update(
+ {
+ "WORLD_INTEL_CACHE_DB": str(tmp_path / "stdio-cache.db"),
+ "XDG_CACHE_HOME": str(tmp_path / "xdg"),
+ "WORLD_INTEL_LOG_LEVEL": "WARNING",
+ }
+ )
+ params = StdioServerParameters(command=str(_CONSOLE_SCRIPT), args=[], env=env)
+ with anyio.fail_after(60):
+ async with stdio_client(params) as (read, write):
+ async with ClientSession(read, write) as session:
+ init = await session.initialize()
+ assert init.capabilities.prompts is not None
+ assert init.capabilities.resources is not None
+
+ listed = await session.list_resources()
+ uris = [str(r.uri) for r in listed.resources]
+ assert uris == [guide.GUIDE_URI, guide.HEALTH_URI, guide.MEASURES_URI]
+
+ read_guide = await session.read_resource(guide.GUIDE_URI)
+ text = read_guide.contents[0].text
+ assert read_guide.contents[0].mimeType == "text/markdown"
+ assert set(_TOOL_LINE.findall(_tools_section(text))) == registered
+
+ read_health = await session.read_resource(guide.HEALTH_URI)
+ health = json.loads(read_health.contents[0].text)
+ assert health["circuit_breakers"] == {}
+ assert Path(health["cache"]["db_path"]) == tmp_path / "stdio-cache.db"
+
+ prompts = await session.list_prompts()
+ assert [p.name for p in prompts.prompts] == [p.name for p in guide_prompts.PROMPTS]
+
+ got = await session.get_prompt("conflict-trend", {"country": "Sudan"})
+ assert "organized violence in Sudan" in got.messages[0].content.text
+
+ with pytest.raises(McpError, match="needs argument 'country'"):
+ await session.get_prompt("conflict-trend", {})
+
+ tools = await session.list_tools()
+ assert {t.name for t in tools.tools} == registered