gravitywell 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.
Files changed (53) hide show
  1. gravitywell-0.1.0/LICENSE +21 -0
  2. gravitywell-0.1.0/PKG-INFO +165 -0
  3. gravitywell-0.1.0/README.md +129 -0
  4. gravitywell-0.1.0/pyproject.toml +97 -0
  5. gravitywell-0.1.0/pyproject.toml.orig +79 -0
  6. gravitywell-0.1.0/src/gravitywell/__init__.py +28 -0
  7. gravitywell-0.1.0/src/gravitywell/_auth.py +134 -0
  8. gravitywell-0.1.0/src/gravitywell/_client.py +323 -0
  9. gravitywell-0.1.0/src/gravitywell/_insights.py +223 -0
  10. gravitywell-0.1.0/src/gravitywell/_resources/__init__.py +1 -0
  11. gravitywell-0.1.0/src/gravitywell/_resources/action.py +150 -0
  12. gravitywell-0.1.0/src/gravitywell/_resources/auth.py +82 -0
  13. gravitywell-0.1.0/src/gravitywell/_resources/clients.py +270 -0
  14. gravitywell-0.1.0/src/gravitywell/_resources/config.py +989 -0
  15. gravitywell-0.1.0/src/gravitywell/_resources/dhcp.py +61 -0
  16. gravitywell-0.1.0/src/gravitywell/_resources/dns.py +88 -0
  17. gravitywell-0.1.0/src/gravitywell/_resources/domains.py +348 -0
  18. gravitywell-0.1.0/src/gravitywell/_resources/groups.py +332 -0
  19. gravitywell-0.1.0/src/gravitywell/_resources/history.py +153 -0
  20. gravitywell-0.1.0/src/gravitywell/_resources/info.py +249 -0
  21. gravitywell-0.1.0/src/gravitywell/_resources/lists.py +272 -0
  22. gravitywell-0.1.0/src/gravitywell/_resources/logs.py +167 -0
  23. gravitywell-0.1.0/src/gravitywell/_resources/network.py +139 -0
  24. gravitywell-0.1.0/src/gravitywell/_resources/padd.py +50 -0
  25. gravitywell-0.1.0/src/gravitywell/_resources/queries.py +178 -0
  26. gravitywell-0.1.0/src/gravitywell/_resources/search.py +73 -0
  27. gravitywell-0.1.0/src/gravitywell/_resources/stats.py +421 -0
  28. gravitywell-0.1.0/src/gravitywell/_resources/teleporter.py +126 -0
  29. gravitywell-0.1.0/src/gravitywell/_version.py +18 -0
  30. gravitywell-0.1.0/src/gravitywell/mcp.py +232 -0
  31. gravitywell-0.1.0/src/gravitywell/models/__init__.py +364 -0
  32. gravitywell-0.1.0/src/gravitywell/models/_action.py +16 -0
  33. gravitywell-0.1.0/src/gravitywell/models/_auth.py +55 -0
  34. gravitywell-0.1.0/src/gravitywell/models/_base.py +67 -0
  35. gravitywell-0.1.0/src/gravitywell/models/_clients.py +83 -0
  36. gravitywell-0.1.0/src/gravitywell/models/_config.py +124 -0
  37. gravitywell-0.1.0/src/gravitywell/models/_dhcp.py +26 -0
  38. gravitywell-0.1.0/src/gravitywell/models/_dns.py +16 -0
  39. gravitywell-0.1.0/src/gravitywell/models/_domains.py +58 -0
  40. gravitywell-0.1.0/src/gravitywell/models/_groups.py +43 -0
  41. gravitywell-0.1.0/src/gravitywell/models/_history.py +98 -0
  42. gravitywell-0.1.0/src/gravitywell/models/_info.py +381 -0
  43. gravitywell-0.1.0/src/gravitywell/models/_insights.py +81 -0
  44. gravitywell-0.1.0/src/gravitywell/models/_lists.py +64 -0
  45. gravitywell-0.1.0/src/gravitywell/models/_logs.py +39 -0
  46. gravitywell-0.1.0/src/gravitywell/models/_network.py +133 -0
  47. gravitywell-0.1.0/src/gravitywell/models/_padd.py +94 -0
  48. gravitywell-0.1.0/src/gravitywell/models/_queries.py +172 -0
  49. gravitywell-0.1.0/src/gravitywell/models/_search.py +62 -0
  50. gravitywell-0.1.0/src/gravitywell/models/_stats.py +219 -0
  51. gravitywell-0.1.0/src/gravitywell/models/_teleporter.py +34 -0
  52. gravitywell-0.1.0/src/gravitywell/models/_time.py +50 -0
  53. gravitywell-0.1.0/src/gravitywell/py.typed +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 slatecipher
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,165 @@
1
+ Metadata-Version: 2.4
2
+ Name: gravitywell
3
+ Version: 0.1.0
4
+ Summary: A third-party, typed Python client for the Pi-hole v6 REST API
5
+ Keywords: pi-hole,dns,ad-blocking,api,client,httpx2,pydantic,typed
6
+ Author: slatecipher
7
+ Author-email: slatecipher <25094255+slatecipher@users.noreply.github.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: Pydantic :: 2
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Internet :: Name Service (DNS)
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Typing :: Typed
23
+ Requires-Dist: anyio>=4.10
24
+ Requires-Dist: clientx>=0.6.0
25
+ Requires-Dist: pydantic>=2.12.5
26
+ Requires-Dist: click>=8.1 ; extra == 'mcp'
27
+ Requires-Dist: clientx[fastmcp]>=0.6.0 ; extra == 'mcp'
28
+ Requires-Dist: python-dotenv>=1.1 ; extra == 'mcp'
29
+ Requires-Python: >=3.12
30
+ Project-URL: Repository, https://github.com/slatecipher/gravitywell
31
+ Project-URL: Documentation, https://github.com/slatecipher/gravitywell/tree/mainline/docs
32
+ Project-URL: Issues, https://github.com/slatecipher/gravitywell/issues
33
+ Project-URL: Changelog, https://github.com/slatecipher/gravitywell/blob/mainline/CHANGELOG.md
34
+ Provides-Extra: mcp
35
+ Description-Content-Type: text/markdown
36
+
37
+ <h1 align="center">
38
+ <picture>
39
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
40
+ <source media="(prefers-color-scheme: light)" srcset="docs/assets/logo-light.svg">
41
+ <img alt="gravitywell" src="https://raw.githubusercontent.com/slatecipher/gravitywell/mainline/docs/assets/logo-light.svg" width="600">
42
+ </picture>
43
+ </h1>
44
+
45
+ <p align="center">
46
+ <em>A third-party, typed Python client for the Pi-hole v6 REST API, with AI tools and an MCP server.</em>
47
+ </p>
48
+
49
+ <p align="center">
50
+ <a href="https://pypi.org/project/gravitywell/"><img src="https://img.shields.io/pypi/v/gravitywell" alt="PyPI"></a>
51
+ <a href="https://pypi.org/project/gravitywell/"><img src="https://img.shields.io/pypi/pyversions/gravitywell" alt="Python versions"></a>
52
+ <a href="https://github.com/slatecipher/gravitywell/actions/workflows/ci.yml"><img src="https://github.com/slatecipher/gravitywell/actions/workflows/ci.yml/badge.svg?branch=mainline" alt="CI"></a>
53
+ <a href="https://github.com/slatecipher/gravitywell/blob/mainline/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT"></a>
54
+ </p>
55
+
56
+ ## Overview
57
+
58
+ gravitywell is a typed Python client for [Pi-hole](https://pi-hole.net)'s v6 REST API, in sync and async versions.
59
+
60
+ It handles the session for you, so you can get straight to work: pause blocking for five minutes, add an allow rule, or pull the last hour of blocked queries from one device. Answers come back as Pydantic models your editor can autocomplete.
61
+
62
+ It's built for AI agents too. Its methods double as tools with descriptions written for a model, and the insights tools answer questions like "why is this domain blocked?" in a single call. `gravitywell-mcp` serves them to Claude and other MCP clients, read-only unless you allow more.
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ pip install gravitywell
68
+ ```
69
+
70
+ For the MCP server, install the `mcp` extra: `pip install "gravitywell[mcp]"`.
71
+
72
+ Using an AI coding assistant? Point it at [llms.txt](https://github.com/slatecipher/gravitywell/blob/mainline/llms.txt), a compact guide to gravitywell for models.
73
+
74
+ ## Quickstart
75
+
76
+ Create an application password in the Pi-hole's web interface, under **Settings › Web interface / API**, and put it in the `PIHOLE_PASSWORD` environment variable:
77
+
78
+ <!-- docs_src/readme/quickstart.py -->
79
+ ```python
80
+ import os
81
+
82
+ from gravitywell import PiHole, PiHoleAuth
83
+
84
+ auth = PiHoleAuth(os.environ["PIHOLE_PASSWORD"]) # an application password
85
+
86
+ with PiHole("http://pi.hole", auth=auth) as api:
87
+ summary = api.stats.summary() # GET /api/stats/summary -> SummaryResponse
88
+ print(f"{summary.queries.percent_blocked:.1f}% of queries blocked in the last 24 hours")
89
+
90
+ status = api.dns.blocking() # GET /api/dns/blocking -> BlockingResponse
91
+ print(f"Blocking is {status.blocking}") # enabled
92
+
93
+ api.dns.set_blocking(False, timer=300) # pause blocking for five minutes
94
+
95
+ why = api.explain_domain("ads.example.com") # rules, lists and recent queries in one call
96
+ for rule in why.rules:
97
+ print(f"{rule.type} rule ({rule.kind}): {rule.domain}")
98
+ ```
99
+
100
+ - The client logs in on its first request, reuses that session, and logs out when the `with` block ends: a Pi-hole allows only a few sessions at a time.
101
+ - Each method returns a Pydantic model of the Pi-hole's answer, which your editor and type checker know field by field.
102
+ - A `4xx` or `5xx` answer raises `httpx2.HTTPStatusError`, with the Pi-hole's reason in its response.
103
+ - For async code, use `AsyncPiHole` and `await` each method, as [Async clients](https://github.com/slatecipher/gravitywell/blob/mainline/docs/async.md) explains.
104
+
105
+ ## Use it from Claude
106
+
107
+ Put the Pi-hole's URL and application password in a file only you can read:
108
+
109
+ ```bash
110
+ mkdir -p ~/.config/gravitywell
111
+ cat > ~/.config/gravitywell/pihole.env <<'EOF'
112
+ PIHOLE_URL=http://pi.hole
113
+ PIHOLE_PASSWORD=your-application-password
114
+ EOF
115
+ chmod 600 ~/.config/gravitywell/pihole.env
116
+ ```
117
+
118
+ Then add the server to Claude Code:
119
+
120
+ ```bash
121
+ claude mcp add --scope user pihole -- \
122
+ uvx --from "gravitywell[mcp]" gravitywell-mcp --env-file ~/.config/gravitywell/pihole.env
123
+ ```
124
+
125
+ Ask "is my Pi-hole healthy?", "why is this site blocked?" or "which device keeps asking for this domain?". It serves read-only tools until you add `--allow-writes` or `--allow-destructive`. [MCP server](https://github.com/slatecipher/gravitywell/blob/mainline/docs/mcp.md) covers Claude Desktop and other MCP clients, and choosing which tools to serve.
126
+
127
+ ## Features
128
+
129
+ - **The whole API.** Blocking, domain rules, lists, groups and clients, search, statistics, activity history, the query log, settings, DHCP, the network, diagnosis, logs, actions, sessions, and Teleporter backups.
130
+ - **Typed throughout.** Pydantic v2 models for every answer, `Literal` types for fixed sets of values, and times as `datetime` objects in UTC. The package type-checks in pyright's strict mode.
131
+ - **Sessions handled.** One login per client, shared by concurrent requests, renewed once when it expires, sent in a header rather than the URL, and logged out on close.
132
+ - **Sync and async.** `PiHole` and `AsyncPiHole` have the same methods, built on httpx2.
133
+ - **AI tools.** Every endpoint is also a tool for a model, with descriptions written for one, JSON Schemas, safety hints, and errors it can act on. The insights tools answer common questions in one call: why a domain is blocked, who a device is, and what's wrong with the Pi-hole.
134
+ - **An MCP server.** `gravitywell-mcp` serves the tools to Claude and other MCP clients, read-only by default, and only the areas you choose.
135
+ - **Guard rails.** It won't delete the Default group, change settings that could lock you out, hand a model the session or the password hashes, or let a misspelled setting slip past silently, as Pi-hole would.
136
+
137
+ ## Guide
138
+
139
+ - [Connecting to a Pi-hole](https://github.com/slatecipher/gravitywell/blob/mainline/docs/connecting.md): the URL, application passwords, sessions, HTTPS certificates, and `app_sudo`.
140
+ - [Async clients](https://github.com/slatecipher/gravitywell/blob/mainline/docs/async.md): `AsyncPiHole`, concurrent requests and streaming.
141
+ - [Blocking and allowing](https://github.com/slatecipher/gravitywell/blob/mainline/docs/blocking.md): pausing blocking, domain rules, lists, groups and clients, and why a domain is blocked.
142
+ - [Settings](https://github.com/slatecipher/gravitywell/blob/mainline/docs/settings.md): local DNS records, upstream servers, reverse servers, static leases, and other settings.
143
+ - [Statistics and the query log](https://github.com/slatecipher/gravitywell/blob/mainline/docs/statistics.md): totals, top lists, time ranges, and the query log.
144
+ - [Health and maintenance](https://github.com/slatecipher/gravitywell/blob/mainline/docs/maintenance.md): health checks, logs, actions, the network, sessions, and backups.
145
+ - [Errors](https://github.com/slatecipher/gravitywell/blob/mainline/docs/errors.md) and [Testing](https://github.com/slatecipher/gravitywell/blob/mainline/docs/testing.md).
146
+ - [AI tools](https://github.com/slatecipher/gravitywell/blob/mainline/docs/ai-tools.md) and the [MCP server](https://github.com/slatecipher/gravitywell/blob/mainline/docs/mcp.md).
147
+ - [API reference](https://github.com/slatecipher/gravitywell/blob/mainline/docs/reference.md): every method, the endpoint it calls, and how its tool is marked.
148
+
149
+ ## Compatibility
150
+
151
+ gravitywell supports Pi-hole v6, whose REST API replaced v5's interface, on Python 3.12 and newer. It was modeled on, and tested against, Pi-hole core v6.6, web v6.6.1 and FTL v6.9, which `gravitywell.PIHOLE_VERSIONS` records. [Pi-hole compatibility](https://github.com/slatecipher/gravitywell/blob/mainline/docs/compatibility.md) covers newer releases, and the few endpoints gravitywell leaves out.
152
+
153
+ ## Project status
154
+
155
+ gravitywell is pre-1.0, so its API may change between minor versions. Changes are listed in the [changelog](https://github.com/slatecipher/gravitywell/blob/mainline/CHANGELOG.md). It's maintained in spare time: issues and pull requests are welcome, and [CONTRIBUTING.md](https://github.com/slatecipher/gravitywell/blob/mainline/CONTRIBUTING.md) explains how to set up and check a change.
156
+
157
+ ## Acknowledgments
158
+
159
+ gravitywell is built on [ClientX](https://github.com/slatecipher/ClientX), [httpx2](https://pypi.org/project/httpx2/) and [Pydantic](https://docs.pydantic.dev), and its MCP server on [FastMCP](https://gofastmcp.com).
160
+
161
+ gravitywell is an independent, third-party project. It isn't made, endorsed or supported by the Pi-hole project, and uses the name "Pi-hole" only to say what it works with. Pi-hole® is a registered trademark of Pi-hole LLC.
162
+
163
+ ## License
164
+
165
+ gravitywell is released under the [MIT License](https://github.com/slatecipher/gravitywell/blob/mainline/LICENSE).
@@ -0,0 +1,129 @@
1
+ <h1 align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
4
+ <source media="(prefers-color-scheme: light)" srcset="docs/assets/logo-light.svg">
5
+ <img alt="gravitywell" src="https://raw.githubusercontent.com/slatecipher/gravitywell/mainline/docs/assets/logo-light.svg" width="600">
6
+ </picture>
7
+ </h1>
8
+
9
+ <p align="center">
10
+ <em>A third-party, typed Python client for the Pi-hole v6 REST API, with AI tools and an MCP server.</em>
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="https://pypi.org/project/gravitywell/"><img src="https://img.shields.io/pypi/v/gravitywell" alt="PyPI"></a>
15
+ <a href="https://pypi.org/project/gravitywell/"><img src="https://img.shields.io/pypi/pyversions/gravitywell" alt="Python versions"></a>
16
+ <a href="https://github.com/slatecipher/gravitywell/actions/workflows/ci.yml"><img src="https://github.com/slatecipher/gravitywell/actions/workflows/ci.yml/badge.svg?branch=mainline" alt="CI"></a>
17
+ <a href="https://github.com/slatecipher/gravitywell/blob/mainline/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT"></a>
18
+ </p>
19
+
20
+ ## Overview
21
+
22
+ gravitywell is a typed Python client for [Pi-hole](https://pi-hole.net)'s v6 REST API, in sync and async versions.
23
+
24
+ It handles the session for you, so you can get straight to work: pause blocking for five minutes, add an allow rule, or pull the last hour of blocked queries from one device. Answers come back as Pydantic models your editor can autocomplete.
25
+
26
+ It's built for AI agents too. Its methods double as tools with descriptions written for a model, and the insights tools answer questions like "why is this domain blocked?" in a single call. `gravitywell-mcp` serves them to Claude and other MCP clients, read-only unless you allow more.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pip install gravitywell
32
+ ```
33
+
34
+ For the MCP server, install the `mcp` extra: `pip install "gravitywell[mcp]"`.
35
+
36
+ Using an AI coding assistant? Point it at [llms.txt](https://github.com/slatecipher/gravitywell/blob/mainline/llms.txt), a compact guide to gravitywell for models.
37
+
38
+ ## Quickstart
39
+
40
+ Create an application password in the Pi-hole's web interface, under **Settings › Web interface / API**, and put it in the `PIHOLE_PASSWORD` environment variable:
41
+
42
+ <!-- docs_src/readme/quickstart.py -->
43
+ ```python
44
+ import os
45
+
46
+ from gravitywell import PiHole, PiHoleAuth
47
+
48
+ auth = PiHoleAuth(os.environ["PIHOLE_PASSWORD"]) # an application password
49
+
50
+ with PiHole("http://pi.hole", auth=auth) as api:
51
+ summary = api.stats.summary() # GET /api/stats/summary -> SummaryResponse
52
+ print(f"{summary.queries.percent_blocked:.1f}% of queries blocked in the last 24 hours")
53
+
54
+ status = api.dns.blocking() # GET /api/dns/blocking -> BlockingResponse
55
+ print(f"Blocking is {status.blocking}") # enabled
56
+
57
+ api.dns.set_blocking(False, timer=300) # pause blocking for five minutes
58
+
59
+ why = api.explain_domain("ads.example.com") # rules, lists and recent queries in one call
60
+ for rule in why.rules:
61
+ print(f"{rule.type} rule ({rule.kind}): {rule.domain}")
62
+ ```
63
+
64
+ - The client logs in on its first request, reuses that session, and logs out when the `with` block ends: a Pi-hole allows only a few sessions at a time.
65
+ - Each method returns a Pydantic model of the Pi-hole's answer, which your editor and type checker know field by field.
66
+ - A `4xx` or `5xx` answer raises `httpx2.HTTPStatusError`, with the Pi-hole's reason in its response.
67
+ - For async code, use `AsyncPiHole` and `await` each method, as [Async clients](https://github.com/slatecipher/gravitywell/blob/mainline/docs/async.md) explains.
68
+
69
+ ## Use it from Claude
70
+
71
+ Put the Pi-hole's URL and application password in a file only you can read:
72
+
73
+ ```bash
74
+ mkdir -p ~/.config/gravitywell
75
+ cat > ~/.config/gravitywell/pihole.env <<'EOF'
76
+ PIHOLE_URL=http://pi.hole
77
+ PIHOLE_PASSWORD=your-application-password
78
+ EOF
79
+ chmod 600 ~/.config/gravitywell/pihole.env
80
+ ```
81
+
82
+ Then add the server to Claude Code:
83
+
84
+ ```bash
85
+ claude mcp add --scope user pihole -- \
86
+ uvx --from "gravitywell[mcp]" gravitywell-mcp --env-file ~/.config/gravitywell/pihole.env
87
+ ```
88
+
89
+ Ask "is my Pi-hole healthy?", "why is this site blocked?" or "which device keeps asking for this domain?". It serves read-only tools until you add `--allow-writes` or `--allow-destructive`. [MCP server](https://github.com/slatecipher/gravitywell/blob/mainline/docs/mcp.md) covers Claude Desktop and other MCP clients, and choosing which tools to serve.
90
+
91
+ ## Features
92
+
93
+ - **The whole API.** Blocking, domain rules, lists, groups and clients, search, statistics, activity history, the query log, settings, DHCP, the network, diagnosis, logs, actions, sessions, and Teleporter backups.
94
+ - **Typed throughout.** Pydantic v2 models for every answer, `Literal` types for fixed sets of values, and times as `datetime` objects in UTC. The package type-checks in pyright's strict mode.
95
+ - **Sessions handled.** One login per client, shared by concurrent requests, renewed once when it expires, sent in a header rather than the URL, and logged out on close.
96
+ - **Sync and async.** `PiHole` and `AsyncPiHole` have the same methods, built on httpx2.
97
+ - **AI tools.** Every endpoint is also a tool for a model, with descriptions written for one, JSON Schemas, safety hints, and errors it can act on. The insights tools answer common questions in one call: why a domain is blocked, who a device is, and what's wrong with the Pi-hole.
98
+ - **An MCP server.** `gravitywell-mcp` serves the tools to Claude and other MCP clients, read-only by default, and only the areas you choose.
99
+ - **Guard rails.** It won't delete the Default group, change settings that could lock you out, hand a model the session or the password hashes, or let a misspelled setting slip past silently, as Pi-hole would.
100
+
101
+ ## Guide
102
+
103
+ - [Connecting to a Pi-hole](https://github.com/slatecipher/gravitywell/blob/mainline/docs/connecting.md): the URL, application passwords, sessions, HTTPS certificates, and `app_sudo`.
104
+ - [Async clients](https://github.com/slatecipher/gravitywell/blob/mainline/docs/async.md): `AsyncPiHole`, concurrent requests and streaming.
105
+ - [Blocking and allowing](https://github.com/slatecipher/gravitywell/blob/mainline/docs/blocking.md): pausing blocking, domain rules, lists, groups and clients, and why a domain is blocked.
106
+ - [Settings](https://github.com/slatecipher/gravitywell/blob/mainline/docs/settings.md): local DNS records, upstream servers, reverse servers, static leases, and other settings.
107
+ - [Statistics and the query log](https://github.com/slatecipher/gravitywell/blob/mainline/docs/statistics.md): totals, top lists, time ranges, and the query log.
108
+ - [Health and maintenance](https://github.com/slatecipher/gravitywell/blob/mainline/docs/maintenance.md): health checks, logs, actions, the network, sessions, and backups.
109
+ - [Errors](https://github.com/slatecipher/gravitywell/blob/mainline/docs/errors.md) and [Testing](https://github.com/slatecipher/gravitywell/blob/mainline/docs/testing.md).
110
+ - [AI tools](https://github.com/slatecipher/gravitywell/blob/mainline/docs/ai-tools.md) and the [MCP server](https://github.com/slatecipher/gravitywell/blob/mainline/docs/mcp.md).
111
+ - [API reference](https://github.com/slatecipher/gravitywell/blob/mainline/docs/reference.md): every method, the endpoint it calls, and how its tool is marked.
112
+
113
+ ## Compatibility
114
+
115
+ gravitywell supports Pi-hole v6, whose REST API replaced v5's interface, on Python 3.12 and newer. It was modeled on, and tested against, Pi-hole core v6.6, web v6.6.1 and FTL v6.9, which `gravitywell.PIHOLE_VERSIONS` records. [Pi-hole compatibility](https://github.com/slatecipher/gravitywell/blob/mainline/docs/compatibility.md) covers newer releases, and the few endpoints gravitywell leaves out.
116
+
117
+ ## Project status
118
+
119
+ gravitywell is pre-1.0, so its API may change between minor versions. Changes are listed in the [changelog](https://github.com/slatecipher/gravitywell/blob/mainline/CHANGELOG.md). It's maintained in spare time: issues and pull requests are welcome, and [CONTRIBUTING.md](https://github.com/slatecipher/gravitywell/blob/mainline/CONTRIBUTING.md) explains how to set up and check a change.
120
+
121
+ ## Acknowledgments
122
+
123
+ gravitywell is built on [ClientX](https://github.com/slatecipher/ClientX), [httpx2](https://pypi.org/project/httpx2/) and [Pydantic](https://docs.pydantic.dev), and its MCP server on [FastMCP](https://gofastmcp.com).
124
+
125
+ gravitywell is an independent, third-party project. It isn't made, endorsed or supported by the Pi-hole project, and uses the name "Pi-hole" only to say what it works with. Pi-hole® is a registered trademark of Pi-hole LLC.
126
+
127
+ ## License
128
+
129
+ gravitywell is released under the [MIT License](https://github.com/slatecipher/gravitywell/blob/mainline/LICENSE).
@@ -0,0 +1,97 @@
1
+ [project]
2
+ name = "gravitywell"
3
+ version = "0.1.0"
4
+ description = "A third-party, typed Python client for the Pi-hole v6 REST API"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ keywords = [
10
+ "pi-hole",
11
+ "dns",
12
+ "ad-blocking",
13
+ "api",
14
+ "client",
15
+ "httpx2",
16
+ "pydantic",
17
+ "typed",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Framework :: Pydantic :: 2",
22
+ "Intended Audience :: Developers",
23
+ "Intended Audience :: System Administrators",
24
+ "Operating System :: OS Independent",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3 :: Only",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Programming Language :: Python :: 3.13",
29
+ "Programming Language :: Python :: 3.14",
30
+ "Topic :: Internet :: Name Service (DNS)",
31
+ "Topic :: Software Development :: Libraries",
32
+ "Typing :: Typed",
33
+ ]
34
+ dependencies = [
35
+ "anyio>=4.10",
36
+ "clientx>=0.6.0",
37
+ "pydantic>=2.12.5",
38
+ ]
39
+
40
+ [[project.authors]]
41
+ name = "slatecipher"
42
+ email = "25094255+slatecipher@users.noreply.github.com"
43
+
44
+ [project.urls]
45
+ Repository = "https://github.com/slatecipher/gravitywell"
46
+ Documentation = "https://github.com/slatecipher/gravitywell/tree/mainline/docs"
47
+ Issues = "https://github.com/slatecipher/gravitywell/issues"
48
+ Changelog = "https://github.com/slatecipher/gravitywell/blob/mainline/CHANGELOG.md"
49
+
50
+ [project.optional-dependencies]
51
+ mcp = [
52
+ "click>=8.1",
53
+ "clientx[fastmcp]>=0.6.0",
54
+ "python-dotenv>=1.1",
55
+ ]
56
+
57
+ [project.scripts]
58
+ gravitywell-mcp = "gravitywell.mcp:main"
59
+
60
+ [build-system]
61
+ requires = ["uv_build>=0.12.3,<0.14.0"]
62
+ build-backend = "uv_build"
63
+
64
+ [dependency-groups]
65
+ dev = [
66
+ "click>=8.1",
67
+ "clientx[fastmcp]>=0.6.0",
68
+ "pyright>=1.1.411",
69
+ "python-dotenv>=1.1",
70
+ "pytest>=9.0.2",
71
+ "pytest-cov>=7.0.0",
72
+ "ruff>=0.14.10",
73
+ ]
74
+
75
+ [tool.pytest]
76
+ addopts = [
77
+ "--import-mode=importlib",
78
+ "-vv",
79
+ "--cov=gravitywell",
80
+ "--cov-report=term-missing",
81
+ ]
82
+ strict = true
83
+
84
+ [tool.pyright]
85
+ include = [
86
+ "src",
87
+ "test",
88
+ "docs_src",
89
+ "scripts",
90
+ ]
91
+ pythonVersion = "3.12"
92
+ typeCheckingMode = "standard"
93
+ strict = [
94
+ "src",
95
+ "docs_src",
96
+ "scripts",
97
+ ]
@@ -0,0 +1,79 @@
1
+ [project]
2
+ name = "gravitywell"
3
+ version = "0.1.0"
4
+ description = "A third-party, typed Python client for the Pi-hole v6 REST API"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "slatecipher", email = "25094255+slatecipher@users.noreply.github.com" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ keywords = ["pi-hole", "dns", "ad-blocking", "api", "client", "httpx2", "pydantic", "typed"]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Framework :: Pydantic :: 2",
16
+ "Intended Audience :: Developers",
17
+ "Intended Audience :: System Administrators",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Topic :: Internet :: Name Service (DNS)",
25
+ "Topic :: Software Development :: Libraries",
26
+ "Typing :: Typed",
27
+ ]
28
+ dependencies = [
29
+ "anyio>=4.10",
30
+ "clientx>=0.6.0",
31
+ "pydantic>=2.12.5",
32
+ ]
33
+
34
+ [project.urls]
35
+ Repository = "https://github.com/slatecipher/gravitywell"
36
+ Documentation = "https://github.com/slatecipher/gravitywell/tree/mainline/docs"
37
+ Issues = "https://github.com/slatecipher/gravitywell/issues"
38
+ Changelog = "https://github.com/slatecipher/gravitywell/blob/mainline/CHANGELOG.md"
39
+
40
+ [project.optional-dependencies]
41
+ # `gravitywell.mcp` and the `gravitywell-mcp` command: an MCP server for the
42
+ # AI tools, on FastMCP.
43
+ mcp = ["click>=8.1", "clientx[fastmcp]>=0.6.0", "python-dotenv>=1.1"]
44
+
45
+ [project.scripts]
46
+ gravitywell-mcp = "gravitywell.mcp:main"
47
+
48
+ [build-system]
49
+ requires = ["uv_build>=0.12.3,<0.14.0"]
50
+ build-backend = "uv_build"
51
+
52
+ [dependency-groups]
53
+ dev = [
54
+ # The `mcp` extra's dependencies, so tests and pyright see them.
55
+ "click>=8.1",
56
+ "clientx[fastmcp]>=0.6.0",
57
+ "pyright>=1.1.411",
58
+ "python-dotenv>=1.1",
59
+ "pytest>=9.0.2",
60
+ "pytest-cov>=7.0.0",
61
+ "ruff>=0.14.10",
62
+ ]
63
+
64
+ [tool.pytest]
65
+ addopts = ["--import-mode=importlib", "-vv", "--cov=gravitywell", "--cov-report=term-missing"]
66
+ # All of pytest's strictness checks. pytest may add more in a release; uv.lock pins it,
67
+ # so a new one shows up in the Dependabot PR that upgrades pytest, not on mainline.
68
+ strict = true
69
+
70
+ [tool.pyright]
71
+ # Editors check every tree. `make typecheck` passes `src`, `docs_src` and
72
+ # `scripts` on the command line (which overrides this list), so CI gates the
73
+ # shipped package, the docs' samples and scripts.
74
+ include = ["src", "test", "docs_src", "scripts"]
75
+ pythonVersion = "3.12"
76
+ typeCheckingMode = "standard"
77
+ # The shipped package, the docs' samples and scripts are held to strict mode;
78
+ # tests stay on standard.
79
+ strict = ["src", "docs_src", "scripts"]
@@ -0,0 +1,28 @@
1
+ """A third-party, typed client for the Pi-hole v6 REST API.
2
+
3
+ The models of request and response bodies are in `gravitywell.models`.
4
+
5
+ Example:
6
+ import os
7
+
8
+ from gravitywell import PiHole, PiHoleAuth
9
+
10
+ auth = PiHoleAuth(os.environ["PIHOLE_PASSWORD"])
11
+ with PiHole("http://pi.hole", auth=auth) as api:
12
+ print(api.info.version().version.ftl.local.version)
13
+ """
14
+
15
+ from gravitywell._auth import PiHoleAuth
16
+ from gravitywell._client import AsyncPiHole, PiHole
17
+ from gravitywell._version import PIHOLE_VERSIONS, __version__
18
+
19
+ __all__ = [
20
+ # gravitywell._version
21
+ "PIHOLE_VERSIONS",
22
+ "__version__",
23
+ # gravitywell._auth
24
+ "PiHoleAuth",
25
+ # gravitywell._client
26
+ "AsyncPiHole",
27
+ "PiHole",
28
+ ]
@@ -0,0 +1,134 @@
1
+ """Session authentication for a Pi-hole."""
2
+
3
+ import threading
4
+ from collections.abc import AsyncGenerator, Callable, Generator
5
+ from contextlib import suppress
6
+ from dataclasses import dataclass
7
+
8
+ import anyio
9
+ import httpx2
10
+
11
+ from gravitywell.models import Session, SessionResponse
12
+
13
+ _SID_HEADER = "X-FTL-SID"
14
+ # A request is sent once, and once more after a 401 with a new login.
15
+ _ATTEMPTS = 2
16
+ _AUTH_PATH = "/api/auth"
17
+
18
+ type PasswordProvider = Callable[[], str]
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class _Login:
23
+ """A session, with the URL that issued it, where logging out goes."""
24
+
25
+ session: Session
26
+ url: httpx2.URL
27
+
28
+
29
+ class PiHoleAuth(httpx2.Auth):
30
+ """Log in to a Pi-hole with a password, and send its session on requests.
31
+
32
+ Pass it as a client's `auth=`:
33
+
34
+ with PiHole("http://pi.hole", auth=PiHoleAuth(password)) as api:
35
+ api.info.version()
36
+
37
+ It logs in before the first request (`POST /api/auth`), sends the session in
38
+ the `X-FTL-SID` header, and logs in again once if a request gets a 401.
39
+ Concurrent requests share one login, since a Pi-hole allows only a few
40
+ sessions at a time. A failed login raises `httpx2.HTTPStatusError` with
41
+ the login's response. The clients log out when they close.
42
+
43
+ Use an application password, which Pi-hole's settings create. Two-factor
44
+ authentication isn't supported. To read the password at each login, such
45
+ as from a secret file that's replaced when it changes, pass a function
46
+ that returns it: `PiHoleAuth(lambda: path.read_text().strip())`. Async
47
+ clients call it in the event loop, so it should be quick.
48
+ """
49
+
50
+ def __init__(self, password: str | PasswordProvider) -> None:
51
+ self._password = password
52
+ # None until logged in. A session whose sid is None means the Pi-hole
53
+ # has no password, so no header is sent.
54
+ self._login: _Login | None = None
55
+ self._sync_lock = threading.Lock()
56
+ self._async_lock = anyio.Lock()
57
+
58
+ def sync_auth_flow(self, request: httpx2.Request) -> Generator[httpx2.Request, httpx2.Response, None]:
59
+ rejected: _Login | None = None
60
+ for _ in range(_ATTEMPTS):
61
+ with self._sync_lock:
62
+ # Log in if there's no session, or if this request's session
63
+ # was rejected and no other request has logged in again since.
64
+ if self._login is None or self._login is rejected:
65
+ login_response = yield self._login_request(request)
66
+ login_response.read()
67
+ self._login = _login_from(login_response)
68
+ login = self._login
69
+ _send_session(request, login.session)
70
+ response = yield request
71
+ if response.status_code != 401:
72
+ return
73
+ rejected = login
74
+
75
+ async def async_auth_flow(self, request: httpx2.Request) -> AsyncGenerator[httpx2.Request, httpx2.Response]:
76
+ rejected: _Login | None = None
77
+ for _ in range(_ATTEMPTS):
78
+ async with self._async_lock:
79
+ # Log in if there's no session, or if this request's session
80
+ # was rejected and no other request has logged in again since.
81
+ if self._login is None or self._login is rejected:
82
+ login_response = yield self._login_request(request)
83
+ await login_response.aread()
84
+ self._login = _login_from(login_response)
85
+ login = self._login
86
+ _send_session(request, login.session)
87
+ response = yield request
88
+ if response.status_code != 401:
89
+ return
90
+ rejected = login
91
+
92
+ def log_out(self, client: httpx2.Client) -> None:
93
+ """Log out of the session through `client`, if there is one.
94
+
95
+ The clients call it when they close. A failed logout is ignored: the
96
+ session expires on its own.
97
+ """
98
+ login, self._login = self._login, None
99
+ if login is not None and login.session.sid is not None:
100
+ with suppress(httpx2.HTTPError):
101
+ client.delete(login.url, headers={_SID_HEADER: login.session.sid}, auth=httpx2.Auth())
102
+
103
+ async def alog_out(self, client: httpx2.AsyncClient) -> None:
104
+ """Log out of the session through `client`, if there is one.
105
+
106
+ The async clients call it when they close. A failed logout is ignored:
107
+ the session expires on its own.
108
+ """
109
+ login, self._login = self._login, None
110
+ if login is not None and login.session.sid is not None:
111
+ with suppress(httpx2.HTTPError):
112
+ await client.delete(login.url, headers={_SID_HEADER: login.session.sid}, auth=httpx2.Auth())
113
+
114
+ def _login_request(self, request: httpx2.Request) -> httpx2.Request:
115
+ # Requests made in an auth flow skip the client's default headers.
116
+ user_agent = request.headers.get("User-Agent")
117
+ headers = {"User-Agent": user_agent} if user_agent is not None else None
118
+ login_url = request.url.copy_with(path=_AUTH_PATH)
119
+ password = self._password if isinstance(self._password, str) else self._password()
120
+ return httpx2.Request("POST", login_url, json={"password": password}, headers=headers)
121
+
122
+
123
+ def _login_from(response: httpx2.Response) -> _Login:
124
+ """Read the session, raising `httpx2.HTTPStatusError` for a failed login."""
125
+ response.raise_for_status()
126
+ body = SessionResponse.model_validate_json(response.content)
127
+ return _Login(body.session, response.request.url)
128
+
129
+
130
+ def _send_session(request: httpx2.Request, session: Session) -> None:
131
+ if session.sid is None:
132
+ request.headers.pop(_SID_HEADER, None)
133
+ else:
134
+ request.headers[_SID_HEADER] = session.sid