Apple Health MCP Connector
by NiksheyYadav
README.md
# Apple Health → Claude (MCP connector)
A private, single-user MCP server that lets Claude query **all** of your Apple Health data. It runs entirely on Cloudflare's free tier and doesn't need a Mac.
```
export.zip ──(Python CLI: parse → plan → upload)──┐
├─► POST /ingest ─► Cloudflare Worker ─► D1 (SQLite)
iPhone Shortcut @23:00 (last 36 h, per type) ──────┘ │
claude.ai custom connector ◄── OAuth (password) ── /mcp (Streamable HTTP) ◄──┘
```
| Piece | What it is |
|---|---|
| `src/index.ts` | `OAuthProvider` (`@cloudflare/workers-oauth-provider`): dynamic client registration, PKCE, single-user password page; `/ingest` behind a Bearer token |
| `src/tools.ts` | 11 MCP tools via `createMcpHandler` from the Agents SDK. `McpAgent` is now deprecated in the SDK, so this uses its stateless successor: no Durable Object needed |
| `src/ingest.ts` | One `INSERT … SELECT FROM json_each(?)` per type per request; idempotent upserts |
| `migrations/0001_init.sql` | Generic schema: new types need no migration |
| `cli/health_import.py` | Stdlib-only streaming importer (iterparse), resumable, daily write budget |
| `docs/SHORTCUT.md` | Nightly Shortcut + automation, and which types Shortcuts can and can't read |
| `plugin/`, `.claude-plugin/` | Claude Code plugin + marketplace (connects to your server, adds a `health-review` skill) |
| `test/` | Synthetic `export.zip` generator and an end-to-end OAuth + MCP smoke test |
## Free-tier limits (checked 2026-11-26) and how the design fits them
| Limit (Workers Free) | Value | Design response |
|---|---|---|
| D1 rows **written** / day | 100,000 (index writes count extra) | `health_samples` is `WITHOUT ROWID` with PK `(type, start_ts, id)`, so **1 row written per sample** and no secondary index. The CLI keeps a per-UTC-day budget (default 90k) from real `rows_written` and resumes the next day |
| D1 rows read / day | 5,000,000 | Every query is a PK range scan; `list_data_types` reads a small `type_stats` table, never `COUNT(*)` |
| D1 storage | 500 MB per DB, 5 GB per account | High-frequency types are stored as **hourly buckets** (sum/mean + min/max/count); routes are downsampled to ≤300 points |
| D1 queries per Worker call | 50 | ≤40 types per request, one statement each, run in a single `batch` |
| Bound params per query | 100 | Rows go in as one JSON string param (`json_each`) |
| Worker CPU / request | 10 ms | No hashing; the CLI sends ≤1,000 pre-aggregated rows per request |
| Worker requests / day | 100,000 | A full backfill uses ~1 request per 1,000 rows |
Daily limits reset at **00:00 UTC (05:30 IST)**. **Nothing here costs money.** Don't upgrade to Workers Paid; if you hit a limit, the CLI just stops and resumes the next day.
### Expected row counts
Run `plan` on your own export: it prints exact per-type numbers before anything is uploaded. As a rough guide for **~5 years of Apple Watch + iPhone**:
| | raw records in export.xml | rows stored in D1 |
|---|---|---|
| Heart rate, steps, energy, distance, exercise/stand minutes, audio, walking metrics… (≈20 high-frequency types, 2 sources) | 5–15 million | ≈ 600–900k (hourly buckets) |
| Sleep stages, RHR, HRV, SpO₂, weight, VO₂max, nutrition… (raw) | 100–300k | same |
| Workouts / routes / ring days | ~1–2k / ~500 / ~1,800 | same |
| **Total** | | **≈ 0.8–1.2 M rows → 9–14 days of backfill at 90k/day, ~80–120 MB** |
The upload goes **newest-first**, so recent months become queryable on day 1. Use `parse --since 2023-01-01` if you only want recent history.
## Setup (PowerShell, Windows)
Prerequisites: Node 20+, Python 3.9+, and a free Cloudflare account. Click **Use this template** on GitHub (or clone the repo) to get your own copy:
```powershell
git clone https://github.com/NiksheyYadav/apple-health-mcp
cd apple-health-mcp
```
```powershell
npm install
copy wrangler.example.toml wrangler.toml
```
`wrangler.toml` is git-ignored, so your database IDs never get committed.
**Not in India?** Set `tz_offset_minutes` in `shared/types.json` to your UTC offset in minutes (e.g. `-300` for New York in winter). Fixed offsets only: DST zones drift by an hour for part of the year.
```powershell
npx wrangler login
```
```powershell
npx wrangler d1 create apple-health
```
Copy the printed `database_id` into `wrangler.toml`.
```powershell
npx wrangler kv namespace create OAUTH_KV
```
Copy the printed `id` into `wrangler.toml`.
```powershell
npx wrangler d1 migrations apply apple-health --remote
```
Set the two secrets. Use long random values: the token goes in the CLI and Shortcut, and the password is what you type when connecting Claude.
```powershell
npx wrangler secret put INGEST_TOKEN
```
```powershell
npx wrangler secret put AUTH_PASSWORD
```
```powershell
npx wrangler deploy
```
Deploy prints your URL, e.g. `https://apple-health-mcp.<you>.workers.dev`. `PUBLIC_URL` is optional: set it in `wrangler.toml` only if you put the Worker on a custom domain.
To generate a random token:
```powershell
python -c "import secrets; print(secrets.token_urlsafe(32))"
```
## Phase 1: import your export
On the iPhone, go to **Health → profile picture → Export All Health Data**, then AirDrop or save `export.zip` to the PC.
Parse it. This streams the file, so it's fine at hundreds of MB, and it prints the row plan:
```powershell
python cli\health_import.py parse C:\path\to\export.zip
```
Re-print the plan at any time:
```powershell
python cli\health_import.py plan
```
Upload. This resumes safely and stops at the daily budget; run the same command again on following days:
```powershell
$env:HEALTH_INGEST_TOKEN = "<INGEST_TOKEN>"
python cli\health_import.py upload --url https://apple-health-mcp.<you>.workers.dev
```
To import a newer export later, use a fresh staging file (`--db health2.staging.db parse …`). Rows already in D1 cost 0 writes.
What gets imported: every `Record` (quantity + category), `Workout` (duration, distance, energy, HR stats, other `WorkoutStatistics`, event counts, metadata), `ActivitySummary`, `workout-routes/*.gpx` (distance, elevation gain, bbox, ≤300 points), and `electrocardiograms/*.csv` (classification and metadata; your name and DOB are dropped). Correlation wrappers and clinical records are skipped.
### curl tests
In PowerShell use `curl.exe`, not the `curl` alias.
```powershell
curl.exe https://apple-health-mcp.<you>.workers.dev/
```
```powershell
curl.exe -X POST https://apple-health-mcp.<you>.workers.dev/ingest -H "Authorization: Bearer <INGEST_TOKEN>" -H "Content-Type: application/json" -d '{\"type\":\"Weight\",\"unit\":\"kg\",\"start\":\"2026-11-26 07:00\",\"value\":\"71.5\",\"sources\":\"curl\"}'
```
Expected: `{"ok":true,"rows_written":1-3,...}` (the sample plus the `type_stats` catalogue). Send it again and you get `"rows_written":0` (dedupe).
```powershell
curl.exe -i -X POST https://apple-health-mcp.<you>.workers.dev/mcp
```
Expected: `401` with a `WWW-Authenticate` header pointing at the OAuth metadata.
If counts in `list_data_types` ever drift, recompute them. This does a full scan, so run it rarely:
```powershell
curl.exe -X POST https://apple-health-mcp.<you>.workers.dev/admin/recount -H "Authorization: Bearer <INGEST_TOKEN>"
```
## Phase 2: MCP tools
All times are **Asia/Kolkata**. Responses are compact JSON (column arrays), capped at 40k characters, with `limit`/`offset` pagination.
| Tool | Purpose |
|---|---|
| `list_data_types` | Every type with unit, rows, first/last date, kind; workout, route, ring and log coverage |
| `query_samples(type, start, end?, aggregate none\|hour\|day\|week\|month, stat?, label?, limit, offset)` | Raw rows or buckets. Default stat is `sum` for cumulative types, `avg` otherwise |
| `get_daily_summary(date?)` | All metrics for a day, rings, workouts, last night's sleep, manual log |
| `get_period_summary(start, end)` | Totals and per-day averages, workouts by type, ring averages and goal hits, sleep averages |
| `get_workouts(start, end?, type?)` / `get_workout_detail(id, include_points?)` | Workouts, plus stats, events, metadata and route summary (≤100 points on request) |
| `get_sleep(start, end?)` | Per night: bedtime, wake, asleep/in-bed hours, core/deep/rem/awake minutes |
| `compare_periods(metric, a_start, a_end, b_start, b_end)` | mean/median/min/max/total and change |
| `correlate(metric_a, metric_b, start, end, lag_days?)` | Daily Pearson r, Spearman ρ, slope |
| `get_streaks(rule)` | e.g. `"exercise_min >= 30"`, `"StepCount >= 10000"`, `"sleep_hours >= 7"` |
| `log_entry(date?, weight_kg?, bedtime?, wake_time?, notes?)` | Manual log (only the given fields change) |
A `metric` is any type name, optionally with a stat (`HeartRate:max`), or one of `sleep_hours, move_kcal, exercise_min, stand_hours, workout_min, workout_count, workout_kcal, weight_kg`.
**How data is counted:**
- **Overlapping sources:** for cumulative types (steps, energy, distance…), the iPhone and Watch are de-duplicated **per hour by taking the larger source**, then the hours are summed. This mirrors Health's own priority closely without double counting.
- **Sleep:** a night is assigned to the IST date it started. Anything starting before 12:00 belongs to the previous date, so an afternoon nap counts toward that evening's night. When several sources (Watch, a sleep app) overlap, the one with the most sleep wins.
- **Resolution:** high-frequency types are hourly (min/avg/max/count). Minute-level detail isn't kept; that's the price of fitting years of data into the free tier.
### Test with MCP Inspector
```powershell
npx @modelcontextprotocol/inspector
```
1. In the Inspector UI, set Transport to **Streamable HTTP** and URL to `https://apple-health-mcp.<you>.workers.dev/mcp`.
2. Click **Connect**. The OAuth flow opens the password page; enter `AUTH_PASSWORD`.
3. Go to **Tools → List Tools**, then run `list_data_types` and `get_daily_summary`.
You can also run the scripted equivalent, which registers a client, logs in, and calls every tool:
```powershell
python test\e2e_mcp.py --url https://apple-health-mcp.<you>.workers.dev --password <AUTH_PASSWORD>
```
### Add to claude.ai as a custom connector
1. In claude.ai, open **Settings → Connectors → Add custom connector**.
2. Name it `Apple Health`; URL `https://apple-health-mcp.<you>.workers.dev/mcp`. Leave the advanced OAuth fields empty: dynamic client registration handles it.
3. Click **Connect**. You'll see this Worker's login page; enter `AUTH_PASSWORD` and approve.
4. In a chat, enable it from the tools menu and ask e.g. *"How did my sleep in October compare to September, and does it correlate with next-day steps?"*
### Use it from Claude Code (plugin)
This repo is also a Claude Code plugin marketplace. The plugin connects Claude Code to **your** deployed server and adds a `health-review` skill:
```powershell
claude plugin marketplace add NiksheyYadav/apple-health-mcp
claude plugin install apple-health@apple-health-mcp
```
On install it asks for your server's MCP URL (`https://apple-health-mcp.<you>.workers.dev/mcp`). On first use you log in with your own `AUTH_PASSWORD`. The plugin holds no data and no credentials; every user points it at their own deployment.
## Phase 3: nightly Shortcut
See **[docs/SHORTCUT.md](docs/SHORTCUT.md)**. It covers the step-by-step build, the 23:00 *Run Immediately* automation plus a charger trigger (Health is unreadable while the phone is locked), and which types Shortcuts can and can't read (compiled from public sources; confirm in the Type picker on your phone).
## Local development
```powershell
npx wrangler d1 migrations apply apple-health --local
```
`.dev.vars` holds local-only secrets (git-ignored), so `npx wrangler dev` runs on `http://localhost:8787`. Then:
```powershell
python test\make_sample_export.py export.zip
python cli\health_import.py --db dev.staging.db parse export.zip
$env:HEALTH_INGEST_TOKEN = "dev-ingest-token"; python cli\health_import.py --db dev.staging.db upload --url http://localhost:8787
python test\e2e_mcp.py --url http://localhost:8787 --password dev-password --write
```
## Troubleshooting
- **claude.ai "connect" fails:** open `https://<your-worker>/.well-known/oauth-protected-resource/mcp`. `resource` must be your real `…workers.dev/mcp` URL. If it shows anything else, set `PUBLIC_URL` in `wrangler.toml` and deploy again.
- **First nightly run:** watch `npx wrangler tail` once. A very large heart-rate POST could exceed the 10 ms CPU limit (error 1102); if so, shorten the window from 36 h to 24 h.
- **Upload stops with a "limit exceeded" error:** that's the D1 daily cap. Re-run the same `upload` command after 05:30 IST.
## Security notes
- `/ingest` and `/admin/*` need the Bearer `INGEST_TOKEN`. MCP needs an OAuth token that is only issued after the password page.
- Password and token checks are constant-time. After 10 wrong passwords in an hour, the form is locked.
- Grant parameters are re-parsed from the URL on submit, so a tampered form body can't change the redirect.
- Your data lives in your own Cloudflare account. Rotate either secret with `wrangler secret put` (OAuth grants live in `OAUTH_KV`).
## License
MIT. Your health data is yours: this repo contains code only, and each person deploys their own server and database.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues