dnb-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.
dnb_mcp/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """dnb_mcp — unofficial read-only MCP server for services.dnb.de.
2
+
3
+ Deutsche Nationalbibliothek catalogue via its official SRU API: keyword, title and author search, ISBN and DNB-ID lookup. No key, no login.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ __version__ = "0.1.0"
dnb_mcp/domain.py ADDED
@@ -0,0 +1,119 @@
1
+ """Domain logic: shape DNB SRU (MARC21-xml) responses into compact
2
+ dicts (stdlib only).
3
+
4
+ Data source: the Deutsche Nationalbibliothek SRU API
5
+ (https://services.dnb.de/sru/dnb) — free, no key, no login.
6
+ CQL indexes used (from the API's own explain response, verified
7
+ 2026-11-10): woe (all terms), tit (title), per (person/author),
8
+ num (number — incl. ISBN), idn (DNB identifier).
9
+
10
+ NOT offered: a newspapers-only search — the `mat` (material type)
11
+ index returns 0 for every German value tried (Bücher, Zeitschriften,
12
+ Zeitung, Zeitungen, Online-Ressource), so no reliable newspaper
13
+ filter exists; newspapers are still found by the keyword/title
14
+ searches. Dublin Core recordSchema is unsupported ("Unknown schema
15
+ for retrieval") — MARC21-xml only.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ import urllib.parse
21
+ import xml.etree.ElementTree as ET
22
+
23
+ BASE = "https://services.dnb.de/sru/dnb"
24
+
25
+ SRW = "{http://www.loc.gov/zing/srw/}"
26
+ M = "{http://www.loc.gov/MARC21/slim}"
27
+
28
+ _ISBN_RE = re.compile(r"^[\d-]{10,17}[0-9Xx]$")
29
+
30
+
31
+ def validate_limit(limit: int) -> int:
32
+ if not 1 <= limit <= 50:
33
+ raise ValueError(f"limit out of range: {limit} (expected 1..50)")
34
+ return limit
35
+
36
+
37
+ def validate_isbn(isbn: str) -> str:
38
+ key = (isbn or "").strip().replace(" ", "")
39
+ if not _ISBN_RE.match(key) or not 10 <= len(key.replace("-", "")) <= 13:
40
+ raise ValueError(f"invalid ISBN: {isbn!r} "
41
+ "(expected 10 or 13 digits, dashes allowed)")
42
+ return key
43
+
44
+
45
+ def validate_dnb_id(dnb_id: str) -> str:
46
+ key = (dnb_id or "").strip()
47
+ if not key.isdigit():
48
+ raise ValueError(f"invalid DNB identifier: {dnb_id!r} "
49
+ "(expected digits, e.g. \"1306459214\")")
50
+ return key
51
+
52
+
53
+ def search_url(query: str, maximum_records: int = 10) -> str:
54
+ params = {
55
+ "operation": "searchRetrieve",
56
+ "version": "1.1",
57
+ "query": query,
58
+ "recordSchema": "MARC21-xml",
59
+ "maximumRecords": str(maximum_records),
60
+ }
61
+ return BASE + "?" + urllib.parse.urlencode(params)
62
+
63
+
64
+ def _subs(record, tag, code):
65
+ return [s.text.strip() for df in record.findall(f"{M}datafield[@tag='{tag}']")
66
+ for s in df.findall(f"{M}subfield[@code='{code}']")
67
+ if (s.text or "").strip()]
68
+
69
+
70
+ def _first(record, tag, code):
71
+ vals = _subs(record, tag, code)
72
+ return vals[0] if vals else ""
73
+
74
+
75
+ def _compact(record) -> dict:
76
+ title = _first(record, "245", "a")
77
+ subtitle = _first(record, "245", "b")
78
+ if subtitle:
79
+ title = f"{title} : {subtitle}"
80
+ author = _first(record, "100", "a") or _first(record, "110", "a")
81
+ return {
82
+ "dnb_id": (record.findtext(f"{M}controlfield[@tag='001']") or "").strip(),
83
+ "title": title,
84
+ "author": author,
85
+ "contributors": _subs(record, "700", "a")[:3],
86
+ "year": _first(record, "264", "c"),
87
+ "publisher": _first(record, "264", "b"),
88
+ "place": _first(record, "264", "a"),
89
+ "edition": _first(record, "250", "a"),
90
+ "isbn": _first(record, "020", "a"),
91
+ "language": _first(record, "041", "a"),
92
+ "pages": _first(record, "300", "a"),
93
+ "subjects": _subs(record, "653", "a")[:5],
94
+ "url": _first(record, "856", "u"),
95
+ }
96
+
97
+
98
+ def parse_search(text: str) -> dict:
99
+ """Parse an SRU searchRetrieve response -> {total_results, items}."""
100
+ try:
101
+ root = ET.fromstring(text)
102
+ except ET.ParseError as e:
103
+ raise ValueError(f"invalid SRU response: {e}") from e
104
+ diag = root.find(f"{SRW}diagnostics")
105
+ if diag is not None:
106
+ details = diag.findtext(".//{http://www.loc.gov/zing/srw/diagnostic/}details") or ""
107
+ msg = diag.findtext(".//{http://www.loc.gov/zing/srw/diagnostic/}message") or ""
108
+ raise ValueError(f"DNB SRU error: {details} ({msg})".strip())
109
+ total = root.findtext(f"{SRW}numberOfRecords")
110
+ try:
111
+ total_n = int(total or "0")
112
+ except ValueError:
113
+ total_n = 0
114
+ items = []
115
+ for rec in root.findall(f"{SRW}records/{SRW}record"):
116
+ data = rec.find(f"{SRW}recordData/{M}record")
117
+ if data is not None:
118
+ items.append(_compact(data))
119
+ return {"total_results": total_n, "items": items}
dnb_mcp/http.py ADDED
@@ -0,0 +1,99 @@
1
+ """HTTP layer for dnb_mcp — plain httpx GETs against services.dnb.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://services.dnb.de/sru/dnb?operation=searchRetrieve&version=1.1&query=woe%3DKafka&recordSchema=MARC21-xml&maximumRecords=1"
19
+ SOURCE = "services.dnb.de"
20
+
21
+
22
+ class DnbMcpError(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 DnbMcpError(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 DnbMcpError(
71
+ f"{SOURCE} returned HTTP 403 for {url} (bot wall) — try again later"
72
+ )
73
+ if r.status_code == 429:
74
+ raise DnbMcpError(
75
+ f"{SOURCE} rate-limited the request (HTTP 429) — try again later"
76
+ )
77
+ if r.status_code != 200:
78
+ raise DnbMcpError(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 DnbMcpError 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}
dnb_mcp/server.py ADDED
@@ -0,0 +1,145 @@
1
+ """MCP server: unofficial read-only access to the Deutsche
2
+ Nationalbibliothek catalogue via its official SRU API. No key, no
3
+ login. NOTE: the `mat` (material type) index returns 0 for every
4
+ German value tried, so no newspapers-only filter is offered."""
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import sys
9
+ from datetime import datetime, timezone
10
+
11
+ from mcp.server.fastmcp import FastMCP
12
+
13
+ from . import domain as _dom
14
+ from . import http as _http
15
+
16
+ INSTRUCTIONS = """\
17
+ Unofficial read-only MCP server for the Deutsche \
18
+ Nationalbibliothek catalogue via its official SRU API (no key, no \
19
+ login): keyword, title and author search, ISBN lookup and full \
20
+ records by DNB identifier. NOTE: the SRU `mat` (material type) \
21
+ index returns 0 for every German value tried, so no newspapers-only \
22
+ filter is offered — newspapers are still found by the keyword and \
23
+ title searches. Built by Mohammad Abbasi (mohammad-abbasi-sh) — \
24
+ https://almanibama.ir · https://mabbasi.ir — Germany MCP factory.\
25
+ """
26
+
27
+ _SOURCE = "services.dnb.de"
28
+ _DISCLAIMER = "Unofficial read-only data from the Deutsche Nationalbibliothek SRU API; verify on dnb.de before acting on it."
29
+
30
+
31
+ def _envelope() -> dict:
32
+ return {
33
+ "fetched_at": datetime.now(timezone.utc).isoformat(),
34
+ "source": _SOURCE,
35
+ "disclaimer": _DISCLAIMER,
36
+ }
37
+
38
+
39
+ def _ok(payload: dict) -> str:
40
+ return json.dumps({**_envelope(), **payload}, ensure_ascii=False)
41
+
42
+
43
+ def _err(e: Exception) -> str:
44
+ return _ok({"error": str(e)})
45
+
46
+
47
+ mcp = FastMCP("dnb-mcp", instructions=INSTRUCTIONS)
48
+
49
+
50
+ def _search(cql: str, limit: int) -> dict:
51
+ lim = _dom.validate_limit(limit)
52
+ parsed = _dom.parse_search(
53
+ _http.fetch_text(_dom.search_url(cql, maximum_records=lim)))
54
+ return {"total_results": parsed["total_results"],
55
+ "count": len(parsed["items"]), "items": parsed["items"]}
56
+
57
+
58
+ @mcp.tool()
59
+ def dnb_search_books(query: str, limit: int = 10) -> str:
60
+ """Keyword search across the whole DNB catalogue (all fields).
61
+ query: keyword or phrase, e.g. "Kafka". limit: 1..50 (default 10)."""
62
+ try:
63
+ q = (query or "").strip()
64
+ if not q:
65
+ raise ValueError("query must not be empty")
66
+ out = _search(f"woe={q}", limit)
67
+ except (_http.DnbMcpError, ValueError) as e:
68
+ return _err(e)
69
+ return _ok({"query": q, **out})
70
+
71
+
72
+ @mcp.tool()
73
+ def dnb_search_by_title(title: str, limit: int = 10) -> str:
74
+ """Search the DNB catalogue by title. title: e.g. "Briefe 1921-1922".
75
+ limit: 1..50 (default 10)."""
76
+ try:
77
+ q = (title or "").strip()
78
+ if not q:
79
+ raise ValueError("title must not be empty")
80
+ out = _search(f"tit={q}", limit)
81
+ except (_http.DnbMcpError, ValueError) as e:
82
+ return _err(e)
83
+ return _ok({"title": q, **out})
84
+
85
+
86
+ @mcp.tool()
87
+ def dnb_search_by_author(author: str, limit: int = 10) -> str:
88
+ """Search the DNB catalogue by author. author: e.g. "Kafka, Franz".
89
+ limit: 1..50 (default 10)."""
90
+ try:
91
+ q = (author or "").strip()
92
+ if not q:
93
+ raise ValueError("author must not be empty")
94
+ out = _search(f"per={q}", limit)
95
+ except (_http.DnbMcpError, ValueError) as e:
96
+ return _err(e)
97
+ return _ok({"author": q, **out})
98
+
99
+
100
+ @mcp.tool()
101
+ def dnb_by_isbn(isbn: str) -> str:
102
+ """Look up one book by ISBN. isbn: 10 or 13 digits, dashes allowed,
103
+ e.g. "9783100381682"."""
104
+ try:
105
+ key = _dom.validate_isbn(isbn)
106
+ out = _search(f"num={key}", 1)
107
+ if not out["items"]:
108
+ return _ok({"isbn": key, "total_results": 0, "count": 0,
109
+ "items": []})
110
+ except (_http.DnbMcpError, ValueError) as e:
111
+ return _err(e)
112
+ return _ok({"isbn": key, **out})
113
+
114
+
115
+ @mcp.tool()
116
+ def dnb_get_record(dnb_id: str) -> str:
117
+ """Full record by DNB identifier. dnb_id: digits, e.g. "1306459214"
118
+ (the ID shown on every record)."""
119
+ try:
120
+ key = _dom.validate_dnb_id(dnb_id)
121
+ out = _search(f"idn={key}", 1)
122
+ if not out["items"]:
123
+ return _ok({"dnb_id": key, "total_results": 0, "count": 0,
124
+ "items": []})
125
+ except (_http.DnbMcpError, ValueError) as e:
126
+ return _err(e)
127
+ return _ok({"dnb_id": key, **out})
128
+
129
+
130
+ @mcp.tool()
131
+ def dnb_health() -> str:
132
+ """Check whether services.dnb.de is reachable right now.
133
+
134
+ Returns status ok (HTTP 200), blocked (HTTP 403/429 — bot wall or
135
+ rate limit) or error, plus the HTTP status and the probed URL.
136
+ One polite request; it does not fetch any listings."""
137
+ return _ok(_http.health_check())
138
+
139
+
140
+ def main() -> None:
141
+ mcp.run()
142
+
143
+
144
+ if __name__ == "__main__":
145
+ sys.exit(main())
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.5
2
+ Name: dnb-mcp
3
+ Version: 0.1.0
4
+ Summary: Unofficial read-only MCP server for the Deutsche Nationalbibliothek catalogue (DNB SRU) — books, authors, ISBN
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
+ # dnb-mcp 📚
14
+
15
+ mcp-name: io.github.mohammad-abbasi-sh/dnb-mcp
16
+
17
+ Unofficial **read-only** MCP server for **[services.dnb.de](https://www.dnb.de)** — Deutsche Nationalbibliothek catalogue via its official SRU API: keyword, title and author search, ISBN and DNB-ID lookup. No key, no login. No key, no login.
18
+
19
+ > Built by Mohammad Abbasi as part of the "Germany MCP factory". Not affiliated with services.dnb.de.
20
+
21
+ ## For AI agents
22
+
23
+ Add to your MCP client config (stdio):
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "dnb": {
29
+ "command": "uvx",
30
+ "args": ["dnb-mcp==0.1.0"]
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ Or run locally: `python -m dnb_mcp.server` (needs `mcp<2`, `httpx`).
37
+
38
+ ## Tools
39
+
40
+ | Tool | Description |
41
+ |------|-------------|
42
+ | `dnb_search_books` | Keyword search across the DNB catalogue — `query`, `limit` 1..50 |
43
+ | `dnb_search_by_title` | Title search — `title`, `limit` 1..50 |
44
+ | `dnb_search_by_author` | Author search — `author` (e.g. "Kafka, Franz"), `limit` 1..50 |
45
+ | `dnb_by_isbn` | Look up one book by ISBN — `isbn` (13 or 10 digits, with or without dashes) |
46
+ | `dnb_get_record` | Full record by DNB identifier — `dnb_id` (e.g. "1306459214") |
47
+ | `dnb_health` | Reachability probe (ok / blocked / error) — one polite request |
48
+
49
+ ## Notes
50
+
51
+ - All data comes from the **Deutsche Nationalbibliothek SRU API** (free, no key, no login).
52
+ - Indexes used (from the API's own explain response): `woe` (all terms), `tit` (title), `per` (person/author), `num` (number incl. ISBN), `idn` (DNB identifier).
53
+ - There is **no newspapers-only filter**: the `mat` (material type) index returns 0 for every German value tried (Bücher, Zeitschriften, Zeitung, Zeitungen, Online-Ressource), so no newspapers-only tool is offered; newspapers are still found by the keyword and title searches.
54
+ - Dublin Core recordSchema is unsupported by the API — MARC21-xml only.
55
+
56
+ Tests: 20/20 green (14 offline + 6 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,9 @@
1
+ dnb_mcp/__init__.py,sha256=37fBPHxxbn7BDs9iesg8V7zWcU2YzZBiQJB7k49Kbj0,271
2
+ dnb_mcp/domain.py,sha256=YcYh7JoXunRbaUhe98IjVKx227x2KsV7c0cfTy-Fvdg,4198
3
+ dnb_mcp/http.py,sha256=VxdQmvGObbIxD6vVgxj-GZQVyefVMflSsQRyeEtlYjQ,3202
4
+ dnb_mcp/server.py,sha256=JWQkWk5I17a4eM26TUBs9nLfSVaF4RuOQhuyvl6dzl8,4647
5
+ dnb_mcp-0.1.0.dist-info/METADATA,sha256=yLpocgeEEM_YPTm2LGzoPqKSTQZBvX261WUngc6bQSE,2575
6
+ dnb_mcp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ dnb_mcp-0.1.0.dist-info/entry_points.txt,sha256=ZfS4P-hGyNtcTe__f_yURUxzTb-qnoDzfam2oItgqb8,48
8
+ dnb_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=HsN4iUNpKeikxp-vzzw-M0KlwyflwVQKzIFR7COhaHs,1072
9
+ dnb_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
+ dnb-mcp = dnb_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.