Loopback Training Server
Queues structured workouts for delivery to Apple Watch via WorkoutKit and stores Apple HealthKit workout and daily health metrics synced from the companion iOS app, letting an AI coach query and create training data for the Apple ecosystem.
Loopback Server
The self-hosted backend behind Loopback – Run Coach, an iOS running app. It stores workout history, queues structured workouts for delivery to Apple Watch via WorkoutKit, manages training plans and daily health metrics, and serves an authenticated web dashboard for athletes and admins.
Website: loopback.ardenlab.dev
Built with FastAPI, PostgreSQL, SQLAlchemy, and React. Includes a built-in MCP (Model Context Protocol) endpoint so an AI assistant can act as your running coach over the same data.
This is the server half of a two-part system — you also need the Loopback iOS app. The app is what feeds the server: it syncs Apple HealthKit workouts and daily health metrics to it, and installs queued workouts on Apple Watch. The server runs fine on its own (API, dashboard, MCP), but without the app nothing puts data in or gets workouts onto your watch. The app installs from the public TestFlight beta (iOS 26), or builds from source.
Naming note: this is the companion server for the Loopback running app — no relation to the LoopBack Node.js framework or Rogue Amoeba's Loopback audio tool. The technical name used throughout the codebase (packages, containers, DB) is
training-api.

Workout detail | Health trends |
|
|
Demo data shown; every screen is scoped to the signed-in athlete.
Features
Workout storage — CRUD API for workouts with activity type, distance, duration, heart rate, splits, and arbitrary JSONB data
Analytics — Summary endpoints with aggregation by week, month, or year
Training queue — Queue structured workouts (intervals, warmup/cooldown, pace alerts) for sync to Apple Watch via an iOS companion app
Workout actions — Edit or delete workouts already synced to Apple Watch via pending action queue
Device inventory — Track what workouts are currently on the user's Apple Watch
Missed workout feedback — Record and query feedback when users miss scheduled workouts, with pattern detection for coaching
Training plans — Create and manage training plans with goals, guardrails, phases, and athlete context stored as flexible JSONB metadata, plus an explicit completion flow (rating + feedback fed back to the coaching context)
Scheduling & calendar — Attach a recurring weekly cadence to a plan and query a unified calendar that merges queued runs with scheduled strength sessions, flagging conflicts
Plan validation — A deterministic "linter" for upcoming schedules: weekly-ramp and taper checks, missing down weeks, back-to-back hard days, guardrail breaches, strength-day collisions — warnings, never blocks (
POST /api/plans/{id}/validate, also returned when queueing)Health metrics — Bulk upsert daily HealthKit metrics (sleep, HR, HRV, weight, VO2Max, steps, body composition) with date-based upsert
Nutrition — Daily dietary totals from HealthKit (energy, macros, fiber, sodium, water, caffeine + open-ended micronutrients), and a summary endpoint that aligns intake with body weight and training load per week or month, including protein g/kg — so diet can be read against performance in one query. Only energy and the macros are true daily totals; the rest are lower bounds, because food databases record them on a fraction of entries — the MCP tells the coach so it can't read a sparse sum as a deficiency
Plan-workout linking — Link queued workouts to plans (
plan_id) and recorded workouts to their planned counterpart (plan_workout_id) for planned-vs-actual analysisMulti-user — Username/password accounts with per-device API tokens (
POST /api/auth/login); all data is scoped per user. The admin invites people with a link, and each picks their own username and password. The phone app connects by scanning a QR code in the dashboard, with nothing to typeWeb dashboard — Authenticated React SPA served same-origin by the API: overview, calendar, workouts, plans, health charts, and queue for athletes; user management and system monitoring for admins
Admin & monitoring — Per-user token inspection/revoke (cut off one stolen device), sync-freshness per athlete, an auth audit trail (logins, password/token/user changes), and a system screen reporting DB size and backup freshness
MCP server — Built in at
/mcp: let AI assistants query your training data, create workouts and plans, and correlate health metrics via natural language. Claude and ChatGPT connect by signing in with OAuth (paste the address once and approve in the dashboard; for Claude that covers the web, the phone and the desktop app); other tools, and Claude Desktop on a server that is not reachable from the internet, use a token
Related MCP server: apple-workouts-mcp
Quick Start
Prerequisites
Docker with Docker Compose v2.24 or newer
1. Clone and configure
git clone https://github.com/aderaaij/loopback-training-server.git
cd loopback-training-server
cp .env.example .envEverything in .env has a sensible default (the comments in the file explain each one) — for a first install you don't need to edit anything.
2. Start
docker compose up -d # or: make upThe first start pulls a prebuilt multi-arch image from GHCR (amd64/arm64; if the pull fails it builds from source instead, which takes a few minutes — docker compose build forces that) and runs the database migrations. The API and dashboard are then at http://localhost:8001 (verify with curl http://localhost:8001/api/health).
3. Create your admin account
Open http://localhost:8001 — a fresh install greets you with a setup screen. Create the admin account there and you land signed in. Admins get the management console (Users + System); regular accounts get the training dashboard.
For headless or scripted installs, set BOOTSTRAP_ADMIN_PASSWORD in .env before the first start instead — the account is created at boot and the setup screen never appears. Either way, setup closes permanently once the admin has a password; if you ever lock yourself out, recovery is the CLI (docker compose exec app python -m app.cli set-password admin).
4. Add your household
One instance serves a household: a handful of accounts, all data scoped per user, and no open registration — nobody gets an account without the admin.
As
admin, open Users → Invite someone. You get a link, which you can copy, share, or show as a QR code to someone next to you. It works once and for seven days, and you can withdraw it under Waiting invitations until it is used. The admin account itself has no training screens, so for your own training invite yourself: the dialog has a link that opens the invitation in the browser you are in.Whoever opens the link picks their own username and password and is signed in to the dashboard at once, on a page that walks them through the next two steps. The admin never sees the password. The link opens the dashboard, so it works where the dashboard does: the device opening it has to be able to reach the server (same network, or your VPN on), and the address in the link is the one your dashboard is open at unless you change it in the dialog.
Each athlete connects the iOS app (TestFlight beta). The quick way is a QR code: in the dashboard, open Settings → Phone app → Show QR code, then tap Scan QR Code on the app's sign-in screen and point it at the screen. Nothing is typed: the app shows the account and the server it is about to connect to, and on your say-so gets a token of its own. The code works once and for five minutes, and the address in it is the one the dashboard is open at, so open the dashboard at an address the phone can reach too (not
localhost), or correct the address shown under the code. Typing the server URL, username and password into the app works as before.Optional AI-coach access: each athlete connects their own assistant from the dashboard (Settings → AI coach → Connect; see MCP Server).
An account can still be made by hand (Users → Create by hand, where you choose the username and the password and pass them on). That is how another admin is added: an invitation only ever makes an ordinary account.
Passwords, per-device tokens (revoke one stolen device without touching the rest), and deactivation are all managed in the dashboard. Changing or resetting an admin's password, or deactivating that admin, also cancels the invitations they made that are still waiting.
A deactivated account keeps its data and its username and can be reactivated. To remove one for good, deactivate it and then choose Delete on its row: the account goes with everything stored for it, the username becomes free again, and it cannot be undone. Backups made before that still contain the account until newer ones replace them (see Backups).
Creating accounts, setting passwords and making tokens also exist as a CLI fallback:
docker compose exec app python -m app.cli --helpTry it with demo data
Want to see a filled-in dashboard before wiring up your own data? A disposable demo stack ships with the repo — its own compose project, database volume, and port, fully isolated from a real deployment:
docker compose -f docker-compose.demo.yml up -d
python3 scripts/seed_demo.py # stdlib only, no dependenciesThe seeder creates a synthetic athlete and ~16 weeks of realistic training through the public API: runs with splits, heart rate, cadence and GPS routes along the Lisbon riverfront, Hevy-style strength sessions, daily health metrics, nutrition logs (deliberately imperfect: a fifth of days unlogged, one week missed, today still in progress), a completed and an active training plan with a strength schedule, queued watch sessions (one skipped, with feedback), and coaching notes. The screenshots above are this data.
Then open http://localhost:8011 and sign in as athlete sofia / sofia-demo (or admin admin / demo-admin for the management console). The seeder also prints an API token you can point an MCP client at.
To put a demo where other people can reach it, see deploy/demo. seed_demo.py --read-only locks the athlete's account once the data is in, so its password can be published: it can be signed in to and looked at, and nothing in it can be changed.
Tear it down (wipes the demo database, touches nothing else):
docker compose -f docker-compose.demo.yml down -vExposing the server
The iOS app syncs in the background, so the server has to be reachable from wherever the phone is — over HTTPS, or over HTTP on a network you trust. Dashboard, API and coach (/mcp) all share the one port, so whichever option you pick covers all three.
Built-in HTTPS (a server with a public IP and a domain)
Point a domain's DNS at the server, make sure ports 80 and 443 are open, and add two lines to .env:
COMPOSE_FILE=docker-compose.yml:deploy/https/caddy.yml
DOMAIN=loopback.example.comThen docker compose up -d. This adds a Caddy container that obtains and renews a Let's Encrypt certificate by itself and serves everything at https://<DOMAIN>. It also closes plain-HTTP port 8001 to everything but the host itself, and makes the server see each client's real address, so the login rate limit applies per client and the audit trail shows who connected.
COMPOSE_FILE replaces Compose's automatic file discovery: if you keep a docker-compose.override.yml, add it to the list (docker-compose.yml:docker-compose.override.yml:deploy/https/caddy.yml). On Windows the separator is ;.
Tailscale (a home server: no domain, no open ports)
Tailscale puts the server on a private network of your own devices (a "tailnet"). The add-on below gives the server a Tailscale device of its own, with HTTPS and a name, and nothing to configure on your router. Add one line to .env:
COMPOSE_FILE=docker-compose.yml:deploy/tailscale/tailscale.ymlThen docker compose up -d, and docker compose logs tailscale: the log shows a link that adds the server to your tailnet. Open it and approve; there is no hurry, the link waits until you use it. (To skip the link, put an auth key in .env as TS_AUTHKEY.) The device is called loopback; set TS_HOSTNAME for another name.
The server then has two entrances, both at loopback.<your-tailnet>.ts.net:
Address | Who can reach it | What is there |
| Devices on your tailnet | Everything: dashboard, API (the phone app), coach |
| The internet | The coach alone, for assistants that connect from the cloud (claude.ai) |
Install Tailscale on each phone and point the app at the first address.
Only the coach is public, and it answers nothing without a token. What reaches the server from the internet is listed in deploy/tailscale/serve.json: /mcp, /oauth/token and two small documents that tell an assistant where to sign in. Tailscale answers every other path itself with a 404, so the dashboard, the API and every page that takes a password stay on your tailnet. Signing in to approve an assistant happens on the first address, in your own browser. The page behind an invitation link is one of those pages: someone you invite has to be on your tailnet before the link opens for them.
Two settings in your tailnet make this work, both in the Tailscale admin console and both one-time: HTTPS certificates (with MagicDNS), and Funnel allowed for the device, which is what makes the second address public. Without Funnel the first address works all the same and only assistants in the cloud cannot connect.
The add-on also closes plain-HTTP port 8001 to everything but the host itself, and makes the server see each client's real address. If your phones were using http://<machine-name>:8001, move them to the first address above. COMPOSE_FILE replaces Compose's automatic file discovery: if you keep a docker-compose.override.yml, add it to the list.
Other ways
Tailscale on the host, without the add-on: install Tailscale on the server and each phone; clients use
http://<machine-name>:8001inside the tailnet and nothing is exposed to the internet.tailscale serve --bg --https 8443 8001adds HTTPS. An assistant in the cloud cannot connect to such a server; that is what the add-on above is for.Cloudflare Tunnel: also works from behind a home router, with a domain on Cloudflare. Be aware that Cloudflare terminates the TLS connection, so it can read the health data passing through; with Caddy or Tailscale it is only ever decrypted on your own machine.
deploy/demo/docker-compose.public.ymlshows the pattern.Your own reverse proxy: put nginx / Traefik / Caddy with a real certificate in front and forward to
127.0.0.1:8001. SetFORWARDED_ALLOW_IPSin.envto the address the proxy connects from, or every client shares one rate limit (see Configuration).LAN only: fine for trying it out, but a phone that leaves the house stops syncing.
If the server ends up publicly reachable: login is rate-limited (5/min per client address), there is no registration endpoint (the first-run setup endpoint closes permanently once the admin account exists), and the admin System screen shows an auth audit trail — but public exposure still means strong passwords on every account.
SECURITY.md says what the server protects and from whom, what leaves it (your AI assistant, map tiles), where its protection stops, and how to report a problem.
Backups
The server backs itself up. A nightly pg_dump (03:30 container time by default) is written into the BACKUP_HOST_DIR mount (default ./backups), keeping the newest 30 dumps; if the server was off at backup time it catches up shortly after starting. Upgrades that include database migrations take an extra dump right before migrating. The admin System screen reports backup freshness (green < 26 h old) and has a Back up now button. Tune with BACKUP_TIME, BACKUP_KEEP, and TZ in .env.
The dumps are plain pg_dump | gzip files — point BACKUP_HOST_DIR at (or sync it to) somewhere off-machine and you're covered. One caveat for NAS setups: the database volume itself must live on local disk — Postgres data over NFS/SMB is the classic self-hoster corruption trap; syncing the dump directory to the NAS is the safe way to get backups off-machine. Restore with:
gunzip -c <dump>.sql.gz | docker exec -i postgres__training-api psql -U training-api training-apiPrefer to manage backups yourself? Set BACKUP_ENABLED=false, mount the directory read-only (:ro in an override file), and run something like this on the host — the System screen reports freshness on whatever training-api-*.sql.gz files it finds either way:
# crontab -e
30 3 * * * docker exec postgres__training-api pg_dump -U training-api training-api | gzip > /path/to/backups/training-api-$(date +\%F).sql.gzReleases & upgrading
Releases are git tags (vX.Y.Z) with notes in CHANGELOG.md; each one publishes multi-arch Docker images to GHCR. Three kinds of image tags exist:
Image tag | Meaning |
| An exact release — immutable |
| The latest patch release of a minor line |
| Every push to |
Compose runs latest by default. Once you depend on the server day-to-day, pin a release in .env — especially if something like Watchtower auto-pulls your containers, since latest tracks unreleased main:
IMAGE_TAG=0.1To upgrade: skim the changelog, then
docker compose pull && docker compose up -dDatabase migrations run automatically on startup, and an upgrade with pending migrations dumps the database first (see Backups). The running version is reported by GET /api/health and on the admin System screen. Versioning is semantic, with the usual 0.x caveat: breaking changes bump the minor version until 1.0, so 0.1 → 0.2 deserves a changelog read while 0.1.x → 0.1.y is always safe.
Going back is not the same as upgrading in reverse. After a release that changed the database, an older version refuses to start on it (the log says it cannot locate a revision), so setting IMAGE_TAG back is not enough: restore the backup from before the upgrade as well.
Configuration
Everything is configured through environment variables in the root .env (read by Docker Compose):
Variable | Default | Purpose |
| (unset) | Headless alternative to the browser setup screen: pre-sets the first-run admin password. Applied only while the admin has none, so rotating it later is a no-op. If that account was deleted and another admin exists, it is not made again |
|
| First-run admin username |
|
| Database credentials (not published outside the compose network; also fed to the app as |
|
| Host port for the API + dashboard |
|
| Serve the coach MCP at |
| (unset) | The server's address as an assistant reaches it, e.g. |
| (unset) | Where the page that asks you to sign in and approve an assistant lives, when that is not the address the assistant connects to: a coach endpoint that is public next to a dashboard that is not |
| (unset) | The same, when the two differ only in the port: the coach on the standard port and the dashboard on this one. |
|
| Name of the server's device on your tailnet, used with |
| (unset) | A Tailscale auth key, to add that device to your tailnet without opening the link from its log |
| (unset) | Behind a reverse proxy: the address(es) or CIDR the proxy connects from, whose |
| (unset) | Hostname for built-in HTTPS, used with |
|
| Host directory the server writes its |
|
| Server-managed backups: nightly dump, catch-up after downtime, pre-migration dump. |
|
| Nightly backup time, container-local (set |
|
| How many dumps to keep — older |
| UTC | Container timezone (e.g. |
| (unset) | Route maps use CARTO's dark tiles, which now require a free API key (non-commercial, up to 5M requests/month, from CARTO); without one the map shows an "API key required" watermark. Setting this switches to the keyed CARTO URL |
| (unset) | Use any other tile provider: a Leaflet URL template ( |
|
| Attribution line shown on the map (HTML allowed); set it to match your provider |
|
| Only used when |
|
| Docker image tag for the app service — pin a release like |
Running the backend outside Docker reads backend/config/.env instead (template: backend/config/.env.example).
Upgrading from a pre-auth version: keep your old API_KEY set in backend/config/.env — the migration seeds it as a token owned by the admin account, so existing clients keep working while you move them to per-user tokens.
Web dashboard
The frontend/ directory holds the React 19 + TypeScript SPA (Vite, TanStack Query, hand-rolled SVG charts, Leaflet route maps). The Docker build bakes frontend/dist into the image and FastAPI serves it at / with an SPA fallback — same origin, no CORS.
Signing in as a regular user shows the athlete screens (overview, calendar, workouts, plans, notes, health, queue). Admins get a management console instead: Users (account CRUD, per-device token revoke, sync freshness) and System (backup freshness, DB size, auth activity feed).
cd frontend
npm run dev # Vite dev server on :5173, proxies /api → localhost:8001
npx tsc -b # typecheck
npm run build # production build (also run inside the Docker build)API
All /api endpoints except /api/health, /api/auth/login, /api/auth/pairing/redeem and the two under /api/auth/invite/ require a Bearer token in the Authorization header. Tokens are issued per device by POST /api/auth/login (username + password, rate-limited 5/min/IP), by trading in the code from the dashboard's QR code, or by accepting an invitation; /api/admin/* additionally requires the admin role. A token is either full (everything its owner can do) or a coach token, which gets a 403 on every endpoint the coach's tools do not call (what that covers).
Wire casing: JSON casing varies by resource — auth, admin, feedback, and calendar are camelCase; workouts, queue, plans, and health metrics are snake_case.
Auth
Method | Endpoint | Description |
|
| Whether first-run setup is open ( |
|
| Create the first admin account (returns a signed-in session; 409 once an admin exists) |
|
| Log in, mint a per-device token (bad credentials → 401) |
|
| Current user + their tokens (each with its |
|
| Change own password (revokes every other token) |
|
| Mint a named token (shown once; optional |
|
| Revoke one of your own tokens |
|
| Make a code for connecting the phone app: |
|
| What became of your code: |
|
| Trade a code for a full per-device token ( |
|
| Whether the code of an invitation link is still good, and who it is from: |
|
| Make the account an invitation is for and sign in to it ( |
|
| The Claude Desktop extension for the coach, as a file (optional |
Signing in from an assistant (OAuth 2.1 with PKCE; see MCP Server). The first four take no token; the last three are the dashboard's approval page acting as the signed-in athlete.
Method | Endpoint | Description |
|
| Which server issues tokens for |
|
| Where to send the athlete and where to trade the code |
|
| Checks an assistant's request and passes the browser on to the approval page |
|
| Trades the one-time code for a token (a coach token; no refresh tokens) |
|
| The request waiting for an answer (404 once answered or after 10 minutes) |
|
| Approve as yourself; returns where to send the browser (403 for an admin account) |
|
| Decline; returns where to send the browser |
Admin
Method | Endpoint | Description |
|
| List users with token stats + sync freshness |
|
| Create a user by hand, with a username and password you choose |
|
| The invitations nobody has used yet (never their codes) |
|
| Make an invitation: |
|
| Withdraw an invitation that is still waiting |
|
| Activate/deactivate (deactivation revokes all tokens), or make read-only with |
|
| Delete an account for good, with all its data. Only a deactivated account (409 otherwise), never your own (400) |
|
| Reset a user's password |
|
| List a user's tokens |
|
| Revoke a single token (one stolen device) |
|
| Auth audit trail (logins, password/token/user changes; prunes >365d on read) |
|
| Backup freshness, DB size, row counts, migration head |
Workouts
Method | Endpoint | Description |
|
| Create or upsert a workout |
|
| List workouts (filters: |
|
| Aggregated stats by period ( |
|
| Get workout detail |
|
| Get per-split breakdown |
|
| Get heart rate samples |
|
| Assign a pair of shoes to a workout ( |
|
| Delete a workout |
|
| List pairs of shoes with their mileage (meters), in use first |
|
| Add a pair ( |
|
| Change a pair: rename, set distances, make it the default, retire it |
|
| Delete a pair (its workouts stay, without a pair) |
Training Queue
Method | Endpoint | Description |
|
| Queue a structured workout (response carries an additive |
|
| Queue several workouts at once → |
|
| List queue items (filter by |
|
| List pending items |
|
| Edit a queue item's fields |
|
| Update item status ( |
|
| Delete a queue item |
|
| App-facing: get pending workouts as WorkoutKit compositions |
|
| App-facing: delivered, still-due workouts as compositions; the app restores missing ones onto a new or reinstalled phone's watch |
|
| App-facing: confirm install → |
|
| App-facing: mark item as synced (persists the record) |
Workout Actions
Method | Endpoint | Description |
|
| List pending edit/delete actions |
|
| Create an edit or delete action |
|
| Create multiple actions at once |
|
| Acknowledge a processed action |
Device Inventory
Method | Endpoint | Description |
|
| Sync full on-device workout snapshot (idempotent replace) |
|
| Get stored inventory |
Missed Workout Feedback
Method | Endpoint | Description |
|
| Record feedback for a missed workout (upsert by |
|
| Retrieve feedback history (filters: |
Training Plans
Method | Endpoint | Description |
|
| Create a training plan |
|
| List plans (filters: |
|
| Get plan with metadata |
|
| Update plan fields |
|
| Complete an active plan (rating/feedback stored as a coaching note) |
|
| Deterministic schedule check → |
|
| Delete a plan (queue items keep |
|
| Get all queued workouts for a plan |
|
| Read the plan's recurring weekly cadence, resolved to dated sessions |
|
| Set the cadence (collisions with queued runs are warned, not blocked) |
|
| Clear the cadence |
Calendar
Method | Endpoint | Description |
|
| Unified timeline merging queued runs + scheduled strength sessions, each with a |
Plan Notes
Method | Endpoint | Description |
|
| Add a cross-conversation coaching note |
|
| List notes (filters: |
|
| Condensed coaching context (plans + notes) for LLM consumption |
|
| Get a note |
|
| Update a note |
|
| Delete a note |
Health Metrics
Method | Endpoint | Description |
|
| Bulk upsert daily health metrics (null fields preserved) |
|
| Query metrics (required: |
Nutrition
Method | Endpoint | Description |
|
| Bulk upsert daily dietary totals (null fields preserved) |
|
| Query daily rows (required: |
|
| Intake, body weight and training load per period (optional: |
|
| Remove a whole day's row |
MCP Server
The server ships with an MCP endpoint that exposes training data to AI assistants (e.g., Claude), so one can act as your running coach. It is part of the same container and needs no setup: wherever the dashboard is reachable, the coach is at /mcp on the same address.
http://<machine-name>:8001/mcpEach person connects as themselves, so the data is scoped to their account — this is the "point your own Claude (or any LLM) at it" path. There are two ways to do that. An assistant that can be given a header sends a token of that person's as Authorization: Bearer (the dashboard's Connect dialog makes one). An assistant that cannot, such as claude.ai, signs in with OAuth: you approve it in the dashboard and it is given a token of its own. Either way the assistant holds a coach token, which works for the coach and nothing else. A request without a valid token gets a 401. Set MCP_ENABLED=false in .env to serve no coach endpoint at all.
Connect a client
The quickest way: in the dashboard, Settings → AI coach → Connect shows the setup for your client: an extension to install for Claude Desktop, the address to paste for Claude on the web and phone, and for the others a snippet with the server address and a new token already filled in. The sections below are the same thing by hand; substitute your server's address and your token.
There are two ways to connect, and for any one assistant you only need one of them:
Sign in (OAuth) | A token | |
Covers | Claude everywhere at once: on the web, in the phone apps and in Claude Desktop. The connection belongs to your Claude account, so you set it up once. ChatGPT connects the same way | The one app you set it up in: Claude Desktop (through the Loopback extension), Claude Code, Cursor, VS Code and other clients on your computer |
You do | Paste the server's address in Claude and approve in the dashboard (steps) | Create a token in the dashboard and give it to that app (below) |
Your server needs | To be reachable from the internet over HTTPS: built-in HTTPS on a server with a domain, or the Tailscale add-on on a home server | To be reachable from the computer the app runs on; a home network or tailnet is enough |
So: if your server can be reached from the internet, sign in once from Claude and you are done for the web, your phone and Claude Desktop. ChatGPT signs in the same way, from its own connector settings. The token route is for Claude Desktop on a server that cannot be reached from the internet, and for tools that run on your computer.
Signing in is new in 0.1.30. Everything that worked with a token before still does, unchanged.
Claude Code
claude mcp add training --scope user --transport http \
http://<machine-name>:8001/mcp \
--header "Authorization: Bearer <your-token>"--scope user makes the server available in every folder. To replace an existing entry (for example after rotating the token), run claude mcp remove training --scope user first; add refuses to overwrite.
Claude Desktop (with the extension, for a server that is not reachable from the internet)
Claude Desktop cannot send a bearer token to a remote server by itself, so Loopback hands out a small extension that does it. Nothing else has to be installed, and no config file is edited.
In the Loopback dashboard go to Settings → AI coach → Connect, pick Claude Desktop and create the token.
Click Download and open the file (
loopback-coach.mcpb). Claude Desktop shows it with an Install button. If the file does not open in Claude Desktop, use Settings → Extensions → Advanced settings → Install Extension… there and pick it.Install it. When it asks for settings, the server address is already filled in; paste the token into Token. Claude Desktop keeps it in the system keychain.
Claude Desktop warns that an extension can access your computer, and lists the developer as unknown. That is expected: it shows both for an extension that is installed from a file and is not signed. This one reads no files. It only passes messages between Claude Desktop and your server, and its two small scripts are readable in
backend/app/desktop_extension/server.Ask in a new chat: "What did I run this week?"
You need the extension only when your server cannot be reached from the internet. If it can, sign in from Claude instead: that one connection also covers Claude Desktop, and you can skip this section. (Do one or the other in Claude Desktop, not both, or the coach is there twice.)
The extension is one small script that passes messages between Claude Desktop and /mcp on your server, run by the Node.js that Claude Desktop ships. If the server restarts while Claude Desktop is open (an upgrade, a reboot), the extension reconnects by itself. The download is the same for everyone on the server: it holds the address but never a token, so it is safe to pass on to someone else in the household, who then pastes their own.
If it does not connect:
Claude says the token was rejected: it was mistyped or revoked. Create a new one (step 1) and paste it under Settings → Extensions → Loopback Coach in Claude Desktop.
The extension shows an error or its tools are missing: this computer cannot reach the server. Open the dashboard address in a browser on the same computer to confirm; on a tailnet, check that Tailscale is on. The extension writes the exact reason to its log in Claude Desktop. Once the address is reachable again, restart Claude Desktop.
The address changed: edit it in the extension's settings; the dashboard address is enough,
/mcpis added for you.
The same connection through a config file and mcp-remote, for a Claude Desktop where extensions are switched off.
Install Node.js (20.18 or newer) if you don't have it. The helper runs through
npx, which comes with Node.Create a token. In the Loopback dashboard go to Settings → AI coach → Connect, pick Claude Desktop, create the token and copy it. It is shown only once. (You do not need the download it also offers.)
Open the config file. In Claude Desktop: Settings → Developer → Edit config. This opens
claude_desktop_config.json:macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
Add the server. If the file is empty, paste this whole block. If it already has an
mcpServerssection, add only the"training": { … }entry inside it.{ "mcpServers": { "training": { "command": "npx", "args": [ "-y", "mcp-remote", "https://<your-server>/mcp", "--header", "Authorization:${AUTH_HEADER}" ], "env": { "AUTH_HEADER": "Bearer <your-token>" } } } }Replace
https://<your-server>/mcpwith the address you open the dashboard at, plus/mcp, and<your-token>with the token from step 2 (keep the wordBearerand the space in front of it).If your address starts with
http://(for examplehttp://<machine-name>:8001inside a tailnet), add one more line toargs, or the helper refuses to connect:"--header", "Authorization:${AUTH_HEADER}", "--allow-http"Quit Claude Desktop completely and reopen it. The config is only read at startup, and closing the window is not enough (macOS: Cmd+Q; Windows: quit from the system tray icon).
Check it works. Settings → Developer should list
trainingwith the status Running. Then ask in a new chat: "What did I run this week?"
If it does not connect:
trainingshows Failed or Not responding: click View logs next to it (the file ismcp-server-training.log, in~/Library/Logs/Claude/on macOS or%APPDATA%\Claude\logs\on Windows). The usual causes are invalid JSON (a missing comma) or Node.js not being found.npxnot found although Node.js is installed: Claude Desktop does not read your shell profile, so a Node.js installed through a version manager (nvm, fnm, asdf) is invisible to it. Runwhich npxin a terminal and use that full path as"command"in place of"npx".401 errors in the log: the token is wrong, was revoked, or
Beareris missing in front of it.Timeouts: this computer cannot reach the server. Open the dashboard address in a browser on the same computer to confirm.
Why the config looks like this: the token goes in env and is referenced as ${AUTH_HEADER} because Claude Desktop on Windows mishandles spaces inside args values (on macOS a plain "Authorization: Bearer <your-token>" argument also works). --allow-http is needed because mcp-remote refuses plain HTTP to anything but localhost; that is acceptable inside a tailnet, where traffic is already encrypted by WireGuard, and not on the open internet.
Claude: web, phone and desktop (signing in with OAuth)
claude.ai and the Claude phone apps cannot be given a token. They sign in instead, with OAuth: you paste the server's address, approve the connection in the Loopback dashboard, and Claude is handed a token of its own.
In the Loopback dashboard, open Settings → AI coach → Connect, pick the entry for Claude and click Open in Claude. Claude opens its Add custom connector form with the name and your server's address filled in. Add it. By hand it is the same form: in Claude, Settings → Connectors → Add custom connector, then paste your server's address followed by
/mcp(the dashboard shows it in that same entry).Click Connect. Your browser opens the Loopback dashboard, which asks you to sign in if you are not, and then whether to let Claude act as your coach. Choose Allow.
Ask in a new chat: "What did I run this week?"
That is the whole setup for Claude. The connector belongs to your Claude account, so it is there in the Claude phone apps and in Claude Desktop too, with nothing to repeat on them. (In Claude Desktop you can also start from its own Settings → Connectors; it is the same connector.)
The connection then shows up as Coach · Claude under Settings → Devices & tokens, where Revoke disconnects it. Claude never sees your password.
What this needs:
A server Claude can reach. Claude connects from Anthropic's servers, so the address has to work from the internet, over HTTPS, on the standard port (443). The built-in HTTPS setup gives you that for a server with a domain, and the Tailscale add-on for a home server, where it publishes the coach and nothing else. A server that is only on your home network or tailnet cannot be connected this way; use Claude Desktop with the extension for that one.
Nothing to configure. The server tells Claude where to sign in, and reads its own address from the request Claude makes, which is right behind Tailscale and Caddy. Behind a proxy that replaces the
Hostheader, setPUBLIC_URL(see Configuration).
Only the coach has to be public for this, not the dashboard. Everything Anthropic's servers call is /mcp, /oauth/token and two documents under /.well-known/. The pages you sign in and approve on are opened by your own browser only, so they can stay on a private address, and no page that takes a password is then on the internet. The Tailscale add-on is set up this way. To do the same behind a proxy of your own, publish only those paths and tell the server where the dashboard is: OAUTH_AUTHORIZATION_PORT if it is the same name on another port, OAUTH_AUTHORIZATION_ORIGIN if it is another name.
This has been used with claude.ai and, since 0.1.32, with ChatGPT: add the same address as a connector there and approve it the same way. Other assistants that sign in with OAuth can connect too, as long as they identify themselves with a published client document (the newer of the two ways an MCP client can introduce itself; Claude Code does, though signing in from it has not been tried here). An assistant Loopback does not know is shown by its web address on the approval page, with a warning. Assistants that expect to register themselves with the server first are not supported yet, and neither are ones that want the answer sent to an address scheme of their own instead of https.
Cursor (~/.cursor/mcp.json)
{
"mcpServers": {
"training": {
"url": "http://<machine-name>:8001/mcp",
"headers": { "Authorization": "Bearer <your-token>" }
}
}
}VS Code (.vscode/mcp.json — the inputs block prompts for the token on first use and keeps it out of the file, which matters if you commit .vscode/)
{
"inputs": [
{
"type": "promptString",
"id": "training-token",
"description": "Training API token",
"password": true
}
],
"servers": {
"training": {
"type": "http",
"url": "http://<machine-name>:8001/mcp",
"headers": { "Authorization": "Bearer ${input:training-token}" }
}
}
}Any other MCP client works the same way — a streamable-HTTP URL plus a bearer
header (Cline, the OpenAI Agents SDK's MCPServerStreamableHttp, LangChain's
langchain-mcp-adapters, and so on). The server speaks plain MCP, so the model
behind the client is your choice. Sanity-check a new setup with
npx @modelcontextprotocol/inspector.
Reachability: clients that run on your own machine (Claude Desktop with the extension, Claude Code, Cursor, VS Code) reach the server directly, at the same address as the dashboard. Cloud-hosted connectors — claude.ai's connectors, OpenAI's hosted MCP tool — call from the provider's servers instead, so they need an address that works from the internet, over HTTPS on port 443.
What an assistant can do with its token
A token an assistant gets by signing in, and one the Connect dialog makes, is a coach token. The server accepts it for the requests the coach's tools make and answers 403 to everything else. So whoever holds one, whether that is Anthropic's or OpenAI's servers or a config file on a laptop:
can read your workouts, plans and notes and the health data you share with the coach, and create or change plans, watch workouts, notes, shoes, fuelling and illness or injury entries. That includes deleting a recorded workout.
cannot change your password, create or revoke tokens, change what you share with the coach, approve another assistant, or upload data as if it were your phone.
cannot read what you chose not to share, also not by calling the API directly. For a coach token the sharing setting in the app is enforced by the server on every request.
It does not expire. If one leaks, or you stop using an assistant, revoke it under Settings → Devices & tokens, where coach tokens are marked Coach only.
Every other token is a full token, which can do everything you can: the ones the dashboard and the phone get when you log in, and the ones you make with New token for a script of your own. Tokens from before 0.1.33 are full tokens too, including those an assistant was given; nothing was taken away from them in the upgrade. To swap one for a coach token, revoke it and connect that assistant again.
Running the MCP on its own
Only needed for a client that launches the server itself over stdio, or to run the MCP on a different machine than the API. It needs uv.
cd mcp
cp config/.env.example config/.env # TRAINING_API_URL + TRAINING_API_KEY
uv run startTRAINING_API_KEY is a token for the account the MCP acts as when the caller
sends no Authorization header (always the case over stdio). The default
transport is stdio; MCP_TRANSPORT=http (with optional MCP_HOST /
MCP_PORT, default 8590) serves streamable HTTP at /mcp instead, forwarding
each caller's own Authorization header to the API. Set
REQUIRE_AUTH_HEADER=true there to disable the TRAINING_API_KEY fallback.
Development
Want to contribute? See CONTRIBUTING.md.
make up # Start containers
make down # Stop containers
make build # Rebuild images
make logs # Tail container logs
make migrate # Run database migrations manually
# Create a new migration after changing models
make create_migration m="add new column"
# Backend tests (inside the container)
docker compose exec app python -m pytest
# The Claude Desktop extension's relay script (Node 18+, no install)
node --test backend/tests/desktop_extension/relay.test.jsCutting a release (maintainers)
Bump
__version__inbackend/app/version.py— the single source of truth (pyproject.toml,/api/health, and the dashboard all derive from it) — and add aCHANGELOG.mdentry.Commit, then tag and push:
git tag -a v0.1.0 -m "v0.1.0" git push origin main v0.1.0The Docker workflow builds and publishes
ghcr.io/aderaaij/loopback-training-server:{0.1.0, 0.1}.The same workflow then lists the release in the MCP Registry from
server.json. It fills in the version and the image tag from the git tag, so that file needs no bump. If this job fails the image is still published; the registry simply keeps showing the previous release.
Project Structure
├── docker-compose.yml # PostgreSQL + API orchestration
├── .env.example # Compose configuration template (copy to .env)
├── .github/ # CI + GHCR image workflows, README screenshots
├── Makefile # Dev shortcuts
├── backend/
│ ├── Dockerfile # Multi-stage build: Node (frontend) + Python 3.13 (uv); context = repo root
│ ├── pyproject.toml # Dependencies (uv/hatch)
│ ├── config/.env.example # Env template for running outside Docker
│ ├── app/
│ │ ├── main.py # FastAPI app (+ serves the SPA build)
│ │ ├── config.py # Settings (pydantic-settings)
│ │ ├── auth.py # Bearer token auth
│ │ ├── auth_events.py # Audit trail recording helper
│ │ ├── cli.py # User/token admin CLI
│ │ ├── coach_extension.py # Builds the Claude Desktop extension (.mcpb) on request
│ │ ├── desktop_extension/ # Its contents: manifest + the stdio-to-/mcp relay (server/relay.js)
│ │ ├── database.py # SQLAlchemy setup
│ │ ├── models/ # ORM models
│ │ ├── routes/ # API endpoints
│ │ └── schemas/ # Pydantic request/response models
│ ├── migrations/ # Alembic migrations
│ └── tests/ # API tests (run in-container)
├── frontend/
│ └── src/
│ ├── components/ # Layout, shared UI, chart primitives, route map
│ ├── lib/ # API client, wire types, auth context, query hooks
│ ├── screens/ # One file per screen (athlete + admin)
│ └── styles/ # Design tokens + per-screen CSS
└── mcp/
├── pyproject.toml # MCP dependencies (a path dependency of the backend)
├── config/.env.example # Environment template for running it standalone
└── training_mcp/ # Mounted by the backend at /mcp (backend/app/mcp_mount.py)
├── main.py # FastMCP server (+ standalone stdio / HTTP entry point)
├── tools/ # MCP tool definitions
└── services/ # API clientLicense
MIT
Available Tools
59 toolsadd_fuel_productA
Save something the athlete drinks or eats on runs, so it can be picked when logging or planning.
Only on the athlete's say-so, with figures they gave you or read off the label. Do not fill in carbohydrates or caffeine from memory of a brand; leave a figure out when the athlete does not know it. Check get_fuel_products first so nothing is saved twice.
Args: name: What the athlete calls it ("Maurten Gel 100 Caf", "Water"). kind: "drink", "gel" or "other" (chews, a bar, a salt tablet). carbs_g: Carbohydrates in g, per piece, or per serving of a drink. caffeine_mg: Caffeine in mg, per piece, or per serving of a drink. volume_ml: For a drink only: the serving the two figures are for, in ml (500 for a 500 ml bottle).
Returns: The saved product, in the shape get_fuel_products lists.
Inputs: kind (required), name (required), carbs_g, volume_ml, +1 more.
add_shoeA
Add a pair of running shoes for the athlete.
Only on the athlete's say-so: they tell you about a new pair, you add it. Check get_shoes first so the same pair is not added twice.
Args: name: What to call the pair, in the athlete's words (e.g. "Pegasus 41"). start_distance_meters: Distance already on the pair, in METERS (250 km is 250000). Zero for a new pair. Runs from before the pair is added are never assigned to it, so this figure is where that earlier distance belongs. target_distance_meters: Where the athlete plans to replace the pair, in METERS. Leave out unless they named one — do not pick a figure for them. is_default: Put new runs on this pair automatically. Replaces the current default.
Returns: The new pair, in the shape get_shoes lists.
Inputs: name (required), is_default, start_distance_meters, target_distance_meters.
add_strength_sessionA
Put one strength session on one date, leaving the rest of the plan's schedule as it is.
This is how to schedule strength for an athlete without fixed gym days:
look at the week's runs with get_training_calendar, then add each
session on the day it fits. It also adds an extra session next to a weekly
pattern. A plan needs no weekly pattern at all; the first session added
starts its schedule.
Like every strength session it is a plan marker, not a watch workout, and it counts as done when a Hevy workout syncs in on that date. Adding the same title on the same date again replaces it.
Args: plan_id: UUID of the strength plan (create_plan with activity_type "strength"). date: The day of the session (YYYY-MM-DD). title: What the session is, e.g. "Lower body + core". routine_id: Optional Hevy routine id (from the hevy-mcp).
Returns:
The resolved schedule: dated sessions (recurring is false for
individual ones, each with a conflict flag) and warnings for run
collisions.
Inputs: date (required), title (required), plan_id (required), routine_id.
append_plan_noteA
Save a continuity note about the user's training.
Call this WITHOUT BEING ASKED whenever ANY of the following happens during a conversation:
• User states a preference. Trigger phrases: "I prefer", "I like", "I hate", "from now on", "going forward", "always", "never". • User makes a plan decision. Trigger phrases: "let's drop", "let's switch", "let's add", "I've decided", "I'm going to", "this week I'll", "starting Monday". • User reveals life context that affects training. Examples: travel, illness, injury, sleep debt, work stress, life events, weather constraints, schedule shifts. • User commits to a change in approach. • A non-obvious insight emerges that future-you would want to know but couldn't infer from workout data alone.
DO save short, partial notes — they are cheap. DO NOT save: chitchat, things derivable from workout/health-metrics data, code-level details, or one-off acknowledgments.
Tip: if a note is temporal (e.g. "traveling Mar 1–5"), set
expires_at so it auto-fades from future context.
Args:
kind: One of:
- "decision" — the user committed to a plan-level change
- "preference" — a stable preference about how training works
- "constraint" — a hard limit (schedule, equipment, injury)
- "life_context" — temporary life situation affecting training
- "observation" — non-obvious insight worth remembering
- "blocker" — something preventing planned training
- "feedback" — the athlete's own review of a plan or block
(the dashboard's plan wrap-up flow writes these too)
summary: One-line summary, ≤280 chars. Lead with the fact, not
"the user said". Example: "Prefers morning runs, never evenings."
body: Optional longer body — the why, edge cases, exceptions.
Future-you reads this when the summary alone is ambiguous.
importance: 1=low, 2=med (default), 3=high. Use 3 sparingly for
hard constraints and committed decisions.
expires_at: Optional ISO 8601 datetime. After this, the note is
excluded from get_plan_context results. Use for temporal
life_context notes (travel, short-term illness, etc.).
plan_id: Optional plan UUID. Omit for global notes that apply
across all plans (e.g. stable preferences).
conversation_id: Optional opaque string to group all notes from
one conversation. Use a stable id throughout the conversation
so future-you can replay what was discussed together.
Returns: The created PlanNote object.
Inputs: kind (required), summary (required), body, plan_id, +3 more.
assign_shoeA
Put a pair of shoes on a workout, or take the pair off.
Use it when the athlete says which pair they wore. It also marks the
workout's pair as checked (shoe_confirmed: true), so call it even when
the athlete confirms the pair already on the run. Never guess a pair from
the kind of session: ask.
Args: workout_id: UUID of the recorded workout (from get_recent_runs). shoe_id: The pair's id from get_shoes. A retired pair is fine, for correcting an older run. Leave out to take the pair off the workout, for a run done in shoes the athlete does not track.
Returns: The workout as get_recent_runs lists it, with the new shoe_id.
Inputs: workout_id (required), shoe_id.
batch_actionsA
Create multiple edit/delete actions in a single call.
Use this instead of calling delete_scheduled_workout or edit_scheduled_workout repeatedly when you need to modify or remove multiple workouts at once. Edit compositions support the same goals and per-step alerts as create_workout (incl. heart-rate zones) — see the input schema.
Args: actions: Action objects. For "edit", composition is the full replacement workout (composition.id may be omitted — it is filled from workoutId). For "delete", omit composition.
Example: actions: [ {"workoutId": "aaa-...", "action": "delete"}, {"workoutId": "bbb-...", "action": "edit", "composition": { "displayName": "Updated Run", "activityType": "running", "location": "outdoor", "scheduledDate": "2026-03-25T07:00:00Z", "blocks": [{"iterations": 1, "steps": [{"purpose": "work", "goal": {"type": "time", "value": 1800, "unit": "seconds"}, "alert": {"type": "heartRateZone", "zone": 3}}]}] }} ]
Returns: List of created action objects.
Inputs: actions (required).
batch_create_workoutsA
Queue multiple workouts for Apple Watch in a single call.
Use this instead of calling create_workout repeatedly when you need to schedule an entire training plan (e.g. 4 weeks of workouts). Each workout supports the same full composition as create_workout: interval blocks, warmup/cooldown, goals (distance/time/energy/open), and per-step alerts — pace/speed range, heart-rate range, heart-rate zone (1-5), cadence, power.
Args: workouts: Workouts to queue — see the input schema for the full structure. Omit workoutData.id to have a UUID generated per workout. Set planId to link a workout to a training plan.
Example: workouts: [ { "activityType": "running", "title": "Easy Z2 5K", "workoutData": { "displayName": "Easy Z2 5K", "activityType": "running", "location": "outdoor", "scheduledDate": "2026-03-20T07:00:00Z", "blocks": [{"iterations": 1, "steps": [{"purpose": "work", "goal": {"type": "distance", "value": 5000, "unit": "meters"}, "alert": {"type": "heartRateZone", "zone": 2}}]}] } } ]
Returns:
Object with items (the created queue items) and validation — a
list of schedule-soundness warnings (ramp rate vs the athlete's
actual 4-week baseline, missing down weeks, long-run share,
back-to-back hard days, taper shape, guardrail breaches, …) covering
the athlete's whole upcoming schedule. ALWAYS review it after
queueing a plan: resolve critical warnings (adjust and re-queue,
or get the athlete's explicit sign-off); mention warn items.
Warnings never block creation.
Inputs: workouts (required).
calculate_paceA
Work out a pace, a finish time or a distance from the other two, with the split times along the way.
USE THIS FOR EVERY SUCH NUMBER YOU QUOTE: a target pace for a goal time, the finish time a pace gives, the clock at each kilometer of a race, the speed for a pace alert. Do not do this arithmetic yourself; it is where slips happen (a half marathon is 21.0975 km, not 21).
Give exactly two of the three: a distance (race or distance_m), a
time, a pace. The third is worked out.
This converts between numbers. It does not say whether a pace is realistic for the athlete; judge that from their training (get_recent_runs, get_training_summary) and the coaching playbook.
Returns:
- solved_for: "pace", "time" or "distance", whichever was left out.
- distance_m, and distance in the athlete's unit ("21.1 km").
- time ("1:45:00") and time_s.
- pace_per_km and pace_per_mile ("4:59", "8:01"), each rounded to the
second, with pace_per_km_s and pace_per_mile_s to one decimal.
Quote the one matching the athlete's units.
- speed_mps: the same pace as meters per second, the form a workout's
speed alert takes (create_workout).
- splits: one row per mark in running order, mark ("5 km", "Half",
"Finish") and the time on the clock there at an even pace. A whole
km or mile that is also a named checkpoint carries checkpoint
("5K"); one that is the finish carries finish: true. Marks between
two whole units carry distance_m. Split times are computed from
the exact pace, so they add up to the finish time even where the
rounded pace would not.
On bad input: {"error": "..."} saying what to change.
Inputs: pace, race, time, units, +2 more.
clear_plan_scheduleA
Remove a plan's whole schedule: the weekly pattern and every individual
session. For a single session use remove_strength_session.
Args: plan_id: UUID of the plan.
Returns: The plan's now-empty schedule response.
Inputs: plan_id (required).
create_planA
Create a new training plan.
Call this before batch_create_workouts to get a plan_id that links all queued workouts together.
Args: name: Plan name (e.g. "Slow Burn 8-Week Return"). activity_type: Primary activity (e.g. "running", "cycling"). start_date: Plan start date (YYYY-MM-DD). end_date: Plan end date (YYYY-MM-DD), or null if open-ended. description: High-level what and why. metadata: Flexible JSON object for goals, guardrails, phases, athlete context, etc. No required keys. Example: { "goals": [{"type": "weekly_volume", "target": 32, "unit": "km", "by_week": 8}], "guardrails": ["Miss a run: don't make it up"], "phases": [{"name": "Base", "weeks": [1, 2], "volume_target_km": 18}], "athlete_context": {"fitness_level": "Detrained"} } status: Defaults to "active" — the block being run right now. Pass "upcoming" for a plan built ahead of its start date: it stays out of "which plan am I on" answers, while its sessions still appear in the calendar and schedule checks so the new block can be validated before it starts. Only one plan per activity should be active at a time; if one is already running, the next block is "upcoming" until the athlete starts it.
Returns: The created plan with its id.
Inputs: name (required), start_date (required), activity_type (required), status, +3 more.
create_workoutA
Create a structured workout and queue it for the user's Apple Watch.
Full WorkoutKit support: repeatable interval blocks, warmup/cooldown steps, goals (distance / time / energy / open), and an optional per-step ALERT that coaches effort on the watch — pace/speed range, heart-rate range (BPM), heart-rate ZONE (1-5), cadence, or running power. E.g. a Zone 2 base run is a single time- or distance-goal step with alert {"type": "heartRateZone", "zone": 2}. WorkoutKit allows one alert per step.
The exact structure of blocks/steps/goals/alerts is defined in this tool's input schema. The workout appears on the watch after the iPhone app syncs.
Args:
activity_type: Sport for the WorkoutKit session.
display_name: Name shown on Apple Watch (e.g. "6x400m Intervals", "Tempo Run").
location: Where the workout happens (affects GPS).
scheduled_date: When the workout should appear, ISO 8601 (e.g. "2026-03-18T07:00:00Z").
blocks: Interval blocks, each repeated iterations times.
warmup: Optional warmup step (goal + optional alert).
cooldown: Optional cooldown step (goal + optional alert).
description: Optional text description of the workout.
plan_id: Optional UUID of the training plan this workout belongs to.
Returns:
The created queue item object, plus a validation list of
schedule-soundness warnings (ramp rate vs the athlete's actual
4-week baseline, back-to-back hard days, guardrail breaches, …)
covering the athlete's whole upcoming schedule. ALWAYS review it:
resolve critical warnings (adjust and re-queue, or get the
athlete's explicit sign-off); mention warn items to the athlete.
Warnings never block creation.
Example — 6x400m intervals with 800m warmup and cooldown: activity_type: "running" display_name: "6x400m Intervals" location: "outdoor" scheduled_date: "2026-03-18T07:00:00Z" warmup: {"goal": {"type": "distance", "value": 800, "unit": "meters"}} blocks: [ { "iterations": 6, "steps": [ { "purpose": "work", "goal": {"type": "distance", "value": 400, "unit": "meters"}, "alert": {"type": "speed", "min": 4.5, "max": 5.0, "unit": "metersPerSecond"} }, { "purpose": "recovery", "goal": {"type": "distance", "value": 400, "unit": "meters"} } ] } ] cooldown: {"goal": {"type": "distance", "value": 800, "unit": "meters"}}
Example — 20-minute tempo run: activity_type: "running" display_name: "20min Tempo" location: "outdoor" scheduled_date: "2026-03-19T07:00:00Z" warmup: {"goal": {"type": "distance", "value": 1600, "unit": "meters"}} blocks: [ { "iterations": 1, "steps": [ { "purpose": "work", "goal": {"type": "time", "value": 20, "unit": "minutes"}, "alert": {"type": "heartRateZone", "zone": 4} } ] } ] cooldown: {"goal": {"type": "distance", "value": 1600, "unit": "meters"}}
Inputs: blocks (required), location (required), display_name (required), activity_type (required), +5 more.
delete_plan_noteA
Delete a plan note. Use only when the note was incorrect or
duplicated. Prefer update_plan_note (or setting expires_at for
temporal notes) over deletion — deleted notes lose history.
Args: note_id: UUID of the note to delete.
Returns: Confirmation with the deleted note id.
Inputs: note_id (required).
delete_scheduled_workoutA
Delete a workout that has already been synced to the user's Apple Watch.
Creates a pending delete action. The next time the iPhone app syncs, it will remove this workout from WorkoutKit on the Apple Watch.
Args: workout_id: UUID of the workout to delete. This is the id from the original queue item that was synced to the watch.
Returns: The created action object.
Inputs: workout_id (required).
delete_workoutA
Delete a recorded workout by ID.
This permanently removes a HealthKit workout record from the database. The workout can be re-synced from the iPhone if needed.
Args: workout_id: UUID of the workout to delete.
Returns: Confirmation with the deleted workout ID.
Inputs: workout_id (required).
edit_scheduled_workoutA
Edit a workout that has already been synced to the user's Apple Watch.
Creates a pending edit action with the full updated composition. The next time the iPhone app syncs, it will replace the old workout with this updated version in WorkoutKit on the Apple Watch. Steps support the same goals and alerts as create_workout — pace/speed range, heart-rate range, heart-rate zone (1-5), cadence, power — see the input schema.
Args: workout_id: UUID of the workout to edit. Must match the id from the original queue item that was synced to the watch. display_name: Updated name shown on Apple Watch. activity_type: Sport for the WorkoutKit session. location: Either "outdoor" or "indoor". scheduled_date: Updated scheduled date, ISO 8601 (e.g. "2026-03-25T07:00:00Z"). blocks: Updated interval blocks (replaces the whole structure). warmup: Optional updated warmup step. cooldown: Optional updated cooldown step.
Returns: The created action object.
Inputs: blocks (required), location (required), workout_id (required), display_name (required), +4 more.
get_coaching_playbookA
Load the coaching methodology to follow when acting as a running coach.
ALWAYS call this before creating a training plan, materially revising one, or advising on training structure/load. It returns the evidence-based playbook this system follows — pace zones from actual data, intensity distribution, progression and recovery rules, readiness gating, and how to map methodology onto this API's plans/queue/calendar — plus a module tailored to the athlete's goal.
Not needed for simple data questions ("what did I run last week?").
Args: goal: The athlete's training goal. Use "first_5k" for someone who has never run or is starting from zero (couch-to-5K style walk/run progression); "general_fitness" when there is no target race. Omit if the goal isn't known yet — the core playbook still applies, and its intake section helps establish the goal. experience: The athlete's experience level, judged from their actual training history (get_recent_runs / get_training_summary), not self-report alone. Omit to get guidance for all levels.
Returns: Object with: - playbook: the methodology as markdown (core principles + goal module when a goal was given) - goal / experience: what the content was tailored to (null = generic) - available_goals: valid goal values - warning: present if the requested goal was unknown
Inputs: goal, experience.
get_device_workoutsA
Get the inventory of workouts currently scheduled on the user's Apple Watch.
This is synced from the iOS app each time the user taps "Check for New Workouts". Use this to discover workout UUIDs when the user asks to edit or delete a workout.
Returns: List of on-device workouts, each with: id, display_name, year, month, day, hour, minute, complete (whether the workout has been done), synced_at.
Inputs: no named parameters.
get_fuel_historyA
The athlete's most recent workouts that have a fuelling log, newest first, each with what was taken and what had been planned for it.
Read this before planning the fuelling for a long run or a race: it shows what the athlete has actually been taking, how much per hour, and whether they kept to earlier plans. To see how a run went against its fuelling, look the workout up with get_workout_detail or get_workout_splits (a fade late in the run next to few carbohydrates per hour is the pattern to look for). A workout that is not listed has no log, which usually means the athlete did not write it down, not that they took nothing.
Args: limit: How many workouts (default 10, at most 50).
Returns: List (camelCase) of: workoutId, activityType, startDate, duration (seconds), totalDistance (METERS), entries and summary (taken), planned and plannedSummary (the plan on the session the workout counted for; empty and null when there was none), plannedSessionId. Entries and summaries are as get_workout_fuel describes them.
Inputs: limit.
get_fuel_planA
The fuelling plan on a planned session: what to drink and eat, and where in the run.
Args: session_id: UUID of the planned session, the queue item's id (from get_plan_workouts, get_pending_workouts or list_queued_workouts).
Returns: Object (camelCase) with entries and summary, as get_workout_fuel describes them. Empty entries means no plan has been written for this session.
Inputs: session_id (required).
get_fuel_productsA
List what the athlete has saved to drink and eat on runs: their gels, drink mixes and so on.
Call this before writing a fuelling plan, so the plan names what the athlete actually carries and its figures are the label's, not yours.
Returns: List of products (camelCase), drinks first: id (pass as product_id in an entry), name, kind, carbsG and caffeineMg (per piece; for a drink, per serving of volumeMl), volumeMl (a drink's serving, null otherwise). Null carbsG or caffeineMg means the athlete did not state it, not zero.
Inputs: no named parameters.
get_health_metricsA
Get daily health metrics synced from HealthKit.
One row per day. Which metrics a row carries varies by athlete — sleep, resting HR, HRV, respiratory rate, SpO2, sleeping wrist temperature, weight, body composition, VO2Max, steps and energy are all possible. Read the fields that are present rather than assuming a fixed set; a field that isn't there is not a zero, and not something to ask the athlete to start recording.
wrist_temperature is the Apple Watch's sleeping wrist temperature in °C,
filed on the day the athlete woke up. The absolute figure means little and
differs between people; what matters is the change against the athlete's
own recent nights. A rise of about half a degree or more that lasts
several nights often goes with illness (also with alcohol, a warm room,
and the menstrual cycle), so read it alongside resting HR and HRV.
Where energy is present: active_energy_burned is movement + exercise (it
already includes workout calories); basal_energy_burned is resting burn,
and may be null on older app builds. Their sum is total daily expenditure.
For anything comparing expenditure against intake, prefer
get_nutrition_summary — it aligns both sides on the same periods and
excludes days still in progress, which these raw rows do not.
Use these to correlate recovery/readiness with training patterns:
Low HRV + poor sleep → suggest an easier workout or a rest day
Declining resting HR trend → improving cardiovascular fitness
Weight/body composition trends alongside training volume
Steps and active energy alongside training load: how much of the day's movement was the session, and how much was the rest of life
Args: start_date: Start date (YYYY-MM-DD) end_date: End date (YYYY-MM-DD), defaults to today
Inputs: start_date (required), end_date.
get_missed_workoutsA
Get currently past-due, incomplete workouts not yet checked in for their current day.
This is a convenience tool that cross-references the on-device workout inventory with existing feedback to find workouts that are overdue and haven't been addressed. A run that was moved and then also went past its new day counts as missed again.
Returns: List of missed workouts, each with: workoutId, displayName, scheduledDate, daysMissed.
Inputs: no named parameters.
get_nutritionA
Get daily nutrition totals synced from HealthKit (food logging apps).
Returns one row per day that has logged food: energy (kcal), carbs, protein,
fat, saturated fat, fiber, sugar, sodium, potassium, cholesterol, water,
caffeine, plus any extra micronutrients under micros, the number of
logged entries and which apps wrote them.
Days with no logging have NO row — absence means "not tracked", not "ate
nothing". A row with partial: true was synced while the day was still in
progress, so its totals are incomplete; exclude those from any average.
ONLY energy_kcal, carbs_g, protein_g and fat_g are daily totals.
sodium_mg, fiber_g, sugar_g, saturated_fat_g, cholesterol_mg,
potassium_mg and every key in micros are LOWER BOUNDS — food databases
record them on only a fraction of entries, so the day sums whichever foods
happened to carry the field. Nothing in the payload marks them, and a
plausible-looking value is not evidence of completeness. Never infer a
deficiency or an excess from one (observed: ~200 mg potassium on a
2,600 kcal day). Null water_ml/caffeine_mg means unreported, not zero.
For trends over more than a couple of weeks, prefer get_nutrition_summary — it aggregates per week or month and aligns intake with weight and training load, at a fraction of the tokens.
Args: start_date: Start date (YYYY-MM-DD) end_date: End date (YYYY-MM-DD), defaults to today limit: Max days returned, newest first (default 60)
Inputs: start_date (required), limit, end_date.
get_nutrition_summaryA
Diet, body weight and training load aligned on the same periods.
This is the tool for "is my nutrition supporting my training?". Each period carries:
nutrition: average intake per LOGGED day (partial days excluded)days_logged/days_in_period: how much of the period that average actually covers — 2 of 7 days is an anecdote, not a weekly averageprotein_g_per_kg: protein against the period's average body weightbody: weight start/end/avg and the change across the periodtraining: workouts, distance, duration and energy burnedexpenditure: energy OUT —active_kcal_avg(movement + exercise),basal_kcal_avg(resting),tdee_kcal_avg(their sum), andbalance_kcal_avg(intake minus TDEE), each with its own day count
Not every block is in every response: body and expenditure depend on
what this athlete's data covers. Work with the blocks you get rather than
asking after the ones you don't.
Active energy already includes workout burn: TDEE is active + basal, and
adding training.energy_kcal on top double-counts every session. Basal is
null until the athlete's app build syncs it, in which case TDEE and balance
are null too and active alone is what you have. Today is excluded from
expenditure — health metrics have no partial-day flag, so a day in progress
holds only the hours elapsed.
Balance is a direction with a magnitude, not a measurement: intake is
self-reported and skews low, which biases the computed deficit larger, and
basal is HealthKit's estimate — the two errors compound rather than cancel.
body carries the unmodelled cross-check: weight_change (a least-squares
fit across the readings' span, not last-minus-first), weight_sd (the
scatter it sits in) and weigh_ins (how many readings back both).
Averages cover energy, macros and the rest of the nutrient columns — but
only energy_kcal, carbs_g, protein_g and fat_g are true totals.
The averages of sodium_mg, fiber_g, sugar_g, saturated_fat_g,
cholesterol_mg and potassium_mg are averages OF LOWER BOUNDS, because
food databases record those on only some entries. Never read one as a
deficiency or an excess; their trends track logging detail as much as diet.
Read days_logged before drawing any conclusion, and remember intake is
self-reported: food logging typically under-reports, so treat the trend
and the macro split as the signal rather than absolute calorie totals.
Weight change over a single week is mostly glycogen and hydration; look
across 3-4 weeks before calling it a trend.
Coaching stance:
Under-fuelling matters more than over-fuelling for an endurance athlete. A persistent deficit alongside hard training is worth flagging even when the athlete asked about weight loss — cross-check how sessions have been going, and recovery metrics if you have them, before saying it's working.
Endurance-relevant anchors: carbohydrate availability around hard/long sessions, protein ~1.6-2.0 g/kg for an athlete in training, and fiber timing before key sessions.
If the athlete wants real micronutrient or sodium status, the answer is a blood test or a dietitian, not this data. Say that plainly.
You are not a dietitian. Flag patterns worth a professional's attention (persistent large deficits, very low intake, an athlete asking about restriction) rather than prescribing an intake plan.
Args: start_date: Start date (YYYY-MM-DD) end_date: End date (YYYY-MM-DD), defaults to today period: "week" (default) or "month" timezone: IANA zone (e.g. "Europe/Amsterdam") used to attribute workouts to a local day; defaults to UTC
Inputs: start_date (required), period, end_date, timezone.
get_pending_actionsA
Get all pending workout actions (edits and deletes) waiting to be synced to Apple Watch.
Returns: List of pending actions, each with: id, workoutId, action ("edit" or "delete"), composition (full workout composition for edits, null for deletes), created_at.
Inputs: no named parameters.
get_pending_workoutsA
Get all pending workout queue items waiting to be processed.
Returns: List of pending queue items, each with: id, activity_type, title, description, workout_data, status, created_at, fetched_at, completed_at.
Inputs: no named parameters.
get_planA
Get a training plan by ID, including its metadata.
Args: plan_id: UUID of the plan.
Returns: Plan object with name, activity_type, status, dates, description, metadata, plus two computed fields: - progress: session counts (total/completed/skipped/remaining) — queued Apple Watch runs, plus scheduled strength sessions for plans with a recurring schedule. A strength session counts as completed when a synced Hevy workout landed on its date, skipped when the date passed with no match, remaining otherwise. (The runs_* field names predate strength support; they count sessions of either kind.) - finishable: true when an active plan looks done (window passed, or every session retired with ≥1 completed and no end date still ahead — a plan queued a week at a time is not done each time its queue runs empty). Nothing auto-completes; if true, offer the athlete a wrap-up (complete_plan on the dashboard or update_plan status="completed").
Inputs: plan_id (required).
get_plan_contextA
Load continuity context for the active training plan.
ALWAYS call this FIRST in any training-related conversation, before answering the user. It returns the active plan plus recent notes (decisions, preferences, constraints, life context, blockers, observations) ranked by importance and recency. This is how you maintain continuity across conversations.
The response includes a continuity_hint string — read it. It tells you
whether continuity is fresh or stale and may instruct you to write notes
aggressively this conversation.
Args: plan_id: UUID of a specific plan. Omit to use the active plan. since_days: Only return notes created within this window (default 60). limit: Maximum number of notes to return (default 40, max 200).
Returns:
Object with:
- plan: the resolved plan (or null if none active)
- notes: list of PlanNote objects (id, kind, summary, body,
importance, conversation_id, expires_at, created_at), ordered
by importance desc then created_at desc
- last_note_age_days: age of the most recent note (or null)
- continuity_hint: a directive for how aggressively to save notes
this conversation
- units: "metric", "imperial" or null (the athlete has not chosen)
- units_hint: how to talk and author workouts for this athlete's
units. Follow it: an athlete on miles should never be handed
kilometers.
- setbacks: the athlete's open illnesses and injuries, plus those
that ended in the last three weeks (kind, severity, startDate,
endDate, days, checkins, and for open ones recovery: whether
the recent data says it looks over). Empty when there are none or
when the athlete does not share them.
- setback_hint: what to do about them. Follow it when it is not
empty: an open setback comes before the plan.
Inputs: limit, plan_id, since_days.
get_plan_scheduleA
Get a plan's schedule (weekly pattern and individual sessions) expanded into concrete dated sessions.
Args: plan_id: UUID of the plan.
Returns:
{plan_id, schedule, sessions[], warnings[]} — sessions carry a
conflict flag where they collide with a queued run.
Inputs: plan_id (required).
get_plan_workoutsB
Get all queued workouts belonging to a plan.
Args: plan_id: UUID of the plan.
Returns: List of queued workouts for this plan.
Inputs: plan_id (required).
get_recent_runsA
List recent workouts, optionally filtered by activity type, date range and the pair of shoes they were done in.
Args: activity_type: Filter by activity type (e.g. "running", "cycling", "swimming"). If omitted, returns all activity types. limit: Maximum number of workouts to return (default 10, max 200). start_after: Only return workouts starting after this datetime (ISO 8601). Example: "2026-03-01T00:00:00" start_before: Only return workouts starting before this datetime (ISO 8601). Example: "2026-03-15T23:59:59" shoe_id: Only return workouts done in this pair of shoes (an id from get_shoes).
Returns: List of workout objects with fields: id, activity_type, start_date, end_date, duration, total_distance, total_energy_burned, source, plan_workout_id, shoe_id, shoe_confirmed, effort_score, estimated_effort_score, end_heart_rate, heart_rate_after_1min, heart_rate_after_2min, vo2_max, created_at.
- shoe_id: the pair of shoes the athlete has on this workout; look it
up in get_shoes. Null means no pair was recorded, not barefoot.
- shoe_confirmed: false means nobody has checked the pair — the run
still has whatever it got automatically (the default pair, or none).
See get_shoes for when that is worth asking the athlete about.
- source: the HealthKit bundle id of the recording app —
"com.apple.health.<UUID>" means recorded directly on the Apple Watch
(the UUID is the device, not an app); others name the app, e.g.
com.hevyapp.hevy (Hevy strength), com.strava.stravaride (Strava),
com.garmin.connect.mobile (Garmin), com.bowery-digital.bend (Bend
stretching).
- effort_score: User-rated post-workout RPE (1–10) from the Apple Watch
effort prompt. The user's perception of the workout — trust it as the
primary signal. May be null when the workout predates iOS 18 / watchOS 11
or the user dismissed the prompt.
- estimated_effort_score: Apple's algorithmic RPE estimate (1–10) computed
from heart rate / activity. Useful for cross-referencing against
effort_score; a large gap (e.g. user 8 vs. estimate 5) can indicate
non-cardiovascular load (heat, sleep debt, dehydration, illness, life
stress) that HR-based estimates miss — worth surfacing during weekly
review when it appears repeatedly. May be null when no estimate exists.
Treat null as "no signal," not "low effort."
- end_heart_rate, heart_rate_after_1min, heart_rate_after_2min: heart
rate (bpm) as the workout ended and one and two minutes later. The
recovery drop is end_heart_rate minus the later reading. How the
athlete stopped decides most of it: a hard effort ended abruptly
gives a large drop, an easy run or a jogged cooldown a small one, so
compare only like with like (intervals with intervals, races with
races) and read a trend over several such sessions, never one run.
A falling drop across comparable hard sessions can point to fatigue;
resting heart rate and HRV are the stronger signals for that. Null
when the watch recorded nothing usable after the end, or the workout
was paused well before it was ended.
- vo2_max: the VO2 max estimate (mL/kg/min) Apple Health recorded for
this workout. Only some outdoor runs, walks and hikes produce one,
and a single reading moves with heat, hills and pacing; the trend
is what counts. Null means none was recorded for this workout, or
the athlete does not share body data with the coach. Do not ask
them to start tracking it.Inputs: limit, shoe_id, start_after, start_before, +1 more.
get_setbacksA
List the athlete's illnesses and injuries, with how they felt day by day.
get_plan_context already hands you the open ones and the ones that ended in the last three weeks, so you rarely need this at the start of a conversation. Use it for the history: how often the athlete is set back, how long each one lasted, and how past ones compare with the current one.
READING ONE AGAINST THE DATA. A setback gives you the dates; the effect is
in the other tools. To see what an illness did, compare the days from
startDate on with the two to four weeks before it: resting heart rate,
HRV, respiratory rate, sleeping wrist temperature and sleep from
get_health_metrics, and for the runs
after it the heart rate at a given easy pace and the heart rate recovery
from get_recent_runs and get_workout_detail. Raised resting heart rate and
lowered HRV that have come back to the earlier range for a few days in a
row, together with the athlete saying they feel fine, is what recovered
looks like. For an injury the numbers say little: go by the daily status
and by runs completed without pain. Say what you see and how sure you are;
this is not a diagnosis.
Args: active_only: Only setbacks that are still going on. since: Only setbacks still going on or ended on or after this day (YYYY-MM-DD).
Returns: List of setbacks, open ones first, then the most recently started. Keys are camelCase:
- id: pass to update_setback and log_setback_status.
- kind: "illness" or "injury".
- severity: "mild", "moderate" or "severe", the athlete's own call.
- startDate / endDate: first and last day (YYYY-MM-DD, the athlete's
local days). endDate is null while it is still going on.
- active: true while there is no end date.
- days: length in days, both ends counted; for an open one, through
today.
- bodyPart: injuries only, free text; may be null.
- note: the athlete's description; may be null.
- checkins: one entry per day the athlete (or you) recorded a status,
oldest first: date, status ("worse", "same", "better", "fine"),
note. Days without an entry were simply not recorded.
- recovery: open setbacks only, else null. The server's own read of
whether it looks over. `status` is "looks_recovered", "not_yet" or
"insufficient_data"; `summary` says why in a sentence; `metrics`
lists resting heart rate, HRV, breathing rate and sleeping wrist
temperature (those the athlete has data for) with the
athlete's `usual` (median of the four weeks before), the
`tolerance` around it, the `latest` reading and its `state`
("normal", "off", "no_recent_data"). `basis` is "metrics" or
"status" (the athlete said "fine" two days running, or a fresh
"worse"/"same" is holding it back). It is a prompt to ask the
athlete, never grounds to close a setback yourself. Injuries get
no metrics: the numbers say little about them.Inputs: since, active_only.
get_shoesA
List the athlete's pairs of running shoes and the distance on each.
CHECKING THE PAIR ON RECENT RUNS. A new run is put on the default pair
automatically, and the athlete often forgets to correct it when they wore
something else. Workouts carry shoe_confirmed: false means the pair was
never checked. When the athlete has MORE THAN ONE pair in rotation and a
run from the last two weeks has shoe_confirmed: false, ask which pair
they wore — once per conversation, all such runs in one question, naming
each run's day, distance and current pair. Then call assign_shoe for every
run they answer, including the ones where the current pair was right:
that is what marks it checked and stops the question coming back. Skip
the question when only one pair is in rotation, for older runs, and for
anything that is not a run.
Args: include_retired: Include pairs the athlete has put away (default true). Pass false for only the pairs in rotation.
Returns: List of pairs, in use first (newest first), then retired. Keys are camelCase and every distance is in METERS:
- id: matches `shoe_id` on a workout (get_recent_runs,
get_workout_detail). Pass it to get_recent_runs as `shoe_id` to list
the runs done in this pair.
- name: what the athlete called the pair.
- distance: total on the pair — `startDistance` plus every workout
assigned to it.
- startDistance: what the pair had on it when it was added. That part
is the athlete's own figure, not recorded runs.
- targetDistance: where the athlete plans to replace the pair, or null
when they set none. Their choice, not a wear measurement.
- workoutCount / lastUsedAt: assigned workouts and the latest one's
start. Zero and null for a pair with no runs on it yet.
- isDefault: new runs land on this pair automatically. At most one.
- retiredAt: when the pair was put away, null while in rotation.
- createdAt: when the pair was added to the app, not when it was bought.
A run with `shoe_id: null` has no pair recorded, which is common: runs
from before the athlete added a pair are never assigned, and walks,
rides and strength sessions never get one automatically. Null does not
mean barefoot, and a pair's `distance` only counts what was assigned.Inputs: include_retired.
get_training_calendarA
Get the unified training calendar: scheduled runs (Apple Watch queue) merged with recurring strength sessions (from active plan schedules), with same-day conflicts flagged.
Call this before scheduling strength days so you can place them on days that don't already have a run.
Args: date_from: Window start (YYYY-MM-DD). Defaults to today. date_to: Window end (YYYY-MM-DD). Defaults to today + 28 days.
Returns:
{from, to, entries[]} where each entry has: date, kind ("run" or
"strength"), title, activityType, status, planId, planName, routineId,
completed, conflict. conflict marks same-day double-bookings only;
adjacent-day concerns (hard run right after a strength day) surface
through validate_plan instead.
Inputs: date_to, date_from.
get_training_summaryA
Get aggregated training summary grouped by time period, newest first.
Args: activity_type: Filter by activity type (e.g. "running"). Omit for all types. period: Grouping period - one of "week", "month", or "year" (default "month"). start_after: Only aggregate workouts starting after this datetime (ISO 8601). start_before: Only aggregate workouts starting before this datetime (ISO 8601). limit: Max rows returned (default 52, max 500). One row per period × activity_type, newest first — without activity_type a period spans multiple rows. History past the limit stays reachable by paging back with start_before.
Returns: List of summary objects, each with: period, activity_type, count, total_distance, total_duration, avg_distance, avg_duration, total_energy_burned.
Inputs: limit, period, start_after, start_before, +1 more.
get_workout_activitiesA
Get the interval/segment breakdown of a workout (warmup, work, rest periods).
This extracts the 'activities' array from a workout, which describes the structured program that was followed — one entry per step the watch ran (warmup, work, rest, cooldown), each with distance, duration, heart rate, and timing.
Args: workout_id: UUID of the workout.
Returns: List of activity segment objects, each with: activityType, startDate, endDate, duration, totalDistance, totalEnergyBurned, averageHeartRate, and metadata — metadata.WOIntervalStepKeyPath encodes the position in the composed structure as "block.iteration.step" (e.g. "1.2.0" = 2nd block, 3rd iteration, 1st step; map it to the queue item's blocks to know whether a segment was work or recovery), with WOIntervalStepSuccessful/HKElevationAscended alongside. Returns an empty list if the workout has no structured activities.
Inputs: workout_id (required).
get_workout_contextA
Get the server-held plan linkage for a recorded workout: the queued session it fulfilled, the training plan behind that session, and any missed-workout feedback filed against it.
Args: workout_id: UUID of the workout (same id as get_recent_runs / get_workout_detail return).
Returns: Object with workout_id, plan_workout_id, plan_link_manual, and three nullable keys: - queue_item: title, description, activity_type, live status (e.g. "completed", "skipped"), scheduled_date, plan_id, the workout_data composition that was planned, completed_at. - plan: id, name, activity_type, status, start_date, end_date. - feedback: reason, reason_note, action (move/adjust/skip), new_date, scheduled_date, dismissed, created_at. Survives queue-item deletion.
All three null (with plan_workout_id null) means an unplanned run —
that's normal, not an error.
plan_link_manual true means the athlete linked this workout to the
session by hand afterwards (or unlinked it). They are saying it counts
for that session, not that they followed it: it may be from another
day, another activity, or a different kind of run than prescribed.
The session is completed either way; read the workout itself for what
was actually done.Useful when reviewing a completed workout: compare what was planned (queue_item.workout_data) against what happened, and see what the athlete said about the session.
Inputs: workout_id (required).
get_workout_detailA
Get full details for a single workout by ID.
Args: workout_id: UUID of the workout.
Returns: Workout object with all fields including the nested data object (splits, structured activities, events, metadata). The raw per-second sample arrays (GPS route, cadence, heart rate — several hundred kB) are replaced by data.samplesSummary: per-series count plus avg/min/max, and elevation gain/loss for the route. Use get_workout_heartrate for the heart rate series and get_workout_splits for splits.
data.events contains only meaningful events (pause/resume); HealthKit
segment events are pruned — they duplicate the interval structure that
activities and splits already encode.
Includes effort_score (user-rated RPE 1–10 from Apple Watch effort prompt;
primary signal of perceived effort) and estimated_effort_score (Apple's
algorithmic RPE estimate 1–10). A large gap between the two can indicate
non-cardiovascular load (heat, sleep debt, illness, stress) that HR-based
estimates miss. Treat null as "no signal," not "low effort."
shoe_id is the pair of shoes on this workout (see get_shoes), or null
when none was recorded. shoe_confirmed false means that pair was
assigned automatically and nobody has checked it.
end_heart_rate, heart_rate_after_1min and heart_rate_after_2min give
the heart rate recovery after the workout, and vo2_max the estimate
Health recorded for it; see get_recent_runs for how to read them.Inputs: workout_id (required).
get_workout_feedbackA
Retrieve the athlete's check-ins on runs they missed or changed ahead of time.
Use this to understand patterns in missed workouts and inform coaching decisions. Query action="adjust" to find workouts the user flagged for plan adjustment.
An entry acknowledged on or before its scheduled day (acknowledgedAt's date not after scheduledDate's) was filed ahead of time: the athlete moved or skipped the run before it lapsed. That is a plan change, not a miss. A missed-run check-in is always filed on a later day. A skip with reason "other" and a note like "Made room for " was cleared off the day another run moved onto.
Args: since: Only return entries with scheduledDate on or after this date (ISO 8601, e.g. "2026-03-01"). limit: Max entries to return (default 20). action: Filter by action type: "move", "adjust", or "skip".
Returns: List of feedback entries, each with: id, workoutId, workoutName, scheduledDate, detectedAt, acknowledgedAt, reason, reasonNote, action, newDate, dismissed.
Inputs: limit, since, action.
get_workout_fuelA
What the athlete drank and ate on one workout, next to what was planned for it.
Use it when reviewing a long run or a race, and whenever the athlete
brings up fuelling, a fade, stomach trouble or cramping on a run. An empty
entries usually means nothing was written down, not that nothing was
taken: ask before concluding anything from it.
Args: workout_id: UUID of the workout (from get_recent_runs).
Returns: Object (camelCase) with entries and summary (what was taken), planned and plannedSummary (the plan on the session this workout counted for; empty and null when there was none), plannedSessionId.
Each entry (camelCase): id, productId (null when typed in by hand or
the product was deleted since), name, kind ("drink", "gel", "other"),
volumeMl (a drink's total), carbsG and caffeineMg (in the entry as a
whole; null means not stated, NOT zero), atDistance (METERS into the
workout, null for a drink or when not placed). Drinks come first, then
the rest in the order taken.
A summary (camelCase): volumeMl, carbsG, caffeineMg, and
carbsPerHourG / fluidPerHourMl over the workout's duration. An entry
without a figure counts as zero, so treat a total as a floor when an
entry has null carbsG. The hourly rates are null for a workout under
20 minutes and for a plan on its own.Inputs: workout_id (required).
get_workout_heartrateA
Get the heart rate series recorded during a workout.
Args: workout_id: UUID of the workout. max_samples: Cap on series length (default 500, max 5000; null for the raw series). Longer series are downsampled by averaging over evenly-sized time buckets, so shape and peaks survive — raw counts grow with workout duration (a 3 h run is ~2000 samples).
Returns: List of {timestamp, value} heart rate samples in workout order.
Inputs: workout_id (required), max_samples.
get_workout_splitsB
Get per-split data for a workout (e.g. per-km or per-mile splits).
Args: workout_id: UUID of the workout.
Returns: List of split objects extracted from the workout's data.splits field.
Inputs: workout_id (required).
list_plan_notesA
List plan notes with filters. Use this for targeted retrieval (e.g. only "decision" notes, or all notes from a specific conversation_id).
For the standard conversation-start fetch, use get_plan_context
instead — it returns plan + notes + a continuity hint in one call.
Args: plan_id: Filter by plan UUID. kind: Filter by kind (decision, preference, constraint, life_context, observation, blocker, feedback). conversation_id: Filter by conversation grouping id. since_days: Only notes created within this window. include_expired: If true, include notes past their expires_at. limit: Max notes to return (default 50, max 200).
Returns: List of PlanNote objects ordered by importance desc, created_at desc.
Inputs: kind, limit, plan_id, since_days, +2 more.
list_plansB
List training plans.
Args: status: Filter by status — "active", "upcoming", "completed", "archived" or "abandoned". "upcoming" is a block built ahead of its start date: its sessions still show in the calendar and schedule checks, but it is not the plan the athlete is on. activity_type: Filter by activity type (e.g. "running").
Returns:
List of plans, newest first. Each carries computed progress and
finishable — see get_plan for their semantics (progress counts
queued runs and scheduled strength sessions alike; finishable=true
means offer a wrap-up).
Inputs: status, activity_type.
list_queued_workoutsA
List all queued workouts, including ones already synced to Apple Watch.
Use this to find the UUID of a workout that has been synced, so you can issue edit or delete actions against it.
Args: status: Optional filter — "pending", "fetched", "synced", "completed", or "skipped". Omit to return all items. limit: Max number of items to return (default 50, max 200).
Returns: List of queue items sorted by creation date (newest first), each with: id, activity_type, title, description, workout_data, status, created_at, fetched_at, completed_at.
Inputs: limit, status.
log_setbackA
Record that the athlete is, or was, ill or injured.
Call this WITHOUT BEING ASKED when the athlete tells you they are sick or
hurt, or that they were on days you had no setback for ("I had the flu
last weekend", "my calf has been sore since Tuesday's intervals"). This is
what makes the next conversation start out knowing it. Check the
setbacks in get_plan_context first: if the same one is already open,
use update_setback or log_setback_status on it. The server refuses a
second open illness, and a second open injury to the same body part.
Ordinary training soreness that fades within two days is not a setback. Tell the athlete you have logged it, in one short sentence.
Args: kind: "illness" (cold, flu, stomach bug, covid) or "injury". start_date: First day affected, YYYY-MM-DD. Ask if it is unclear; it is the anchor every before/after comparison uses. severity: "mild" (could have trained easy), "moderate" (no training) or "severe" (in bed, or cannot walk without pain). Ask rather than guess when the athlete's words do not settle it. end_date: Last day affected, YYYY-MM-DD. Leave out while it is still going on, and while the athlete is "better but not right yet". body_part: Injuries only, in the athlete's words ("left calf"). note: Symptoms and anything that explains it, in a line or two.
Returns: The setback, in the shape get_setbacks lists.
Inputs: kind (required), start_date (required), note, end_date, +2 more.
log_setback_statusA
Record how the athlete felt on one day of a setback.
While a setback is open, ask how they are today when the conversation starts and record the answer here, unless today already has an entry. One entry per day; logging the same day again replaces it. These entries are the subjective side of the recovery curve, and for an injury they are most of it.
"fine" does not close the setback. When the athlete says "fine", ask whether they consider themselves recovered, and close it with update_setback if they do.
Args: setback_id: The setback's id. status: "worse", "same" or "better" compared with the day before, or "fine" when they feel normal again. date: The day it describes, YYYY-MM-DD. Defaults to today; pass it when the athlete is describing an earlier day. note: Their words, shortened ("fever gone, still coughing").
Returns: The setback with its check-ins.
Inputs: status (required), setback_id (required), date, note.
log_workout_fuelA
Write down what the athlete drank and ate on a workout, on their say-so.
The athlete can log this in the app themselves; use this when they tell you in conversation instead ("I had two gels and a bottle of water on Sunday's long run"). Log what they say, not what was planned, and ask rather than guess when they are vague about an amount. A drink is ONE entry with the total volume; each gel is its own entry, with at_distance_m when they remember where they took it.
Args:
workout_id: UUID of the workout (from get_recent_runs).
entries: What to log. Prefer product_id (get_fuel_products) so the
figures are the athlete's own.
replace: False (default) adds to what is already logged. True
replaces the whole log with entries; use it to correct a log,
after reading it with get_workout_fuel.
Returns: The workout's fuelling afterwards, in the shape get_workout_fuel returns.
Inputs: entries (required), workout_id (required), replace.
move_strength_sessionA
Move the strength session on one date to another date, keeping its title and routine.
Works for an individual session and for one occurrence of a weekly pattern; the pattern's other weeks stay where they are. Use it when the athlete says a session doesn't fit that day this week.
Args: plan_id: UUID of the strength plan. date: The day the session is on now (YYYY-MM-DD). to_date: The day to move it to (YYYY-MM-DD).
Returns:
The resolved schedule after the move. An error when nothing is
scheduled on date.
Inputs: date (required), plan_id (required), to_date (required).
remove_strength_sessionA
Take the strength session on one date off the plan.
An individual session is removed. One occurrence of a weekly pattern is
skipped for that date only and the pattern carries on. To drop the whole
schedule use clear_plan_schedule.
Args: plan_id: UUID of the strength plan. date: The day of the session to remove (YYYY-MM-DD).
Returns:
The resolved schedule after the removal. An error when nothing is
scheduled on date.
Inputs: date (required), plan_id (required).
set_fuel_planA
Write the fuelling plan for a planned session. It replaces any plan the session already has; an empty list removes it.
The athlete sees the plan on the session in the app, and after the run next to what they logged, where one tap logs it as planned. So write the plan you would want them to follow, item by item, not a general remark: that belongs in the conversation or the session's description.
BEFORE WRITING ONE: get_fuel_products for what the athlete carries, and get_fuel_history for what they have taken on earlier long runs and how much per hour. Build on that; a plan far above what they are used to is one their stomach has not practised. Say in the conversation what the plan adds up to per hour and why.
One entry per drink with the total to drink over the run (volume_ml), and one entry per gel or other item with where to take it (at_distance_m, METERS). Use product_id wherever the athlete has the product saved.
This is not medical advice, and caffeine and sodium tolerance are personal: where the athlete has not used something before, say so and suggest trying it in training first.
Args: session_id: UUID of the planned session, the queue item's id (from get_plan_workouts, get_pending_workouts or list_queued_workouts). entries: The whole plan.
Returns: The session's plan afterwards, in the shape get_fuel_plan returns.
Inputs: entries (required), session_id (required).
set_strength_scheduleA
Set a recurring weekly schedule on a plan — which routine runs on which weekday, for a number of weeks.
Only for an athlete who lifts on fixed weekdays. One who fits strength
around the rest of the week has no "every Tuesday": give them individual
sessions with add_strength_session instead, and skip this tool. The two
also combine: a weekly pattern, with move_strength_session or
remove_strength_session for the weeks that differ.
Use this for strength / Hevy cycles: the schedule references Hevy routines
by id + title (get them from the hevy-mcp first). These sessions are plan
markers only — they are NOT pushed to the Apple Watch (that's for running
interval workouts). Completed strength sessions auto-match by date via the
HealthKit traditionalStrength workouts that Hevy already syncs in.
IMPORTANT — avoid conflicts: call get_training_calendar first to see
scheduled runs, and place strength days on free weekdays. The response also
returns a warnings list flagging any day where a strength session lands on
the same date as a scheduled run (surfaced, not blocked — you decide).
Args: plan_id: UUID of the plan this cycle belongs to (create one first via create_plan with activity_type "strength"). start_date: First week's anchor date (YYYY-MM-DD). weeks: How many weeks the cycle runs (1–52). days: Which weekday gets which routine — set only the days that have a session. Example: { "mon": {"title": "Lower", "routineId": "hevy-abc"}, "wed": {"title": "Upper Push", "routineId": "hevy-def"}, "fri": {"title": "Deadlifts + Pull", "routineId": "hevy-ghi"} } time: Optional default time of day "HH:MM". timezone: Optional IANA timezone (e.g. "Europe/Lisbon").
Returns:
The resolved schedule: concrete dated sessions (each with a conflict
flag) and a warnings list for run collisions.
Inputs: days (required), weeks (required), plan_id (required), start_date (required), +2 more.
update_planA
Update a training plan.
Common uses: mark as completed/abandoned, start an upcoming block, update metadata, adjust dates.
Args: plan_id: UUID of the plan. name: New plan name. status: New status — "active", "upcoming", "completed", "archived" or "abandoned". Nothing promotes a plan on its start date, so starting an upcoming block is an explicit update_plan(status="active"). description: Updated description. metadata: Replacement metadata object (replaces entire metadata, not merged). end_date: New end date (YYYY-MM-DD).
Returns: The updated plan.
Inputs: plan_id (required), name, status, end_date, +2 more.
update_plan_noteA
Update a plan note. Use when a previous note was wrong, became obsolete, or needs a tighter summary. Prefer updating over deleting + re-creating so the note's history is preserved.
Args: note_id: UUID of the note. kind: New kind, if changing categorization. summary: New one-line summary (≤280 chars). body: New body text. importance: New importance (1–3). expires_at: New expiry, or pass to add expiry to a note that didn't have one.
Returns: The updated PlanNote.
Inputs: note_id (required), body, kind, summary, +2 more.
update_queued_workoutA
Update an existing queued workout. Only provided fields are changed.
Use this to reschedule a workout, change the interval structure, rename it, or modify any part of the composition before it syncs to Apple Watch. Steps support the same goals and alerts (incl. heart-rate zones) as create_workout — see that tool's input schema.
Args: item_id: UUID of the queue item (from get_pending_workouts). display_name: New name shown on Apple Watch. activity_type: New activity type (running, cycling, etc.). location: New location ("outdoor" or "indoor"). scheduled_date: New scheduled date (ISO 8601). blocks: New interval blocks (replaces all existing blocks). warmup: New warmup step (omit to leave unchanged). cooldown: New cooldown step (omit to leave unchanged). clear_warmup: Set true to remove the existing warmup. clear_cooldown: Set true to remove the existing cooldown. description: New text description. plan_id: UUID of the training plan to assign this workout to.
Returns: The updated queue item object.
Inputs: item_id (required), blocks, warmup, plan_id, +8 more.
update_setbackA
Change a setback: close it, reopen it, or correct what was recorded. Only what you pass changes.
CLOSING. Set end_date when the athlete says they are recovered. Their
word decides it, not the numbers: if the metrics look normal but they
still feel off, it stays open, and if they say they are fine while resting
heart rate is still raised, close it and say what you see. After closing,
the plan still needs a gradual build back (coaching playbook, return to
running).
Args: setback_id: The setback's id, from get_plan_context or get_setbacks. end_date: Last day affected, YYYY-MM-DD. Closes the setback. reopen: True to clear the end date, when it came back. severity: "mild", "moderate" or "severe". start_date: Corrected first day, YYYY-MM-DD. kind: "illness" or "injury". body_part: Injuries only. note: Replaces the note. Include what was there if it still holds.
Returns: The setback after the change.
Inputs: setback_id (required), kind, note, reopen, +4 more.
update_shoeA
Change a pair of shoes: rename it, correct its distances, make it the default, retire it or bring it back. Only what you pass changes.
There is no tool to delete a pair; that stays in the app. Retire a pair the athlete has stopped using — its runs and distance are kept.
Args: shoe_id: The pair's id from get_shoes. name: New name. start_distance_meters: Distance the pair had before it was added, in METERS. This is not the pair's total: the total is this plus its assigned runs, so to correct a total, work out the difference. target_distance_meters: New replacement distance, in METERS. clear_target: True removes the replacement distance. Do not combine with target_distance_meters. is_default: True makes this the pair new runs land on (replacing the current default); false leaves the athlete with no default. A retired pair cannot be the default. retired: True puts the pair away (it also stops being the default); false brings it back into rotation.
Returns: The updated pair, in the shape get_shoes lists.
Inputs: shoe_id (required), name, retired, is_default, +3 more.
update_workout_statusA
Update the status of a queue item.
Lifecycle: pending -> fetched -> synced -> completed. "skipped" retires the item (the watch endpoints stop serving it and it no longer counts as a schedule collision) — normally set via missed-workout feedback with action "skip", but it can be set directly here too.
Args: item_id: UUID of the queue item. status: New status. Setting "fetched" records the fetch timestamp; "completed" records the completion timestamp.
Returns: The updated queue item object.
Inputs: status (required), item_id (required).
validate_planA
Deterministically check the athlete's upcoming schedule for soundness, using this plan's context (guardrails, race date from metadata).
Run this after queueing or reshuffling a plan's workouts, and before
presenting a plan to the athlete as final. It is pure arithmetic over the
queue + the athlete's real workout history — no LLM judgment — checking
the coaching playbook's numeric invariants: weekly ramp vs the actual
4-week baseline, missing down weeks, long-run share, back-to-back hard
days, taper shape before race_date, and the plan's own declared
guardrails.
Interpreting results: critical warnings should be resolved (adjust the
schedule and re-queue) or explicitly signed off by the athlete; warn
items should at least be mentioned; info is context. estimated: true
means the numbers rest on a pace assumption (time-based steps without a
pace alert). Warnings never block anything.
Note strength_collision (info) fires for a hard run the day after a
strength session — an interference heads-up, deliberately broader than
the calendar's conflict flag, which only marks two sessions sharing a
date. A day-after warning here with conflict=false on the calendar is
consistent, not contradictory.
Args: plan_id: UUID of the plan whose context (guardrails, race date) frames the check. The schedule itself is always the athlete's full upcoming queue — runs from other plans count too.
Returns: {plan_id, warnings[], weeks[]} — warnings have {code, severity, message, week, data, estimated}; weeks summarize each planned week (planned_km, actual_km, total_km, run_days, hard_days, longest_km, baseline_km, ratio).
Inputs: plan_id (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 59 tools
Several tools overlap in purpose: get_pending_workouts vs list_queued_workouts, get_pending_actions vs get_pending_workouts, edit_scheduled_workout vs update_queued_workout, and delete_scheduled_workout vs delete_workout. Descriptions do clarify the distinctions (queue vs on-device vs recorded, pending actions vs pending workouts), but an agent can still misselect without reading carefully. The large surface makes some confusion likely, though most domains remain separable.
The overwhelming majority of tools follow snake_case verb_noun naming (get_recent_runs, create_plan, update_shoe, log_workout_fuel). A few outliers exist, such as batch_actions and batch_create_workouts, which are still understandable. The set is predictable enough for reliable tool selection.
With 59 tools, the surface is far above the typical well-scoped range and includes many CRUD variants across workouts, plans, strength scheduling, fuel, shoes, notes, health, and setbacks. While the coaching domain is broad, this many tools creates maintenance and selection overhead. Several overlapping pairs suggest the count could be reduced through consolidation.
The server covers the domain thoroughly: workout queue and recorded-workout lifecycle, plans, strength schedule management, fuelling, shoes, notes, health metrics, setbacks, feedback, calendar, validation, and coaching context. Minor gaps exist, such as no update/delete for fuel products (only add/list), but core workflows are well supported. Agents are unlikely to hit dead ends in normal training-coaching use.
Maintenance
Related MCP Connectors
Running coach: your AI reads your runs and recovery, and writes sessions to your watch or phone.
Your AI writes training plans that arrive as structured workouts on iPhone and Apple Watch.
AI coach for Garmin: builds training plans and structured workouts, synced straight to your watch.
Your AI becomes your fitness coach. It writes your plan; the app tracks progress and health for it.
Related MCP Servers
- FlicenseNot gradedqualityAmaintenanceGrants AI assistants read-only access to your WHOOP recovery, sleep, HRV, strain, and workout history so you can ask natural-language questions about daily readiness, personal baselines, sleep debt, trends, and weekly reviews. It also rebuilds HYROX and triathlon sessions, tracks race load and readiness, and runs a local dashboard for auditing and correcting performance data.14 npm-
- AlicenseAqualityBmaintenanceLets Claude build structured runs, strength sessions, and multi-week training plans — including race and high-school track blocks — and publish them through a feed that an iPhone app schedules onto the Apple Watch via WorkoutKit. It also reads recent Strava activities and sync status so plans can be sized to real fitness and confirmed as actually on the wrist.141MIT
- AlicenseAqualityCmaintenanceTurns your own wearable data into coaching for hybrid fitness races by exposing readiness, running coach plans, fitness trends and training summaries as tools an agent can query. Keeps your data read-only at the provider and lets you log the station work and race profile your watch can't see in a local database.91MIT
- AlicenseAqualityAmaintenanceEnables AI assistants to answer training questions from a user's own Garmin Connect data — training load, form, ACWR, HRV-based morning readiness, activities, sleep and health — using locally cached data and cited sports-science methods. Also turns requests into structured workouts that can be previewed, scheduled to the Garmin calendar and synced to the watch.212MIT

