Skip to main content
Glama

Garmin Connect in Gemini and Claude: your own MCP server on Cloudflare

CI Deploy to Cloudflare

A small, private server that lets the Gemini web app (gemini.google.com), Claude or any other MCP client read your own Garmin Connect data: activities, sleep, HRV, Body Battery, VO2 max, weight, Fitness Age, heart rate zones, logged food, Health Snapshots and daily health stats. It runs on Cloudflare's free plan, nothing sits in between, and only you can connect apps to it. Optionally it also sends you a morning summary in Telegram.

You ask Gemini things like "@Garmin Connect how did I sleep this week?", and Gemini calls your server, which reads the data from Garmin's official Personal API.

Why this approach

  • Official API, no Garmin password. It uses a Garmin Personal API key that you create and can revoke at any time, instead of logging in with your Garmin password or imitating the Garmin Connect website.

  • Remote, so it works everywhere. It runs on Cloudflare, so it works in the browser and on your phone, with nothing running on your computer.

  • One command or one click, free. npm run setup (or the Deploy to Cloudflare button) deploys it on Cloudflare's free plan.

  • Locked to you. Apps can connect only after you approve them with your own password.

Using an AI coding agent (Claude Code, Codex, Cursor...)? Clone this repo, open it in the agent and say "Set this up for me." The agent's instructions are in AGENTS.md. Or install the setup skill and just ask for your Garmin data in Gemini or Claude.


Quick start (about 5 minutes)

What you need

What

How to get it

1

Node.js 22.12 or newer

Check with node --version. Install the LTS version from nodejs.org if needed.

2

Git

Check with git --version. Install from git-scm.com if needed.

3

A Cloudflare account (free)

Sign up at dash.cloudflare.com/sign-up. Setup logs you in through the browser.

4

A Garmin Personal API key

See Getting a Garmin Personal API key below.

5

Gemini or Claude

Gemini with "Connect to an MCP server" in its settings, or Claude with custom connectors (see Other MCP clients).

Install and deploy

git clone https://github.com/an1no/garmin-mcp.git
cd garmin-mcp
npm install
npm run setup

These commands work the same in PowerShell, Windows Terminal, macOS Terminal and Linux shells.

npm run setup does everything in six steps and tells you what it's doing:

  1. Prerequisites: checks Node.js and installs dependencies if needed.

  2. Cloudflare login: if you're not logged in, it opens your browser so you can log in (or sign up). If you have several Cloudflare accounts, it asks which one to use.

  3. Settings: makes sure "today" means today where you live (the server reads your timezone from your Garmin profile).

  4. Secrets: asks you to paste your Garmin Personal API key (the input is hidden), checks it with Garmin, and generates a strong admin password.

  5. Deploy: uploads the server to Cloudflare with both secrets. Cloudflare's storage (KV) is created automatically.

  6. Check: makes sure the live server answers, then prints:

    • your MCP server URL, e.g. https://garmin-mcp.<your-subdomain>.workers.dev/mcp

    • your admin password (also saved in admin-password.txt, which git ignores)

If Cloudflare asks you to register a workers.dev subdomain (first time only), pick any free name. It becomes part of all your Worker URLs. Then run npm run setup again.

Running npm run setup again later is safe: it redeploys and keeps your existing password and Garmin key.

Or: deploy with one click (no terminal)

Deploy to Cloudflare

The button copies this repository into your GitHub (or GitLab) account and deploys it from there:

  1. Log in to Cloudflare and connect your GitHub account when asked. Ticking Create private Git repository is a good idea.

  2. Project name: keep garmin-mcp or choose another; it becomes part of your URL. KV namespace: Create new.

  3. Fill in the two secrets: GARMIN_PERSONAL_API_KEY (see below) and MCP_ADMIN_PASSWORD: a long random password (at least 12 characters) that you keep in a password manager. Leave TIMEZONE as auto.

  4. Deploy. When the build finishes, your MCP server URL is https://<project-name>.<your-subdomain>.workers.dev/mcp.

Every push to your copy redeploys it automatically. Your copy doesn't follow this repository by itself: to get updates, pull them from an1no/garmin-mcp into your copy (or use npm run setup from a clone of this one).

Or: let an Agent Skill do it

skills/garmin-mcp-setup is an Agent Skill: instructions an AI coding agent loads when your request matches, here "I want my Garmin data in Gemini/Claude". It clones this repository and follows AGENTS.md, with the same rules (you fill in secrets yourself, never in the chat).

For Claude Code, install it as a personal skill:

New-Item -ItemType Directory -Force "$HOME/.claude/skills/garmin-mcp-setup" | Out-Null; Invoke-WebRequest "https://raw.githubusercontent.com/an1no/garmin-mcp/main/skills/garmin-mcp-setup/SKILL.md" -OutFile "$HOME/.claude/skills/garmin-mcp-setup/SKILL.md"

On macOS or Linux:

mkdir -p ~/.claude/skills/garmin-mcp-setup && curl -fsSL https://raw.githubusercontent.com/an1no/garmin-mcp/main/skills/garmin-mcp-setup/SKILL.md -o ~/.claude/skills/garmin-mcp-setup/SKILL.md

Then ask, for example, "Set up my Garmin data in Gemini." Other agents that support Agent Skills take the same folder in their own skills directory (see their docs).

Connect it to Gemini

  1. Open gemini.google.com, go to Settings, find the connected apps section and choose to connect an MCP server. The dialog is titled "Connect to an MCP server"; Google moves these menus around from time to time.

  2. Paste your MCP server URL (the one ending in /mcp).

  3. Leave "Additional settings" empty. Gemini registers itself automatically; you don't need a client ID or secret.

  4. A page from your server opens: "Connect your Garmin data". Check that access will be sent to a Google address, enter your admin password and select Approve.

  5. In a chat, type @, pick the app, then ask your question.

Always @-mention the app. Without it, Gemini answers from general knowledge and says it can't see your Garmin data. Gemini's Developer Mode panel shows the app's tools (Tool schemas) and every call it makes (Event log), which helps if something looks wrong.

Gemini keeps you connected as long as you use the app at least once every 30 days.

Other MCP clients

The server speaks standard MCP over Streamable HTTP with OAuth (Dynamic Client Registration and Client ID Metadata Documents), so clients that support remote MCP servers with OAuth work the same way: add the server URL, approve on the password page, ask. Tested end to end: the Gemini web app and Claude.

Claude (claude.ai, desktop and mobile apps):

  1. Settings → Connectors → Add custom connector.

  2. Name it (e.g. Garmin Connect), paste your MCP server URL, leave the advanced settings empty, Add.

  3. Connect. On the approval page, check that access will be sent to claude.ai (or claude.com), enter your admin password and Approve.

  4. In a chat, make sure the connector is enabled (tools menu next to the message box), then ask.

If you try another client, please open an issue with how it went.

On the approval page, always check that access will be sent to the app you're connecting (the page shows the destination host) before you enter your password.

Getting a Garmin Personal API key

  1. Sign in to Garmin Connect on the web.

  2. Open the Personal API Key page (Garmin's instructions: Garmin Connect Personal API).

  3. Select Create Key, accept the terms and choose an expiration: 30 days, 90 days, 180 days or 1 year.

  4. Copy the key right away. Garmin shows it only once. If you lose it, delete it and create a new one.

Garmin emails you about a week before the key expires. See Renewing the Garmin key.


Related MCP server: Garmin MCP Worker

What you can ask

Tool

What it returns

Range per call

get_trends

Weekly or monthly statistics computed on the server. Sleep: average hours, stage minutes, score, best/worst night. Daily: steps, distance, resting heart rate, stress, Body Battery, intensity minutes. HRV: average, range, status counts. Activities: count, distance, time, elevation, calories, per type, longest. On request also VO2 max and weight

Up to 1 year in one call

get_activities

Activity list: activityId, name, type, event type, start time, location, distance (m), duration (s), elevation gain (m), average/max heart rate, average speed (m/s), calories, power

Up to 100, paged; filter by dates, type, subtype, text, event type (e.g. races), distance, duration, elevation, power, favorites or start area; sort by date, distance, duration or name

get_activity_details

One workout: speed, heart rate, power, cadence, elevation, training effect and load, temperature, splits. includeWorkout: true adds the planned workout it followed, as readable steps and targets (e.g. "1 km at 4:00–4:10 /km", "repeat 4 times"); raw: true returns everything

One activity

get_daily_summary

Steps, distance, calories, resting/min/max heart rate, stress, Body Battery, intensity minutes, floors, SpO2, respiration, hydration

One day, or up to 1 year

get_sleep_data

Total sleep, deep/light/REM/awake time, sleep score and sub-scores, overnight heart rate, stress, SpO2, respiration, sleep need

One night, or up to 31

get_hrv_data

Last-night HRV average and 5-minute high, 7-day average, HRV status, baseline range

Last 7 days by default

get_body_battery

Charged/drained, start/end/highest/lowest level, the events that moved it, optional intraday timeline

Up to 31 days

get_day_details

One day in local time: heart rate per interval (avg/min/max, default 15 min), resting, the day's lowest/highest reading with times, abnormal readings; overnight HRV readings with sleep start/end; SpO2 hourly averages, sleep average, latest

One day

get_vo2max

VO2 max (ml/kg/min) for running/walking, cycling and rowing: first and latest value, change, min/max, the dates it changed

Up to 1 year (default 365 days)

get_weight

Weight, BMI, body fat and water %, muscle and bone mass, visceral fat, metabolic age: first/latest/lowest/highest, change, average, weight goal, daily values or monthly averages

Up to 1 year (default 90 days)

get_fitness_profile

Fitness Age with its components (e.g. vigorous days, resting heart rate, BMI), each with its target and the Fitness Age reachable by meeting it; heart rate zones 1-5 in bpm per sport, max/resting/lactate-threshold heart rate

As of one date

get_nutrition

Food logged in Garmin Connect: calories, carbs, protein, fat against the goals; for one day each meal and its foods

One day, or up to 14 days

get_health_snapshots

Health Snapshot sessions started on the watch: date, local time, duration, average/lowest/highest heart rate, HRV (RMSSD and SDRR), stress, respiration and SpO2; averages over the range

Up to 1 year (default 30 days)

get_menstrual_cycle

Opt-in, off by default (see Cycle tracking). Day in cycle, cycle start, predicted length, period days, fertile window and luteal phase start as day numbers, predicted ovulation, days until the next phase, pregnancy week; the day's logged flow, symptoms and moods. history: N adds the N completed cycles before it (start, length, period days) with the average, shortest and longest

One day, plus up to 12 past cycles

Example prompts:

  • @Garmin Connect list my last 5 activities

  • @Garmin Connect how did I sleep last night, compared with the rest of the week?

  • @Garmin Connect show my HRV status and Body Battery for the last 7 days

  • @Garmin Connect give me the details of my most recent ride

  • @Garmin Connect how did my sleep change month by month this year?

  • @Garmin Connect how far did I run in 2025, and what was my longest run?

  • @Garmin Connect list all my races

  • @Garmin Connect how has my VO2 max changed this year?

  • @Garmin Connect what was my heart rate like yesterday afternoon, and how did my HRV look overnight?

  • @Garmin Connect did I stick to the planned workout in my last run?

  • @Garmin Connect how did my VO2 max and weight change month by month this year?

  • @Garmin Connect show my Health Snapshots from this month

  • @Garmin Connect how much weight have I lost since January, and how far am I from my goal?

  • @Garmin Connect what is my Fitness Age and what would improve it most?

  • @Garmin Connect what are my heart rate zones for running?

  • @Garmin Connect how many calories and how much protein did I log this week?

Charts. In clients that support MCP Apps, such as Claude, get_trends and get_day_details also show interactive charts right in the chat: sleep, resting heart rate, HRV, steps, stress, distance, VO2 max and weight per week or month, or heart rate (with its min-max band), overnight HRV and SpO2 through a day. They follow the light or dark theme, and hovering shows each value. Other clients, Gemini included, show the same numbers as text, as before.

get_trends exists so that questions about long periods stay fast and accurate: instead of sending the model a year of days (hundreds of records), the server sends one row per week or month plus an overall summary.

All tools are read-only: nothing is ever changed in your Garmin account. Dates are YYYY-MM-DD; when a question has no date, "today" is computed in the timezone from your Garmin profile (or the zone you set as TIMEZONE in wrangler.jsonc).

Morning summary in Telegram (optional)

Your server can also send you one short message every morning, without you asking: last night's sleep, HRV, Body Battery and resting heart rate next to your 7-day averages, plus yesterday's steps and activities. On Mondays it adds last week compared with the week before. For example (made-up numbers):

Good morning! Tuesday, 24 November

😴 Sleep: 7 h 12 min, score 82 (good)
      7-day average: 6 h 50 min, score 76
💓 HRV: 48 ms, balanced · 7-day average 46 ms
🔋 Body Battery: 78 on waking, +52 during sleep
❤️ Resting heart rate: 54 bpm · 7-day average 56 bpm

Yesterday
👟 9,812 steps (goal 8,000)
🏃 Morning Run: 8.2 km, 42:10

How it works. A cron trigger checks every 15 minutes. From 8:00 your time (the time zone in your Garmin profile, or TIMEZONE) it waits for last night's sleep to sync from the watch and sends the message as soon as it's there; if the sleep still hasn't synced by 11:00, it sends without it. One message a day. If Garmin can't be read at all (for example because the key expired), the message says so.

Turn it on (about 2 minutes):

  1. In Telegram, open @BotFather, send /newbot, choose a name and a username (it must end in bot), and copy the token it gives you.

  2. Open your new bot (BotFather sends a link) and press Start.

  3. In this folder, run npm run telegram and paste the token (the input is hidden). The script checks the token, finds your chat, stores TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID as Worker secrets and sends a test message. Without a terminal to type into (an AI agent's shell), it creates .secrets.env for the token instead and exits with code 2; with code 3 when you haven't pressed Start yet.

To change the hour, set DAILY_SUMMARY_HOUR (0-20) in wrangler.jsonc and run npm run deploy. To turn it off: npm run telegram -- --off. Deployed with the button and no terminal? Add the two secrets under your Worker's Settings → Variables and Secrets; after pressing Start, open https://api.telegram.org/bot<token>/getUpdates in a browser, and the "chat":{"id":...} there is your chat ID.

Privacy. The message goes from Cloudflare to Telegram and on to your chat, so Telegram's servers see these numbers (chats with bots aren't end-to-end encrypted). The bot only ever writes to your chat and doesn't answer anyone. The server stores nothing but a "sent today" marker. Without the Telegram secrets the cron trigger still runs, but does nothing. (Cloudflare's free plan allows 5 cron triggers per account; this uses one.)


How it works

Gemini ──OAuth (DCR + PKCE)──► /register, /authorize (your password), /token
Gemini ──Bearer token────────► /mcp ──► GarminMCP (Durable Object) ──► personal.connectapi.garmin.com
                                                     │
                                                     └── OAUTH_KV: OAuth grants (hashed) + Garmin token (AES-GCM)

There are two "locks":

  1. Gemini → your server (OAuth 2.1). Gemini registers itself (Dynamic Client Registration), opens your /authorize page and gets tokens only after you enter your admin password. Access tokens last 1 hour; refresh tokens keep the connection alive while it's used at least every 30 days.

  2. Your server → Garmin. The server trades your Personal API key for a Garmin access token (valid 24 hours), caches it encrypted for about 23 hours, and uses it to read your data.

Stack: Cloudflare Workers + Durable Objects (agents / McpAgent), Streamable HTTP at /mcp, @cloudflare/workers-oauth-provider, @modelcontextprotocol/sdk, TypeScript.

Where your secrets live

Secret

Where

Notes

Garmin Personal API key

Cloudflare, as an encrypted Worker secret

Not in the code, not on GitHub, not on your computer after setup

Admin password

Cloudflare (encrypted secret) + admin-password.txt on your computer

Move it to a password manager, then delete the file

Garmin access token

Cloudflare KV, AES-GCM encrypted with a key derived from your API key

Renewed automatically every ~23 hours

Gemini's OAuth tokens

Cloudflare KV, stored only as hashes

Telegram bot token (optional)

Cloudflare (encrypted secret)

Only if you turned on the morning summary

Cloudflare secrets are write-only: nobody, including you, can read them back. If you lose the admin password, set a new one (see Maintenance).

Security

  • Only you can connect apps. Any app can register, but it gets a token only after the correct admin password. The comparison is constant-time.

  • Brute-force protection. 5 wrong passwords from one IP lock that IP out for 15 minutes; 20 wrong passwords in an hour pause all new approvals for that hour. Connected apps keep working.

  • Hardened approval page. Each page works once, for 10 minutes, only in the browser that opened it; it can't be framed and loads no scripts. It shows where tokens will be sent.

  • One server per person. Everyone deploys their own copy with their own key; nobody else's server sees your data.

Found a security problem? Please report it privately, as described in SECURITY.md.


Maintenance

Task

Command

Deploy after changing code

npm run check, then npm run deploy (or npm run setup)

Renew the Garmin key

npm run setup -- --update-key

Change the admin password

npx wrangler secret put MCP_ADMIN_PASSWORD

Turn cycle tracking on or off

Set CYCLE_TRACKING in wrangler.jsonc to "on" or "off", then npm run deploy (see Cycle tracking)

Change the timezone

By default ("TIMEZONE": "auto") it follows your Garmin profile, re-read once a day. To force one, set TIMEZONE in wrangler.jsonc (e.g. Europe/Berlin), then npm run deploy

Watch live logs

npx wrangler tail, or the dashboard (see Logs)

Turn the morning summary on or off

npm run telegram, or npm run telegram -- --off (see Morning summary)

Save your changes to GitHub

git add -A, git commit -m "Describe what changed", git push

Cycle tracking (opt-in)

get_menstrual_cycle reads Garmin Connect's menstrual cycle tracking. It's off by default: while CYCLE_TRACKING in wrangler.jsonc is "off", the tool isn't registered, so Gemini or Claude can't see or call it. To turn it on, set "CYCLE_TRACKING": "on" and run npm run deploy (or choose on in the Deploy to Cloudflare form). The approval page then lists cycle tracking among the data an app gets.

When on, it returns the cycle's day numbers (period, fertile window, luteal phase start), the predicted ovulation date, days until the next phase, the pregnancy week if Garmin tracks a pregnancy, and the day's logged flow, symptoms and moods. With history it also counts back through up to 12 earlier cycles: each one's start, end, length and period days, plus the average, shortest and longest cycle (predicted cycles and pregnancies are marked and left out of the averages). It deliberately leaves out sexual activity, sex drive, discharge and free-text notes, and Garmin's cycle analysis. Garmin reports the current phase only as an undocumented number, so the tool gives the day numbers instead of guessing phase names.

Logs

The server writes one structured log line per tool call, per decision on the approval page and per morning summary step, so you can see what happened without guessing:

Event

Fields

tool_call

tool, ok, durationMs; on failure errorKind (garmin, invalid_input, timeout, unexpected) and garminStatus (e.g. 429); partialErrors when one part of a combined result failed (e.g. one get_trends metric)

authorize

outcome: approved (with scope), denied, wrong_password or locked_out (with retryAfterSeconds)

daily_summary

outcome: sent, send_failed (with telegramStatus) or waiting_for_sleep; partialErrors when part of the data couldn't be read, garminUnavailable when none could

Arguments, dates, activity IDs, returned data, the password, tokens, the Telegram chat and IP addresses are never logged.

To read them: dash.cloudflare.com → Workers & Pages → your Worker → Observability, then filter, for example event = tool_call and ok = false. Or watch live with npx wrangler tail. On the free plan Cloudflare keeps them for a few days.

If Gemini shows an error for a tool call and there is no tool_call line for it, the request never reached the tool (for example a connection problem between Gemini and the server, or arguments the tool's schema rejected).

Renewing the Garmin key

Create a new key on Garmin Connect (see above), then run:

npm run setup -- --update-key

It asks for the new key, checks it and stores it. The cached Garmin token is tied to the old key, so the new key is used immediately. Gemini stays connected.

Revoking access

Disconnect the app in Gemini, then delete the stored grants and tokens (the server's single user is owner). List them first:

npx wrangler kv key list --binding OAUTH_KV --remote --prefix "grant:owner:"

Then delete all grants and tokens in one go:

foreach ($prefix in "grant:owner:", "token:owner:") { (npx wrangler kv key list --binding OAUTH_KV --remote --prefix $prefix | ConvertFrom-Json) | ForEach-Object { npx wrangler kv key delete --binding OAUTH_KV --remote $_.name } }

Changing the admin password stops new approvals with the old password but doesn't disconnect apps that are already approved; delete their grants as shown above.


Setup options

npm run setup -- --help

Option

Effect

--name <worker-name>

Deploy under another Worker name (default: name in wrangler.jsonc, i.e. garmin-mcp)

--update-key

Ask for a new Garmin key even if one is already stored

--skip-garmin-check

Don't check the key with Garmin before deploying (e.g. if Garmin is down)

Environment variable

Effect

CLOUDFLARE_API_TOKEN

Use an API token instead of the browser login

CLOUDFLARE_ACCOUNT_ID

Pick the account when you have several

GARMIN_PERSONAL_API_KEY

Provide the key without the prompt

MCP_ADMIN_PASSWORD

Use your own admin password (at least 12 characters) instead of a generated one

Non-interactive mode (when there's no terminal to type into, e.g. an AI agent runs the script): if the Garmin key isn't provided, setup creates a git-ignored .secrets.env with an empty GARMIN_PERSONAL_API_KEY= line and exits with code 2. Paste the key after the =, save, and run npm run setup again. Setup deletes the file after deploying and never prints secrets in this mode.

Exit codes: 0 done, 1 error (the message says what to fix), 2 action needed (paste the Garmin key).

Manual setup (without the script)

  1. npx wrangler login

  2. Create a git-ignored .secrets.env in this folder, with no quotes:

    GARMIN_PERSONAL_API_KEY=your-key
    MCP_ADMIN_PASSWORD=a-long-random-password
  3. npx wrangler deploy --secrets-file .secrets.env. The first deploy must include both secrets because wrangler.jsonc lists them under secrets.required; Wrangler creates the KV namespace by itself.

  4. Delete .secrets.env.


Local development

Copy-Item .dev.vars.example .dev.vars

Put real values in .dev.vars (git-ignored), then:

npm run dev

The server runs at http://localhost:8787, with MCP at http://localhost:8787/mcp. Try it with the MCP Inspector (Streamable HTTP transport), which handles the OAuth flow:

npx @modelcontextprotocol/inspector

Command

What it does

npm run setup

Log in, store secrets, deploy and check (safe to re-run)

npm run deploy

Deploy the current code

npm run dev

Run locally

npm run typecheck

tsc --noEmit

npm test

Run all tests once: unit and end-to-end (npm run test:unit, npm run test:e2e for one kind, npm run test:watch to re-run as you edit)

npm run check

Lockfile check, type check, all tests, then a test bundle with wrangler deploy --dry-run. Run it before every deploy

npm run cf-typegen

Regenerate worker-configuration.d.ts after editing wrangler.jsonc

Tests

None of the tests need a Cloudflare account, a Garmin key or the network, and none touch your deployed server: all Garmin data in them is synthetic, and the secrets are test values.

End-to-end (test/e2e/, Vitest with Cloudflare's @cloudflare/vitest-plugin): the whole Worker runs inside a local copy of the Workers runtime (workerd), with its own throwaway KV and Durable Objects, and Garmin is answered by MSW. A test client goes through exactly what Gemini does: registers itself, gets approved on the password page, exchanges the code for tokens (PKCE), opens an MCP session over Streamable HTTP, lists the tools and calls one, which reaches the mocked Garmin API with the right credentials. It also checks the OAuth metadata, the 401 without a token, a wrong password, refresh tokens, forged tokens, the granted scope and how Garmin errors reach the client.

Unit (test/*.test.ts) run in Node with fake Garmin responses, a fake KV and stubbed fetch. They cover:

  • The approval page: password check, deny, the fixed read-only scope, the 5-attempt lockout per IP and the global pause, OAuth errors, HTML escaping and security headers.

  • The Garmin client: the token request (including the Accept header Garmin needs), memory and encrypted KV caching, retry on 401, error messages, token formats.

  • Every tool's data handling: date ranges and limits, chunking (sleep 31 days, others 28), weekly/monthly aggregation, unit conversion (grams to kg), local times and timezone handling, partial failures.

  • The MCP layer: each of the thirteen tools (plus the opt-in cycle tool) is called through a real MCP client and server (in-memory transport): the tool list and annotations, argument validation, how arguments become Garmin requests, defaults that depend on "today", and how errors reach the model.

GitHub Actions runs the same checks on Node 22 and 24 for every push and pull request (.github/workflows/ci.yml). Dependabot (.github/dependabot.yml) opens weekly pull requests for dependency updates (and immediately for security fixes); CI checks each one, and nothing is merged or deployed automatically. After a deploy, npm run setup (or the checks in AGENTS.md) verifies the live endpoints.

npm run check also runs scripts/check-lockfile.mjs: npm sometimes drops other platforms' optional binaries from package-lock.json after an incremental npm install, which makes npm ci fail on Linux. If the check fails, regenerate the lockfile with rm -rf node_modules package-lock.json && npm install.


Troubleshooting

Symptom

Fix

Setup: "register a workers.dev subdomain"

First deploy on a new Cloudflare account. Open dash.cloudflare.com → Workers & Pages, choose a subdomain, run npm run setup again.

Setup: "several Cloudflare accounts"

Choose one when asked, or set CLOUDFLARE_ACCOUNT_ID.

Setup: "Garmin rejected this API key"

The key is mistyped, expired or deleted. Copy it again or create a new one.

Setup: "isn't answering yet"

A brand-new workers.dev subdomain can take a few minutes. Open the URL again later.

Gemini says it has no access to Garmin

@-mention the app in the chat (type @ and pick it).

Tool error: "Garmin rejected the Personal API key"

The key expired. Run npm run setup -- --update-key.

Approval page: "Server not configured"

The admin password secret is missing. Run npm run setup or npx wrangler secret put MCP_ADMIN_PASSWORD.

Approval page: "Too many attempts"

Wait 15 minutes (up to 1 hour), then start the connection again from Gemini.

Approval page: "expired or was already used"

Start the connection again from Gemini; each page works once, for 10 minutes.

Gemini asks to reconnect

The connection wasn't used for 30 days, or grants were deleted. Reconnect and approve again.

"Date range is N days"

Sleep and Body Battery allow 31 days per call, daily summaries 366. For longer periods ask for trends (get_trends covers a year per call) or shorter ranges.

get_trends shows errors for one metric

Garmin refused or timed out for that data (e.g. rate limiting); the other metrics are still correct. Ask again a bit later.

"Today" is off by a day

Check the time zone in your Garmin Connect profile settings (the server re-reads it daily), or set TIMEZONE in wrangler.jsonc to your zone and deploy.

Gemini insists on a client ID and secret

Register a client yourself (below), then paste its client_id and client_secret.

Registering a client by hand (replace both placeholders; Gemini shows its redirect URL in the advanced settings):

Invoke-RestMethod -Method Post -Uri "https://garmin-mcp.<your-subdomain>.workers.dev/register" -ContentType "application/json" -Body '{"client_name":"Gemini","redirect_uris":["<GEMINI_REDIRECT_URL>"],"grant_types":["authorization_code","refresh_token"],"response_types":["code"]}'

Project layout

scripts/setup.mjs        npm run setup: login, secrets, deploy, checks
scripts/check-lockfile.mjs  Fails if package-lock.json lacks a platform's optional binaries
scripts/telegram.mjs     npm run telegram: turns the morning summary on or off
src/
  index.ts               OAuthProvider setup (DCR, CIMD, scopes, token lifetimes), Worker entry point
  auth-handler.ts        Landing page and the password-protected /authorize consent flow
  security.ts            Constant-time password check and KV-backed brute-force lockout
  html.ts                HTML templates and security headers for the auth pages
  mcp.ts                 GarminMCP (McpAgent Durable Object): Garmin client, timezone, registers the tools
  tools.ts               The MCP tools: schemas, descriptions, argument handling, error messages
  trends.ts              get_trends: chunked fetching and weekly/monthly aggregation
  fitness.ts             get_vo2max, get_weight, get_fitness_profile: fetching and shaping
  charts.ts              SVG charts for get_trends and get_day_details (sent in the result's _meta)
  chart-app.ts           The MCP App (sandboxed HTML) that shows those charts in Claude and other hosts
  cycle.ts               get_menstrual_cycle (opt-in via CYCLE_TRACKING), with optional cycle history
  workouts.ts            Planned workout of an activity, decoded into readable steps and targets
  nutrition.ts           get_nutrition: one day in detail, or daily totals for up to 14 days
  snapshots.ts           get_health_snapshots: Health Snapshot sessions with avg/min/max per metric
  parts.ts               Runs several Garmin requests; one failing part is reported, not fatal
  intraday.ts            get_day_details: heart rate, overnight HRV and SpO2 per interval, in local time
  summary.ts             Morning summary in Telegram: the cron job, its data and the message
  profile.ts             Timezone for "today": TIMEZONE, or the Garmin profile's (cached in KV)
  garmin.ts              Garmin Personal API client with encrypted token caching
  format.ts              Date helpers and response shaping
wrangler.jsonc           Worker config: Durable Object, KV (auto-provisioned), vars, required secrets
worker-configuration.d.ts  Generated by `wrangler types` (Env + runtime types)
test/                    Unit tests (Vitest, Node); helpers.ts has the fake KV and Garmin client
test/e2e/                End-to-end tests in local workerd; Garmin mocked with MSW (network.ts)
vitest.config.ts         Two test projects: unit (Node) and e2e (Workers runtime, test-only secrets)
.github/workflows/ci.yml Lockfile check, type check, tests and dry-run bundle on every push and pull request
.github/dependabot.yml   Weekly dependency update pull requests
AGENTS.md                Instructions for AI coding agents
skills/garmin-mcp-setup/ Agent Skill that sets the server up (clones the repo, follows AGENTS.md)
SECURITY.md              How to report vulnerabilities
LICENSE                  MIT

Notes

  • wrangler.jsonc deliberately has no KV namespace id. On a first deploy Wrangler creates the namespace (named <worker-name>-oauth-kv); later deploys keep the one already bound to the Worker. After an interactive deploy Wrangler may write the new id into wrangler.jsonc; keeping or discarding that change both work.

  • Garmin's token endpoint answers 406 Not Acceptable to Accept: application/json alone, so the client sends Accept: application/json, text/plain, */*.

  • agents 0.34 marks McpAgent as feature-frozen in favour of its newer createMcpHandler API for MCP SDK v2. McpAgent is still supported and is used here with @modelcontextprotocol/sdk 1.x; agents/mcp also imports @modelcontextprotocol/server and @modelcontextprotocol/client (v2), so they're installed at the exact versions its peer dependencies require.

  • The OAuth resource identifier is derived from the request origin, so the same build works on workers.dev, a custom domain and wrangler dev without config changes.

  • Garmin describes the Connect Personal API as being for personal use, so customers can access their own data; it isn't meant for commercial apps that serve many users. That's why this project has no shared server: each person deploys their own copy with their own key. Garmin's terms are shown when you create the key; read them there.

  • Garmin's API can change. If a tool starts failing after a Garmin update, please open an issue.

Contributing

Issues and pull requests are welcome. Before opening a pull request, run npm run check (type check, unit tests and a dry-run bundle), add tests in test/ for new behaviour, and describe how you tested the change. Never include real health data, keys or passwords in issues, logs, test fixtures or screenshots.

License and disclaimer

MIT. This is an independent personal project. It is not affiliated with, endorsed by or supported by Garmin, Google or Cloudflare. Garmin and Garmin Connect are trademarks of Garmin Ltd. or its subsidiaries; Gemini is a trademark of Google LLC; Cloudflare is a trademark of Cloudflare, Inc. The software is provided "as is", without warranty of any kind; you are responsible for your own deployment and your own data.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      B
      maintenance
      Ask your AI assistant about your Garmin data: sleep, HRV, recovery, training, km splits and more. Uses Garmin's official Personal API: no password, read-only, and nothing breaks when Garmin changes its login. Install in Claude Desktop with one click, run locally with npx -y garmin-mcp, or self-host on Cloudflare for phone and web apps.
      30
      365 npm
      1
      MIT
    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables Claude and other remote MCP clients to query a user's Garmin Connect data through the official Personal API, including recovery trends, sleep, HRV, Body Battery, activities, and daily wellness metrics. It provides read-only, OAuth-secured access on Cloudflare Workers, so users can ask natural-language questions about their own training and health data from desktop or mobile.
      MIT
    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      A read-only remote MCP server that connects Claude or any OAuth-capable MCP client to a Garmin Connect account through Garmin's official Personal API, running on Cloudflare Workers. It lets users query recovery trends, HRV, sleep, Body Battery, stress, heart rate, and activities in natural language from phone or desktop.
      MIT
    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables Claude and other remote MCP clients to query a user's own Garmin Connect data — sleep, HRV, Body Battery, stress, heart rate, and activity history — through Garmin's official read-only Personal API, so training and recovery questions can be answered in natural language from phone or desktop. It runs on Cloudflare Workers' free tier with OAuth 2.1 sign-in and no stored passwords.
      MIT