Skip to main content
Glama
README.md
# Splitline Garmin MCP

Self-hosted Garmin Connect workout and training-plan MCP server and setup Web UI built on [`python-garminconnect`](https://github.com/cyberjunky/python-garminconnect), designed as a companion to [Splitline](https://github.com/splitline-php/splitline).

- **Splitline MCP (read-only)** handles your historical activities, PMC training load (CTL/ATL/TSB/ACWR), HRV/sleep trends, aerobic decoupling, HR zones, and best efforts via Garmin's official Personal API.
- **Splitline Garmin MCP (this repo)** stages, previews, pushes, updates, and removes structured **Running, Cycling, Swimming, and Strength** workouts on your Garmin Connect calendar so they sync to your watch.

> **Personal-use disclaimer:** Uses `python-garminconnect` against Garmin Connect's unofficial mobile/web endpoints for your own personal account. Not affiliated with or endorsed by Garmin Ltd.

## Features

- **Single container, one port (`8081`), one `/data` volume:**
  - `/`: Setup Web UI (offline-first with bundled fonts, zero third-party browser requests) for Garmin sign-in with MFA, VPS token import, MCP Bearer token management, client snippets, and plan review.
  - `/mcp`: Streamable HTTP MCP endpoint (fails closed `401` without Bearer token; validates `Host`, `Origin`, CORS preflights, and per-IP rate limits).
  - `/health`: Minimal liveness endpoint (`{"status": "ok"}`).
  - `garmin-mcp stdio`: Local or `docker exec` stdio MCP transport sharing `/data`.
- **Configurable write control:**
  - `GARMIN_WRITE_MODE=enabled` *(default)*: AI stages plans with `stage-plan` for preview and conflict checks, then syncs with `push-plan(plan_id)` after approval. Can be switched to **Staged Only** in the Web UI at any time.
  - `GARMIN_WRITE_MODE=staged_only`: Hard server-side ceiling. MCP can read and stage plans, while pushing to Garmin requires clicking **Push** in the Web UI. Unrecognized values fail closed to `staged_only`.
- **Local plan ledger (SQLite WAL):** Tracks Garmin template and schedule IDs per account so revisions update modified workouts in place (`PUT`), reschedule moved dates, skip unchanged sessions, checkpoint partial failures safely, and remove dropped workouts without hitting Garmin's 500-template library cap.
- **Supported sports:**
  - **Running:** pace (`min/km`), HR zone or custom bpm, cadence, distance/time/lap-button steps, repeats, `skip_last_rest`.
  - **Cycling:** power zones or custom watts with optional cadence secondary target, speed, HR.
  - **Swimming:** pool length, `min/100m` pace, and `swim_css_offset_sec` (mapped to Garmin's secondary CSS offset target).
  - **Strength:** rep-based and timed sets, target weight in kg, and search/validation across Garmin's bundled strength exercise catalog.

## Quick Start (Docker Compose)

```bash
curl -fsSLO https://raw.githubusercontent.com/splitline-php/garmin-mcp/main/compose.yaml
curl -fsSLO https://raw.githubusercontent.com/splitline-php/garmin-mcp/main/.env.example
cp .env.example .env
docker compose up -d
```

To build locally from a cloned checkout:

```bash
docker compose -f compose.yaml -f compose.local.yaml up -d --build
```

1. Open `http://localhost:8081`.
2. Sign in to Garmin Connect (including your 6-digit MFA code if prompted). Your password is never stored; auto-refreshing OAuth tokens are saved to `/data/garmin_tokens/garmin_tokens.json` (`0600`).
3. Click **Generate Token** in the MCP Server card and copy the OpenCode, Claude Code, Cursor, or VS Code snippet.

### Importing Tokens on a Cloud VPS

If Cloudflare rate-limits login from a cloud VPS IP, sign in once on your laptop (nothing is left on disk unless `DATA_DIR` is set) and paste the printed JSON into the **Import Tokens (VPS)** tab:

```bash
uvx --from "git+https://github.com/splitline-php/garmin-mcp@v0.1.0" garmin-mcp login --export
```

### Pairing with Splitline (`opencode.json`)

```json
{
  "mcp": {
    "splitline": {
      "type": "remote",
      "url": "http://localhost:8080/mcp",
      "headers": {
        "Authorization": "Bearer <SPLITLINE_MCP_TOKEN>"
      },
      "oauth": false
    },
    "garmin": {
      "type": "remote",
      "url": "http://localhost:8081/mcp",
      "headers": {
        "Authorization": "Bearer <GARMIN_MCP_TOKEN>"
      },
      "oauth": false
    }
  }
}
```

## MCP Tools

| Tool | Purpose |
| :--- | :--- |
| `get-connection-status` | Garmin auth state, write mode, library template count (vs 500 ceiling), and tracked plans. |
| `list-workouts` | List saved Garmin Connect workout templates (optional sport filter). |
| `get-workout` | Fetch full step details for one workout by `workout_id`. |
| `list-scheduled-workouts` | Calendar items in a date range, including adaptive Garmin Coach workouts. |
| `search-strength-exercises` | Search Garmin's strength exercise catalog for valid names and category/exercise pairs. |
| `stage-plan` | Validate, compile, check conflicts, save a new draft locally, and return preview and review URL. |
| `update-staged-plan` | Revise an existing plan by `plan_id` and generate an updated preview and diff. |
| `push-plan` | Sync a staged plan to Garmin Connect (create, update in place, reschedule, delete dropped sessions). |
| `unschedule-workout` | Preview (`confirm=False`) or remove (`confirm=True`) one calendar entry (`scheduled_workout_id`). |
| `delete-plan` | Preview (`confirm=False`) or remove (`confirm=True`) a managed plan's workouts (`keep_past` supported). |

## Environment Variables

| Variable | Default | Description |
| :--- | :--- | :--- |
| `APP_URL` | `http://localhost:8081` | External URL of this Web UI and `/mcp` host. |
| `SPLITLINE_URL` | `http://localhost:8080` | Splitline URL used to prefill the combined OpenCode snippet. |
| `TIMEZONE` / `TZ` | `UTC` | Fallback IANA timezone for date checks (Garmin profile timezone is preferred when connected). |
| `HOST` / `PORT` | `127.0.0.1` / `8081` | Bind host and port (`Dockerfile` sets `HOST=0.0.0.0`). |
| `DATA_DIR` | `/data` or `./data` | Persistent directory for `state.sqlite` and `garmin_tokens/`. |
| `GARMIN_WRITE_MODE` | `enabled` | Hard write ceiling (`enabled` or `staged_only`; unknown values fail closed to `staged_only`). |
| `GARMIN_WRITE_PACING_MS` | `500` | Minimum delay in ms between Garmin write calls. |
| `GARMIN_LIBRARY_SOFT_LIMIT` / `HARD_LIMIT` | `480` / `500` | Warning and hard-stop workout template thresholds. |
| `GARMIN_MFA_TTL_SECONDS` | `600` | In-memory lifetime of a pending MFA challenge. |
| `MCP_ENABLED` / `MCP_WEB_ENABLED` | `true` / `true` | Hard ceilings for stdio and HTTP `/mcp`. |
| `MCP_TOKEN` | *(empty)* | Optional static Bearer token (32+ chars recommended; locks UI rotation). |
| `MCP_ALLOWED_ORIGINS` | *(empty)* | Comma-separated trusted browser origins (never use `*`). |
| `MCP_RATE_LIMIT` | `120` | Per-IP requests per minute on `/mcp`. |
| `TRUSTED_PROXIES` | *(empty)* | Reverse-proxy IPs/CIDRs trusted for `X-Forwarded-For`. |
| `SESSION_SECURE_COOKIE` | `false` (`true` for `https://` `APP_URL`) | Mark CSRF/flash/MFA cookies `Secure`. |

## Local Development

```bash
uv sync --locked
uv run ruff check src tests
uv run mypy src tests
uv run pytest -v
uv run garmin-mcp serve
```

## Security

See [SECURITY.md](SECURITY.md) for deployment isolation, reverse-proxy forward-auth configuration, CSRF/Host protections, and MCP Bearer token handling.

## License

Licensed under the [MIT License](LICENSE).