Skip to main content
Glama
README.md
<img src="assets/icon.svg" width="64" height="64" alt="">

# garmin-mcp

Your Garmin Connect data in Claude, ChatGPT and any other [MCP](https://modelcontextprotocol.io) app: activities, sleep, HRV, training status, weight, workouts, calendar, courses, gear and more, read and write (362 tools). Self-hosted on your own Cloudflare account, on the free plan.

Prefer not to run it yourself? A hosted version is at [garmin-mcp.alexjamesgodfrey.workers.dev](https://garmin-mcp.alexjamesgodfrey.workers.dev).

> **Unofficial.** This uses the same interface as the Garmin Connect mobile app, not a Garmin partner API. Garmin can change or block it without notice. Not affiliated with Garmin.

## Self-host in five minutes

[![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/serviettellc/garmin-mcp)

The button forks this repository into your GitHub, creates the Worker, its KV namespace and Durable Object in your Cloudflare account, and asks for one secret, `MASTER_SECRET` (any 32+ random characters, e.g. from `openssl rand -base64 48`).

Or from a terminal:

```sh
git clone https://github.com/serviettellc/garmin-mcp && cd garmin-mcp
npm install
npx wrangler login
openssl rand -base64 48 | npx wrangler secret put MASTER_SECRET
npx wrangler deploy
```

Then:

1. Open the URL it prints (`https://garmin-mcp.<you>.workers.dev`) and click **Connect Garmin**. Sign in with your Garmin email and password (and the emailed code if Garmin asks). The first account to sign in owns the server; with `SINGLE_USER` set to `"true"` (the default here) no other Garmin account can link.
2. Click **Add to your agent** and pick your app, or add `https://garmin-mcp.<you>.workers.dev/mcp` as a custom connector / remote MCP server yourself. Approve it on the page that opens.

To share the server with others, set `SINGLE_USER` to `"false"` in `wrangler.jsonc` (optionally with `INVITE_CODES`) and deploy again.

## How it works

```
AI app (Claude, ChatGPT, Executor, ...)
   |  OAuth 2.1 + MCP over Streamable HTTP
   v
Worker ── /authorize   consent page: read only, or read and change
   |      /mcp         tools, built per request for the signed-in user
   |      /link        pairing page for linking a Garmin account
   v
GarminAccount Durable Object, one per Garmin user
   holds that user's encrypted tokens and is the only thing that refreshes them
   |
   v
connectapi.garmin.com
```

- **One Worker** hosts both OAuth roles (`@cloudflare/workers-oauth-provider`) and the MCP endpoint (`agents` + the MCP SDK). OAuth state lives in one KV namespace.
- **One Durable Object per user.** Garmin refresh tokens rotate on every use, so two refreshes racing each other would lock the user out. A single owner per user prevents that. It also rate-limits, backs off when Garmin does, keeps a log of changes, and refreshes idle accounts before the 30-day token expiry.
- **Tokens never leave that object.** Tools hand it a request and get the response back.
- **An optional D1 database** holds the operator's user list and usage counts, and nothing from Garmin beyond a name and an account id. See [User database](#user-database).

## Linking a Garmin account

The link page is a Garmin sign-in form. The Worker loads Garmin's mobile sign-in page, posts the email and password to it, and, if Garmin asks for the emailed code, shows a code step and posts that in the same Garmin session (its cookies are kept sealed in KV for up to 10 minutes; the password is never stored). Garmin answers with a one-time ticket, which the Worker trades for app tokens, checks whose they are, stores them in that user's object and signs in the browser that typed the password.

Garmin's sign-in accepted a request from a Worker when tested on 2026-12-02 (a made-up email got "invalid username or password", not a block). Whether it keeps doing so at volume is not known. Per-address and per-account limits apply to the form.

For anyone who would rather not type their Garmin password into this service, the page also offers a helper:

1. The link page shows a one-time pairing code inside a command:
   `uv run https://<your-host>/connect.py --code XXXX-XXXX-...`
2. The user runs it on their own computer. [`helper/connect.py`](helper/connect.py) signs in to Garmin locally with [python-garminconnect](https://github.com/cyberjunky/python-garminconnect) and uploads only the resulting tokens with the code. The password goes to Garmin and nowhere else.
3. The Worker asks Garmin whose tokens they are and stores them in that user's object. It answers the helper with a one-time claim link, which the helper opens in the browser on that same computer. That browser confirms the account and is signed in.

The browser that displayed the code is deliberately not signed in by the upload. A pairing code can be handed to someone else ("run this for me"); the claim link only ever exists on the machine where the Garmin password was typed. A copy of the helper served by a host will not send tokens to any other host.

The Garmin account is the identity: there is no separate sign-up. A browser stays signed in for 30 days.

Once one browser is signed in, "Sign in on another device" on `/account` makes a one-time link (20 minutes) that signs a second browser in to the same account, through the same confirmation page. A browser that was part-way through connecting an app when it is signed in this way carries on with that app.

An experimental browser-only path (sign in on Garmin's own page, paste the resulting address) is behind `ENABLE_TICKET_LINK=true`. It is untested.

## Settings

| Setting | Kind | Purpose |
|---|---|---|
| `MASTER_SECRET` | secret, required | 32+ random characters. Every signing and encryption key derives from it. Changing it signs everyone out and makes stored Garmin tokens unreadable. |
| `SINGLE_USER` | var | `"true"`: only the first Garmin account to link may use the server. |
| `INVITE_CODES` | secret, optional | Comma-separated codes. When set, linking a Garmin account that is new to the service needs one. |
| `CANARY_USER_ID` | secret, optional | Account id (shown on your `/account` page) whose Garmin link a daily job reads to detect Garmin API changes. |
| `ADMIN_USER_IDS` | secret, optional | Comma-separated account ids that may open `/admin` (needs the user database). |
| `PUBLIC_URL` | var, optional | Pin one canonical origin. Other hostnames redirect to it. |
| `SERVICE_NAME` | var | Name shown on pages. |
| `ENABLE_TICKET_LINK` | var | `"true"` shows the experimental browser-only linking path. |
| Billing | secrets and vars | Optional Stripe subscriptions; off unless configured. See [Billing](#billing). |

## Connecting an app

Add `https://<your-host>/mcp` as a remote MCP server. The app sends the user to link (if needed) and to the consent page.

| URL | Lists |
|---|---|
| `/mcp` | About 90 common tools, plus `find_tools` and `call_tool` to reach the rest |
| `/mcp?toolsets=all` | All 362 tools |
| `/mcp?toolsets=health,workouts` | Every tool of the named areas |
| `...&readonly=1` | Nothing that changes data, whatever was granted |

Areas: `profile`, `activities`, `health`, `metrics`, `body`, `nutrition`, `workouts`, `calendar`, `courses`, `gear`, `devices`, `womens_health`, `achievements`, `golf`, `dogs`, `advanced`.

Checked against the live deployment through each client's own OAuth sign-in:

```sh
claude mcp add --transport http garmin https://<your-host>/mcp && claude mcp login garmin
codex mcp add garmin --url https://<your-host>/mcp          # then: codex mcp login garmin
opencode mcp auth garmin     # after adding {"mcp": {"garmin": {"type": "remote", "url": "https://<your-host>/mcp"}}} to opencode.json
```

ChatGPT: add the `/mcp` URL as a custom connector (developer mode or Plugins, depending on plan and date). Connected and used successfully from ChatGPT on 2026-12-02.

Access is decided on the consent page, where "change your Garmin data" is ticked by default and can be unticked. A read-only grant never sees a tool that changes data, and the raw API tools (`garmin_api_get`, `garmin_api_write`, `garmin_api_delete`) are available only to connections that may change data, because an arbitrary path cannot be shown to be harmless. Tools that delete need `confirm: true` on every call. Users review connected apps and recent changes, revoke an app, sign out everywhere, or delete everything at `/account`.

### Trying tools by hand

`/console`, linked from `/account`, runs any tool against the signed-in user's own Garmin account without an app: search the catalogue, fill in the arguments (a form, or raw JSON) and read the result. Tools that change data run only after ticking "Allow this page to change my Garmin data", which is off on every page load, and deletions still need `confirm: true`. Two one-tap checks sit at the top: a read-only pass over eight common tools, and a write test that creates one workout, reads it back, deletes it and checks it is gone.

## Safeguards

- Garmin tokens are encrypted (AES-GCM, key derived from `MASTER_SECRET`, bound to the user) and stored only in that user's Durable Object. OAuth grants carry the account id, never a Garmin token.
- Apart from those tokens, the service keeps a user list for the operator: each user's Garmin name and account id, when they linked and last used the service, how many tool calls they make per day, and which apps they connected. It holds no Garmin health data and does not record which tools were called or with what. "Disconnect Garmin and delete my data" on `/account` removes all of it.
- The token is only ever sent to `*.garmin.com` (or `*.garmin.cn` for China-region accounts); every path is validated before use. The two regions are separate id spaces and are kept apart.
- Identity comes from Garmin's answer about the uploaded tokens, not from anything the uploader claims.
- A tool marked read-only cannot send Garmin anything but a GET, except at the few call sites that declare a POST to be a search.
- Browser sessions and download links are stateless but revocable: disconnecting, "sign out everywhere" and removing an app void everything issued before that moment (KV, so allow up to a minute to reach every location).
- Per-user request budget against Garmin and a per-user cooldown when Garmin limits or blocks a request. A block on the service's own token traffic pauses the service for everyone for three minutes.
- Per-address limits on the anonymous endpoints: starting a link, uploading tokens, invite and ticket forms, client registration. A pairing code is withdrawn after three uploads Garmin refuses.
- A link nobody uses for 400 days is deleted. Browser sessions and app connections also last 400 days from their last use, so nothing signs out while it is in use.

## Billing

Optional, off unless `STRIPE_SECRET_KEY` and `STRIPE_PRICE_ID` are set. Each account gets `TRIAL_DAYS` (default 3) free from its first link, then needs a Stripe subscription (the price decides the amount; currently $6/month).

- When an account has no access, every tool returns an error telling the app to send the user to `/billing`. Nothing reaches Garmin.
- `/billing` shows the plan and opens Stripe Checkout or the customer portal. Returning from Checkout reads the session from Stripe directly, so access comes back without waiting for the webhook.
- `POST /stripe/webhook` (signature checked) keeps the status current: `checkout.session.completed` and `customer.subscription.created|updated|deleted`. Active, trialing and past_due keep access.
- The billing record (trial start, Stripe customer and subscription ids, status) is kept in KV under the account id and survives Disconnect, so relinking does not restart the trial.
- `BILLING_EXEMPT_USER_IDS` (comma-separated account ids) never pay.
- Settings: secrets `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `BILLING_EXEMPT_USER_IDS`; vars `STRIPE_PRICE_ID`, `STRIPE_PORTAL_CONFIG` (optional), `TRIAL_DAYS`.

## Operations

- `GET /healthz` reports configuration, whether Garmin is currently blocking the service, and the last canary result.
- "Check connection" on `/account` asks Garmin whether that user's stored sign-in still works, renewing it first if it has not been renewed in the last 15 minutes.
- A daily cron purges expired OAuth records and runs the canary.
- Every outbound request carries Cloudflare's `CF-Worker` header naming your zone, so Garmin can identify and block the whole service with one rule.
- One `MASTER_SECRET` signs sessions and download links and encrypts Garmin tokens, so they cannot be rotated separately. Rotating it signs everyone out and requires everyone to link again.
- Workers Logs record request URLs, which include `/dl/<token>` download links and `/link/claim?t=<token>` claim links. Both are single-purpose and expire within 20 minutes.
- Set `PUBLIC_URL` once you have settled on a hostname.
- CPU: large responses are parsed and trimmed in the Worker. The Workers Paid plan is the safer choice.

## User database

Optional. With a D1 database bound as `DB`, the operator gets a user list and the `/admin` page. Without it nothing is recorded and everything else works the same; if it fails, requests carry on and the failure is logged.

| Table | One row per | Holds |
|---|---|---|
| `users` | linked account | Account id, Garmin profile number and region, Garmin display name and full name, `status` (`active` or `needs_relink`), first and latest link time, when a tool was last run, how many times the account was linked. |
| `user_events` | event | `linked`, `relinked`, `app_connected` (the app's name, and whether it may change data), `app_revoked`, `needs_relink`, `disconnected`. |
| `usage_daily` | account and UTC day | Tool calls, calls to tools that can change data, and calls that failed. |

Never Garmin tokens, health data, tool names, arguments or results. Disconnecting deletes the account's rows from all three tables and leaves one `disconnected` event with no account id, so the operator can still count departures. An account that was linked before the database existed appears the first time it runs a tool or connects an app.

```sh
npx wrangler d1 create garmin-mcp
npx wrangler d1 migrations apply garmin-mcp --remote
npx wrangler secret put ADMIN_USER_IDS     # your account id from /account; several are comma-separated
npx wrangler deploy
```

It is not in `wrangler.jsonc` by default: create one with `npx wrangler d1 create garmin-mcp`, add the `d1_databases` block it prints (binding `DB`, `migrations_dir` `migrations`) and apply the migration with `npx wrangler d1 migrations apply DB --remote`. A database without the migration has no tables: the service runs, logs that nothing is being recorded, and `/admin` says so.

`/admin` shows totals, the users (50 to a page) and the 50 most recent events, read-only. It is served only to a signed-in account listed in `ADMIN_USER_IDS`; anyone else gets the same 404 as a path that does not exist.

### Moving to PostgreSQL

The code is written so that this is a change to one file:

- [`migrations/0001_init.sql`](migrations/0001_init.sql) runs unmodified on PostgreSQL 15+, and every query in [`src/db`](src/db) stays inside what SQLite and PostgreSQL share: `$1` placeholders, `ON CONFLICT (...)` upserts, timestamps passed in as ISO-8601 strings, no date functions. A unit test fails on anything else.
- [`src/db/client.ts`](src/db/client.ts) is the only file that touches D1. Add a second implementation of its three-method `Database` interface on a PostgreSQL driver (reached through Hyperdrive; the driver would be the one new dependency) and return it from `database()`. `batch` must run its statements in one transaction and report the rows each changed.
- Apply the migration file to the new database and copy the three tables across. D1 stores the timestamps as text in a form PostgreSQL reads as `timestamptz`.
- PostgreSQL drivers return counts as strings and timestamps as `Date`; the admin queries already accept both.

The schema and every query have been run by hand against PostgreSQL 16. The test suite runs against D1 only.

## Development

```sh
cp .dev.vars.example .dev.vars   # set MASTER_SECRET
npx wrangler d1 migrations apply garmin-mcp --local   # optional: tables for the user database
npm run dev -- --port 8799
npm test                         # unit tests, then tests inside the Workers runtime
npm run typecheck
```

Tests never contact Garmin: they replace `fetch`.

To check a running server against a real account from a terminal, [`scripts/live.py`](scripts/live.py) acts as a browser plus an MCP client (link, sign in, approve an app, call tools), and [`scripts/sweep.py`](scripts/sweep.py) calls every read-only tool once and records what came back. Their state, a browser session and OAuth tokens, is kept in `.live/` and is not committed. Tool definitions live in [`src/mcp/tools`](src/mcp/tools), one file per area; [`src/mcp/define.ts`](src/mcp/define.ts) is the contract they are written against.

## What is and is not verified

Verified by the test suite, against a mocked Garmin: the OAuth flow end to end, linking, consent, scope enforcement, token refresh and rotation handling (including a link or unlink arriving mid-refresh), rate-limit and block handling, revocation, the account page, the console, download links, the user database and admin page (against local D1), and that every tool is well-formed. The FIT file writer is checked byte-for-byte against python-garminconnect's. The sign-in, session and token code has had one independent security review; its confirmed findings are fixed and covered by tests.

Verified against one live Garmin account (December 2026):

- Linking through the helper, including Garmin's emailed verification code, against a deployed Worker.
- API calls, file downloads and a token renewal from Cloudflare's network.
- All 274 read-only tools. Those that returned nothing are features the account does not use (nutrition, strength 1RM history, golf).
- About 80 of the 88 tools that change data, each on objects created for the test and deleted afterwards: workouts, scheduling, calendar notes and events, a manual and an imported activity, activity images, gear, courses, weigh-ins, body composition, blood pressure, hydration, jet-lag trips, dogs, heart-rate and power zones, user settings, the steps goal.
- Claude Code, Codex and OpenCode connecting through their own OAuth clients.
- The user database on a deployed D1, the admin page, and the console in headless Chrome on the deployed Worker.

Not verified: anything that acts on a watch (`push_workout_to_device`, `send_scheduled_workouts_to_devices`, `update_device_settings`, the primary-device setters), the women's-health and nutrition write tools, training-plan scheduling, `set_sleep_window`, `set_daily_goal`, a fresh `upload_activity` (Garmin refused the test file as a duplicate), China-region accounts, and how any of this behaves beyond one account and one day. One other project reported token refresh still working from Cloudflare after a month; nothing here has run that long.

Known and accepted: pairing is a device-code style flow, so it rests on users not running commands or opening links that someone else sent them; the helper and the pages say so. Two uploads racing on the same pairing code both succeed and the later one wins. A 400 from Garmin's token endpoint is always read as "sign in again", which would be wrong if Garmin ever answers 400 for another reason. An app the user approves but that never collects its code still appears under "Apps with access" until removed.

## Credits

Endpoints, payloads and the FIT weight encoder are ported from [python-garminconnect](https://github.com/cyberjunky/python-garminconnect) (MIT, © Ron Klinkien). The nutrition tools and the course-saving payload are ported from [Taxuspt/garmin_mcp](https://github.com/Taxuspt/garmin_mcp) (MIT).

Built in [T3 Code](https://t3.codes). MIT licensed, see [LICENSE](LICENSE).