govdata-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
@@ -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.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.5
2
+ Name: govdata-mcp
3
+ Version: 0.1.0
4
+ Summary: Unofficial read-only MCP server for govdata.de (German open data, CKAN) — search datasets, publishers, resources
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
+ # govdata-mcp 🗃️
14
+
15
+ mcp-name: io.github.mohammad-abbasi-sh/govdata-mcp
16
+
17
+ Unofficial **read-only** MCP server for **[govdata.de](https://www.govdata.de)** — Germany's national open-data portal govdata.de via its official CKAN API: search 163,000+ datasets, dataset details, publishers, recent datasets and resource details. No key, no login. No key, no login.
18
+
19
+ > Built by Mohammad Abbasi as part of the "Germany MCP factory". Not affiliated with govdata.de.
20
+
21
+ ## For AI agents
22
+
23
+ Add to your MCP client config (stdio):
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "govdata": {
29
+ "command": "uvx",
30
+ "args": ["govdata-mcp==0.1.0"]
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ Or run locally: `python -m govdata_mcp.server` (needs `mcp<2`, `httpx`).
37
+
38
+ ## Tools
39
+
40
+ | Tool | Description |
41
+ |------|-------------|
42
+ | `govdata_search_datasets` | Search govdata.de datasets — `query`, `limit` 1..50, `sort` (relevance/recent) |
43
+ | `govdata_get_dataset` | Full details of one dataset — `dataset_id` (id or name, e.g. "wohnatlas-berlin") |
44
+ | `govdata_list_publishers` | Publishing organisations on govdata.de, most datasets first — `limit` 1..50 |
45
+ | `govdata_recent_datasets` | Most recently updated datasets — `limit` 1..50 |
46
+ | `govdata_get_resource` | Details of one dataset resource (file/API link) — `resource_id` |
47
+ | `govdata_health` | Reachability probe (ok / blocked / error) — one polite request |
48
+
49
+ ## Notes
50
+
51
+ - All data comes from the **govdata.de CKAN API** (free, no key, no login) — 163,247 datasets at last check.
52
+ - Competition note: pipeworx-io/mcp-govdata-de (★0, 2026-11-09) covers the same portal but only ships 2 tools (`list_organizations`, `list_groups`) behind a commercial gateway and has no dataset search; this server adds search, dataset/resource details, recency and tests.
53
+
54
+ Tests: 19/19 green (13 offline + 6 live, 2026-11-10).
55
+
56
+ ## Development
57
+
58
+ ```bash
59
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
60
+ .venv/bin/pip install -e .
61
+ .venv/bin/python -m pytest tests/ -q
62
+ ```
63
+
64
+ ## License
65
+
66
+ MIT
67
+
68
+ ---
69
+
70
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,51 @@
1
+ # govdata-mcp 🗃️
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/govdata-mcp
4
+
5
+ Inoffizieller **nur lesender** MCP-Server für **[govdata.de](https://www.govdata.de)** — Deutschlands nationales Open-Data-Portal govdata.de über die offizielle CKAN-API: über 163.000 Datensätze durchsuchen, Datensatzdetails, Herausgeber, neueste Datensätze und Ressourcendetails. Kein Schlüssel, kein Login. Kein Schlüssel, keine Anmeldung.
6
+
7
+ > Gebaut von Mohammad Abbasi als Teil der "Germany MCP factory". Nicht mit govdata.de verbunden.
8
+
9
+ ## Für KI-Agenten
10
+
11
+ Zur MCP-Client-Konfiguration hinzufügen (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "govdata": {
17
+ "command": "uvx",
18
+ "args": ["govdata-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Oder lokal starten: `python -m govdata_mcp.server` (benötigt `mcp<2`, `httpx`).
25
+
26
+ ## Tools
27
+
28
+ | Tool | Beschreibung |
29
+ |------|-------------|
30
+ | `govdata_search_datasets` | Datensätze auf govdata.de suchen |
31
+ | `govdata_get_dataset` | Vollständige Details eines Datensatzes |
32
+ | `govdata_list_publishers` | Herausgeber, nach Datensatzzahl sortiert |
33
+ | `govdata_recent_datasets` | Zuletzt aktualisierte Datensätze |
34
+ | `govdata_get_resource` | Details einer Datensatz-Ressource |
35
+ | `govdata_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
+ # govdata-mcp 🗃️
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/govdata-mcp
4
+
5
+ سرور MCP غیررسمی و **فقط‌خواندنی** برای **[govdata.de](https://www.govdata.de)** — پورتال ملی داده‌های باز آلمان govdata.de از طریق API رسمی CKAN: جست‌وجو در بیش از ۱۶۳٬۰۰۰ مجموعه‌داده، جزئیات مجموعه‌داده، ناشران، تازه‌ترین مجموعه‌داده‌ها و جزئیات منبع. بدون کلید، بدون ورود. بدون کلید، بدون ورود.
6
+
7
+ > ساختهٔ محمد عباسی، بخشی از «کارخانهٔ MCP آلمان». وابسته به govdata.de نیست.
8
+
9
+ ## برای ایجنت‌های هوش مصنوعی
10
+
11
+ به پیکربندی MCP کلاینت اضافه کنید (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "govdata": {
17
+ "command": "uvx",
18
+ "args": ["govdata-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ یا به‌صورت محلی اجرا کنید: `python -m govdata_mcp.server` (نیازمند `mcp<2` و `httpx`).
25
+
26
+ ## ابزارها
27
+
28
+ | ابزار | توضیح |
29
+ |------|-------|
30
+ | `govdata_search_datasets` | جست‌وجوی مجموعه‌داده‌ها در govdata.de |
31
+ | `govdata_get_dataset` | جزئیات کامل یک مجموعه‌داده |
32
+ | `govdata_list_publishers` | ناشران، به ترتیب بیشترین مجموعه‌داده |
33
+ | `govdata_recent_datasets` | تازه‌ترین مجموعه‌داده‌های به‌روز شده |
34
+ | `govdata_get_resource` | جزئیات یک منبع مجموعه‌داده |
35
+ | `govdata_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,58 @@
1
+ # govdata-mcp 🗃️
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/govdata-mcp
4
+
5
+ Unofficial **read-only** MCP server for **[govdata.de](https://www.govdata.de)** — Germany's national open-data portal govdata.de via its official CKAN API: search 163,000+ datasets, dataset details, publishers, recent datasets and resource details. No key, no login. No key, no login.
6
+
7
+ > Built by Mohammad Abbasi as part of the "Germany MCP factory". Not affiliated with govdata.de.
8
+
9
+ ## For AI agents
10
+
11
+ Add to your MCP client config (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "govdata": {
17
+ "command": "uvx",
18
+ "args": ["govdata-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Or run locally: `python -m govdata_mcp.server` (needs `mcp<2`, `httpx`).
25
+
26
+ ## Tools
27
+
28
+ | Tool | Description |
29
+ |------|-------------|
30
+ | `govdata_search_datasets` | Search govdata.de datasets — `query`, `limit` 1..50, `sort` (relevance/recent) |
31
+ | `govdata_get_dataset` | Full details of one dataset — `dataset_id` (id or name, e.g. "wohnatlas-berlin") |
32
+ | `govdata_list_publishers` | Publishing organisations on govdata.de, most datasets first — `limit` 1..50 |
33
+ | `govdata_recent_datasets` | Most recently updated datasets — `limit` 1..50 |
34
+ | `govdata_get_resource` | Details of one dataset resource (file/API link) — `resource_id` |
35
+ | `govdata_health` | Reachability probe (ok / blocked / error) — one polite request |
36
+
37
+ ## Notes
38
+
39
+ - All data comes from the **govdata.de CKAN API** (free, no key, no login) — 163,247 datasets at last check.
40
+ - Competition note: pipeworx-io/mcp-govdata-de (★0, 2026-11-09) covers the same portal but only ships 2 tools (`list_organizations`, `list_groups`) behind a commercial gateway and has no dataset search; this server adds search, dataset/resource details, recency and tests.
41
+
42
+ Tests: 19/19 green (13 offline + 6 live, 2026-11-10).
43
+
44
+ ## Development
45
+
46
+ ```bash
47
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
48
+ .venv/bin/pip install -e .
49
+ .venv/bin/python -m pytest tests/ -q
50
+ ```
51
+
52
+ ## License
53
+
54
+ MIT
55
+
56
+ ---
57
+
58
+ 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 = "govdata-mcp"
7
+ version = "0.1.0"
8
+ description = "Unofficial read-only MCP server for govdata.de (German open data, CKAN) — search datasets, publishers, resources"
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
+ govdata-mcp = "govdata_mcp.server:main"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/govdata_mcp"]
23
+
24
+ [tool.pytest.ini_options]
25
+ markers = ["live: tests that hit the real https://www.govdata.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 govdata.de open data (CKAN) — search datasets & publishers.", "name": "io.github.mohammad-abbasi-sh/govdata-mcp", "packages": [{"identifier": "govdata-mcp", "registryBaseUrl": "https://pypi.org", "registryType": "pypi", "transport": {"type": "stdio"}, "version": "0.1.0"}], "repository": {"source": "github", "url": "https://github.com/mohammad-abbasi-sh/govdata-mcp"}, "title": "GovData — Germany's open-data portal: search 163,000+ datasets, publishers & resources", "version": "0.1.0", "websiteUrl": "https://github.com/mohammad-abbasi-sh/govdata-mcp"}
@@ -0,0 +1,7 @@
1
+ """govdata_mcp — unofficial read-only MCP server for govdata.de.
2
+
3
+ Germany's national open-data portal govdata.de via its official CKAN API: search 163,000+ datasets, dataset details, publishers, recent datasets and resource details. No key, no login.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,117 @@
1
+ """Domain logic: shape govdata.de CKAN API responses into compact
2
+ dicts (stdlib only).
3
+
4
+ Data source: the official CKAN API of Germany's national open-data
5
+ portal (https://www.govdata.de/ckan/api/3/action/...) — free, no key,
6
+ no login. Actions used: package_search, package_show,
7
+ organization_list, resource_show.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import urllib.parse
13
+
14
+ BASE = "https://www.govdata.de/ckan/api/3/action"
15
+
16
+
17
+ def validate_limit(limit: int) -> int:
18
+ if not 1 <= limit <= 50:
19
+ raise ValueError(f"limit out of range: {limit} (expected 1..50)")
20
+ return limit
21
+
22
+
23
+ def search_url(query: str, rows: int, sort: str) -> str:
24
+ params = {"q": query, "rows": str(rows)}
25
+ if sort == "recent":
26
+ params["sort"] = "metadata_modified desc"
27
+ return BASE + "/package_search?" + urllib.parse.urlencode(params)
28
+
29
+
30
+ def recent_url(rows: int) -> str:
31
+ params = {"rows": str(rows), "sort": "metadata_modified desc"}
32
+ return BASE + "/package_search?" + urllib.parse.urlencode(params)
33
+
34
+
35
+ def dataset_url(dataset_id: str) -> str:
36
+ return BASE + "/package_show?" + urllib.parse.urlencode({"id": dataset_id})
37
+
38
+
39
+ def publishers_url(limit: int) -> str:
40
+ params = {"all_fields": "true", "limit": str(limit)}
41
+ return BASE + "/organization_list?" + urllib.parse.urlencode(params)
42
+
43
+
44
+ def resource_url(resource_id: str) -> str:
45
+ return BASE + "/resource_show?" + urllib.parse.urlencode({"id": resource_id})
46
+
47
+
48
+ def _load(text: str, what: str) -> dict:
49
+ try:
50
+ data = json.loads(text)
51
+ except json.JSONDecodeError as e:
52
+ raise ValueError(f"invalid {what}: {e}") from e
53
+ if not data.get("success"):
54
+ err = data.get("error") or {}
55
+ raise ValueError(f"govdata.de error: {err.get('message') or err}")
56
+ return data["result"]
57
+
58
+
59
+ def _compact_dataset(pkg: dict) -> dict:
60
+ org = pkg.get("organization") or {}
61
+ return {
62
+ "id": pkg.get("id") or "",
63
+ "name": pkg.get("name") or "",
64
+ "title": pkg.get("title") or "",
65
+ "notes": (pkg.get("notes") or "")[:400],
66
+ "organization": org.get("title") or org.get("name") or "",
67
+ "license": pkg.get("license_title") or "",
68
+ "num_resources": pkg.get("num_resources") or 0,
69
+ "tags": [t.get("name") for t in (pkg.get("tags") or [])[:5]],
70
+ "metadata_modified": pkg.get("metadata_modified") or "",
71
+ "resources": [
72
+ {"id": r.get("id") or "", "name": r.get("name") or "",
73
+ "format": r.get("format") or "", "url": r.get("url") or ""}
74
+ for r in (pkg.get("resources") or [])[:10]
75
+ ],
76
+ }
77
+
78
+
79
+ def parse_search(text: str) -> dict:
80
+ result = _load(text, "package_search response")
81
+ return {
82
+ "total_results": result.get("count") or 0,
83
+ "items": [_compact_dataset(p) for p in result.get("results") or []],
84
+ }
85
+
86
+
87
+ def parse_dataset(text: str) -> dict:
88
+ return _compact_dataset(_load(text, "package_show response"))
89
+
90
+
91
+ def parse_publishers(text: str) -> list[dict]:
92
+ result = _load(text, "organization_list response")
93
+ orgs = [{
94
+ "id": o.get("id") or "",
95
+ "name": o.get("name") or "",
96
+ "title": o.get("title") or "",
97
+ "package_count": o.get("package_count") or 0,
98
+ "description": (o.get("description") or "")[:200],
99
+ } for o in result]
100
+ orgs.sort(key=lambda o: o["package_count"], reverse=True)
101
+ return orgs
102
+
103
+
104
+ def parse_resource(text: str) -> dict:
105
+ r = _load(text, "resource_show response")
106
+ return {
107
+ "id": r.get("id") or "",
108
+ "name": r.get("name") or "",
109
+ "format": r.get("format") or "",
110
+ "url": r.get("url") or r.get("download_url") or "",
111
+ "description": (r.get("description") or "")[:400],
112
+ "size": r.get("size"),
113
+ "mimetype": r.get("mimetype") or "",
114
+ "created": r.get("created") or "",
115
+ "last_modified": r.get("last_modified") or "",
116
+ "package_id": r.get("package_id") or "",
117
+ }
@@ -0,0 +1,99 @@
1
+ """HTTP layer for govdata_mcp — plain httpx GETs against govdata.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.govdata.de/ckan/api/3/action/package_search?q=berlin&rows=1"
19
+ SOURCE = "govdata.de"
20
+
21
+
22
+ class GovdataMcpError(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 GovdataMcpError(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 GovdataMcpError(
71
+ f"{SOURCE} returned HTTP 403 for {url} (bot wall) — try again later"
72
+ )
73
+ if r.status_code == 429:
74
+ raise GovdataMcpError(
75
+ f"{SOURCE} rate-limited the request (HTTP 429) — try again later"
76
+ )
77
+ if r.status_code != 200:
78
+ raise GovdataMcpError(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 GovdataMcpError 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}