Skip to main content
Glama
Training MCP Server

Training MCP Server

by wtle2
README.md
# Training MCP Server

A personal MCP server that gives Claude (Claude Code and the Claude desktop app) read-only
access to your training data. I built it to help me train for **IRONMAN 70.3 *. Set your own race in `.env` and Claude gets it as context.

Ask Claude things like *"How did my sleep and HRV look this week?"*, *"Was Saturday's run really
easy, with HR under 155?"* or *"Am I ready for intervals today?"* and it answers from your
Strava and Garmin data.

- **Workouts:** Strava (official API). If Strava fails, it falls back to Garmin Connect.
- **Sleep and recovery:** Garmin Connect (unofficial, through `python-garminconnect`).
- **Zones and targets:** stored locally in `data/zones.json`.

Everything runs on your own computer over stdio. Nothing is hosted.

## What's in the folder

| Path | What it does |
|---|---|
| `server.py` | The MCP tools |
| `workouts.py`, `recovery.py` | Tool logic (Strava first with Garmin fallback, readiness labels) |
| `strava/` | Strava OAuth tokens, API client, unit conversion |
| `garmin/` | Garmin session (tokens only) and data cleanup |
| `cache/` | SQLite cache and the Strava rate-limit ledger |
| `common/` | Settings, Central time dates, units, HR zones |
| `auth_strava.py`, `auth_garmin.py` | One-time logins |
| `scripts/smoke_test.py` | Calls every tool once against your real accounts |
| `tests/` | Offline tests with mocked API responses (`uv run pytest`) |
| `data/` | Your tokens, cache and zones. Gitignored. Never share this folder. |

## Setup

You need Python 3.12+ and [uv](https://docs.astral.sh/uv/). On Windows, uv installs to
`%USERPROFILE%\.local\bin\uv.exe`. The commands below are PowerShell; on macOS or Linux, use `cp` instead of `copy`.

```powershell
git clone https://github.com/wtle2/training-mcp-server.git
cd training-mcp-server
uv sync
copy .env.example .env
```

Below, `<project-folder>` means the full path of this folder, and `<uv>` means the full path of
`uv.exe` (find it with `(Get-Command uv).Source`).

### 1. Create your Strava API app

1. Sign in to Strava, then open **https://www.strava.com/settings/api**.
2. Fill in the form:
   - **Application Name:** anything you like, for example `My Training MCP`.
   - **Category:** Training.
   - **Club:** leave it blank.
   - **Website:** `http://localhost`
   - **Authorization Callback Domain:** `localhost` (exactly this, with no port and no `http://`)
3. Accept the API agreement and click **Create**. Strava may ask you to upload an app icon; any small image works.
4. The page now shows **Client ID** and **Client Secret** (click *show*). Open `.env` in a text
   editor and paste them in:
   ```
   STRAVA_CLIENT_ID=123456
   STRAVA_CLIENT_SECRET=abc123...
   ```
   Keep the secret out of chats, screenshots and git.

New Strava apps start in "single player mode", where only your own account can connect. That's fine for this server.

### 2. Connect Strava (one time)

```powershell
uv run auth_strava.py
```

A browser tab opens on Strava's permission page. **Leave every box ticked**: the server needs
`read`, `activity:read_all` (including private activities) and `profile:read_all` (your HR
zones). Click **Authorize**. The tab should say "Strava connected". The refresh token is saved
to `data/strava_tokens.json`, and from then on the server renews access tokens (which last 6 hours) by itself.

### 3. Log in to Garmin (one time)

```powershell
uv run auth_garmin.py
```

Enter your Garmin email and password, plus the MFA code if Garmin sends one. Only session
tokens are saved, to `~/.garminconnect/garmin_tokens.json`. **The password is never written
to disk.** The server only ever uses those tokens.

### 4. Check it against your real data

```powershell
uv run scripts/smoke_test.py
```

You should see `[OK ]` for each tool. A night with no sleep recorded or a swim with no HR
shows up as `recorded: false` or `null`, not as an error.

### 5. Add it to Claude

**Claude Code** (user scope, so it works in every project):

```powershell
claude mcp add --scope user training -- "<uv>" --directory "<project-folder>" run server.py
```

**Claude desktop app:** open Settings → Developer → Edit Config, which opens the right file.
Where that file lives depends on how Claude was installed:

| Install | Config file |
|---|---|
| Standard installer (Windows) | `%APPDATA%\Claude\claude_desktop_config.json` |
| Microsoft Store (Windows) | `%LOCALAPPDATA%\Claude-Data\<package-id>\claude_desktop_config.json` |
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |

On the Store version, `%APPDATA%\Claude` may exist but holds only a marker file, so edits there do
nothing. The app saves its own settings in the same file, so add only the `mcpServers` part below,
keeping everything else, and back the file up first. Use double backslashes in Windows paths. Then
fully quit Claude (tray icon → Quit) and reopen it:

```json
{
  "mcpServers": {
    "training": {
      "command": "C:\\Users\\<you>\\.local\\bin\\uv.exe",
      "args": ["--directory", "C:\\path\\to\\training-mcp-server", "run", "server.py"]
    }
  }
}
```

## Re-authenticating

The tools tell you when you need to do this. The `fix` field in the reply names the script to run.

| Message mentions | Run |
|---|---|
| `auth_strava.py` (no tokens, revoked, or refresh rejected) | `uv run auth_strava.py` |
| `auth_garmin.py` (session expired or rejected) | `uv run auth_garmin.py` |
| Garmin "rate-limiting or blocking (429)" | Wait an hour or two, then run `uv run auth_garmin.py` if it continues |

You can revoke the server's Strava access at any time under strava.com → Settings → My Apps.
To remove the Garmin session, delete `~/.garminconnect\garmin_tokens.json`.

## Tools

Dates are `YYYY-MM-DD` in **America/Chicago**. `today` and `yesterday` also work. Run and bike
distances are in miles, run pace in min/mi, bike speed in mph, and swims in yards with pace per 100 yd.

| Tool | What it returns |
|---|---|
| `list_activities(start_date, end_date?, sport?)` | Date, sport, name, duration, distance, avg/max HR, pace or speed, avg power, elevation (ft). `sport` = swim / bike / run / other |
| `get_activity(activity_id)` | Full detail: laps, mile splits (runs), pace and HR per lap, time in HR zones |
| `weekly_summary(week_start?)` | Hours, distance and sessions per sport, plus time in each HR zone for 7 days (default: this Monday) |
| `get_sleep(start_date, end_date?)` | Total sleep, stages, sleep score, overnight HRV, bed and wake times |
| `get_hrv(start_date, end_date?)` | Nightly HRV average, weekly average, baseline range, status |
| `get_resting_hr(start_date, end_date?)` | Daily resting HR and Garmin's 7-day average |
| `get_body_battery_and_stress(date)` | Body Battery charged, drained, high, low and latest; stress average and max |
| `get_training_status()` | Training status, acute and chronic load, load balance, VO2 max, readiness score, recovery time |
| `readiness_today()` | Sleep, HRV, resting HR, Body Battery and yesterday's load, each labeled `normal` / `below baseline` / `above baseline` |
| `set_zones(max_hr?, threshold_hr?, easy_pace?, css_per_100yd?, ftp?)` | Saves your numbers to `data/zones.json` |
| `get_zones()` | Your stored numbers and the HR zones built from them |
| `compare_to_target(activity_id, target)` | For example `"easy run, HR under 155"`, `"HR 140-150"`, `"pace 8:30-8:45"`, `"power 180-200"`, `"zone 2"`: percent of time in range and whether the average met it |

Workout ids are Strava ids. When Strava is down, results come from Garmin with ids like
`garmin:12345678`, plus a `strava_error` field that says why.

### How the numbers are worked out

- **HR zones (5):** If you set `threshold_hr`, the boundaries are 85 / 90 / 95 / 100 % of it (Friel style).
  Otherwise, if you set `max_hr`, they're 60 / 70 / 80 / 90 %. Otherwise your Strava zones are used.
  Time in each zone comes from the second-by-second HR data, with pauses capped at 10 seconds.
- **Readiness baselines:**
  - Sleep score is compared with the average of the previous 7 nights (±10 %).
  - HRV is compared with Garmin's own baseline band.
  - Resting HR is compared with Garmin's 7-day average (±3 bpm).
  - The Body Battery daily high is compared with the previous 7 days (±10 %).
  - Yesterday's Garmin training load is compared with your 28-day daily average (0.7–1.3×).
- **Caching (`data/cache.sqlite3`):** Activities more than about 2 days old are kept for 30 days. Recent ones are refreshed
  after 15 minutes. Recovery data for finished days is kept for 7 days, and today's for 30 minutes.
- **Strava rate limits:** Strava allows 100 requests per 15 minutes and 1,000 per day. The server stops at 95 and 950,
  counting both its own requests and Strava's `X-ReadRateLimit-Usage` header. Network errors
  and 5xx responses are retried with exponential backoff. A 429 stops the request and returns a clear message.

## Risks — please read

- **The Garmin access is unofficial.** `python-garminconnect` copies the Garmin Connect mobile
  app's login and calls internal endpoints. Garmin can change or block it at any time, and that has
  happened: `garth` was deprecated in March 2026 after a login change. The version is pinned
  (`garminconnect==0.3.21`). If Garmin breaks, check the
  [project's releases](https://github.com/cyberjunky/python-garminconnect/releases) and bump the pin.
- **It logs in with your real Garmin credentials.** That's against the spirit, and possibly the letter,
  of Garmin's terms. The account could be flagged or rate-limited. The password is typed only into
  `auth_garmin.py` and isn't stored, but the session tokens in `~/.garminconnect` give full access
  to your Garmin account. Protect them like a password.
- **Strava's API agreement (2024)** limits how API data may be used. It bans using it to train AI
  models, for example. Sending your own data to Claude for your own analysis isn't training, but read
  the current agreement yourself. Your data goes to Anthropic when Claude reads it.
- **Health data** (sleep, HRV, HR) is sensitive. `data/` and `.env` are gitignored. Keep them out
  of cloud-synced or shared folders.
- This server only reads. It never posts, edits or deletes anything on Strava or Garmin.

## Tests

```powershell
uv run pytest
```

The tests are offline. They mock Strava with `respx` and use a fake Garmin object. They cover unit conversions, Central
time dates, zones, caching, token refresh, rate limits, the Garmin fallback, swims with no HR,
nights with no sleep, readiness labels, and target checks.

## Optional: hosting it as a remote connector (not built)

To use it from the Claude mobile app, the server would have to be reachable over HTTPS as a
*remote MCP server* and added under Settings → Connectors. In outline:

1. **Switch the transport.** `mcp.run(transport="streamable-http")` serves MCP over HTTP. Put it
   behind **OAuth**: Claude's connectors expect an OAuth 2.1 authorization server, and the
   SDK has `auth_server_provider` / `token_verifier` hooks for it. A static bearer token at minimum works for
   testing, but never expose it with no auth, because it serves your health data.
2. **Pick a host.**
   - **Fly.io:** the easiest fit for this Python code. Add a Dockerfile, run `fly launch`,
     and put a Fly volume at `/data` for the SQLite cache and tokens. Store the Strava secret
     with `fly secrets set`. Keep one machine so the rate-limit ledger isn't split.
   - **Cloudflare Workers:** best for Cloudflare's own MCP tooling (`workers-oauth-provider`
     does the OAuth part well). Python Workers can't run `garminconnect`/`curl_cffi`,
     though, so this would mean a TypeScript rewrite, with KV or D1 for storage.
3. **Garmin from a data-center IP** is much more likely to be blocked than from your home
   connection. Expect the Garmin tools to be the fragile part of a hosted version.
4. Re-run the auth scripts locally and upload the resulting token files as secrets, or add
   web-based login pages.

Ask if you'd like this built. It's a separate piece of work.

## License

MIT. See [LICENSE](LICENSE). Not affiliated with Strava, Garmin or IRONMAN.