dbx
Query databases from AI agents using connections configured in DBX.
T8t8y2/dbx32k近 7 天新增 726 个 star
Self-hosted running coach: your Apple Health training data, plans and Apple Watch workouts.
A self-hosted running coach for Claude, ChatGPT or another AI assistant. The assistant you already use connects to the built-in MCP endpoint and does more than read your data: the training plan it writes becomes structured workouts on your Apple Watch, and each finished run comes back linked to the workout it was planned as. Loopback Server keeps your runs, sleep and recovery data from Apple Health next to your plans, and a web dashboard shows the same data to athletes and admins.
It is the server half of Loopback – Running Coach, an open-source app for iPhone and Apple Watch.
Website: loopback.ardenlab.dev
Built with FastAPI, PostgreSQL, SQLAlchemy, and React. The MCP (Model Context Protocol) endpoint is part of the same container and needs no setup of its own.
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.
/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 tokenPOST /api/plans/{id}/validate, also returned when queueing)plan_id) and recorded workouts to their planned counterpart (plan_workout_id) for planned-vs-actual analysisPOST /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 typegit clone https://github.com/aderaaij/loopback-training-server.git
cd loopback-training-server
cp .env.example .env
Everything 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.
docker compose up -d # or: make up
The 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).
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).
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.
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.localhost), or correct the address shown under the code. Typing the server URL, username and password into the app works as before.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 --help
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 dependencies
The 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 -v
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.
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.com
Then 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 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.yml
Then 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 |
|---|---|---|
https://loopback.<your-tailnet>.ts.net:8443 | Devices on your tailnet | Everything: dashboard, API (the phone app), coach |
https://loopback.<your-tailnet>.ts.net/mcp | 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.
Everything a person does with the server happens on the first address: opening their invitation, connecting the app, the app's syncing, and signing in to approve an assistant. So each device they use has to get there, and three things have to be true for that:
Tailscale on each of their devices, installed, signed in and switched on. That is the phone the app runs on, and whatever they open the invitation on.
A place on your tailnet. In the Tailscale admin console, invite them on the Users page, or share the server's device with them from the Machines page (for someone with a tailnet of their own, who then sees that one device and nothing else of yours).
Access to the server's device on TCP port 8443. A tailnet starts out letting every device reach every other, and then there is nothing to do. If yours has rules of its own (the Access controls page), being on the tailnet is not enough: add a rule for them. As a grant, with the Tailscale IP address of the server's device from the Machines page:
{ "src": ["[email protected]"], "dst": ["100.101.102.103"], "ip": ["tcp:8443"] }
When one of the three is missing, nothing says which: the invitation link does not load, the app reports that it could not reach the server, and an assistant's sign-in page stays empty. The dashboard therefore says it up front: Users → Invite someone lists the three with the name and the port from the link.
Each name on your tailnet is a device with rules of its own. If the server can also be reached under another one (Tailscale on the host itself next to the add-on, say), hand out one address, or give people access to both. With PUBLIC_URL set to the add-on's address (https://loopback.<your-tailnet>.ts.net), a dashboard opened under the other name knows where assistants send people to sign in, lists that address in the invitation dialog as well, and checks it from the device before someone sets off to connect Claude.
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.
http://<machine-name>:8001 inside the tailnet and nothing is exposed to the internet. tailscale serve --bg --https 8443 8001 adds HTTPS. An assistant in the cloud cannot connect to such a server; that is what the add-on above is for.deploy/demo/docker-compose.public.yml shows the pattern.The way you expose the server decides what has to be in place on the devices of the people you invite, before their invitation link opens at all. A link to a server a device cannot reach opens nothing, not even a page that says why, so this is worth a look before you send one.
| The server's address is | Each of their devices needs | You arrange |
|---|---|---|
| Public: built-in HTTPS, a Cloudflare Tunnel, a reverse proxy of your own | Nothing | Nothing |
| On Tailscale | Tailscale installed, signed in and switched on | A place on your tailnet, and access to the server's port: Adding a person on Tailscale |
| On another VPN (WireGuard, ZeroTier and the like) | That VPN set up and switched on | Their device as a peer, let through to the server's address and port |
| On your home network and nowhere else | To be on that network | Nothing. Their phone syncs only at home |
"Their devices" is the phone the app runs on, and whatever they open the invitation or approve an assistant on.
Two things hold whichever row is yours:
https. Certificates from Let's Encrypt (the built-in HTTPS), Tailscale and Cloudflare are trusted everywhere. One your server signed itself, or one from a certificate authority of your own, has to be installed and trusted on each device first: without that a browser warns, and the app does not connect.The dashboard says what it can tell from the address when you invite someone (Users → Invite someone): for a Tailscale address the list above with the name and the port filled in, for a private address (192.168.…, 10.…, a .local name) that their device has to be on that network or on a VPN that leads to it. For both it offers the invited person's part as a note to send with the link. A public name gets no list, since it asks nothing of them. On the phone, the app's sign-in screen says the same when nothing answers at a Tailscale address.
127.0.0.1:8001. Set FORWARDED_ALLOW_IPS in .env to the address the proxy connects from, or every client shares one rate limit (see Configuration).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.
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.
Restoring. A dump holds the whole database and loads into an empty one, so restoring empties the database first, and everything stored since the dump was made is gone afterwards:
docker compose stop app
docker exec postgres__training-api dropdb -U training-api training-api
docker exec postgres__training-api createdb -U training-api training-api
gunzip -c backups/<dump>.sql.gz | docker exec -i postgres__training-api psql -U training-api training-api
docker compose up -d
The first line stops the server so nothing writes while the dump loads, the next two empty the database, and the last starts the server again, which brings a dump from an older version up to date. Do not skip the two in the middle: loaded into a database that still holds data, nearly every statement fails because the tables are already there, nothing is put back, and psql does not say so at the end. One line of output is expected, ERROR: unrecognized configuration parameter "transaction_timeout": the dump is written by a newer pg_dump than the PostgreSQL 16 it is loaded into, and that setting is all that is lost. On a new machine the steps are the same after a first docker compose up -d, and there is no admin account to create, since the accounts are in the dump.
Prefer 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.gz
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 |
|---|---|
0.1.0 | An exact release — immutable |
0.1 | The latest patch release of a minor line |
latest | Every push to main — may be ahead of any release |
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.1
To upgrade: skim the changelog, then
docker compose pull && docker compose up -d
Database 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: the backup from before the upgrade has to go back as well. Set IMAGE_TAG to the older version, then follow the restore steps under Backups with the dump the upgrade made, the …-premigrate.sql.gz file with the time of the upgrade in its name. Their last line starts the server on the version you set. Do not leave an older version running on the newer database in the meantime: it restarts over and over, and every restart writes another -premigrate dump, of the newer database, which pushes your older dumps out once there are more than BACKUP_KEEP.
Everything is configured through environment variables in the root .env (read by Docker Compose):
| Variable | Default | Purpose |
|---|---|---|
BOOTSTRAP_ADMIN_PASSWORD | (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 |
BOOTSTRAP_ADMIN_USERNAME | admin | First-run admin username |
POSTGRES_PASSWORD / POSTGRES_USER / POSTGRES_DB | training-api | Database credentials (not published outside the compose network; also fed to the app as DATABASE_URL) |
API_PORT | 8001 | Host port for the API + dashboard |
MCP_ENABLED | true | Serve the coach MCP at /mcp on the same port (see MCP Server). false removes the endpoint |
PUBLIC_URL | (unset) | The server's address as an assistant reaches it, e.g. https://loopback.example.com. Only needed behind a proxy that does not pass the original Host header on: the server otherwise reads its address from each request (see Signing in from an assistant) |
OAUTH_AUTHORIZATION_ORIGIN | (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 |
OAUTH_AUTHORIZATION_PORT | (unset) | The same, when the two differ only in the port: the coach on the standard port and the dashboard on this one. deploy/tailscale/tailscale.yml sets it to 8443 for you |
TS_HOSTNAME | loopback | Name of the server's device on your tailnet, used with deploy/tailscale/tailscale.yml (see Exposing the server) |
TS_AUTHKEY | (unset) | A Tailscale auth key, to add that device to your tailnet without opening the link from its log |
FORWARDED_ALLOW_IPS | (unset) | Behind a reverse proxy: the address(es) or CIDR the proxy connects from, whose X-Forwarded-For the server trusts for the client address (login rate limit, audit trail). Unset, only loopback is trusted and every proxied client looks like the proxy. deploy/https/caddy.yml sets this for you. Never use * while port 8001 is reachable by anything but the proxy |
DOMAIN | (unset) | Hostname for built-in HTTPS, used with deploy/https/caddy.yml (see Exposing the server) |
BACKUP_HOST_DIR | ./backups | Host directory the server writes its pg_dump backups to (and reports freshness from) |
BACKUP_ENABLED | true | Server-managed backups: nightly dump, catch-up after downtime, pre-migration dump. false = bring your own (see Backups) |
BACKUP_TIME | 03:30 | Nightly backup time, container-local (set TZ to make it your local time) |
BACKUP_KEEP | 30 | How many dumps to keep — older training-api-*.sql.gz files in the backup dir are pruned |
TZ | UTC | Container timezone (e.g. Europe/Lisbon), used by BACKUP_TIME |
CARTO_API_KEY | (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 |
MAP_TILE_URL | (unset) | Use any other tile provider: a Leaflet URL template ({s} {z} {x} {y} {r} and a ?key=… query are fine). Overrides CARTO_API_KEY |
MAP_TILE_ATTRIBUTION | © OpenStreetMap © CARTO | Attribution line shown on the map (HTML allowed); set it to match your provider |
MAP_TILE_SUBDOMAINS | abcd | Only used when MAP_TILE_URL contains {s} |
IMAGE_TAG | latest | Docker image tag for the app service — pin a release like 0.1 or 0.1.0 (see Releases & upgrading) |
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.
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)
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.
| Method | Endpoint | Description |
|---|---|---|
GET | /api/auth/setup | Whether first-run setup is open ({"required": bool}; unauthenticated) |
POST | /api/auth/setup | Create the first admin account (returns a signed-in session; 409 once an admin exists) |
POST | /api/auth/login | Log in, mint a per-device token (bad credentials → 401) |
GET | /api/auth/me | Current user + their tokens (each with its scope: full or coach) |
POST | /api/auth/password | Change own password (revokes every other token) |
POST | /api/auth/tokens | Mint a named token (shown once; optional expiresAt; "scope": "coach" makes a coach token, the default is full) |
DELETE | /api/auth/tokens/{id} | Revoke one of your own tokens |
POST | /api/auth/pairing | Make a code for connecting the phone app: {id, code, expiresAt, expiresIn}. Good once, for five minutes; replaces your earlier code. The dashboard shows it as a QR code holding https://loopback.ardenlab.dev/connect/#server=<address>&user=<username>&code=<code>, a link iOS opens in the app (403 for an admin account or a coach token) |
GET | /api/auth/pairing/{id} | What became of your code: status is waiting, connected (with the phone's deviceName) or expired |
POST | /api/auth/pairing/redeem | Trade a code for a full per-device token ({code, deviceName}; unauthenticated, 10/min/IP; answers like a login; 401 for a code that is used, expired, unknown or not shaped like one) |
POST | /api/auth/invite/check | Whether the code of an invitation link is still good, and who it is from: {displayName, invitedBy, expiresAt} ({code} in the body; unauthenticated, 10/min/IP; 404 for a code that is used, withdrawn, expired or unknown) |
POST | /api/auth/invite/accept | Make the account an invitation is for and sign in to it ({code, username, password, displayName?}; unauthenticated, 10/min/IP; answers like a login). The username is 1 to 32 lower-case letters, digits, dots, hyphens or underscores; the password at least 8 characters. 404 for a code that is no longer good, 409 for a taken username, 400 for a username or password that cannot be used; after a 409 or 400 the invitation is still good |
GET | /api/coach/claude-desktop.mcpb | The Claude Desktop extension for the coach, as a file (optional serverUrl fills in the server address; never contains a token) |
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 |
|---|---|---|
GET | /.well-known/oauth-protected-resource | Which server issues tokens for /mcp (also at …/oauth-protected-resource/mcp) |
GET | /.well-known/oauth-authorization-server | Where to send the athlete and where to trade the code |
GET | /oauth/authorize | Checks an assistant's request and passes the browser on to the approval page |
POST | /oauth/token | Trades the one-time code for a token (a coach token; no refresh tokens) |
GET | /api/oauth/requests/{id} | The request waiting for an answer (404 once answered or after 10 minutes) |
POST | /api/oauth/requests/{id}/approve | Approve as yourself; returns where to send the browser (403 for an admin account) |
POST | /api/oauth/requests/{id}/deny | Decline; returns where to send the browser |
| Method | Endpoint | Description |
|---|---|---|
GET | /api/admin/users | List users with token stats + sync freshness |
POST | /api/admin/users | Create a user by hand, with a username and password you choose |
GET | /api/admin/invites | The invitations nobody has used yet (never their codes) |
POST | /api/admin/invites | Make an invitation: {id, code, displayName, createdBy, createdAt, expiresAt} (optional displayName says who it is for). Good once, for seven days. The code is shown only here; the dashboard puts it in a link to its own page, <address>/join#code=<code> |
DELETE | /api/admin/invites/{id} | Withdraw an invitation that is still waiting |
PATCH | /api/admin/users/{id} | Activate/deactivate (deactivation revokes all tokens), or make read-only with {"readOnly": true}: the account can then be read and every change is refused with a 403 (not for admins) |
DELETE | /api/admin/users/{id} | Delete an account for good, with all its data. Only a deactivated account (409 otherwise), never your own (400) |
POST | /api/admin/users/{id}/password | Reset a user's password |
GET | /api/admin/users/{id}/tokens | List a user's tokens |
DELETE | /api/admin/users/{id}/tokens/{tid} | Revoke a single token (one stolen device) |
GET | /api/admin/events | Auth audit trail (logins, password/token/user changes; prunes >365d on read) |
GET | /api/admin/system | Backup freshness, DB size, row counts, migration head |
| Method | Endpoint | Description |
|---|---|---|
POST | /api/workouts | Create or upsert a workout |
GET | /api/workouts | List workouts (filters: activity_type, start_after, start_before, plan_workout_id, limit, offset) |
GET | /api/workouts/summary | Aggregated stats by period (week/month/year) and activity type |
GET | /api/workouts/{id} | Get workout detail |
GET | /api/workouts/{id}/splits | Get per-split breakdown |
GET | /api/workouts/{id}/heartrate | Get heart rate samples |
PUT | /api/workouts/{id}/shoe | Assign a pair of shoes to a workout ({"shoeId": null} takes it off) |
DELETE | /api/workouts/{id} | Delete a workout |
GET | /api/shoes | List pairs of shoes with their mileage (meters), in use first |
POST | /api/shoes | Add a pair (name, startDistance, targetDistance, isDefault) |
PATCH | /api/shoes/{id} | Change a pair: rename, set distances, make it the default, retire it |
DELETE | /api/shoes/{id} | Delete a pair (its workouts stay, without a pair) |
| Method | Endpoint | Description |
|---|---|---|
POST | /api/queue | Queue a structured workout (response carries an additive validation key with schedule warnings) |
POST | /api/queue/batch | Queue several workouts at once → {items, validation} envelope |
GET | /api/queue | List queue items (filter by status) |
GET | /api/queue/pending | List pending items |
PATCH | /api/queue/{id} | Edit a queue item's fields |
PATCH | /api/queue/{id}/status | Update item status (pending / fetched / synced / completed / skipped) |
DELETE | /api/queue/{id} | Delete a queue item |
GET | /api/workouts/queue | App-facing: get pending workouts as WorkoutKit compositions |
GET | /api/workouts/queue/scheduled?from= | App-facing: delivered, still-due workouts as compositions; the app restores missing ones onto a new or reinstalled phone's watch |
PATCH | /api/workouts/queue/{id} | App-facing: confirm install → synced (never downgrades completed/skipped) |
DELETE | /api/workouts/queue/{id} | App-facing: mark item as synced (persists the record) |
| Method | Endpoint | Description |
|---|---|---|
GET | /api/workouts/actions | List pending edit/delete actions |
POST | /api/workouts/actions | Create an edit or delete action |
POST | /api/workouts/actions/batch | Create multiple actions at once |
DELETE | /api/workouts/actions/{id} | Acknowledge a processed action |
| Method | Endpoint | Description |
|---|---|---|
PUT | /api/workouts/inventory | Sync full on-device workout snapshot (idempotent replace) |
GET | /api/workouts/inventory | Get stored inventory |
| Method | Endpoint | Description |
|---|---|---|
POST | /api/workouts/feedback | Record feedback for a missed workout (upsert by workoutId; action: "skip" retires the queue item) |
GET | /api/workouts/feedback | Retrieve feedback history (filters: since, limit, action) |
| Method | Endpoint | Description |
|---|---|---|
POST | /api/plans | Create a training plan |
GET | /api/plans | List plans (filters: status, activity_type; includes computed progress + finishable) |
GET | /api/plans/{id} | Get plan with metadata |
PATCH | /api/plans/{id} | Update plan fields |
POST | /api/plans/{id}/complete | Complete an active plan (rating/feedback stored as a coaching note) |
POST | /api/plans/{id}/validate | Deterministic schedule check → {plan_id, warnings, weeks} (ramp, taper, collisions, guardrails) |
DELETE | /api/plans/{id} | Delete a plan (queue items keep plan_id set to null) |
GET | /api/plans/{id}/workouts | Get all queued workouts for a plan |
GET | /api/plans/{id}/schedule | Read the plan's recurring weekly cadence, resolved to dated sessions |
PUT | /api/plans/{id}/schedule | Set the cadence (collisions with queued runs are warned, not blocked) |
DELETE | /api/plans/{id}/schedule | Clear the cadence |
| Method | Endpoint | Description |
|---|---|---|
GET | /api/schedule/calendar?from=&to= | Unified timeline merging queued runs + scheduled strength sessions, each with a conflict flag |
| Method | Endpoint | Description |
|---|---|---|
POST | /api/plan-notes | Add a cross-conversation coaching note |
GET | /api/plan-notes | List notes (filters: plan_id, kind, conversation_id, since_days, limit) |
GET | /api/plan-notes/context | Condensed coaching context (plans + notes) for LLM consumption |
GET | /api/plan-notes/{id} | Get a note |
PATCH | /api/plan-notes/{id} | Update a note |
DELETE | /api/plan-notes/{id} | Delete a note |
| Method | Endpoint | Description |
|---|---|---|
POST | /api/health/metrics | Bulk upsert daily health metrics (null fields preserved) |
GET | /api/health/metrics | Query metrics (required: start_date, optional: end_date) |
| Method | Endpoint | Description |
|---|---|---|
POST | /api/nutrition | Bulk upsert daily dietary totals (null fields preserved) |
GET | /api/nutrition | Query daily rows (required: start_date; optional: end_date, limit) |
GET | /api/nutrition/summary | Intake, body weight and training load per period (optional: period=week|month, timezone) |
DELETE | /api/nutrition/{date} | Remove a whole day's row |
The server ships with an MCP endpoint that exposes training data to AI assistants (Claude or ChatGPT, for example), 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/mcp
Each 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.
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:
/mcp is added for you.mcp-remote)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:
~/Library/Application Support/Claude/claude_desktop_config.json%APPDATA%\Claude\claude_desktop_config.jsonAdd the server. If the file is empty, paste this whole block. If it already has an mcpServers section, 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>/mcp with the address you open the dashboard at, plus /mcp, and <your-token> with the token from step 2 (keep the word Bearer and the space in front of it).
If your address starts with http:// (for example http://<machine-name>:8001 inside a tailnet), add one more line to args, 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 training with the status Running. Then ask in a new chat: "What did I run this week?"
If it does not connect:
training shows Failed or Not responding: click View logs next to it (the file is mcp-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.npx not 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. Run which npx in a terminal and use that full path as "command" in place of "npx".Bearer is missing in front of it.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.
/mcp (the dashboard shows it in that same entry).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:
Host header, set PUBLIC_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.
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:
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.
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 start
TRAINING_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.
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.js
Bump __version__ in backend/app/version.py — the single source of truth (pyproject.toml, /api/health, and the dashboard all derive from it) — and add a CHANGELOG.md entry.
Commit, then tag and push:
git tag -a v0.1.0 -m "v0.1.0"
git push origin main v0.1.0
The 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.
├── 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 client
MIT
Query databases from AI agents using connections configured in DBX.
T8t8y2/dbx32k近 7 天新增 726 个 star
Run Windmill scripts and flows and manage jobs, schedules, resources and variables.
WIwindmill-labs/windmill19k近 7 天新增 82 个 star
MCP Toolbox for Databases enables your agent to connect to your database.
GOgoogleapis/mcp-toolbox17k近 7 天新增 77 个 star
Open-source, self-hosted alerting for metrics, logs, and databases. Includes a built-in AI agent and MCP server.
CCccfos/nightingale14k近 7 天新增 10 个 star
Real-time Kubernetes network traffic visibility and API analysis for HTTP, gRPC, Redis, Kafka, DNS.
KUkubeshark/kubeshark12k近 7 天新增 5 个 star
Let your users work with their own data through an AI assistant, limited to what they can see.
NHnhost/nhost9.4k近 7 天新增 1 个 star