Skip to main content
Glama
README.md
# rhythm-fitbit-mcp

A self-hosted, single-user MCP server that gives AI agents (Claude web/desktop/mobile, Claude Code, ChatGPT, Cursor, Codex,
Gemini CLI, …) access to **all raw data** from a Fitbit Air, via the Google Health API.

It is a pure **data layer**. It fetches every readable data type, keeps it fresh in SQLite, and serves it
through MCP tools. All analysis, including trends, baselines, correlations and dashboards, is left to the agent.

```
Fitbit Air ─BT─► Google Health app ─► Google cloud ──webhook / 30-min poll──► SQLite (data/fitbit.db)
                                                                                    │
Claude / ChatGPT / Cursor … ──HTTPS + (Google login | bearer token)──► nginx ──► MCP server (/mcp)
```

- **Data**: all 40 readable Google Health data types plus profile, settings and devices. Data is kept at full
  resolution (per-second heart rate, per-minute steps/SpO2…), with the full API JSON preserved and history backfilled.
- **Fresh**: webhooks (near real-time), a 30-minute catch-up poll, a nightly 7-day re-sync, and an on-demand
  freshness check before answering.
- **Private**: OAuth login restricted to one Google account, or a generated bearer token. `run_sql` is read-only,
  enforced by the SQLite engine.

> The legacy Fitbit Web API was shut down on 2026-11-02. This server uses its replacement, the
> [Google Health API](https://developers.google.com/health).

---

## 1. Google Cloud setup (one time, about 10 minutes)

1. **Phone**: install the **Google Health** app, sign in, and make sure your Fitbit Air syncs.
   The API only returns data for accounts linked to Google Health.
2. [console.cloud.google.com](https://console.cloud.google.com) → **New project**.
   Note the **project number** shown on the dashboard.
3. **APIs & Services → Library** → enable **Google Health API**.
4. **Google Auth Platform → Branding / Audience**: user type **External**. Fill in the app name and emails.
5. **Data Access → Add or remove scopes** → add every `googlehealth.*.readonly` scope (activity_and_fitness,
   health_metrics_and_measurements, sleep, nutrition, ecg, irn, location, profile, settings), plus `openid` and
   `.../auth/userinfo.email`.
6. **Audience**: keep publishing status **Testing** and add your Google account under **Test users**.
   In Testing mode Google expires the refresh token after **7 days**. When it does, reconnect (`/setup` →
   Reconnect, or `fitbit-mcp auth` locally). `data_status` and `/setup` show when access expires, warn 48 h
   ahead, and the catch-up fills any gap once you reconnect, so no data is lost. Claude web / ChatGPT
   connectors will also ask you to sign in again about weekly.
7. **Clients → Create client → Web application**. Add these **Authorized redirect URIs**:
   - `https://YOUR_DOMAIN/google/callback` (health-data consent, setup login, webhook registration)
   - `https://YOUR_DOMAIN/auth/callback` (MCP client login)
   - `http://localhost:8765/callback` (optional: local development)

   Copy the **Client ID** and **Client secret**.

## 2. Deploy on the VPS

Requirements: Docker + Compose, your existing nginx, certbot, and a DNS A record for `YOUR_DOMAIN` pointing at the VPS.

```bash
git clone https://github.com/vaasminion/rhythm-fitbit-mcp-public.git fitbit-mcp && cd fitbit-mcp
cp .env.example .env        # fill the 5 values: DOMAIN, ALLOWED_EMAIL, GOOGLE_CLIENT_ID,
                            # GOOGLE_CLIENT_SECRET, GOOGLE_PROJECT_NUMBER
docker compose up -d        # app listens on 127.0.0.1:8000 only

# hook it into your existing nginx
sudo cp deploy/nginx/fitbit-mcp.conf /etc/nginx/sites-available/
sudo nano /etc/nginx/sites-available/fitbit-mcp.conf      # set server_name to YOUR_DOMAIN
sudo ln -s /etc/nginx/sites-available/fitbit-mcp.conf /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d YOUR_DOMAIN
```

Then open **`https://YOUR_DOMAIN/setup`**:

1. Sign in with Google. Only `ALLOWED_EMAIL` is accepted.
2. **Connect Fitbit data** → approve all scopes. The backfill starts automatically, newest 14 days first.
3. **Enable webhooks** (recommended). This asks Google once for Cloud-project access to register the webhook
   subscribers. That token is used once and then revoked. Without webhooks, data still syncs every 30 minutes.
4. Copy your MCP URL / bearer token / client snippet.

All data lives in the **`./data` folder next to `docker-compose.yml`**, so you can read it directly on the VPS:

| Path | What |
|---|---|
| `data/fitbit.db` | SQLite database. Open it with `sqlite3 data/fitbit.db` or DB Browser (copy it first, or use a backup, while the server runs) |
| `data/backups/` | nightly backups, 7 kept |
| `data/secrets/` | generated bearer token + encryption keys. Never in `.env` or git; keep private |
| `data/oauth/` | encrypted MCP client registrations |

Files are owned by `PUID:PGID` (default `10001`). Set `PUID=$(id -u)` and `PGID=$(id -g)` in `.env` so your own user
owns them, then restart the container.

If your nginx runs in Docker itself, put both containers on one network and use `proxy_pass http://fitbit-mcp:8000`.

## 3. Connect your AI clients

MCP URL: `https://YOUR_DOMAIN/mcp`. `/setup` shows ready-to-paste snippets with your token.

| Client | Auth | How |
|---|---|---|
| Claude web / desktop / mobile | Google login | Settings → Connectors → Add custom connector → URL |
| ChatGPT | Google login | Settings → Apps & Connectors → Advanced → **Developer mode** → Create → URL, OAuth |
| Claude Code | bearer | `claude mcp add --transport http fitbit https://YOUR_DOMAIN/mcp --header "Authorization: Bearer <TOKEN>"` |
| Codex CLI | bearer | `~/.codex/config.toml`: `[mcp_servers.fitbit]` `url` + `http_headers` |
| Cursor / VS Code / Windsurf | Google login or bearer | `mcp.json` → `url` + `headers` |
| Gemini CLI | bearer | `settings.json` → `mcpServers.fitbit.httpUrl` + `headers` |
| n8n / LangChain / Agents SDK / scripts | bearer | any MCP client with Streamable HTTP + header |
| stdio-only clients | bearer | `npx -y mcp-remote https://YOUR_DOMAIN/mcp --header "Authorization: Bearer <TOKEN>"` |

The server speaks Streamable HTTP only. Clients that only support the legacy SSE transport can connect through
`mcp-remote`. To allow another OAuth client's redirect URI, add it to `OAUTH_REDIRECT_ALLOWLIST` in `.env`.

## 4. Tools

| Tool | What it returns |
|---|---|
| `data_status` | connection, freshness, device battery/last sync, backfill progress, which types have data |
| `list_data_types` | every type with counts, date coverage, sync status, value fields |
| `get_schema` / `run_sql` | SQLite schema + example queries / read-only SQL over everything (5000-row cap, 15 s timeout) |
| `get_raw_data` | exact API JSON, cursor-paginated (any type, any view) |
| `api_passthrough` | live read-only Google Health API call (list / reconcile / rollUp / dailyRollUp) |
| `get_daily_data` | Google's daily records + daily rollups per local day |
| `get_sleep` | sessions, local bed/wake times, stages, short awakenings |
| `get_heart_rate` | per-sample or bucketed (1min…1h) heart rate in local time |
| `get_intraday` | any minute-level type (steps, SpO2, AZM, altitude…) |
| `get_exercises` / `get_exercise_tcx` | workouts / raw TCX (GPS route) |
| `get_timezones` | UTC offset per local day as reported by the data (travel) |
| `get_profile` / `get_settings` / `get_devices` | account resources |
| `export_csv` | CSV inline (+ a 15-minute download link over HTTP) |
| `sync_now` | fetch from Google immediately |

**Not available from Google's API**: Fitbit's sleep score, readiness score and cardio load. The write-only
types (menstrual cycle, moods, ovulation tests, symptoms) can't be read either.

## 5. Local development (no Docker needed)

Windows PowerShell shown; on macOS/Linux use `python3.11 -m venv .venv && source .venv/bin/activate`.

```powershell
py -3.11 -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements-dev.txt   # pinned, tested versions
pip install -e . --no-deps
pre-commit install
copy .env.example .env       # set LOCAL_MODE=1, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET
fitbit-mcp auth              # browser consent → http://localhost:8765/callback
fitbit-mcp status
fitbit-mcp sync --days 14    # or: fitbit-mcp sync --backfill
fitbit-mcp serve             # stdio, e.g. claude mcp add fitbit -- <path>\.venv\Scripts\fitbit-mcp.exe serve
fitbit-mcp serve --transport http --port 8000   # bearer-only HTTP (fitbit-mcp token prints the token)
npx @modelcontextprotocol/inspector .venv\Scripts\fitbit-mcp.exe serve
pytest
```

**Local Docker mode** (Claude Code running in a container next to it): use the same image with
`fitbit-mcp serve --transport stdio` and `LOCAL_MODE=1`, mounting the same `./data` folder at `/data`.

**Dependencies**: declared in `pyproject.toml`; `requirements.txt` (runtime) and `requirements-dev.txt` are pinned
lock files generated from it. After changing dependencies, regenerate both:

```powershell
pip-compile --strip-extras -o requirements.txt pyproject.toml
pip-compile --strip-extras --extra dev -o requirements-dev.txt pyproject.toml
```

When compiling on Windows, pip-compile pins Windows-only packages (`pywin32`) without a marker. Re-add
`; sys_platform == "win32"` to that line in both files, or the Linux Docker build fails.

## 6. Operations

- **Update**: `git pull && docker compose up -d --build`
- **Logs**: `docker compose logs -f app`
- **Status**: `docker compose exec app fitbit-mcp status`
- **Bearer token**: `docker compose exec app fitbit-mcp token`
- **Backups**: nightly at 03:30 UTC into `./data/backups/` (7 kept). Copy them anywhere, e.g. `scp vps:fitbit-mcp/data/backups/* .`
- **Sync everything missing** (full history, gaps): `docker compose exec app fitbit-mcp sync --missing`
- **Re-auth**: if Google revokes the token, `data_status` reports `reauth_required` and `/setup` shows *Reconnect*.
- **Force older history**: `docker compose exec app fitbit-mcp sync --backfill --since 2018-01-01 --types steps,heart-rate`

## 7. Security model

- The app binds to `127.0.0.1` on the VPS. Only nginx (TLS via certbot) can reach it.
- **OAuth 2.1** (DCR + CIMD, PKCE S256, RFC 9207 `iss`) via FastMCP's OAuth proxy. Login is delegated to Google, and
  the verifier rejects every account except the verified `ALLOWED_EMAIL`. MCP client redirect URIs are allowlisted.
- **Bearer token** is generated randomly on first boot and compared in constant time.
- **Google refresh token** is Fernet-encrypted at rest. The OAuth client store is encrypted too. Secrets live in
  `./data/secrets` with mode 0600.
- **`run_sql`** uses a read-only connection, `PRAGMA query_only`, an authorizer that permits only SELECT/READ/FUNCTION,
  a 15 s progress-handler timeout and a row cap.
- **Webhooks** check the shared secret (constant time) and Google's ECDSA signature against the rotating public
  keyset. They acknowledge with 204 and process asynchronously.
- **No writes to Google**: the server requests read-only scopes. `api_passthrough` blocks write methods.
- Logs never contain health values or tokens.

## Contributing

Issues and pull requests are welcome. Before opening a PR:

```bash
pip install -r requirements-dev.txt && pip install -e . --no-deps
pre-commit install     # ruff + detect-secrets
pytest
```

Never commit `.env`, anything under `data/`, or real health data. Tests use synthetic fixtures only.

## Disclaimer

This is an independent project. It is not affiliated with, endorsed by, or supported by Google or Fitbit.
"Fitbit" and "Google Health" are trademarks of Google LLC. The data it serves is not medical advice.

## License

[MIT](LICENSE)