{
  "markdown": "# Vaultbeat Local MCP Server\n\n**Your Apple Health data — sleep stages, cycle, HRV, resting heart rate, workouts, weight, VO₂ max, meals, lifts, notes — readable and writable by your own AI agent (Claude Code, Hermes, OpenClaw, anything MCP), end-to-end encrypted so that only your machine ever sees plaintext.** The [Vaultbeat](https://vaultbeat.app) iPhone app captures from HealthKit; this package is the local server that decrypts for the agent.\n\nTechnically: the local service program for Vaultbeat's encrypted health-data recipient flow.\nPublished externally as [`Fino-wind/vaultbeat-apple-health`](https://github.com/Fino-wind/vaultbeat-apple-health)\n(public package name `vaultbeat-apple-health` since 0.6.2; `vaultbeat-mcp` and\n`vaultbeat-mcp-local` remain back-compat console scripts). This directory is the source of truth — after any user-visible change here,\nre-export the public repo and update its README tool table + the website `/mcp` page\n(see CLAUDE.md \"Sync duty\").\n\nIt runs on the user's computer, generates the Curve25519 keypair used by the iOS app,\nshows a QR binding payload, receives a one-time server token from the cloud API, and\nthen exposes decrypted health data — sleep, water, weight, cycle, activity, vitals —\nthrough either a CLI or a stdio MCP server. Read-only: data is written by the iOS app.\n\n## Commands\n\n```bash\npython -m pip install -e './mcp-local-server[qr]'\n# try every read tool against synthetic data — no pairing, no cloud, no Apple Health\nvaultbeat-apple-health --demo sleep --limit 5\nvaultbeat-apple-health --demo doctor\n\nvaultbeat-apple-health bind\nvaultbeat-apple-health status\n\n# read decrypted health data — every data subcommand accepts\n# --owner <user-id prefix> to filter to one person (omitting it mixes\n# both partners' records into one pool; aggregates become meaningless)\nvaultbeat-apple-health sleep --limit 5 --owner a1a1        # sleep sessions + provenance\nvaultbeat-apple-health sleep-detail --limit 1 --owner a1a1 # HR+RR+stage timeline\nvaultbeat-apple-health water --limit 30 --owner a1a1       # water intake + daily average\nvaultbeat-apple-health weight --limit 90 --owner b2b2      # weight trend (latest/avg/weekly rate)\nvaultbeat-apple-health menstrual --limit 60 --owner b2b2   # menstrual cycle (sensitive)\nvaultbeat-apple-health activity --limit 30 --owner a1a1    # daily activity rings\nvaultbeat-apple-health resting-hr --limit 30 --owner a1a1  # resting heart rate\nvaultbeat-apple-health workouts --limit 20 --owner a1a1    # workout records\nvaultbeat-apple-health mindfulness --limit 30 --owner a1a1 # mindful minutes\nvaultbeat-apple-health hrv --limit 30 --owner a1a1         # HRV / SDNN (hourly buckets by default; --granularity raw for per-sample)\nvaultbeat-apple-health wrist-temp --limit 30 --owner a1a1  # sleeping wrist temperature\nvaultbeat-apple-health symptoms --limit 30                 # symptom days (grouped by owner)\nvaultbeat-apple-health notes --kind sleep --limit 30       # free-text day annotations\n\n# run as an MCP server\nvaultbeat-apple-health serve --transport stdio\nvaultbeat-apple-health serve --transport http --host 127.0.0.1 --port 8000 --path /mcp\nvaultbeat-apple-health --demo serve --transport stdio   # same synthetic dataset, wired into a client\n```\n\n`--demo` is a **global flag**, not a subcommand: it goes before the subcommand\n(`vaultbeat-apple-health --demo sleep`), and `VAULTBEAT_DEMO=1` does the same thing. It serves a\ndeterministic synthetic dataset — the same records on every machine, every run — so demo\noutput can be pasted into a bug report as a shared baseline. Nothing is fetched and nothing\nis decrypted; there is no private key involved at all. Every payload carries `demo_mode:\ntrue` plus a `[SYNTHETIC DEMO DATA]` banner, the tool descriptions say so, and the server\nlists itself as `Vaultbeat Health [DEMO — SYNTHETIC DATA]`, so demo output cannot pass for a\nreal export. **Read tools only** — the `log_*` write tools refuse, because writing needs a\nreal key and a real account, and a write that pretends to succeed is worse than one that says\nit needs pairing. It applies to that one invocation and is never written to the config file.\n\n`http` is a CLI alias for MCP's `streamable-http` transport.\nThe default transport remains `stdio` for local desktop MCP clients.\n\nThe config file defaults to `~/.tether/mcp-local/config.json` and is written with\n`0600` permissions. It contains the cloud-issued server token and your **public**\nkey; do not commit or share it.\n\n### Where the private key lives\n\nNot in `config.json`. It is looked for in three places, in order:\n\n1. **`VAULTBEAT_PRIVATE_KEY`** — read if set, never written back, for operators\n   who inject it from systemd-creds / a vault / a KMS.\n2. **The system keyring** — the normal case on a desktop.\n3. **`~/.tether/mcp-local/identity.key`**, mode `0600` — the automatic fallback\n   on a machine with no keyring backend at all.\n\nKeeping it out of `config.json` is a boundary, not tidiness: the server token\nalone can download your ciphertext but not read it, and the private key alone\nhas nothing to decrypt. `config.json` is the file people `cat` into bug reports.\n\n> 🔴 **Never delete `config.json` to \"start clean\".** The private key is not in\n> it, so deleting does not clear a bad key — it mints a brand-new identity, and\n> every record already encrypted for the old one becomes permanently unreadable.\n> If a command reports missing key material, the error names all three locations\n> and what was found in each; read that before removing anything.\n\n**Headless servers**: if the keyring is unreachable, do *not* set\n`PYTHON_KEYRING_BACKEND` to the null backend. That backend accepts writes and\nstores nothing; since 0.4.3 every keyring write is verified by reading it back,\nso a null backend just lands the key in layer 3's `identity.key` file — the same\noutcome as having no keyring, with a keyring you might have reached hidden behind\nit. Either let layer 3 handle it (automatic when no backend exists) or, if a\nD-Bus session exists but this process cannot see it, pass\n`DBUS_SESSION_BUS_ADDRESS` through explicitly — `XDG_RUNTIME_DIR` on its own is\nnot enough.\n\n> **`.tether`, not `.vaultbeat` — that is deliberate, do not \"fix\" it.** The app\n> was renamed but this path is frozen at the pre-rename location, because the\n> Keychain username embeds the resolved config path (`_keychain_username` in\n> `store.py`). Moving the directory orphans the bound config *and* its\n> private-key Keychain entry for every existing install. Until 2026-07-28 this\n> README wrote `~/.vaultbeat/...`, which does not exist — so anyone who came here\n> to destroy their credentials `rm -rf`'d an empty path, got no error, and left\n> the real key in place.\n\nWhen using HTTP transport, the server binds to `127.0.0.1:8000` and serves MCP at\n`/mcp` by default, and requires a bearer token (see \"Authenticating HTTP transport\"\nbelow). Binding a non-loopback address fails closed unless you pass both a token and\n`--allow-remote`; always front a network-exposed server with TLS (a reverse proxy).\n\n## Binding Flow\n\n1. `vaultbeat-apple-health bind` generates a fresh `pollID` and prints a QR payload:\n   `{\"pollID\":\"...\",\"publicKeyBase64\":\"...\",\"serverName\":\"...\"}`\n2. The iOS app scans that payload and calls the `mcp-bind-local` Edge Function.\n3. The local service polls the `mcp-poll-binding` Edge Function.\n4. Once bound, the local config stores `serverID` and `serverToken`.\n5. All read commands call the `mcp-sync` Edge Function, decrypt the returned envelopes\n   locally, and return plaintext JSON. (All privileged routes are Supabase Edge\n   Functions at `/functions/v1/<name>`.)\n\n### Troubleshooting: `vaultbeat-apple-health doctor`\n\nIf binding or reads fail, run the self-diagnosis:\n\n```bash\nvaultbeat-apple-health doctor          # human-readable [OK]/[FAIL] checklist with hints\nvaultbeat-apple-health doctor --json   # machine-readable, for agents\n```\n\nIt checks, in order: config file → identity key (Keychain) → cloud reachability →\nbinding state → a real fetch-and-decrypt round trip, and prints a targeted hint for\nthe first thing that's broken (e.g. \"codes expire after 10 minutes — re-run bind for\na fresh QR\", or \"the stored key can no longer decrypt your data — delete this server\nin the iOS app and bind again\"). Exit code 0 = all healthy, 1 = something needs the\nhint above.\n\n## MCP Tools (33)\n\n`vaultbeat-apple-health serve` can start either a stdio MCP server or a streamable HTTP MCP\nserver. Every data tool accepts `owner` (user-ID prefix) to filter to one person and\n`fresh` to bypass the local cache — omit `owner` and both partners' records mix into\none pool, so per-person analysis must always pass it. The tool names dropped the old\nmisleading `get_partner_*` prefix in the 16-tool release (2026-07-16): the tools\nreturn whichever owners' envelopes this server holds, not specifically \"the partner\".\n\nBinding / status:\n\n- `vaultbeat_status` — local binding state (no keys/tokens in the result)\n- `vaultbeat_start_binding` — generate a fresh QR binding payload\n- `vaultbeat_poll_binding` — poll once for the iOS authorization\n- `vaultbeat_doctor` — diagnose this install end to end, and report which data types\n  are unavailable and why. Call it before telling a user their data is missing.\n\nHealth data:\n\n- `vaultbeat_sync_sleep` — recent sleep records (incl. heart-rate samples) with per-day\n  primary-session selection matching the iOS app\n- `get_sleep_detail` — per-night HR+RR+stage timeline with stage intervals\n- `get_water_intake` — recent daily intake + computed `average_daily_intake_liters`\n- `get_weight_trend` — daily weights + latest/avg/min/max + OLS weekly rate\n- `get_menstrual_cycle` — recent cycle samples + a next-period prediction (sensitive)\n- `get_symptoms` — recent HealthKit symptom days grouped by data owner (sensitive)\n- `get_notes` — free-text sleep/menstrual day annotations with their writer (sensitive)\n- `get_strength_log` — strength-training sessions with exercise-level sets × reps and\n  per-session `total_volume_kg` (owner's own sessions only; logged manually in the app)\n- `get_food_log` — per-day meals and items, with optional per-item kcal/protein/fat/carbs\n- `get_activity` — daily activity rings (steps/energy/exercise/stand/distance)\n- `get_resting_hr` — resting heart rate records + mean\n- `get_workouts` — workout records (type/duration/calories/distance)\n- `get_mindfulness` — mindful sessions per day\n- `get_hrv` — HRV/SDNN records + mean. `granularity=\"hourly\"` (default, `hrv_hourly` kind, one bucket/UTC hour w/ `sample_count`, 30-day window) or `\"raw\"` (`hrv` kind, per-sample, 3-day window)\n- `get_wrist_temp` — sleeping wrist-temperature baseline deviation\n- `get_vo2max` — cardiorespiratory fitness. Sparse by design: Apple only computes it\n  during outdoor walk/run/hike, so a handful of samples across a year is normal\n- `get_basal_energy` — basal metabolism (BMR) kcal, hourly buckets\n- `get_total_energy_burned` — basal + active = TDEE, with a 7-day average\n\nAnalysis (arithmetic over a daily series — the tools above return the rows, these\nreturn the maths):\n\n- `list_metric_series` — the series names the three tools below accept, with units.\n  Call it before guessing a name.\n- `get_metric_trend` — least-squares slope per day, endpoints, mean/median/min/max\n- `compare_metric_periods` — newest N days vs the N days before them, with the differences\n- `correlate_metric_series` — Pearson r between two series over days that have both\n\nThey exist because an agent asked for a trend produces one either way, and a\ncoefficient computed token-by-token is the least reliable number an LLM emits.\nThese return numbers only — no threshold, band, grade or verdict — and refuse rather\nthan fit a line to two points. Kinds with a richer shape (sleep stages, workouts,\nstrength sets, food, notes, symptoms, cycle) are deliberately not series: flattening\nthem to one number per day would answer a question you did not ask.\n\n**Every read tool also returns a `coverage` block**, and an agent that wants to say\n\"this is based on N days\" has nothing else to read. Fields: `days_covered`,\n`days_in_payload` (how many of those days have a row printed — smaller only when a\ndisplay cap cut the list), `first_day`, `last_day`, `span_days`,\n`days_missing_in_span`, `rows_counted`, `requested`, `requested_unit`,\n`window_satisfied`. Two things it exists to stop: counting the returned\narray instead (`limit` has already cut it, so the length answers a different question),\nand reading a long `span_days` as coverage — `days_covered: 12` with `span_days: 200` is\ntwelve scattered days, not seven months. Quote `days_covered` beside any average, trend\nor comparison drawn from a result: an average over 3 days and one over 30 are the same\nshape and the same number of digits, and this is the only field that tells them apart.\n\nWrites (all scoped to the account that paired this machine — none takes an `owner`\nargument, so an agent can write to its own account and nowhere else):\n\n- `log_weight_entry` — record a weigh-in. Carries that day's existing body composition\n  forward instead of erasing it. No `_append` twin: a day has one weight.\n- `log_strength_entry` / `log_food_entry` / `log_note` — **replace that whole day**. Each\n  returns a `replaced_*` field naming exactly what it removed, so an agent can notice and\n  re-send. `merge=True` appends instead, kept for existing callers.\n- `log_strength_append` / `log_food_append` / `log_note_append` — add to a day and\n  **cannot delete anything**.\n\n> ⚠️ **`log_*` and `log_*_append` are different operations, and the names are the whole\n> point.** An agent picks a tool by name, and `log_food_entry` reads as \"record something I\n> ate\" while it actually means \"overwrite this day with what I pass\" — a default that lives\n> in a schema nobody re-reads. **When a day may already have entries, `log_*_append` is\n> almost always the one you want**, and it is the safe default for an agent that cannot see\n> what is already there. The split also lets the two be annotated differently\n> (`destructiveHint` true vs false), which a boolean argument structurally cannot be.\n\n(The health-memory fact tools — `health_recall_*` / `health_remember` — were deleted with\nthe fact system in `491c850`, 2026-06-29: long-lived health knowledge lives in local\nmarkdown managed by the user's agent, not in an E2EE cloud round trip.)\n\nEvery health kind shares one decryption path (Curve25519 ECDH + HKDF-SHA256 + AES-GCM);\nthe server routes on `encrypted_sleep_blobs.metric_type` (the live kind list is whatever `check_metric_type_contract.py` prints — see\n`KNOWN_METRIC_TYPES` in `service.py`) and only the per-kind JSON decode/aggregate\ndiffers. The same service-layer functions back both the MCP tools and the matching CLI\nsubcommands — no duplicated logic.\n\n**Local record cache (2026-07-09):** all reads are cache-first. Decrypted records are\nkept per metric type under `~/.tether/mcp-local/cache/` (owner-only 0600 files, 0700\ndir, stamped with server_id + fetch time + the fetch's decrypt-error list). Default TTL\n600 s — override with `VAULTBEAT_MCP_CACHE_TTL` (0 disables). Within the TTL a repeat query\nis answered locally with zero network (~0.2 s vs 5-35 s); pass `--fresh` (CLI) or\n`fresh=true` (MCP tools) to force a cloud round trip. (Re)binding clears the cache.\n`mcp-sync` also accepts `?metric_type=` so single-metric fetches stop paying for every\nother kind's ciphertext; the client keeps its own post-decrypt filter, so older edge\ndeployments stay correct.\n\nMenstrual data is **sensitive**: it only reaches this server when the user explicitly\nopted in on iOS (absent otherwise), is decrypted locally, and is never re-exported.\n\nThe MCP server never exposes the private key or server token through tool results.\n\n## MCP Prompts\n\n`prompts/list` is the only channel through which an agent can ask what this server is\n*for*, rather than what it can call. Without it every client invents its own analysis\nroutine, and the two mistakes that do real damage with health data — reporting an\nassociation as a cause, and reading a gap as a zero — are left to whichever agent\nhappened to connect. Each entry names the tools it should call, and every one of them\nends with the same two shared constants: a style rule (say what the data covers before\nconcluding; describe, do not prescribe; no invented scores, grades or verdicts) and,\nwherever a read can legitimately come back empty, the absence rule (an empty result has\nfour different causes that need opposite fixes — call `vaultbeat_doctor`, which is the\ntool that tells them apart).\n\nEvery argument is optional. Omitted ones are filled with a default written into the\nprompt, so a client that sends nothing still gets a whole sentence rather than a hole.\n\n| Prompt | Argument | What it asks for |\n| --- | --- | --- |\n| `daily_brief` | — | The most recent day, set against the fortnight behind it, with the newest date named up front |\n| `sleep_review` | `nights` | Duration and stages across recent nights — keeping the nights that were never measured out of the average instead of folding them in as zeros |\n| `energy_balance` | `days` | Calories in against calories out, with the hours-incomplete days excluded rather than quietly dragging the average down |\n| `training_block_review` | `days` | Lifting and cardio volume beside the recovery signals from the same weeks, as context rather than a verdict |\n| `cycle_aware_read` | `metric` | A metric read against the same phase of earlier cycles, instead of against last week — which mixes phases and manufactures a trend |\n| `partner_check_in` | `days` | Both people's shared data side by side, read once per owner rather than averaged across two bodies, and never turned into a judgement of either |\n| `log_from_conversation` | `entry` | Turn something said in passing into an entry, asking for the parts that were left out rather than filling them in |\n| `why_is_this_empty` | `context` | Work out which of the four causes is behind an empty or stale result, and give the one next action for that one |\n\n## Transport Options\n\nStdio transport, for local MCP clients that launch the server as a subprocess:\n\n```bash\nvaultbeat-apple-health serve --transport stdio\n```\n\nHTTP transport, for MCP clients that connect over a network or reverse proxy:\n\n```bash\nvaultbeat-apple-health serve --transport http --host 127.0.0.1 --port 8000 --path /mcp\n```\n\nOptional HTTP flags:\n\n- `--sse-response` to use SSE-style HTTP responses instead of JSON responses.\n- `--stateful-http` to disable stateless HTTP mode for clients that require sessions.\n- `--generate-token` to mint and persist a bearer token, print client config, then exit.\n- `--show-token` to print the stored bearer token and exit.\n- `--allow-remote` to permit a non-loopback bind (requires a token; confirms intent).\n- `--no-token` to serve loopback HTTP without bearer auth.\n\n## Authenticating HTTP transport\n\nThe HTTP tool surface exposes **decrypted** health data, so it is gated by a static\nbearer token and refuses to bind a network-reachable address without explicit opt-in.\n\nGenerate (and persist) a token, then print ready-to-paste client config:\n\n```bash\nvaultbeat-apple-health serve --generate-token\n```\n\nServe over HTTP on loopback. Auth is on by default; the token is read from\n`VAULTBEAT_MCP_HTTP_TOKEN` (preferred, keeps it out of shell history) or the stored config:\n\n```bash\nvaultbeat-apple-health serve --transport http              # 127.0.0.1, bearer required\nvaultbeat-apple-health serve --transport http --no-token   # loopback only, no auth\n```\n\nClients send the token as a request header:\n\n```\nAuthorization: Bearer <token>\n```\n\nExample `mcp.json` (VS Code / Cursor style):\n\n```json\n{\n  \"servers\": {\n    \"vaultbeat-local\": {\n      \"type\": \"http\",\n      \"url\": \"http://127.0.0.1:8000/mcp\",\n      \"headers\": { \"Authorization\": \"Bearer <token>\" }\n    }\n  }\n}\n```\n\n**Binding beyond loopback** (e.g. `--host 0.0.0.0` for LAN/VPS) fails closed: it\nrequires both a token *and* the explicit `--allow-remote` flag. The token crosses the\nwire in clear text, so you must terminate TLS in front of it (e.g. Caddy / Cloudflare /\nnginx):\n\n```bash\nVAULTBEAT_MCP_HTTP_TOKEN=<token> vaultbeat-apple-health serve \\\n  --transport http --host 0.0.0.0 --allow-remote\n```\n\nClaude Desktop's config only speaks stdio, so bridge it to the HTTP server with\n[`mcp-remote`](https://github.com/geelen/mcp-remote):\n\n```json\n{\n  \"mcpServers\": {\n    \"vaultbeat-local\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"-y\", \"mcp-remote\", \"http://127.0.0.1:8000/mcp\",\n        \"--header\", \"Authorization: Bearer <token>\"\n      ]\n    }\n  }\n}\n```\n\nReveal the stored token any time with `vaultbeat-apple-health serve --show-token`.\n\n## Verification\n\n```bash\npython -m pytest -q mcp-local-server/tests\npython -m ruff check mcp-local-server/src mcp-local-server/tests\npython -m mypy mcp-local-server/src\n```\n\n<!-- mcp-name: io.github.Fino-wind/vaultbeat-apple-health -->\n",
  "bytes": 21000,
  "sha": "9614d4d765e9dccf492d88a1222c533f1437dca86f3ecd43f4b5a6423862ad2f",
  "repo_slug": "fino-wind/vaultbeat-mcp",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_fino_wind_vaultbeat_c13f7d2e/readme"
}