govdata-mcp 0.1.0__py3-none-any.whl

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,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"
govdata_mcp/domain.py ADDED
@@ -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
+ }
govdata_mcp/http.py ADDED
@@ -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}
govdata_mcp/server.py ADDED
@@ -0,0 +1,140 @@
1
+ """MCP server: unofficial read-only access to Germany's national
2
+ open-data portal govdata.de via its official CKAN API. No key, no
3
+ login."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import sys
8
+ from datetime import datetime, timezone
9
+
10
+ from mcp.server.fastmcp import FastMCP
11
+
12
+ from . import domain as _dom
13
+ from . import http as _http
14
+
15
+ INSTRUCTIONS = """\
16
+ Unofficial read-only MCP server for Germany's national open-data \
17
+ portal govdata.de via its official CKAN API (no key, no login): \
18
+ search 163,000+ datasets, full dataset details, publishing \
19
+ organisations, most recently updated datasets and resource details. \
20
+ Built by Mohammad Abbasi (mohammad-abbasi-sh) โ€” \
21
+ https://almanibama.ir ยท https://mabbasi.ir โ€” Germany MCP factory.\
22
+ """
23
+
24
+ _SOURCE = "govdata.de"
25
+ _DISCLAIMER = "Unofficial read-only data from the govdata.de CKAN API; verify on the site before acting on it."
26
+
27
+
28
+ def _envelope() -> dict:
29
+ return {
30
+ "fetched_at": datetime.now(timezone.utc).isoformat(),
31
+ "source": _SOURCE,
32
+ "disclaimer": _DISCLAIMER,
33
+ }
34
+
35
+
36
+ def _ok(payload: dict) -> str:
37
+ return json.dumps({**_envelope(), **payload}, ensure_ascii=False)
38
+
39
+
40
+ def _err(e: Exception) -> str:
41
+ return _ok({"error": str(e)})
42
+
43
+
44
+ mcp = FastMCP("govdata-mcp", instructions=INSTRUCTIONS)
45
+
46
+
47
+ @mcp.tool()
48
+ def govdata_search_datasets(query: str, limit: int = 10,
49
+ sort: str = "relevance") -> str:
50
+ """Search govdata.de datasets. query: keyword or phrase, e.g.
51
+ "berlin". limit: 1..50 (default 10). sort: "relevance" or "recent"."""
52
+ try:
53
+ q = (query or "").strip()
54
+ if not q:
55
+ raise ValueError("query must not be empty")
56
+ lim = _dom.validate_limit(limit)
57
+ s = (sort or "relevance").strip().lower()
58
+ if s not in ("relevance", "recent"):
59
+ raise ValueError(f"unsupported sort: {sort!r} (relevance/recent)")
60
+ parsed = _dom.parse_search(
61
+ _http.fetch_text(_dom.search_url(q, lim, s)))
62
+ except (_http.GovdataMcpError, ValueError) as e:
63
+ return _err(e)
64
+ return _ok({"query": q, "sort": s,
65
+ "total_results": parsed["total_results"],
66
+ "count": len(parsed["items"]), "items": parsed["items"]})
67
+
68
+
69
+ @mcp.tool()
70
+ def govdata_get_dataset(dataset_id: str) -> str:
71
+ """Full details of one dataset. dataset_id: the dataset id (UUID)
72
+ or name, e.g. "wohnatlas-berlin"."""
73
+ try:
74
+ did = (dataset_id or "").strip()
75
+ if not did:
76
+ raise ValueError("dataset_id must not be empty")
77
+ out = _dom.parse_dataset(_http.fetch_text(_dom.dataset_url(did)))
78
+ except (_http.GovdataMcpError, ValueError) as e:
79
+ return _err(e)
80
+ return _ok(out)
81
+
82
+
83
+ @mcp.tool()
84
+ def govdata_list_publishers(limit: int = 10) -> str:
85
+ """Publishing organisations on govdata.de, most datasets first.
86
+ limit: 1..50 (default 10)."""
87
+ try:
88
+ lim = _dom.validate_limit(limit)
89
+ orgs = _dom.parse_publishers(
90
+ _http.fetch_text(_dom.publishers_url(50)))
91
+ except (_http.GovdataMcpError, ValueError) as e:
92
+ return _err(e)
93
+ return _ok({"total_results": len(orgs),
94
+ "count": min(lim, len(orgs)), "items": orgs[:lim]})
95
+
96
+
97
+ @mcp.tool()
98
+ def govdata_recent_datasets(limit: int = 10) -> str:
99
+ """Most recently updated datasets on govdata.de.
100
+ limit: 1..50 (default 10)."""
101
+ try:
102
+ lim = _dom.validate_limit(limit)
103
+ parsed = _dom.parse_search(
104
+ _http.fetch_text(_dom.recent_url(lim)))
105
+ except (_http.GovdataMcpError, ValueError) as e:
106
+ return _err(e)
107
+ return _ok({"total_results": parsed["total_results"],
108
+ "count": len(parsed["items"]), "items": parsed["items"]})
109
+
110
+
111
+ @mcp.tool()
112
+ def govdata_get_resource(resource_id: str) -> str:
113
+ """Details of one dataset resource (file/API download link).
114
+ resource_id: the resource UUID, shown on dataset resources."""
115
+ try:
116
+ rid = (resource_id or "").strip()
117
+ if not rid:
118
+ raise ValueError("resource_id must not be empty")
119
+ out = _dom.parse_resource(_http.fetch_text(_dom.resource_url(rid)))
120
+ except (_http.GovdataMcpError, ValueError) as e:
121
+ return _err(e)
122
+ return _ok(out)
123
+
124
+
125
+ @mcp.tool()
126
+ def govdata_health() -> str:
127
+ """Check whether govdata.de is reachable right now.
128
+
129
+ Returns status ok (HTTP 200), blocked (HTTP 403/429 โ€” bot wall or
130
+ rate limit) or error, plus the HTTP status and the probed URL.
131
+ One polite request; it does not fetch any listings."""
132
+ return _ok(_http.health_check())
133
+
134
+
135
+ def main() -> None:
136
+ mcp.run()
137
+
138
+
139
+ if __name__ == "__main__":
140
+ sys.exit(main())
@@ -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,9 @@
1
+ govdata_mcp/__init__.py,sha256=QNPc42Q4dquZ5KHwkTLPCQkGeGPyY8ClrlS0vBv_Bus,315
2
+ govdata_mcp/domain.py,sha256=uc9En0LWj2_rtttujOdnyvGfCUJ6TLndqnFNkdtsLqI,3939
3
+ govdata_mcp/http.py,sha256=9ZvQcSDxAIPcLslRbvtYsq8XbOu4WCTHSgwTSLhbxU8,3164
4
+ govdata_mcp/server.py,sha256=IR2ZtAZaG6-cBn0ynv-WN5f8nYBYMbwywsrL5m6bT44,4627
5
+ govdata_mcp-0.1.0.dist-info/METADATA,sha256=o58gKduiUHYWnflaFI43Rb4obnrdOBTHYJZCLX2O__M,2500
6
+ govdata_mcp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ govdata_mcp-0.1.0.dist-info/entry_points.txt,sha256=6nt1UOz0rOLjY9X4wX6JSOZYWG4eCIhqtHlJiHFbYzc,56
8
+ govdata_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=HsN4iUNpKeikxp-vzzw-M0KlwyflwVQKzIFR7COhaHs,1072
9
+ govdata_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ govdata-mcp = govdata_mcp.server:main
@@ -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.