ntv-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ permissions:
11
+ id-token: write # required for PyPI trusted publishing (OIDC)
12
+ contents: read
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.12"
18
+ - run: pip install build
19
+ - run: python -m build
20
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,61 @@
1
+ name: Publish to MCP Registry
2
+
3
+ # Official MCP Registry (registry.modelcontextprotocol.io) via GitHub OIDC.
4
+ # No secret, no interactive login: the runner's OIDC token proves ownership
5
+ # of the io.github.mohammad-abbasi-sh/* namespace.
6
+ # Refs: https://github.com/modelcontextprotocol/registry
7
+
8
+ on:
9
+ push:
10
+ tags: ["v*"]
11
+ workflow_dispatch:
12
+
13
+ jobs:
14
+ publish:
15
+ runs-on: ubuntu-latest
16
+ permissions:
17
+ id-token: write # required for OIDC -> MCP Registry
18
+ contents: read
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+
22
+ - name: Sync server.json version to tag
23
+ # Only sync when running on a version tag (v*). On workflow_dispatch
24
+ # (ref = refs/heads/main) keep the version committed in server.json.
25
+ run: |
26
+ VER=""
27
+ if [[ "$GITHUB_REF" == refs/tags/* ]]; then
28
+ TAG="${GITHUB_REF#refs/tags/}"
29
+ VER="${TAG#v}"
30
+ fi
31
+ if [ -n "$VER" ]; then
32
+ python3 - "$VER" << 'EOF'
33
+ import json, sys
34
+ ver = sys.argv[1]
35
+ d = json.load(open('server.json'))
36
+ d['version'] = ver
37
+ for pkg in d.get('packages', []):
38
+ pkg['version'] = ver
39
+ json.dump(d, open('server.json', 'w'), indent=2, ensure_ascii=False)
40
+ print('server.json version ->', ver)
41
+ EOF
42
+ else
43
+ echo "No version tag ($GITHUB_REF); keeping server.json version as-is"
44
+ fi
45
+
46
+ - name: Install mcp-publisher
47
+ run: |
48
+ curl -sL "https://github.com/modelcontextprotocol/registry/releases/download/v1.8.7/mcp-publisher_linux_amd64.tar.gz" -o /tmp/mcp-publisher.tar.gz
49
+ tar -xzf /tmp/mcp-publisher.tar.gz -C /tmp
50
+ sudo mv /tmp/mcp-publisher /usr/local/bin/mcp-publisher
51
+ mcp-publisher --version
52
+
53
+ - name: Validate server.json
54
+ run: mcp-publisher validate server.json
55
+
56
+ - name: Publish to MCP Registry (OIDC)
57
+ run: |
58
+ mcp-publisher login github-oidc
59
+ mcp-publisher publish server.json
60
+ # A registry outage must never break the release; re-run from Actions if needed.
61
+ continue-on-error: true
@@ -0,0 +1,21 @@
1
+ name: Daily live smoke
2
+
3
+ # One fixed probe per day: catches fingerprint rot / bot-wall changes
4
+ # before users hit them. Fails visibly on 403/timeout.
5
+ on:
6
+ schedule:
7
+ - cron: "0 6 * * *"
8
+ workflow_dispatch:
9
+
10
+ jobs:
11
+ smoke:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.12"
18
+ - name: Install
19
+ run: pip install -e .
20
+ - name: Smoke probe
21
+ run: python tests/smoke_live.py
ntv_mcp-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohammad Abbasi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ntv_mcp-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.5
2
+ Name: ntv-mcp
3
+ Version: 0.1.0
4
+ Summary: Unofficial read-only MCP server for n-tv news (n-tv.de) — headlines, markets, videos & articles
5
+ Author: Mohammad Abbasi
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: httpx>=0.27
10
+ Requires-Dist: mcp<2
11
+ Description-Content-Type: text/markdown
12
+
13
+ # ntv-mcp 📺
14
+
15
+ mcp-name: io.github.mohammad-abbasi-sh/ntv-mcp
16
+
17
+ Unofficial **read-only** MCP server for **[n-tv.de](https://www.n-tv.de)** — n-tv news from its official RSS feeds: latest headlines by section, market news, latest videos, keyword search and full article text. No key, no login. No key, no login.
18
+
19
+ > Built by Mohammad Abbasi as part of the "Germany MCP factory". Not affiliated with n-tv.de.
20
+
21
+ ## For AI agents
22
+
23
+ Add to your MCP client config (stdio):
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "ntv": {
29
+ "command": "uvx",
30
+ "args": ["ntv-mcp==0.1.0"]
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ Or run locally: `python -m ntv_mcp.server` (needs `mcp<2`, `httpx`).
37
+
38
+ ## Tools
39
+
40
+ | Tool | Description |
41
+ |------|-------------|
42
+ | `ntv_headlines` | Latest n-tv headlines — `section` (all/politik/wirtschaft/sport/technik/panorama/wissen/der_tag), `limit` 1..50 |
43
+ | `ntv_markets` | Latest n-tv market news (Börse feed) — `limit` 1..50 |
44
+ | `ntv_videos` | Latest n-tv videos — `limit` 1..50 |
45
+ | `ntv_search_news` | Keyword search over the latest n-tv headlines — `query`, `limit` 1..50 |
46
+ | `ntv_get_article` | Full text of one n-tv article — `url` (an n-tv.de article link) |
47
+ | `ntv_health` | Reachability probe (ok / blocked / error) — one polite request |
48
+
49
+ ## Notes
50
+
51
+ - All data comes from **n-tv's official RSS feeds** (free, no key, no login).
52
+ - There is **no dedicated breaking-news feed** — `/eilmeldungen/rss` 404s (verified 2026-11-10) — so no breaking-news tool is offered.
53
+ - The Börse feed carries market **news**, not live quotes.
54
+ - Article bodies are extracted from n-tv's server-rendered pages (JSON-LD headline/date + cleaned `<p>` text); video pages may return little or no body text.
55
+
56
+ Tests: 22/22 green (15 offline + 7 live, 2026-11-10).
57
+
58
+ ## Development
59
+
60
+ ```bash
61
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
62
+ .venv/bin/pip install -e .
63
+ .venv/bin/python -m pytest tests/ -q
64
+ ```
65
+
66
+ ## License
67
+
68
+ MIT
69
+
70
+ ---
71
+
72
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,51 @@
1
+ # ntv-mcp 📺
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/ntv-mcp
4
+
5
+ Inoffizieller **nur lesender** MCP-Server für **[n-tv.de](https://www.n-tv.de)** — n-tv-Nachrichten über die offiziellen RSS-Feeds: neueste Schlagzeilen nach Ressort, Börsennachrichten, neueste Videos, Stichwortsuche und Volltexte. Kein Schlüssel, kein Login. Kein Schlüssel, keine Anmeldung.
6
+
7
+ > Gebaut von Mohammad Abbasi als Teil der "Germany MCP factory". Nicht mit n-tv.de verbunden.
8
+
9
+ ## Für KI-Agenten
10
+
11
+ Zur MCP-Client-Konfiguration hinzufügen (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "ntv": {
17
+ "command": "uvx",
18
+ "args": ["ntv-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Oder lokal starten: `python -m ntv_mcp.server` (benötigt `mcp<2`, `httpx`).
25
+
26
+ ## Tools
27
+
28
+ | Tool | Beschreibung |
29
+ |------|-------------|
30
+ | `ntv_headlines` | Neueste n-tv-Schlagzeilen nach Ressort |
31
+ | `ntv_markets` | Neueste n-tv-Börsennachrichten |
32
+ | `ntv_videos` | Neueste n-tv-Videos |
33
+ | `ntv_search_news` | Neueste n-tv-Schlagzeilen nach Stichwort suchen |
34
+ | `ntv_get_article` | Volltext eines n-tv-Artikels |
35
+ | `ntv_health` | Erreichbarkeitsprüfung (ok / blocked / error) — eine höfliche Anfrage |
36
+
37
+ ## Entwicklung
38
+
39
+ ```bash
40
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
41
+ .venv/bin/pip install -e .
42
+ .venv/bin/python -m pytest tests/ -q
43
+ ```
44
+
45
+ ## Lizenz
46
+
47
+ MIT
48
+
49
+ ---
50
+
51
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,51 @@
1
+ # ntv-mcp 📺
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/ntv-mcp
4
+
5
+ سرور MCP غیررسمی و **فقط‌خواندنی** برای **[n-tv.de](https://www.n-tv.de)** — اخبار n-tv از فیدهای RSS رسمی: تازه‌ترین تیترها بر اساس بخش، اخبار بازار، تازه‌ترین ویدیوها، جست‌وجوی کلیدواژه و متن کامل مقاله. بدون کلید، بدون ورود. بدون کلید، بدون ورود.
6
+
7
+ > ساختهٔ محمد عباسی، بخشی از «کارخانهٔ MCP آلمان». وابسته به n-tv.de نیست.
8
+
9
+ ## برای ایجنت‌های هوش مصنوعی
10
+
11
+ به پیکربندی MCP کلاینت اضافه کنید (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "ntv": {
17
+ "command": "uvx",
18
+ "args": ["ntv-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ یا به‌صورت محلی اجرا کنید: `python -m ntv_mcp.server` (نیازمند `mcp<2` و `httpx`).
25
+
26
+ ## ابزارها
27
+
28
+ | ابزار | توضیح |
29
+ |------|-------|
30
+ | `ntv_headlines` | تازه‌ترین تیترهای n-tv بر اساس بخش |
31
+ | `ntv_markets` | تازه‌ترین اخبار بازار n-tv |
32
+ | `ntv_videos` | تازه‌ترین ویدیوهای n-tv |
33
+ | `ntv_search_news` | جست‌وجوی تیترهای اخیر n-tv با کلیدواژه |
34
+ | `ntv_get_article` | متن کامل یک مقالهٔ n-tv |
35
+ | `ntv_health` | بررسی دسترس‌پذیری (ok / blocked / error) — یک درخواست مؤدبانه |
36
+
37
+ ## توسعه
38
+
39
+ ```bash
40
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
41
+ .venv/bin/pip install -e .
42
+ .venv/bin/python -m pytest tests/ -q
43
+ ```
44
+
45
+ ## لایسنس
46
+
47
+ MIT
48
+
49
+ ---
50
+
51
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,60 @@
1
+ # ntv-mcp 📺
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/ntv-mcp
4
+
5
+ Unofficial **read-only** MCP server for **[n-tv.de](https://www.n-tv.de)** — n-tv news from its official RSS feeds: latest headlines by section, market news, latest videos, keyword search and full article text. No key, no login. No key, no login.
6
+
7
+ > Built by Mohammad Abbasi as part of the "Germany MCP factory". Not affiliated with n-tv.de.
8
+
9
+ ## For AI agents
10
+
11
+ Add to your MCP client config (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "ntv": {
17
+ "command": "uvx",
18
+ "args": ["ntv-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Or run locally: `python -m ntv_mcp.server` (needs `mcp<2`, `httpx`).
25
+
26
+ ## Tools
27
+
28
+ | Tool | Description |
29
+ |------|-------------|
30
+ | `ntv_headlines` | Latest n-tv headlines — `section` (all/politik/wirtschaft/sport/technik/panorama/wissen/der_tag), `limit` 1..50 |
31
+ | `ntv_markets` | Latest n-tv market news (Börse feed) — `limit` 1..50 |
32
+ | `ntv_videos` | Latest n-tv videos — `limit` 1..50 |
33
+ | `ntv_search_news` | Keyword search over the latest n-tv headlines — `query`, `limit` 1..50 |
34
+ | `ntv_get_article` | Full text of one n-tv article — `url` (an n-tv.de article link) |
35
+ | `ntv_health` | Reachability probe (ok / blocked / error) — one polite request |
36
+
37
+ ## Notes
38
+
39
+ - All data comes from **n-tv's official RSS feeds** (free, no key, no login).
40
+ - There is **no dedicated breaking-news feed** — `/eilmeldungen/rss` 404s (verified 2026-11-10) — so no breaking-news tool is offered.
41
+ - The Börse feed carries market **news**, not live quotes.
42
+ - Article bodies are extracted from n-tv's server-rendered pages (JSON-LD headline/date + cleaned `<p>` text); video pages may return little or no body text.
43
+
44
+ Tests: 22/22 green (15 offline + 7 live, 2026-11-10).
45
+
46
+ ## Development
47
+
48
+ ```bash
49
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
50
+ .venv/bin/pip install -e .
51
+ .venv/bin/python -m pytest tests/ -q
52
+ ```
53
+
54
+ ## License
55
+
56
+ MIT
57
+
58
+ ---
59
+
60
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ntv-mcp"
7
+ version = "0.1.0"
8
+ description = "Unofficial read-only MCP server for n-tv news (n-tv.de) — headlines, markets, videos & articles"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "mcp<2",
14
+ "httpx>=0.27",
15
+ ]
16
+ authors = [{ name = "Mohammad Abbasi" }]
17
+
18
+ [project.scripts]
19
+ ntv-mcp = "ntv_mcp.server:main"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/ntv_mcp"]
23
+
24
+ [tool.pytest.ini_options]
25
+ markers = ["live: tests that hit the real https://www.n-tv.de site"]
@@ -0,0 +1 @@
1
+ {"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "description": "Unofficial read-only MCP server for n-tv news — headlines, markets, videos & articles.", "name": "io.github.mohammad-abbasi-sh/ntv-mcp", "packages": [{"identifier": "ntv-mcp", "registryBaseUrl": "https://pypi.org", "registryType": "pypi", "transport": {"type": "stdio"}, "version": "0.1.0"}], "repository": {"source": "github", "url": "https://github.com/mohammad-abbasi-sh/ntv-mcp"}, "title": "n-tv — German TV news: headlines by section, markets, videos & articles", "version": "0.1.0", "websiteUrl": "https://github.com/mohammad-abbasi-sh/ntv-mcp"}
@@ -0,0 +1,7 @@
1
+ """ntv_mcp — unofficial read-only MCP server for n-tv.de.
2
+
3
+ n-tv news from its official RSS feeds: latest headlines by section, market news, latest videos, keyword search and full article text. No key, no login.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,106 @@
1
+ """Domain logic: shape n-tv RSS feeds + article HTML into compact dicts
2
+ (stdlib only).
3
+
4
+ Data source: n-tv's official RSS feeds (https://www.n-tv.de/rss and
5
+ per-section /{section}/rss, /wirtschaft/boerse/rss,
6
+ /mediathek/videos/rss) and n-tv.de article pages — free, no key, no
7
+ login. There is NO dedicated breaking-news feed (/eilmeldungen/rss
8
+ 404s, verified 2026-11-10), so no breaking-news tool is offered.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import html as _html
13
+ import json
14
+ import re
15
+ import xml.etree.ElementTree as ET
16
+
17
+ BASE = "https://www.n-tv.de"
18
+
19
+ SECTIONS = {
20
+ "all", "politik", "wirtschaft", "sport", "technik", "panorama",
21
+ "wissen", "der_tag",
22
+ }
23
+
24
+ _LD_RE = re.compile(r'<script[^>]*application/ld\+json[^>]*>(.*?)</script>', re.S)
25
+ _P_RE = re.compile(r'<p[^>]*>(.*?)</p>', re.S)
26
+ _TAG_RE = re.compile(r'<[^>]+>')
27
+
28
+
29
+ def validate_section(section: str) -> str:
30
+ key = (section or "").strip().lower()
31
+ if key not in SECTIONS:
32
+ raise ValueError(
33
+ f"unsupported section: {section!r} "
34
+ f"(use one of: {', '.join(sorted(SECTIONS))})"
35
+ )
36
+ return key
37
+
38
+
39
+ def validate_limit(limit: int) -> int:
40
+ if not 1 <= limit <= 50:
41
+ raise ValueError(f"limit out of range: {limit} (expected 1..50)")
42
+ return limit
43
+
44
+
45
+ def feed_url(section: str) -> str:
46
+ if section == "all":
47
+ return f"{BASE}/rss"
48
+ return f"{BASE}/{section}/rss"
49
+
50
+
51
+ BOERSE_URL = f"{BASE}/wirtschaft/boerse/rss"
52
+ VIDEOS_URL = f"{BASE}/mediathek/videos/rss"
53
+
54
+
55
+ def _parse_xml(text: str, what: str) -> ET.Element:
56
+ try:
57
+ return ET.fromstring(text)
58
+ except ET.ParseError as e:
59
+ raise ValueError(f"invalid {what}: {e}") from e
60
+
61
+
62
+ def parse_feed(text: str) -> list[dict]:
63
+ """[{title, url, published, description, category}] — feed order."""
64
+ root = _parse_xml(text, "RSS feed")
65
+ channel = root.find("channel")
66
+ if channel is None:
67
+ raise ValueError("invalid RSS feed: no channel element")
68
+ out = []
69
+ for item in channel.findall("item"):
70
+ out.append({
71
+ "title": item.findtext("title") or "",
72
+ "url": item.findtext("link") or item.findtext("guid") or "",
73
+ "published": item.findtext("pubDate") or "",
74
+ "description": (item.findtext("description") or "").strip(),
75
+ "category": item.findtext("category") or "",
76
+ })
77
+ return out
78
+
79
+
80
+ def parse_article(html_text: str) -> dict:
81
+ """Extract headline/date (JSON-LD NewsArticle) + cleaned body <p>s.
82
+
83
+ n-tv article pages are server-rendered: the body is plain <p>
84
+ tags. The first <p> is navigation junk (starts with "Ressorts")
85
+ and is dropped. JSON-LD articleBody is empty (verified 2026-11-10).
86
+ """
87
+ headline, published = "", ""
88
+ for m in _LD_RE.finditer(html_text):
89
+ try:
90
+ ld = json.loads(m.group(1))
91
+ except json.JSONDecodeError:
92
+ continue
93
+ if isinstance(ld, dict) and ld.get("@type") == "NewsArticle":
94
+ headline = ld.get("headline") or ""
95
+ published = ld.get("datePublished") or ""
96
+ break
97
+ paras = []
98
+ for raw in _P_RE.findall(html_text):
99
+ txt = _html.unescape(_TAG_RE.sub("", raw)).replace("\u00a0", " ").strip()
100
+ if not txt:
101
+ continue
102
+ if txt.startswith("Ressorts"):
103
+ continue
104
+ paras.append(txt)
105
+ return {"headline": headline, "published": published,
106
+ "body": "\n\n".join(paras)}
@@ -0,0 +1,99 @@
1
+ """HTTP layer for ntv_mcp — plain httpx GETs against n-tv.de.
2
+
3
+ No key, no login. One retry on 429/5xx; error taxonomy (403/429/other).
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import ssl
9
+ import time
10
+
11
+ import httpx
12
+
13
+ UA = (
14
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
15
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
16
+ )
17
+ TIMEOUT = 25.0
18
+ PROBE_URL = "https://www.n-tv.de/rss"
19
+ SOURCE = "n-tv.de"
20
+
21
+
22
+ class NtvMcpError(RuntimeError):
23
+ pass
24
+
25
+
26
+ def _verify():
27
+ """TLS trust store: the OS bundle when present, else httpx/certifi."""
28
+ for path in (
29
+ "/etc/ssl/certs/ca-certificates.crt",
30
+ ssl.get_default_verify_paths().openssl_cafile,
31
+ ):
32
+ if path and os.path.exists(path):
33
+ return ssl.create_default_context(cafile=path)
34
+ return True
35
+
36
+
37
+ def _client() -> httpx.Client:
38
+ # NOTE: we read the proxy URL from the environment but never log it.
39
+ proxy = os.environ.get("https_proxy") or os.environ.get("HTTPS_PROXY")
40
+ return httpx.Client(
41
+ headers={"User-Agent": UA, "Accept": "application/json, application/xml, text/html, */*"},
42
+ timeout=TIMEOUT,
43
+ proxy=proxy or None,
44
+ trust_env=False,
45
+ verify=_verify(),
46
+ )
47
+
48
+
49
+ def fetch_text(url: str) -> str:
50
+ """GET one URL and return its text. One retry on 429/5xx."""
51
+ last_exc: Exception | None = None
52
+ r: httpx.Response | None = None
53
+ for attempt in range(2):
54
+ try:
55
+ with _client() as c:
56
+ r = c.get(url)
57
+ except httpx.HTTPError as e:
58
+ last_exc = e
59
+ if attempt == 0:
60
+ time.sleep(1.0)
61
+ continue
62
+ raise NtvMcpError(f"network error fetching {url}: {e}") from e
63
+ if r.status_code in (429, 500, 502, 503):
64
+ if attempt == 0:
65
+ time.sleep(1.0)
66
+ continue
67
+ break
68
+ assert r is not None # loop always assigns r or raises
69
+ if r.status_code == 403:
70
+ raise NtvMcpError(
71
+ f"{SOURCE} returned HTTP 403 for {url} (bot wall) — try again later"
72
+ )
73
+ if r.status_code == 429:
74
+ raise NtvMcpError(
75
+ f"{SOURCE} rate-limited the request (HTTP 429) — try again later"
76
+ )
77
+ if r.status_code != 200:
78
+ raise NtvMcpError(f"{SOURCE} returned HTTP {r.status_code} for {url}")
79
+ return r.text
80
+
81
+
82
+ def health_check() -> dict:
83
+ """One polite probe of the source site.
84
+
85
+ Returns {"status": "ok"|"blocked"|"error", "http_status": int|None,
86
+ "url": ..., "detail": ...}. Used by the `<prefix>_health` tool
87
+ and the daily smoke CI.
88
+ """
89
+ url = PROBE_URL
90
+ try:
91
+ fetch_text(url)
92
+ except NtvMcpError as e:
93
+ msg = str(e)
94
+ if "403" in msg:
95
+ return {"status": "blocked", "http_status": 403, "url": url, "detail": msg}
96
+ if "429" in msg:
97
+ return {"status": "blocked", "http_status": 429, "url": url, "detail": msg}
98
+ return {"status": "error", "http_status": None, "url": url, "detail": msg}
99
+ return {"status": "ok", "http_status": 200, "url": url}