Skip to main content
Glama
garmin-personal-mcp

garmin-personal-mcp

by nikakhachi
README.md
# garmin-personal-mcp

A [Model Context Protocol](https://modelcontextprotocol.io) server that gives Claude **read-only** access to
**your own** Garmin Connect data through Garmin's **official Personal API**: sleep, HRV, Body Battery, stress,
heart rate, activities, VO2 max and body composition.

You can run it two ways:

- **Remote, on Cloudflare Workers.** You add it to Claude as a custom connector and use it from claude.ai, Claude
  Desktop or the mobile apps. Each request carries your own Garmin key in a request header.
- **Local, over stdio.** It runs on your machine and plugs into Claude Desktop.

Its flagship tool, `weekly_checkin`, returns a compact week-over-week health and fitness report in a single call,
so "How was my week?" just works.

> **Unofficial project.** It is not affiliated with, endorsed by or supported by Garmin. It is meant for each
> person to use with **their own** Garmin Personal API key, under Garmin's terms. Each key only ever reads its
> owner's data.

## Contents

- [Features](#features) · [Tools](#tools) · [Create a Personal API key](#create-a-garmin-personal-api-key)
- [Remote: deploy your own copy on Cloudflare Workers](#remote-deploy-your-own-copy-on-cloudflare-workers)
  - [Add it to Claude](#add-it-to-claude) · [Adding people later](#adding-people-later) ·
    [Opening it to anyone](#opening-it-to-anyone) · [How the remote server works](#how-the-remote-server-works)
- [Local: run it on your machine (stdio)](#local-run-it-on-your-machine-stdio)
- [Troubleshooting](#troubleshooting) · [Privacy and security](#privacy-and-security) ·
  [Limitations](#limitations) · [Development](#development)

## Features

- **11 read-only tools** covering daily wellness, sleep, HRV, Body Battery and stress, heart rate, fitness,
  activities and body composition. All of them are annotated `readOnlyHint` for the client.
- **Claude-friendly output.** Responses are compact JSON plus a one-line summary. Units are converted (h:mm, km,
  kg) and times are local. Missing data is marked explicitly with `no_data` or `partial` instead of empty objects.
  Intraday series come only on request, downsampled to 15 minutes.
- **Robust client.** It handles the key → token exchange and caches the token: a 0600 file locally, encrypted KV
  remotely. It renews tokens automatically and retries once on 401. On 429 and 5xx it backs off with jitter and
  honours `Retry-After`. It splits date ranges where Garmin caps them.
- **Safe by construction.** Secrets never appear in logs or errors. Activity output is built from a field
  whitelist, so GPS tracks, polylines, FIT files and owner details never reach the model. The remote server logs
  only the tool name, status and latency of each call.
- **Spec-driven.** Types are generated from Garmin's OpenAPI document. Observed quirks are recorded in
  [`docs/API_NOTES.md`](docs/API_NOTES.md).

## Tools

| Tool                          | What it returns                                                                                                                                                                                                                        | Try asking                                                  |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| `weekly_checkin`              | **Start here for weekly reviews.** A Mon–Sun table of sleep, sleep score, HRV, resting HR, Body Battery high/low, stress and steps; averages and deltas against the previous week; all activities; VO2 max change; data-quality notes. | "Do my weekly health check-in."                             |
| `get_daily_summary`           | One day: steps, calories, resting/min/max HR, stress, Body Battery, intensity minutes, floors, SpO2, respiration.                                                                                                                      | "How did yesterday look?"                                   |
| `get_sleep`                   | For each night (≤31): duration, stages, bed and wake times, respiration, resting HR, plus score, need and naps when Garmin provides them.                                                                                              | "How has my sleep been this month?"                         |
| `get_hrv`                     | Overnight HRV, 7-day average, baseline and status, or an explicit "no HRV" answer.                                                                                                                                                     | "Is my HRV trending down?"                                  |
| `get_body_battery_and_stress` | Daily Body Battery and stress; optional 15-minute Body Battery samples (≤7 days).                                                                                                                                                      | "When did my Body Battery crash on Tuesday?"                |
| `get_heart_rate`              | Daily resting/min/max HR and HR zones; optional 15-minute intraday series (≤7 days).                                                                                                                                                   | "What's my resting heart rate trend over the last 3 weeks?" |
| `get_fitness_metrics`         | VO2 max trend (running and cycling), fitness age and what drives it, HR zones.                                                                                                                                                         | "Is my VO2 max improving since September?"                  |
| `list_activities`             | Workouts in a range (≤90 days), optionally filtered by type: duration, distance, pace or speed, HR, calories, training effect.                                                                                                         | "List my runs from the last month."                         |
| `get_activity`                | One activity in detail: splits, training effect and load, cadence, power, workout steps. Never GPS.                                                                                                                                    | "Break down yesterday's interval session."                  |
| `get_body_composition`        | Weigh-ins, BMI, body fat and other composition fields, weight trend, weight goal.                                                                                                                                                      | "How has my weight changed this quarter?"                   |
| `get_api_status`              | Whether the key works, token source, age and expiry, region, time zone, access mode, and how to fix problems. Never shows the key or its hash.                                                                                         | "Is Garmin connected?"                                      |

Dates are `YYYY-MM-DD` local calendar days. Sleep nights are labelled with the date you **woke up**.

## Create a Garmin Personal API key

1. In Garmin Connect, open **Personal API Key** (Garmin Connect → Settings → Personal API Key) and create a key.
2. Pick an expiry: 30, 90, 180 or 365 days. When the key expires, the server stops working until you create a
   new one. `get_api_status` will tell you when that happens.
3. Copy the key somewhere safe. Treat it like a password: anyone with it can read your Garmin data.

Garmin's API reference: [Personal API docs](https://developer.garmin.com/gc-developer-program/personal/swagger-docs/).

## Remote: deploy your own copy on Cloudflare Workers

The remote server is a stateless MCP endpoint at `https://<worker>.<subdomain>.workers.dev/mcp`, served over
HTTPS on port 443. By default it only accepts keys you have explicitly allowed (by hash), so a deployed copy is
private to you until you add other people.

### What you need

- A [Cloudflare](https://dash.cloudflare.com/sign-up) account. The Free plan works; see
  [Costs and limits](#costs-and-limits).
- Node.js 22.12 or newer, and this repository: `git clone <this repository> && cd garmin-personal-mcp && npm ci`.
- A Garmin Personal API key ([see above](#create-a-garmin-personal-api-key)).

### Deploy

1. **Log in to Cloudflare.**

   ```bash
   npx wrangler login
   ```

2. **Create the KV namespace** that caches access tokens. Paste the `id` it prints into `wrangler.toml`, in place
   of `REPLACE_WITH_YOUR_KV_NAMESPACE_ID`:

   ```bash
   npx wrangler kv namespace create TOKEN_KV
   ```

3. **Hash your key.** The script reads the key from a hidden prompt (or from a pipe) and prints only its SHA-256.
   The key never leaves your machine.

   ```bash
   npm run --silent hash-key
   ```

4. **Allow your key** by storing the hash as a Worker secret. Paste the hash when prompted. If the Worker doesn't
   exist yet, Wrangler offers to create it; answer yes.

   ```bash
   npx wrangler secret put ALLOWED_KEY_HASHES
   ```

5. **Deploy.**

   ```bash
   npx wrangler deploy
   ```

   Wrangler prints the URL, e.g. `https://garmin-personal-mcp.<your-subdomain>.workers.dev`.
   `curl https://garmin-personal-mcp.<your-subdomain>.workers.dev/health` should answer `ok`.

### Add it to Claude

In Claude, go to **Customize → Connectors → Add → Custom → Web** and fill in:

| Field           | Value                                                                                                                              |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| URL             | `https://<worker>.<subdomain>.workers.dev/mcp`                                                                                     |
| Authentication  | **No sign in**                                                                                                                     |
| Request headers | `Authorization` = `Bearer <your Garmin Personal API key>`                                                                          |
|                 | Optional: `X-Timezone` = an [IANA time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) such as `Europe/Berlin` |

Then ask Claude _"Is Garmin connected?"_ or _"Do my weekly health check-in"_.

Without `X-Timezone`, the server uses the time zone from your Garmin profile, which it caches for 12 hours, to work
out what "today" is and to show local times. Set the header if you want a different zone, for example while
travelling.

### Adding people later

Each person uses their **own** Garmin key. To let someone in:

1. They run `npm run --silent hash-key` on their own machine (or any SHA-256 tool on their key) and send you only
   the hash. You never need their key.
2. Set the secret again with **every** allowed hash, comma-separated. `secret put` replaces the whole value:

   ```bash
   npx wrangler secret put ALLOWED_KEY_HASHES
   # paste: <your hash>,<their hash>
   ```

That's all. You don't redeploy any code, because the new secret takes effect on the next request. Each person then
adds the connector in their own Claude account with their own key. When someone's key expires, they create a new
one and you replace their hash.

### Opening it to anyone

The Worker can also accept **any** well-formed key. Only switch this on deliberately:

1. **Add a rate limit first.** In `wrangler.toml`, uncomment the `[[ratelimits]]` block (binding `RATE_LIMITER`).
   It limits requests per key hash, 60 per minute by default. Cloudflare counts per location and approximately.
2. **Set `ALLOW_ANY_KEY = "true"`** in the `[vars]` section of `wrangler.toml`.
3. **Redeploy:** `npx wrangler deploy`. `get_api_status` then reports `access_mode: "open"` and
   `rate_limit: "on"`.

> **Whoever runs the Worker sees every key sent to it.** The code never logs or stores keys, but an operator can
> change the code. If you use someone else's deployment, you are trusting them with read access to your Garmin
> data. The safest setup is for everyone to deploy their own copy.

Open mode also lets strangers make your Worker call Garmin's token service with arbitrary keys. The rate limit
bounds that, but you pay for (and are accountable for) the traffic.

### How the remote server works

- **Transport:** MCP Streamable HTTP at `/mcp`, stateless (no sessions, plain JSON responses, POST only).
  `GET /health` answers `ok`. Every other path returns 404. In particular there is no OAuth and there are no
  OAuth discovery documents. Plain `http://` is refused (except `localhost` for development), and no CORS headers
  are sent.
- **Access check, before any KV or Garmin call:** the `Authorization: Bearer <key>` header must be well formed.
  In allowlist mode, the key's SHA-256 must also be in `ALLOWED_KEY_HASHES`; this comparison is constant-time. If
  the secret is missing or empty, nobody is allowed. Every failure gets the same 401 JSON error. The optional rate
  limit applies next.
- **Token cache:** Garmin access tokens are cached in KV under `token:<sha256(key)>` and expire 5 minutes before
  the token does. The value is encrypted with AES-256-GCM under a key derived from your API key (HKDF-SHA-256). So
  someone who can read the KV namespace can't use the tokens or tie an entry to a key without that key. On a 401
  from Garmin, the cached token is dropped, a new one is fetched and the call is retried once. The profile time
  zone is cached the same way under `tz:<sha256(key)>` for 12 hours.
- **Logging:** one line per tool call, `{"tool":"get_sleep","status":"ok","ms":312}`. Nothing else: no keys,
  tokens, hashes, URLs or Garmin data, which is health data. Cloudflare's automatic invocation logs are turned off
  in `wrangler.toml`.

### Remote configuration

| Name                 | Kind                  | Default          | Meaning                                                                                 |
| -------------------- | --------------------- | ---------------- | --------------------------------------------------------------------------------------- |
| `ALLOWED_KEY_HASHES` | secret                | (none: deny all) | Comma-separated SHA-256 hex digests of allowed keys (`npm run --silent hash-key`).      |
| `ALLOW_ANY_KEY`      | var (`wrangler.toml`) | `"false"`        | `"true"` skips the allowlist and accepts any well-formed key. Add the rate limit first. |
| `GARMIN_REGION`      | var (`wrangler.toml`) | `"global"`       | `"cn"` for Garmin Connect China accounts. One region per deployment.                    |
| `TOKEN_KV`           | KV binding            | (required)       | Encrypted token and time-zone cache.                                                    |
| `RATE_LIMITER`       | rate-limit binding    | (off)            | Optional per-key rate limit. Required before opening the server.                        |

| Request header  | Required | Meaning                                                                                  |
| --------------- | -------- | ---------------------------------------------------------------------------------------- |
| `Authorization` | yes      | `Bearer <Garmin Personal API key>`                                                       |
| `X-Timezone`    | no       | IANA zone overriding the Garmin profile zone. Invalid values are ignored with a warning. |

### Costs and limits

- **Workers Free** includes 100,000 requests a day, but only **10 ms of CPU per request**. Most calls use far less.
  A heavy call such as `weekly_checkin` or an intraday series may occasionally exceed it. If Claude reports
  errors like "exceeded CPU limit", the Workers Paid plan removes the problem.
- **KV Free** allows 1,000 writes a day. The server writes about two entries per user per day: a token and a time
  zone.

### Developing the remote server locally

```bash
# .dev.vars is gitignored. Its presence also stops wrangler from loading your .env.
echo "ALLOWED_KEY_HASHES=$(npm run --silent hash-key)" > .dev.vars
npm run dev:worker                    # http://localhost:8787/mcp
npx @modelcontextprotocol/inspector --cli http://localhost:8787/mcp --transport http \
  --header "Authorization: Bearer <your key>" --method tools/list
```

`npm run build:worker` bundles the Worker without deploying it (CI runs this).

## Local: run it on your machine (stdio)

The same tools also run as a local stdio server for Claude Desktop. The key stays on your machine, in its config.

1. **Install and build:** `npm ci && npm run build`. Node.js 22.12 or newer is required.
2. **Optionally check your key end to end:** `cp .env.example .env`, paste the key after `GARMIN_API_KEY=`, then
   `npm run smoke`.
3. **Print a Claude Desktop config snippet** with absolute paths for your machine: `npm run print-config`.

   ```json
   {
     "mcpServers": {
       "garmin": {
         "command": "/usr/local/bin/node",
         "args": ["/absolute/path/to/garmin-personal-mcp/dist/index.js"],
         "env": { "GARMIN_API_KEY": "<your Garmin Personal API key>" }
       }
     }
   }
   ```

   Merge the `garmin` entry into `mcpServers` in `~/Library/Application Support/Claude/claude_desktop_config.json`
   (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows). Use absolute paths: Claude Desktop doesn't
   read your shell's `PATH`.

4. **Fully quit** Claude Desktop (macOS: ⌘Q; Windows: tray icon → Quit) and reopen it.

Local configuration is through environment variables, either in the `env` block or in a `.env` file next to the
server:

| Variable         | Default                    | Meaning                                                                                                                            |
| ---------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `GARMIN_API_KEY` | (required)                 | Your Personal API key.                                                                                                             |
| `GARMIN_REGION`  | `global`                   | `cn` for Garmin Connect China accounts.                                                                                            |
| `GARMIN_TZ`      | system time zone           | IANA zone used for "today" and local times. Set it to your Garmin profile's zone if they differ; `get_api_status` warns you if so. |
| `LOG_LEVEL`      | `info`                     | `debug`, `info`, `warn` or `error`. Logs go to stderr only.                                                                        |
| `TOKEN_CACHE`    | `~/.garmin-mcp/token.json` | Where the 24 h access token is cached (mode 0600). `off` disables the disk cache.                                                  |

## Troubleshooting

**Claude can't connect to the remote server.** Check these in order:

- the URL ends in `/mcp`;
- Authentication is "No sign in";
- the header is named exactly `Authorization` and its value is `Bearer ` followed by the key, with nothing else
  and no quotes.

In allowlist mode, the key's hash must be in `ALLOWED_KEY_HASHES`. Run `npm run --silent hash-key` again and
compare. Every failed check returns the same 401 on purpose. `curl https://…/health` tells you whether the Worker
itself is up.

**"Garmin authentication failed" or the key expired.** Ask Claude to run `get_api_status`. Keys expire after the
period you chose, and deleting a key revokes its tokens immediately. Create a new key in Garmin Connect, then
update it where you configured it:

- **Remote:** in the connector's `Authorization` header. The operator must also add the new key's hash.
- **Local:** in `GARMIN_API_KEY`, then fully quit and reopen Claude Desktop.

Cached tokens are tied to the key, so a new key never reuses an old token.

**"Today" or times are off by some hours.** The remote server uses your Garmin profile's time zone. It caches the
zone for 12 hours and falls back to UTC if the profile has none. Add an `X-Timezone` header to override it.
`get_api_status` shows the zone in use and where it came from.

**Rate limited (HTTP 429).** Garmin doesn't publish its limits. The server retries up to 3 times with backoff and
honours `Retry-After`. If Garmin asks for a long wait, the tool says so instead of hanging. A 429 from the Worker
itself means its own rate limit (open mode): wait a minute.

**"no data: watch may not have synced".** Garmin has nothing for that day yet. Sync the watch in the Garmin Connect
app and ask again. Today's data is always partial until the watch syncs.

**Some metrics are always missing.** Sleep scores, sleep need, HRV and Body Battery events are defined in Garmin's
spec, but the Personal API doesn't return them for every device or account. Tools say so explicitly. See
[`docs/API_NOTES.md`](docs/API_NOTES.md).

**Claude Desktop shows the local server as failed.** Check `~/Library/Logs/Claude/mcp-server-garmin.log` (macOS)
or `%APPDATA%\Claude\logs\` (Windows). Also make sure `command` is the absolute path to Node 22+ and `args` points
to `dist/index.js`; run `npm run build` if it's missing. Running `GARMIN_API_KEY=… node dist/index.js` by hand
should print "ready on stdio" to stderr. Never write to stdout in `src/`: it carries the stdio protocol.

## Privacy and security

- **Read-only.** The Personal API is pull-only, and this server only calls `GET` endpoints, plus the token
  exchange.
- **Your data, your key.** Each request is authorised with its own Garmin key, and a key only reads its owner's
  data. There is no shared account, no telemetry and no third-party service besides Garmin and, remotely,
  Cloudflare.
- **What Claude sees.** Tool results become part of your Claude conversation, like anything else you share with
  Claude. Tools return summaries by default; GPS tracks and raw FIT files are never returned.
- **Secrets.** Keys and tokens are never logged and are redacted from errors.
  - Locally, the key comes only from `GARMIN_API_KEY`, and the token is cached in a 0600 file.
  - Remotely, the key arrives in each request's header and is never stored. Only its SHA-256 is used, as a KV
    entry name and for the allowlist. Tokens are cached encrypted under a key derived from your API key.
  - The repository contains no secrets. Its test fixtures are synthetic.
- **Operator trust.** Whoever deploys the Worker could change it to capture keys. Use your own deployment, or one
  run by someone you trust.

## Limitations

- **Not in the Personal API:** Training Status, Training Readiness, race predictor, official PRs, gear, courses,
  and pushing workouts to the watch.
- **No intraday stress series.** Only daily stress summaries exist. Body Battery intraday is available.
- **Sparse VO2 max.** Garmin only records a new value after qualifying outdoor activities.
- **Range caps.** Per tool: 31 days for daily data, 90 for activity lists, 364 for weight, 7 for intraday samples.
- **No OAuth.** The remote server authenticates with the Garmin key in a request header.
- **One region per deployment.** A China account (`GARMIN_REGION = "cn"`) needs its own deployment. The China
  region has not been tested against a live account.
- **Women's health endpoints** are not exposed.

## Development

```bash
npm test             # unit + integration tests (no network)
npm run coverage     # tests with coverage thresholds
npm run lint && npm run typecheck
npm run dev          # local stdio server from source (tsx watch)
npm run dev:worker   # remote server under wrangler dev (needs .dev.vars, see above)
npm run build:worker # bundle the Worker without deploying
npm run inspect      # build and open the MCP Inspector UI on the stdio server
npm run smoke        # live end-to-end check of the stdio server (needs a key)
npm run hash-key     # SHA-256 of a key for ALLOWED_KEY_HASHES
npm run generate-fixtures # regenerate the synthetic test fixtures
npm run fetch-openapi && npm run gen:types   # refresh the spec and generated types
npm run scan-secrets # scan tracked files and full git history for credentials before pushing
```

```text
src/
  index.ts          stdio entrypoint (Node only)
  worker.ts         Cloudflare Workers entrypoint (default export only)
  remote/           request handler, access checks, encrypted KV cache, time-zone resolution
  server.ts         createServer(): registers tools; transport- and runtime-agnostic
  config.ts         stdio env + .env loading and validation (Node only)
  logger.ts         logger and secret redaction
  garmin/           auth (TokenManager + token stores), client, http retries, errors, wire types
  shape/            pure functions: raw responses → compact summaries
  tools/            one file per tool: zod schema, description, handler
scripts/            fetch-openapi, generate-fixtures, record-fixtures, smoke, print-config, hash-key, scan-secrets
test/               unit, integration (in-memory MCP client, Worker over HTTP, stdio), synthetic fixtures
docs/               openapi.json, API_NOTES.md
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for conventions.

## License

[MIT](LICENSE)

Garmin, Garmin Connect, Body Battery and related marks are trademarks of Garmin Ltd. or its subsidiaries. This
project is independent and not affiliated with Garmin.

TDQS

A4.2/5.0

Scored across 11 tools

Disambiguation4/5

Each tool targets a distinct Garmin data domain (sleep, HRV, heart rate, Body Battery/stress, activities, body composition, fitness metrics) and descriptions explicitly route the agent between them, including when to start with weekly_checkin. Minor overlap remains: heart-rate zones are returned by both get_heart_rate and get_fitness_metrics, and weekly_checkin repackages data also available from the range tools.

Naming Consistency4/5

Ten of eleven tools follow a clean verb_noun pattern (get_daily_summary, get_sleep, list_activities, get_activity, get_api_status), all sharing the get_/list_ prefix. weekly_checkin drops the verb prefix but is still readable and unambiguous, making this a minor deviation rather than an inconsistency.

Tool Count5/5

Eleven tools is well within the sweet spot and each one maps to a real user question (weekly review, single day, sleep, HRV, stress, HR, fitness, activities, body composition, connectivity). Nothing looks redundant or like a thin wrapper.

Completeness4/5

The read-only surface covers the full wellness lifecycle from daily summary through weekly aggregate with drill-downs for every core metric, plus an auth/status escape hatch. Gaps are modest and mostly API-imposed: no intraday stress series, no GPS/FIT access, and no nutrition, hydration, workout creation, or personal-record queries.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues