tether-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.
- tether_mcp-0.1.0.dist-info/METADATA +178 -0
- tether_mcp-0.1.0.dist-info/RECORD +14 -0
- tether_mcp-0.1.0.dist-info/WHEEL +5 -0
- tether_mcp-0.1.0.dist-info/entry_points.txt +3 -0
- tether_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
- tether_mcp-0.1.0.dist-info/top_level.txt +1 -0
- tether_mcp_local/__init__.py +5 -0
- tether_mcp_local/cache.py +157 -0
- tether_mcp_local/cli.py +613 -0
- tether_mcp_local/client.py +100 -0
- tether_mcp_local/crypto.py +236 -0
- tether_mcp_local/mcp_server.py +338 -0
- tether_mcp_local/service.py +1928 -0
- tether_mcp_local/store.py +287 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tether-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Local MCP server for Tether — AI Health Sync: your AI agent reads your end-to-end-encrypted Apple Health data (sleep, cycle, weight, water), decrypted only on your machine
|
|
5
|
+
Author: Fino-wind
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 Fino-wind (Tether — AI Health Sync)
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://tetherme.app
|
|
29
|
+
Project-URL: Documentation, https://tetherme.app/mcp
|
|
30
|
+
Project-URL: Repository, https://github.com/Fino-wind/tether-mcp
|
|
31
|
+
Project-URL: Issues, https://github.com/Fino-wind/tether-community/issues
|
|
32
|
+
Project-URL: App Store, https://apps.apple.com/us/app/tether-ai-health-sync/id6759241985
|
|
33
|
+
Keywords: mcp,model-context-protocol,apple-health,healthkit,e2ee,claude,ai-agent,sleep,health
|
|
34
|
+
Classifier: Development Status :: 4 - Beta
|
|
35
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
36
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
37
|
+
Classifier: Operating System :: OS Independent
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
41
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
42
|
+
Classifier: Topic :: Security :: Cryptography
|
|
43
|
+
Requires-Python: >=3.11
|
|
44
|
+
Description-Content-Type: text/markdown
|
|
45
|
+
License-File: LICENSE
|
|
46
|
+
Requires-Dist: cryptography<47.0.0,>=42.0.0
|
|
47
|
+
Requires-Dist: httpx<1.0.0,>=0.28.0
|
|
48
|
+
Requires-Dist: keyring>=24
|
|
49
|
+
Requires-Dist: mcp<2.0.0,>=1.13.0
|
|
50
|
+
Provides-Extra: dev
|
|
51
|
+
Requires-Dist: pytest<9.0.0,>=8.3.0; extra == "dev"
|
|
52
|
+
Requires-Dist: ruff<1.0.0,>=0.11.0; extra == "dev"
|
|
53
|
+
Requires-Dist: mypy<2.0.0,>=1.13.0; extra == "dev"
|
|
54
|
+
Provides-Extra: qr
|
|
55
|
+
Requires-Dist: qrcode<9.0.0,>=8.0.0; extra == "qr"
|
|
56
|
+
Dynamic: license-file
|
|
57
|
+
|
|
58
|
+
# Tether MCP Server
|
|
59
|
+
|
|
60
|
+
**Let your own AI agent read your health data — without the cloud ever seeing it.**
|
|
61
|
+
|
|
62
|
+
This is the official local [MCP](https://modelcontextprotocol.io) server for [Tether — AI Health Sync](https://apps.apple.com/us/app/tether-ai-health-sync/id6759241985), the iOS app that syncs Apple Health data (sleep, heart rate, menstrual cycle, weight, water, symptoms) between partners and to your own AI — end-to-end encrypted.
|
|
63
|
+
|
|
64
|
+
Tether embeds no AI and runs no model on your phone. Intelligence lives where you control it: Claude Code, Claude Desktop, or any MCP-capable agent running on your own machine. This server is the bridge — it holds a private key that never leaves your computer, pulls ciphertext from the cloud, and decrypts **only locally**.
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
iPhone (Apple Health) ──E2EE──▶ cloud (ciphertext only) ──E2EE──▶ this server (your machine) ──▶ your AI agent
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Requirements
|
|
71
|
+
|
|
72
|
+
- [Tether — AI Health Sync](https://apps.apple.com/us/app/tether-ai-health-sync/id6759241985) on iOS, with a **Pro** subscription (the AI-agent interface is the Pro tier)
|
|
73
|
+
- Python 3.11+ on the machine where your agent runs (macOS / Linux / Windows)
|
|
74
|
+
|
|
75
|
+
## Quick start
|
|
76
|
+
|
|
77
|
+
### 1. Install
|
|
78
|
+
|
|
79
|
+
With [uv](https://docs.astral.sh/uv/) (recommended — no clone needed):
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
uvx --from 'git+https://github.com/Fino-wind/tether-mcp' tether-mcp status
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Or with pip:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
pip install 'tether-mcp[qr] @ git+https://github.com/Fino-wind/tether-mcp'
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### 2. Bind your phone
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
tether-mcp bind
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
This generates a keypair on your machine and prints a QR code. In the Tether iOS app, open **Settings → Data & AI → MCP Server** and scan it (or import a QR screenshot from Photos). The app authorizes this machine and starts sealing your health envelopes to its public key. The private key stays in `~/.tether/mcp-local/` (owner-only `0600` permissions, OS keychain where available) — it is never uploaded anywhere.
|
|
98
|
+
|
|
99
|
+
### 3. Connect your agent
|
|
100
|
+
|
|
101
|
+
**Claude Code** (one line):
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
claude mcp add tether-health -- uvx --from 'git+https://github.com/Fino-wind/tether-mcp' tether-mcp serve --transport stdio
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
**Claude Desktop** (`claude_desktop_config.json`):
|
|
108
|
+
|
|
109
|
+
```json
|
|
110
|
+
{
|
|
111
|
+
"mcpServers": {
|
|
112
|
+
"tether-health": {
|
|
113
|
+
"command": "uvx",
|
|
114
|
+
"args": ["--from", "git+https://github.com/Fino-wind/tether-mcp", "tether-mcp", "serve", "--transport", "stdio"]
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Any other MCP client: run `tether-mcp serve --transport stdio`, or `serve --transport http` for a loopback streamable-HTTP endpoint with bearer-token auth.
|
|
121
|
+
|
|
122
|
+
> **Claude Desktop note**: it does not inherit your shell `PATH`. If `uvx` isn't found, use the absolute path (`which uvx`) as `command`.
|
|
123
|
+
|
|
124
|
+
Debugging: `npx @modelcontextprotocol/inspector uvx --from 'git+https://github.com/Fino-wind/tether-mcp' tether-mcp serve --transport stdio`
|
|
125
|
+
|
|
126
|
+
Then just ask your agent: *“How did we sleep last night?”*
|
|
127
|
+
|
|
128
|
+
## MCP tools (16)
|
|
129
|
+
|
|
130
|
+
| Tool | Returns |
|
|
131
|
+
|---|---|
|
|
132
|
+
| `tether_status` | Local binding state (never exposes keys or tokens) |
|
|
133
|
+
| `tether_start_binding` | A fresh QR binding payload for the iOS app to scan |
|
|
134
|
+
| `tether_poll_binding` | One poll for the iOS authorization to complete binding |
|
|
135
|
+
| `tether_sync_sleep` | Recent sleep sessions incl. heart-rate samples, per-day primary-session selection matching the iOS app |
|
|
136
|
+
| `get_sleep_detail` | Per-night heart-rate + respiratory-rate + sleep-stage timeline |
|
|
137
|
+
| `get_water_intake` | Daily water intake + computed daily average |
|
|
138
|
+
| `get_weight_trend` | Daily weights + latest/avg/min/max + weekly trend rate |
|
|
139
|
+
| `get_menstrual_cycle` | Cycle samples + next-period prediction *(sensitive — explicit iOS opt-in required)* |
|
|
140
|
+
| `get_symptoms` | HealthKit symptom days grouped by data owner *(sensitive)* |
|
|
141
|
+
| `get_notes` | Free-text day annotations with their writer *(sensitive)* |
|
|
142
|
+
| `get_activity` | Daily activity rings: steps / energy / exercise minutes / stand hours / distance |
|
|
143
|
+
| `get_resting_hr` | Resting heart-rate records + window mean |
|
|
144
|
+
| `get_workouts` | Workout records: type / duration / calories / distance |
|
|
145
|
+
| `get_mindfulness` | Mindful sessions and minutes per day |
|
|
146
|
+
| `get_hrv` | Heart-rate variability (SDNN) records + window mean |
|
|
147
|
+
| `get_wrist_temp` | Sleeping wrist-temperature baseline deviation |
|
|
148
|
+
|
|
149
|
+
Every data tool accepts `owner` (a user-ID prefix) to filter to one person — the server may hold both your and your partner's shared records, and omitting `owner` mixes them into one pool, so per-person questions should always pass it. (Earlier releases named some tools `get_partner_*`; they were renamed in the 16-tool release since they return whichever owners' records this server holds, not specifically the partner's.)
|
|
150
|
+
|
|
151
|
+
Reads are cache-first: decrypted records are cached locally (owner-only files, 600 s TTL, `TETHER_MCP_CACHE_TTL` to override) so repeat queries answer in ~0.2 s with zero network; pass `fresh=true` to force a cloud round trip. The same service layer backs a full CLI (`tether-mcp sleep / water / weight / …` — every data subcommand takes `--owner` too) if you prefer scripts over MCP.
|
|
152
|
+
|
|
153
|
+
## Privacy & security model
|
|
154
|
+
|
|
155
|
+
- **End-to-end encryption**: Curve25519 ECDH + HKDF-SHA256 + AES-GCM. Every health record is sealed on-device to each authorized recipient's public key (your partner, and this server once bound).
|
|
156
|
+
- **The cloud only ever holds ciphertext.** Tether's backend cannot read your health data — architecturally, not just by policy.
|
|
157
|
+
- **Decryption happens here**, on hardware you own. The private key and server token are never exposed through any tool result.
|
|
158
|
+
- **Sensitive kinds** (menstrual cycle, symptoms, notes) reach this server only if explicitly opted in inside the iOS app, and are never re-exported by the server.
|
|
159
|
+
- HTTP transport binds to loopback by default and requires a bearer token; binding a non-loopback address fails closed unless explicitly allowed — front it with TLS if you must expose it.
|
|
160
|
+
|
|
161
|
+
You can audit all of the above in this repository — that is why it is open source.
|
|
162
|
+
|
|
163
|
+
## Development
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
pip install -e '.[dev,qr]'
|
|
167
|
+
pytest
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## License
|
|
171
|
+
|
|
172
|
+
[MIT](LICENSE). The Tether iOS app and cloud service are separate proprietary components; this repository covers the local MCP server only.
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
*Website: [tetherme.app](https://tetherme.app) · App Store: [Tether — AI Health Sync](https://apps.apple.com/us/app/tether-ai-health-sync/id6759241985) · Bugs & feedback: [tether-community](https://github.com/Fino-wind/tether-community/issues)*
|
|
177
|
+
|
|
178
|
+
<!-- mcp-name: io.github.fino-wind/tether -->
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
tether_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=e6YRPkoYVJJ__Cu8PhSbj_i8w7fAnQxnX2fUswa58tw,1094
|
|
2
|
+
tether_mcp_local/__init__.py,sha256=Osv-JZSy8d2Pkf7ZQ2B4ulIhVc7XhWZDeJgRmpiDezg,85
|
|
3
|
+
tether_mcp_local/cache.py,sha256=f_FfwTus-ewMQC1zw-waxpOtRReQQVyZRdYhHG-mQy0,5643
|
|
4
|
+
tether_mcp_local/cli.py,sha256=JwlSYUIox940-4_JiTc4dQNKN3hlriDpxybuPH84L34,22676
|
|
5
|
+
tether_mcp_local/client.py,sha256=Pd_jzz7mtSOJi2dfkUD6o8TCJCYd1fUpjdFwOIqACEk,3810
|
|
6
|
+
tether_mcp_local/crypto.py,sha256=l3jUXXBcSxDl98rJDn_VYdfrNoB93olR7XDjq2W_4Aw,9463
|
|
7
|
+
tether_mcp_local/mcp_server.py,sha256=lY8we04cGDpBl-SPqeW7t9IjFF-KqnAJATm_W8Pd8cs,14150
|
|
8
|
+
tether_mcp_local/service.py,sha256=52q4afTTMbbk6e9yYIsDB3U671OuO_UiQ1tYYIS7etE,80996
|
|
9
|
+
tether_mcp_local/store.py,sha256=63M5Nm81d86W7ekzs5UG8a90stzZLGgKXsum4C8HfY4,10980
|
|
10
|
+
tether_mcp-0.1.0.dist-info/METADATA,sha256=UWifwkkoGCF4hy8DmgGRO2aVPUQHgWysJ4E-kDscC6g,9442
|
|
11
|
+
tether_mcp-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
12
|
+
tether_mcp-0.1.0.dist-info/entry_points.txt,sha256=CCu044oVcIax7pgxSHpMS0hiY590iyIg178U2m_pUeg,102
|
|
13
|
+
tether_mcp-0.1.0.dist-info/top_level.txt,sha256=ssiRFfAkXLgg4VUu0I8GKeN0Uk0MiBthhMZuhUDjT9c,17
|
|
14
|
+
tether_mcp-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fino-wind (Tether — AI Health Sync)
|
|
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 @@
|
|
|
1
|
+
tether_mcp_local
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from tether_mcp_local.store import write_secret_file
|
|
11
|
+
|
|
12
|
+
_LOG = logging.getLogger("tether_mcp_local.cache")
|
|
13
|
+
|
|
14
|
+
# Cache freshness window. Health data lands in the cloud at the phone's
|
|
15
|
+
# background-sync cadence (minutes-to-hours), so an agent asking twice within a
|
|
16
|
+
# few minutes should not pay a second cloud round trip. Override with
|
|
17
|
+
# TETHER_MCP_CACHE_TTL (seconds); 0 disables the cache entirely.
|
|
18
|
+
DEFAULT_TTL_SECONDS = 600.0
|
|
19
|
+
TTL_ENV = "TETHER_MCP_CACHE_TTL"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _ttl_from_env(default: float) -> float:
|
|
23
|
+
raw = os.getenv(TTL_ENV, "").strip()
|
|
24
|
+
if not raw:
|
|
25
|
+
return default
|
|
26
|
+
try:
|
|
27
|
+
return max(float(raw), 0.0)
|
|
28
|
+
except ValueError:
|
|
29
|
+
_LOG.warning("Ignoring non-numeric %s=%r", TTL_ENV, raw)
|
|
30
|
+
return default
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class LocalRecordCache:
|
|
34
|
+
"""Decrypted-record cache on the user's own machine.
|
|
35
|
+
|
|
36
|
+
Stores DECRYPTED plaintext JSON — acceptable by design: the whole point of
|
|
37
|
+
the local MCP server is that decryption happens in the user's trusted
|
|
38
|
+
environment, and the files are owner-only (0600 via `write_secret_file`,
|
|
39
|
+
0700 directory). E2EE protects the wire and the cloud, not the user's own
|
|
40
|
+
disk from the user.
|
|
41
|
+
|
|
42
|
+
One file per metric_type (plus one for the unfiltered "all" set), each
|
|
43
|
+
stamped with the server_id it was fetched for, a fetch timestamp, and the
|
|
44
|
+
fetch's decrypt-error list (a cache hit must report the same errors the
|
|
45
|
+
fetch did): a bind to a different server or an expired TTL reads as a miss.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, directory: Path, *, ttl_seconds: float | None = None):
|
|
49
|
+
self.directory = directory
|
|
50
|
+
# An explicit ttl_seconds always wins; the env var only replaces the
|
|
51
|
+
# built-in default — so `LocalRecordCache(dir, ttl_seconds=0)` really
|
|
52
|
+
# disables the cache regardless of the caller's shell environment.
|
|
53
|
+
self.ttl_seconds = (
|
|
54
|
+
_ttl_from_env(DEFAULT_TTL_SECONDS) if ttl_seconds is None else max(ttl_seconds, 0.0)
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def enabled(self) -> bool:
|
|
59
|
+
return self.ttl_seconds > 0
|
|
60
|
+
|
|
61
|
+
def _path(self, metric_type: str | None) -> Path:
|
|
62
|
+
return self.directory / f"records-{metric_type or 'all'}.json"
|
|
63
|
+
|
|
64
|
+
def load(
|
|
65
|
+
self, *, server_id: str, metric_type: str | None
|
|
66
|
+
) -> tuple[list[dict[str, Any]], list[str]] | None:
|
|
67
|
+
"""Cached (records, errors), or None on miss/stale/mismatch/disabled.
|
|
68
|
+
|
|
69
|
+
The early `return None`s below are ordinary cache-miss control flow,
|
|
70
|
+
not swallowed failures — the caller answers a miss with a cloud fetch.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
if not self.enabled:
|
|
74
|
+
return None
|
|
75
|
+
path = self._path(metric_type)
|
|
76
|
+
try:
|
|
77
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
78
|
+
except FileNotFoundError:
|
|
79
|
+
return None
|
|
80
|
+
except (OSError, json.JSONDecodeError) as error:
|
|
81
|
+
_LOG.warning("Discarding unreadable cache %s: %s", path.name, type(error).__name__)
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
if not isinstance(raw, dict) or raw.get("server_id") != server_id:
|
|
85
|
+
return None
|
|
86
|
+
fetched_at = raw.get("fetched_at")
|
|
87
|
+
if not isinstance(fetched_at, (int, float)):
|
|
88
|
+
return None
|
|
89
|
+
if (time.time() - float(fetched_at)) > self.ttl_seconds:
|
|
90
|
+
return None
|
|
91
|
+
records = raw.get("records")
|
|
92
|
+
if not isinstance(records, list):
|
|
93
|
+
return None
|
|
94
|
+
errors = raw.get("errors")
|
|
95
|
+
if not isinstance(errors, list):
|
|
96
|
+
errors = []
|
|
97
|
+
return (
|
|
98
|
+
[row for row in records if isinstance(row, dict)],
|
|
99
|
+
[str(item) for item in errors],
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
def save(
|
|
103
|
+
self,
|
|
104
|
+
records: list[dict[str, Any]],
|
|
105
|
+
*,
|
|
106
|
+
server_id: str,
|
|
107
|
+
metric_type: str | None,
|
|
108
|
+
errors: list[str] | None = None,
|
|
109
|
+
) -> None:
|
|
110
|
+
"""Persist a FULL (never limit-truncated) result set; best-effort.
|
|
111
|
+
|
|
112
|
+
`errors` carries the fetch's per-envelope decrypt failures so a cache
|
|
113
|
+
hit reports the same problem set the underlying fetch did — without it,
|
|
114
|
+
a poisoned envelope's error (and the CLI's exit code 3) would flap
|
|
115
|
+
with cache warmth.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
if not self.enabled:
|
|
119
|
+
return
|
|
120
|
+
payload = {
|
|
121
|
+
"server_id": server_id,
|
|
122
|
+
"metric_type": metric_type,
|
|
123
|
+
"fetched_at": time.time(),
|
|
124
|
+
"records": records,
|
|
125
|
+
"errors": errors or [],
|
|
126
|
+
}
|
|
127
|
+
try:
|
|
128
|
+
write_secret_file(
|
|
129
|
+
self._path(metric_type),
|
|
130
|
+
json.dumps(payload, separators=(",", ":"), sort_keys=True) + "\n",
|
|
131
|
+
harden_parent=True,
|
|
132
|
+
)
|
|
133
|
+
except OSError as error:
|
|
134
|
+
_LOG.warning("Cache write failed (%s); continuing uncached", type(error).__name__)
|
|
135
|
+
|
|
136
|
+
def clear(self) -> None:
|
|
137
|
+
"""Drop every cached record file (used when (re)binding)."""
|
|
138
|
+
|
|
139
|
+
try:
|
|
140
|
+
entries = list(self.directory.glob("records-*.json"))
|
|
141
|
+
except OSError as error:
|
|
142
|
+
_LOG.warning(
|
|
143
|
+
"Cache clear could not list %s (%s); stale plaintext may remain",
|
|
144
|
+
self.directory,
|
|
145
|
+
type(error).__name__,
|
|
146
|
+
)
|
|
147
|
+
return
|
|
148
|
+
for path in entries:
|
|
149
|
+
try:
|
|
150
|
+
path.unlink()
|
|
151
|
+
except OSError as error:
|
|
152
|
+
_LOG.warning(
|
|
153
|
+
"Cache clear could not remove %s (%s); stale plaintext may remain",
|
|
154
|
+
path.name,
|
|
155
|
+
type(error).__name__,
|
|
156
|
+
)
|
|
157
|
+
continue
|