apple-health-mcp
README.md
# apple-health-mcp
Sync **Apple Health** from your iPhone to a small server of your own, and let any AI agent that speaks
**MCP** read it. Ask it about your health data, track goals, and get daily and weekly summaries.
```
iPhone server (e.g. on Vercel) AI agent
┌──────────────┐ sends ┌──────────────────────────┐ asks ┌─────────────┐
│ iOS app │ ───────▶ │ Database + MCP server │ ◀──── │ Questions, │
│ (reads │ health │ (stores (answers │ tools │ summaries, │
│ HealthKit) │ data │ history) questions) │ │ goals │
└──────────────┘ └──────────────────────────┘ └─────────────┘
ios/ folder src/ folder Grok Bot, Claude Code, ...
```
Apple Health data lives only on your iPhone, so an app on the phone has to send it out.
This service is the mailbox it sends to. It stores the history and lets your agent look things up.
It was built for [Grok Bot](https://docs.x.ai/grok-bot), but works with any MCP client that can send an
`Authorization: Bearer` header.
## How it works
| Piece | What it does | File |
| --- | --- | --- |
| **Ingest endpoint** `POST /api/ingest` | The iPhone app uploads data here. Needs `INGEST_TOKEN`. | `src/ingest.ts` |
| **MCP endpoint** `POST /api/mcp` | Your agent calls tools here. Needs `MCP_TOKEN`. | `src/mcp.ts` |
| **Database** | Daily numbers, workouts, goals. Postgres (Neon) | `src/db.ts`, `src/store.ts` |
| **Goals** | Daily / weekly / monthly targets, and deadline targets like a goal weight | `src/goals.ts` |
| **Summaries** | Totals, averages, comparisons, trends | `src/summary.ts` |
**MCP** (Model Context Protocol) is a standard plug shape for giving an AI new abilities. You give your agent
this service's address and key, and it gains these tools:
| Tool | Use it for |
| --- | --- |
| `get_overview` | Today's date, units, how fresh the data is, list of goals |
| `get_day` | "How did I do yesterday?" Every metric, workouts, daily goals |
| `get_period_summary` | Weekly/monthly reviews, compared with the previous period |
| `get_metric_trend` | "Is my resting heart rate going down?" Daily series + 7-day average |
| `list_workouts` | Runs (with pace), lifting sessions, etc. |
| `get_goal_progress` | On track / behind / met, hit rate, streaks, weight-goal projection |
| `set_goal` / `archive_goal` | "Set a goal to run 3 times a week" |
| `get_sleep_nights` | Bedtime, wake, time in bed, awake gaps, night-time pickups, time zone and city, night by night |
| `correct_sleep_night` | "I actually went to bed at 11:30 last night" (the phone then fixes Apple Health) |
### Metrics
Steps, walking + running distance, active calories, exercise minutes, calories eaten, protein, carbs, fat,
sleep (total, deep, REM, core, awake; needs a wearable), time in bed (from the phone's dock and alarm), resting heart rate, HRV, VO2 max, weight, body fat %.
> **Calories eaten** only appear in Apple Health if you log food in an app that writes to Health
> (MyFitnessPal, Lose It!, Cronometer, ...).
>
> **Weightlifting**: Apple Health records the workout's time, calories and heart rate, but not sets/reps/weights.
## Sleep without a watch
The iPhone app logs each night from the phone's charger dock and alarm, through three Shortcuts actions
(Log Bedtime, Log Off Charger, Log Wake) that run while the phone is locked. Each night goes to Apple Health
as In Bed blocks (Awake blocks for time up in the night) and to the server with its raw events and city.
Nights are filed under the evening they started: Friday night to Saturday morning is Friday.
Setup is in the app under **4. Sleep**. The rules are in `ios/HealthBridge/Sleep/SleepEngine.swift`.
| Piece | File |
| --- | --- |
| Upload `POST /api/sleep`, corrections `GET /api/sleep/pending` + `POST /api/sleep/applied` (all need `INGEST_TOKEN`) | `src/sleep.ts`, `src/routes.ts` |
| Nights table `sleep_nights`; the server keeps the daily `time_in_bed` metric in step with it | `src/db.ts`, `src/sleep.ts` |
## Try it on your computer
You need [Node.js](https://nodejs.org) 20 or newer.
```bash
npm install
```
```bash
npm run dev
```
This starts the service at `http://localhost:8787` with a throwaway database full of **fake** data
(90 days of someone who runs and lifts 3x a week). Nothing is saved when you stop it (Ctrl+C).
Use `FAKE_DATA=0 npm run dev` to start empty, e.g. to test the iPhone app with your real data.
Run the automatic checks:
```bash
npm test
```
## Settings (environment variables)
See `.env.example`. On Vercel, these go in *Project → Settings → Environment Variables*.
| Name | Meaning |
| --- | --- |
| `DATABASE_URL` | Postgres connection string (Neon) |
| `INGEST_TOKEN` | Secret key the iPhone app uses (make one with `openssl rand -hex 32`) |
| `MCP_TOKEN` | A *different* secret key your agent uses |
| `USER_TIMEZONE` | e.g. `America/New_York`, decides what "today" means |
| `UNITS` | `imperial` (lb, mi) or `metric` (kg, km) |
## Upload format (for the iPhone app)
```json
{
"daily": [
{ "date": "2026-11-22", "metric": "steps", "value": 8123 },
{ "date": "2026-11-22", "metric": "weight", "value": 84.2 }
],
"workouts": [
{ "id": "HealthKit-UUID", "activity_type": "running",
"start": "2026-11-22T13:05:00Z", "end": "2026-11-22T13:41:00Z",
"duration_s": 2160, "distance_m": 5000, "energy_kcal": 380,
"avg_heart_rate": 151, "max_heart_rate": 171, "source": "Apple Watch" }
],
"deleted_workout_ids": []
}
```
- `date` is the day in the phone's time zone. Re-sending a day overwrites it, so the phone can safely re-send recent days.
- Values are in storage units: kg, km, kcal, g, minutes (sleep), bpm, ms, %, mL/kg/min.
- `activity_type` is the HealthKit workout type in snake_case (`running`, `traditional_strength_training`, ...).
## Privacy
This holds sensitive health data. Both endpoints require a secret key. Without a key configured, the endpoint
refuses all requests. Keep the keys out of git (`.env` is ignored), and use different keys for the
phone and for your agent. Run your own copy: don't send your health data to a server someone else controls.
## Put it online
1. Import this repo into [Vercel](https://vercel.com). It detects Hono and runs `src/index.ts` with no extra setup.
2. Add a Postgres database from the Vercel Marketplace (Neon). That sets `DATABASE_URL`; tables are created on first use.
3. Set `INGEST_TOKEN`, `MCP_TOKEN`, `USER_TIMEZONE` and `UNITS` (see above), then redeploy.
4. Build the iPhone app and point it at `https://<your-app>.vercel.app` with `INGEST_TOKEN`: see [`ios/README.md`](ios/README.md).
## Connect your agent
The MCP address is `https://<your-app>.vercel.app/api/mcp`, with the header `Authorization: Bearer <MCP_TOKEN>`.
- **Grok Bot:** ask it in chat to add a remote MCP connector with that address. It collects the key in a secure field.
- **Claude Code:**
```bash
claude mcp add --transport http apple-health https://<your-app>.vercel.app/api/mcp --header "Authorization: Bearer <MCP_TOKEN>"
```
- **Anything else:** try it first with the [MCP Inspector](https://github.com/modelcontextprotocol/inspector)
(`npx @modelcontextprotocol/inspector`, transport "Streamable HTTP").
Some clients save the tool list when you add the connector and don't fetch it again. If your agent doesn't see a
new tool after an update, remove the connector and add it at a new address (e.g. `.../api/mcp?v=2`; the server
ignores the query string). `get_overview` always lists the tools the server has now.
## License
[MIT](LICENSE)