hadathana-mcp 0.2.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abdo Kamar
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,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: hadathana-mcp
3
+ Version: 0.2.0
4
+ Summary: MCP server over the Hadathna API: Sahih al-Bukhari hadiths and their narrators
5
+ Keywords: mcp,hadith,bukhari,arabic,islam
6
+ Author: Abdo Kamar
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Natural Language :: Arabic
11
+ Classifier: Topic :: Religion
12
+ Requires-Dist: mcp>=2.3,<3
13
+ Requires-Dist: httpx>=0.27,<1
14
+ Requires-Python: >=3.11
15
+ Project-URL: Repository, https://github.com/abdelrahmaan/hadathana-mcp
16
+ Project-URL: Issues, https://github.com/abdelrahmaan/hadathana-mcp/issues
17
+ Description-Content-Type: text/markdown
18
+
19
+ # hadathana-mcp
20
+
21
+ An MCP server over Sahih al-Bukhari: its hadiths, their chains of narrators, and the
22
+ narrators' biographies. Any MCP client (Claude, Codex, Cursor, VS Code, your own agent)
23
+ can ask it questions, and the model answers with hadith numbers it can cite.
24
+
25
+ It reads the public Hadathna API (`https://api.hadathana.app`). No key, no account.
26
+
27
+ <!-- mcp-name: io.github.abdelrahmaan/hadathana-mcp -->
28
+
29
+ ## Tools
30
+
31
+ | Tool | What it does |
32
+ |---|---|
33
+ | `search_hadiths` | Search by words in the text, narrator, book or topic; at most 20 entries a page, each with its `citation` and `page_url` |
34
+ | `search_hadiths_by_meaning` | Search by meaning: the idea in other words; write the query in Arabic; at most 20 entries |
35
+ | `get_hadith` | The whole entry for a hadith number: sanad, matn, tawabi, chains (each with a `summary` in words), its `citation` and its `page_url` |
36
+ | `verify_quote` | Check that quoted words occur letter for letter in a hadith's sanad or matn, in one hadith (`number`) or the whole book; each match gives the entry's own wording, the text around it, whether the sentence goes on, `citation` and `page_url` |
37
+ | `search_narrators` | Find a narrator's `narrator_id` by name; each result carries its `page_url` |
38
+ | `get_narrator` | Name, rank, hadith count, top teachers and students, each with `page_url` |
39
+ | `get_narrator_biography` | What the classical tarajim books say, source by source: each source keeps its end within a per-source limit and a total budget; `source` and `offset` read one source fully in pages |
40
+ | `list_topics` | The topics hadiths are tagged with |
41
+
42
+ All tools are read-only. Inputs are Arabic; diacritics and hamza forms do not matter.
43
+
44
+ `page_url` is the reader's page on Hadathana (`https://www.hadathana.app/hadith/<number>` or
45
+ `/narrator/<id>`), the link to cite. The source site's page is not returned.
46
+
47
+ Every hadith entry also carries `citation`, the reference in words, built only from the
48
+ entry's own book, chapter and hadith numbers (Western digits, every number listed):
49
+ «صحيح البخاري، كتاب الصوم، باب وجوب صوم رمضان، رقم (1891)». It names no edition, volume or
50
+ page. Cite a hadith with `citation` and `page_url` together.
51
+
52
+ Search results stay small: at most 20 entries per call, and a matn longer than 800
53
+ characters is cut to its first 800 with «…» and `matn_truncated: true`; `get_hadith`
54
+ returns the whole matn. Page through `search_hadiths` with `offset` and `next_offset`.
55
+
56
+ `verify_quote` takes the quoted words (`text`, 2 to 300 characters) and, optionally, a
57
+ hadith `number`. It ignores diacritics, tatweel, hamza forms, ة/ه, ى/ي, punctuation and
58
+ spacing, and matches whole words only. Without `number` it finds candidates with the phrase
59
+ search and reads up to 5 entries in full, so a call makes at most 8 API requests and
60
+ returns at most 3 matches. `found: false` means not letter for letter; for a paraphrase,
61
+ use `search_hadiths_by_meaning`.
62
+
63
+ A refused argument (a number out of range, a search with nothing to filter by) comes
64
+ back as a sentence that says what to try instead, not as a validation dump.
65
+ Each chain's `summary` reads the chain in order, from al-Bukhari's teacher to the
66
+ last link, without adding a name the data does not hold.
67
+
68
+ The evals in `evals/` score 21 Arabic questions end to end — the answer, the tools called and
69
+ the bytes those tools returned — without an LLM judge; `evals/README.md` shows how to run them.
70
+
71
+ ## Install
72
+
73
+ It needs [uv](https://docs.astral.sh/uv/). `uvx` downloads and runs the one version you pin.
74
+
75
+ **Claude Code**
76
+
77
+ ```bash
78
+ claude mcp add hadathna -- uvx hadathana-mcp@0.2.0
79
+ ```
80
+
81
+ **Claude Desktop, Cursor, VS Code** (the `mcpServers` block of the client's config)
82
+
83
+ ```json
84
+ {
85
+ "mcpServers": {
86
+ "hadathna": { "command": "uvx", "args": ["hadathana-mcp@0.2.0"] }
87
+ }
88
+ }
89
+ ```
90
+
91
+ **Codex** (`~/.codex/config.toml`)
92
+
93
+ ```toml
94
+ [mcp_servers.hadathna]
95
+ command = "uvx"
96
+ args = ["hadathana-mcp@0.2.0"]
97
+ ```
98
+
99
+ Then ask, for example: «ما هو حديث بدء الوحي؟» or «من هو أبو هريرة؟».
100
+
101
+ ## Settings
102
+
103
+ | Variable | Default | Use |
104
+ |---|---|---|
105
+ | `HADATHNA_API_URL` | `https://api.hadathana.app` | Point at another copy of the API, such as a local one |
106
+ | `HADATHNA_SITE_URL` | `https://www.hadathana.app` | Point `page_url` at another copy of the site |
107
+ | `HADATHNA_HTTP_HOST` | `127.0.0.1` | Address for `--http`; the container sets `0.0.0.0` |
108
+ | `HADATHNA_HTTP_PORT` | `8765` | Port for `--http`; `--port` wins over it |
109
+ | `HADATHNA_ALLOWED_HOSTS` | the package's default | Host headers `--http` accepts, comma-separated, such as `mcp.hadathana.app,mcp-dev.hadathana.app` |
110
+ | `HADATHNA_MAX_CONCURRENT` | `16` | Tool calls that may run at once; one that waits over 10 seconds for a slot is told to retry |
111
+
112
+ ## Remote
113
+
114
+ `https://mcp.hadathana.app/mcp` is a hosted Streamable HTTP copy: the same eight tools, no
115
+ sign-in and no key. It is public and read-only, rate limited per client, and the
116
+ container holds no secret — it reaches only the public API.
117
+
118
+ **claude.ai** — Customize > Connectors > Add custom connector, URL
119
+ `https://mcp.hadathana.app/mcp`, Authentication «No sign in».
120
+
121
+ **Claude Code**
122
+
123
+ ```bash
124
+ claude mcp add --transport http hadathna https://mcp.hadathana.app/mcp
125
+ ```
126
+
127
+ **Cursor** (the `mcpServers` block of the client's config)
128
+
129
+ ```json
130
+ {
131
+ "mcpServers": {
132
+ "hadathna": { "url": "https://mcp.hadathana.app/mcp" }
133
+ }
134
+ }
135
+ ```
136
+
137
+ **Codex**
138
+
139
+ ```bash
140
+ codex mcp add hadathna --url https://mcp.hadathana.app/mcp
141
+ ```
142
+
143
+ **ChatGPT** — on Business, Enterprise and Edu plans, add it as a custom MCP server with
144
+ URL `https://mcp.hadathana.app/mcp` and **No authentication**.
145
+
146
+ The same server runs on your machine over stdio, as installed above.
147
+
148
+ ## What it sends
149
+
150
+ Each call to the API carries two headers, `User-Agent: hadathna-mcp/<version>` and
151
+ `X-MCP-Tool: <tool name>`, so the API can count calls per tool and version. Nothing
152
+ else is sent: not your question, not the model's text, no identifier.
153
+
154
+ ## Source
155
+
156
+ [github.com/abdelrahmaan/hadathana-mcp](https://github.com/abdelrahmaan/hadathana-mcp).
157
+
158
+ ## License
159
+
160
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,142 @@
1
+ # hadathana-mcp
2
+
3
+ An MCP server over Sahih al-Bukhari: its hadiths, their chains of narrators, and the
4
+ narrators' biographies. Any MCP client (Claude, Codex, Cursor, VS Code, your own agent)
5
+ can ask it questions, and the model answers with hadith numbers it can cite.
6
+
7
+ It reads the public Hadathna API (`https://api.hadathana.app`). No key, no account.
8
+
9
+ <!-- mcp-name: io.github.abdelrahmaan/hadathana-mcp -->
10
+
11
+ ## Tools
12
+
13
+ | Tool | What it does |
14
+ |---|---|
15
+ | `search_hadiths` | Search by words in the text, narrator, book or topic; at most 20 entries a page, each with its `citation` and `page_url` |
16
+ | `search_hadiths_by_meaning` | Search by meaning: the idea in other words; write the query in Arabic; at most 20 entries |
17
+ | `get_hadith` | The whole entry for a hadith number: sanad, matn, tawabi, chains (each with a `summary` in words), its `citation` and its `page_url` |
18
+ | `verify_quote` | Check that quoted words occur letter for letter in a hadith's sanad or matn, in one hadith (`number`) or the whole book; each match gives the entry's own wording, the text around it, whether the sentence goes on, `citation` and `page_url` |
19
+ | `search_narrators` | Find a narrator's `narrator_id` by name; each result carries its `page_url` |
20
+ | `get_narrator` | Name, rank, hadith count, top teachers and students, each with `page_url` |
21
+ | `get_narrator_biography` | What the classical tarajim books say, source by source: each source keeps its end within a per-source limit and a total budget; `source` and `offset` read one source fully in pages |
22
+ | `list_topics` | The topics hadiths are tagged with |
23
+
24
+ All tools are read-only. Inputs are Arabic; diacritics and hamza forms do not matter.
25
+
26
+ `page_url` is the reader's page on Hadathana (`https://www.hadathana.app/hadith/<number>` or
27
+ `/narrator/<id>`), the link to cite. The source site's page is not returned.
28
+
29
+ Every hadith entry also carries `citation`, the reference in words, built only from the
30
+ entry's own book, chapter and hadith numbers (Western digits, every number listed):
31
+ «صحيح البخاري، كتاب الصوم، باب وجوب صوم رمضان، رقم (1891)». It names no edition, volume or
32
+ page. Cite a hadith with `citation` and `page_url` together.
33
+
34
+ Search results stay small: at most 20 entries per call, and a matn longer than 800
35
+ characters is cut to its first 800 with «…» and `matn_truncated: true`; `get_hadith`
36
+ returns the whole matn. Page through `search_hadiths` with `offset` and `next_offset`.
37
+
38
+ `verify_quote` takes the quoted words (`text`, 2 to 300 characters) and, optionally, a
39
+ hadith `number`. It ignores diacritics, tatweel, hamza forms, ة/ه, ى/ي, punctuation and
40
+ spacing, and matches whole words only. Without `number` it finds candidates with the phrase
41
+ search and reads up to 5 entries in full, so a call makes at most 8 API requests and
42
+ returns at most 3 matches. `found: false` means not letter for letter; for a paraphrase,
43
+ use `search_hadiths_by_meaning`.
44
+
45
+ A refused argument (a number out of range, a search with nothing to filter by) comes
46
+ back as a sentence that says what to try instead, not as a validation dump.
47
+ Each chain's `summary` reads the chain in order, from al-Bukhari's teacher to the
48
+ last link, without adding a name the data does not hold.
49
+
50
+ The evals in `evals/` score 21 Arabic questions end to end — the answer, the tools called and
51
+ the bytes those tools returned — without an LLM judge; `evals/README.md` shows how to run them.
52
+
53
+ ## Install
54
+
55
+ It needs [uv](https://docs.astral.sh/uv/). `uvx` downloads and runs the one version you pin.
56
+
57
+ **Claude Code**
58
+
59
+ ```bash
60
+ claude mcp add hadathna -- uvx hadathana-mcp@0.2.0
61
+ ```
62
+
63
+ **Claude Desktop, Cursor, VS Code** (the `mcpServers` block of the client's config)
64
+
65
+ ```json
66
+ {
67
+ "mcpServers": {
68
+ "hadathna": { "command": "uvx", "args": ["hadathana-mcp@0.2.0"] }
69
+ }
70
+ }
71
+ ```
72
+
73
+ **Codex** (`~/.codex/config.toml`)
74
+
75
+ ```toml
76
+ [mcp_servers.hadathna]
77
+ command = "uvx"
78
+ args = ["hadathana-mcp@0.2.0"]
79
+ ```
80
+
81
+ Then ask, for example: «ما هو حديث بدء الوحي؟» or «من هو أبو هريرة؟».
82
+
83
+ ## Settings
84
+
85
+ | Variable | Default | Use |
86
+ |---|---|---|
87
+ | `HADATHNA_API_URL` | `https://api.hadathana.app` | Point at another copy of the API, such as a local one |
88
+ | `HADATHNA_SITE_URL` | `https://www.hadathana.app` | Point `page_url` at another copy of the site |
89
+ | `HADATHNA_HTTP_HOST` | `127.0.0.1` | Address for `--http`; the container sets `0.0.0.0` |
90
+ | `HADATHNA_HTTP_PORT` | `8765` | Port for `--http`; `--port` wins over it |
91
+ | `HADATHNA_ALLOWED_HOSTS` | the package's default | Host headers `--http` accepts, comma-separated, such as `mcp.hadathana.app,mcp-dev.hadathana.app` |
92
+ | `HADATHNA_MAX_CONCURRENT` | `16` | Tool calls that may run at once; one that waits over 10 seconds for a slot is told to retry |
93
+
94
+ ## Remote
95
+
96
+ `https://mcp.hadathana.app/mcp` is a hosted Streamable HTTP copy: the same eight tools, no
97
+ sign-in and no key. It is public and read-only, rate limited per client, and the
98
+ container holds no secret — it reaches only the public API.
99
+
100
+ **claude.ai** — Customize > Connectors > Add custom connector, URL
101
+ `https://mcp.hadathana.app/mcp`, Authentication «No sign in».
102
+
103
+ **Claude Code**
104
+
105
+ ```bash
106
+ claude mcp add --transport http hadathna https://mcp.hadathana.app/mcp
107
+ ```
108
+
109
+ **Cursor** (the `mcpServers` block of the client's config)
110
+
111
+ ```json
112
+ {
113
+ "mcpServers": {
114
+ "hadathna": { "url": "https://mcp.hadathana.app/mcp" }
115
+ }
116
+ }
117
+ ```
118
+
119
+ **Codex**
120
+
121
+ ```bash
122
+ codex mcp add hadathna --url https://mcp.hadathana.app/mcp
123
+ ```
124
+
125
+ **ChatGPT** — on Business, Enterprise and Edu plans, add it as a custom MCP server with
126
+ URL `https://mcp.hadathana.app/mcp` and **No authentication**.
127
+
128
+ The same server runs on your machine over stdio, as installed above.
129
+
130
+ ## What it sends
131
+
132
+ Each call to the API carries two headers, `User-Agent: hadathna-mcp/<version>` and
133
+ `X-MCP-Tool: <tool name>`, so the API can count calls per tool and version. Nothing
134
+ else is sent: not your question, not the model's text, no identifier.
135
+
136
+ ## Source
137
+
138
+ [github.com/abdelrahmaan/hadathana-mcp](https://github.com/abdelrahmaan/hadathana-mcp).
139
+
140
+ ## License
141
+
142
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,62 @@
1
+ [project]
2
+ name = "hadathana-mcp"
3
+ version = "0.2.0"
4
+ description = "MCP server over the Hadathna API: Sahih al-Bukhari hadiths and their narrators"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ keywords = [
10
+ "mcp",
11
+ "hadith",
12
+ "bukhari",
13
+ "arabic",
14
+ "islam",
15
+ ]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Natural Language :: Arabic",
19
+ "Topic :: Religion",
20
+ ]
21
+ dependencies = [
22
+ "mcp>=2.3,<3",
23
+ "httpx>=0.27,<1",
24
+ ]
25
+
26
+ [[project.authors]]
27
+ name = "Abdo Kamar"
28
+
29
+ [project.urls]
30
+ Repository = "https://github.com/abdelrahmaan/hadathana-mcp"
31
+ Issues = "https://github.com/abdelrahmaan/hadathana-mcp/issues"
32
+
33
+ [project.scripts]
34
+ hadathana-mcp = "hadathna_mcp.server:main"
35
+
36
+ [dependency-groups]
37
+ dev = [
38
+ "pytest>=8",
39
+ "ruff>=0.6",
40
+ ]
41
+
42
+ [build-system]
43
+ requires = ["uv_build>=0.9,<0.14"]
44
+ build-backend = "uv_build"
45
+
46
+ [tool.uv.build-backend]
47
+ module-name = "hadathna_mcp"
48
+
49
+ [tool.pytest.ini_options]
50
+ testpaths = ["tests"]
51
+
52
+ [tool.ruff]
53
+ target-version = "py311"
54
+ line-length = 88
55
+
56
+ [tool.ruff.lint]
57
+ select = [
58
+ "E",
59
+ "F",
60
+ "I",
61
+ ]
62
+ ignore = ["E501"]
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "hadathana-mcp"
3
+ version = "0.2.0"
4
+ description = "MCP server over the Hadathna API: Sahih al-Bukhari hadiths and their narrators"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ authors = [{ name = "Abdo Kamar" }]
10
+ keywords = ["mcp", "hadith", "bukhari", "arabic", "islam"]
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3",
13
+ "Natural Language :: Arabic",
14
+ "Topic :: Religion",
15
+ ]
16
+ dependencies = [
17
+ "mcp>=2.3,<3",
18
+ "httpx>=0.27,<1",
19
+ ]
20
+
21
+ [project.urls]
22
+ Repository = "https://github.com/abdelrahmaan/hadathana-mcp"
23
+ Issues = "https://github.com/abdelrahmaan/hadathana-mcp/issues"
24
+
25
+ [project.scripts]
26
+ hadathana-mcp = "hadathna_mcp.server:main"
27
+
28
+ [dependency-groups]
29
+ dev = [
30
+ "pytest>=8",
31
+ "ruff>=0.6",
32
+ ]
33
+
34
+ [build-system]
35
+ requires = ["uv_build>=0.9,<0.14"]
36
+ build-backend = "uv_build"
37
+
38
+ [tool.uv.build-backend]
39
+ # The import package keeps its first name; only the distribution and the command are renamed.
40
+ module-name = "hadathna_mcp"
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+
45
+ [tool.ruff]
46
+ target-version = "py311"
47
+ line-length = 88
48
+
49
+ [tool.ruff.lint]
50
+ select = ["E", "F", "I"]
51
+ ignore = ["E501"]
@@ -0,0 +1 @@
1
+ """MCP server over the Hadathna API: Sahih al-Bukhari hadiths and their narrators."""
@@ -0,0 +1,113 @@
1
+ """The one place the server talks to the Hadathna REST API."""
2
+
3
+ import logging
4
+ import os
5
+ from importlib.metadata import PackageNotFoundError, version
6
+ from typing import Any
7
+
8
+ import httpx
9
+ from mcp.server.mcpserver.exceptions import ToolError
10
+
11
+ DEFAULT_API_URL = "https://api.hadathana.app" # the public API; dev sets HADATHNA_API_URL
12
+ TIMEOUT_SECONDS = 10.0
13
+ UNAVAILABLE = (
14
+ "خدمة حدّثنا غير متاحة الآن؛ أعد المحاولة بعد قليل. "
15
+ "The Hadathna service is unavailable right now; try again in a moment."
16
+ )
17
+
18
+ logger = logging.getLogger("hadathna_mcp")
19
+
20
+
21
+ def package_version() -> str:
22
+ """The installed package's version, or 0.0.0 when the metadata is missing."""
23
+ try:
24
+ return version("hadathana-mcp")
25
+ except PackageNotFoundError:
26
+ return "0.0.0"
27
+
28
+
29
+ # Sent with every call so the API can count usage per version and tool; nothing else.
30
+ # The token keeps the old name: the API (app/mcp_usage.py) counts only `hadathna-mcp/<version>`.
31
+ USER_AGENT = f"hadathna-mcp/{package_version()}"
32
+
33
+
34
+ def api_url() -> str:
35
+ """The API's base URL, from HADATHNA_API_URL, or the public API's."""
36
+ return os.environ.get("HADATHNA_API_URL", DEFAULT_API_URL).rstrip("/")
37
+
38
+
39
+ def new_http_client() -> httpx.AsyncClient:
40
+ return httpx.AsyncClient(base_url=api_url(), timeout=TIMEOUT_SECONDS)
41
+
42
+
43
+ class HadathnaAPI:
44
+ """Reads JSON from the API and turns its failures into errors the model can read."""
45
+
46
+ def __init__(self, http: httpx.AsyncClient) -> None:
47
+ self._http = http
48
+
49
+ async def get(self, path: str, *, tool: str, **params: Any) -> dict[str, Any] | None:
50
+ """GET `path` for `tool` with the params that are not None; None on a 404."""
51
+ sent = {key: value for key, value in params.items() if value is not None}
52
+ headers = {"User-Agent": USER_AGENT, "X-MCP-Tool": tool}
53
+ try:
54
+ response = await self._http.get(path, params=sent, headers=headers)
55
+ except httpx.TransportError as error:
56
+ # The address and the error stay in the server's log; the model reads why not.
57
+ logger.warning(
58
+ "api unreachable: %s %s (%s)", self._http.base_url, path, type(error).__name__
59
+ )
60
+ raise ToolError(UNAVAILABLE) from error
61
+ if response.status_code == 404:
62
+ return None
63
+ if response.status_code >= 500:
64
+ logger.warning("api answered %s for %s", response.status_code, path)
65
+ raise ToolError(UNAVAILABLE)
66
+ if response.is_error:
67
+ raise ToolError(
68
+ f"The Hadathna API answered {response.status_code} for {path}"
69
+ f"{_detail(response)}."
70
+ )
71
+ return response.json()
72
+
73
+ async def get_page(self, path: str, *, tool: str, **params: Any) -> dict[str, Any]:
74
+ """GET a list route, which always exists: a 404 means the API is the wrong one."""
75
+ page = await self.get(path, tool=tool, **params)
76
+ if page is None:
77
+ logger.error(
78
+ "the API at %s has no %s: HADATHNA_API_URL must serve /api/v3",
79
+ self._http.base_url,
80
+ path,
81
+ )
82
+ raise ToolError(UNAVAILABLE)
83
+ return page
84
+
85
+
86
+ def _detail(response: httpx.Response) -> str:
87
+ """The API's own reason (FastAPI's `detail`), when it gave one.
88
+
89
+ Most errors carry a string. A 422 carries a list, whose items read
90
+ "field: reason", joined by "; ".
91
+ """
92
+ try:
93
+ detail = response.json().get("detail")
94
+ except (ValueError, AttributeError):
95
+ return ""
96
+ if isinstance(detail, str):
97
+ text = detail
98
+ elif isinstance(detail, list):
99
+ text = "; ".join(_validation_item(item) for item in detail)
100
+ else:
101
+ return ""
102
+ return f": {text.rstrip('.')}" if text else ""
103
+
104
+
105
+ def _validation_item(item: Any) -> str:
106
+ """One item of a 422 `detail`: "field: reason", without its query/path source."""
107
+ if not isinstance(item, dict):
108
+ return str(item)
109
+ location = ".".join(
110
+ str(part) for part in item.get("loc", ()) if part not in ("query", "path")
111
+ )
112
+ reason = item.get("msg", "")
113
+ return f"{location}: {reason}" if location else reason
@@ -0,0 +1,29 @@
1
+ """Links into the Hadathana site: the reader's page for a hadith or a narrator.
2
+
3
+ The API's own `url` points at the source the text came from (bukhari-pedia.net); the
4
+ server leaves it out. These are the pages a reader can open on Hadathana itself.
5
+ """
6
+
7
+ import os
8
+
9
+ DEFAULT_SITE_URL = "https://www.hadathana.app"
10
+
11
+
12
+ def site_url() -> str:
13
+ """The site's base URL, from HADATHNA_SITE_URL, or the public site's."""
14
+ return os.environ.get("HADATHNA_SITE_URL", DEFAULT_SITE_URL).rstrip("/")
15
+
16
+
17
+ def hadith_page_url(number: int) -> str:
18
+ """The reader's page for a hadith number."""
19
+ return f"{site_url()}/hadith/{number}"
20
+
21
+
22
+ def narrator_page_url(narrator_id: int) -> str:
23
+ """The reader's page for a narrator: /narrator/{id}, the site's one URL for it.
24
+
25
+ The public site still serves only /narrator?nid={id}; the endpoint goes public
26
+ with the release that brings /narrator/{id} there (dev has it, and redirects the
27
+ old form to it).
28
+ """
29
+ return f"{site_url()}/narrator/{narrator_id}"