Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
MCP log_workout: 20 saves an hour, a stderr line per save, no em dashes for the model (#739)
Duarte Santosbeed2965e44a
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex ef411547b..c6e097339 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -34,7 +34,7 @@ flowchart LRW <-- WatchConnectivity --> II -- App Group snapshot --> WG- MCP["mcp/ (optional)<br/>stdio, read-only"] -.reads.-> D+ MCP["mcp/ (optional)<br/>stdio, reads data, logs via API"] -.reads.-> DAI["AI provider<br/>(optional Coach)"]API -.Coach jobs.-> AII -.on-device Coach.-> AI@@ -57,7 +57,7 @@ in a file in the app's private storage (MOBILE.md explains the modes).| `api/coach/` | The optional AI Coach. `core/` has no server state and is shared with the phone apps || `web/` | The nginx image: builds the frontend, adds `catalogue/media`, proxies `/api` || `catalogue/` | The exercise database: one JSON per exercise, translations, the licensed 180 px media |-| `mcp/` | Optional MCP server, read-only, for AI clients on the same machine |+| `mcp/` | Optional MCP server for AI clients: reads the data folder, `log_workout` saves through the API || `scripts/` | Build and release helpers, see [scripts/README.md](../scripts/README.md) || `website/` | opengym.ch, plain HTML || `helm/`, `kubernetes/`, `contrib/nix/` | Other ways to deploy |diff --git a/mcp/README.md b/mcp/README.mdindex f53501bf6..588c323fa 100644--- a/mcp/README.md+++ b/mcp/README.md@@ -112,6 +112,10 @@ between two entries: "lever chest press" is two in the library, and a name likematches nothing, comes back as a question with candidates. It only creates one of your ownexercises when you confirm the library has none.+It saves at most 20 workouts an hour (a forgotten week is fine, a client stuck in a loop is+not), and each save leaves one line on the MCP server's stderr with the workout's id, day and+the server revision it landed at. Workouts it logged have ids starting with `mw`.+### PairingWrites go through the api rather than straight into `./data`, because the api is what keeps adiff --git a/mcp/src/api-client.js b/mcp/src/api-client.jsindex c439e9f5f..1b58dce0f 100644--- a/mcp/src/api-client.js+++ b/mcp/src/api-client.js@@ -27,7 +27,7 @@ function fail(code, message, extra) {export function apiBase(raw) {let utry { u = new URL(String(raw || '').trim()) } catch {- throw fail('ENOCONFIG', 'OPENGYM_URL is not a URL — the address you open openGym at, e.g. https://gym.example.com')+ throw fail('ENOCONFIG', 'OPENGYM_URL is not a URL: the address you open openGym at, e.g. https://gym.example.com')}if (u.protocol !== 'https:' && !(u.protocol === 'http:' && LOOPBACK.has(u.hostname))) {throw fail('ENOCONFIG', 'OPENGYM_URL must be https:// (plain http only for localhost): the token it carries is a full sign-in to your profile')diff --git a/mcp/src/write-tools.js b/mcp/src/write-tools.jsindex b1c8ae046..64d0386e5 100644--- a/mcp/src/write-tools.js+++ b/mcp/src/write-tools.js@@ -19,6 +19,12 @@ const hhmm = t => { const d = new Date(t); return String(d.getHours()).padStart(// Two writers racing the same profile resolve in a round or two; past that something keeps// writing, and the user is better told than retried at.const MAX_ATTEMPTS = 3+// Saves per hour, per MCP process. Logging a week someone forgot is a handful; a client looping on+// the tool is not, and each save is a full profile write on the server that every device pulls.+export const WRITE_LIMIT = 20+const WINDOW_MS = 60 * 60000+let saves = []+export const _resetWriteWindow = () => { saves = [] }function fail(code, message) {const err = new Error(message)@@ -84,9 +90,9 @@ function viewOf(w, S, resolved) {}const setSchema = z.object({- reps: z.number().int().min(1).max(LOG_LIMITS.maxReps).optional().describe('Reps done. Give reps for a rep exercise, or seconds for a hold — never both in one exercise.'),+ reps: z.number().int().min(1).max(LOG_LIMITS.maxReps).optional().describe('Reps done. Give reps for a rep exercise, or seconds for a hold, never both in one exercise.'),seconds: z.number().min(1).max(LOG_LIMITS.maxSec).optional().describe('Seconds held, for a timed exercise (plank, hang, wall sit).'),- weight: z.number().min(0).optional().describe('Load in `unit`. Omit or 0 for bodyweight. On an assistance machine it is the help (less is better). For dumbbells: as the profile logs that exercise — see weight_means in the reply.'),+ weight: z.number().min(0).optional().describe('Load in `unit`. Omit or 0 for bodyweight. On an assistance machine it is the help (less is better). For dumbbells: as the profile logs that exercise (see weight_means in the reply).'),warmup: z.boolean().optional().describe('A warm-up set: kept out of volume, PRs and the next suggested weight.'),failure: z.boolean().optional().describe('Taken to failure.'),rir: z.number().min(0).max(10).optional().describe('Reps in reserve, if the user said it. Not with rpe.'),@@ -126,6 +132,10 @@ export const logWorkout = {const opts = fetchImpl ? { fetchImpl } : {}// One clock for every attempt: a retry after a conflict files the same workout, not a later one.const now = Date.now()+ saves = saves.filter(t => now - t < WINDOW_MS)+ if (!params.dry_run && saves.length >= WRITE_LIMIT) {+ throw fail('ERATE', `log_workout already saved ${WRITE_LIMIT} workouts in the last hour, the most it takes in one go; nothing was saved. Wait a bit, or log the rest in the app.`)+ }const input = inputOf({ ...params, date: params.date || localIso(new Date(now)) })const me = await apiFetch(cfg, '/api/me', opts)@@ -173,6 +183,11 @@ export const logWorkout = {const put = await apiFetch(cfg, '/api/data', { ...opts, method: 'PUT', body: { state: S, baseRev: got.body.rev ?? 0, ...(typeof doc._wid === 'string' ? { baseWid: doc._wid } : {}) } })if (put.status !== 409) {invalidate()+ saves.push(now)+ // The operator's trail (stderr, as the profile guard's): which workout went in, for what+ // day and at which revision. Never the token, and nothing the model sees.+ const sets = added.workout.entries.reduce((n, e) => n + e.sets.length, 0)+ console.error(`[opengym-mcp] log_workout saved ${added.workout.id} for ${added.workout.d} (${added.workout.entries.length} exercises, ${sets} sets), rev ${put.body?.rev ?? '?'}`)return { logged: true, ...viewOf(added.workout, S, built), revision: put.body?.rev ?? null }}// Another device wrote in between: the server sent its current document back with the 409,@@ -183,7 +198,7 @@ export const logWorkout = {}got = { status: 200, body: { state: put.body.state, rev: put.body.rev } }}- throw fail('ECONFLICT', `the profile kept changing on the server (${MAX_ATTEMPTS} attempts); nothing was saved — try again in a moment`)+ throw fail('ECONFLICT', `the profile kept changing on the server (${MAX_ATTEMPTS} attempts); nothing was saved, try again in a moment`)},}diff --git a/mcp/test/write-tools.test.js b/mcp/test/write-tools.test.jsindex 9de19fe3c..89816da82 100644--- a/mcp/test/write-tools.test.js+++ b/mcp/test/write-tools.test.js@@ -1,9 +1,9 @@// log_workout against a stand-in for the api: a node:http server that answers /api/me and// /api/data the way api/server.js does, and records what it is sent. What the real server does// with the write is log-workout.e2e.test.js; the arithmetic is frontend/src/lib/log-workout.test.js.-import { describe, test, expect, beforeEach, afterEach } from 'vitest'+import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest'import http from 'node:http'-import { logWorkout } from '../src/write-tools.js'+import { logWorkout, WRITE_LIMIT, _resetWriteWindow } from '../src/write-tools.js'import { apiBase, apiConfig } from '../src/api-client.js'import { _seedStateForTests } from '../src/state.js'@@ -42,6 +42,7 @@ function stubApi(doc, script = {}) {}))}afterEach(() => api?.server.close())+beforeEach(() => _resetWriteWindow())const DOC = () => ({ unit: 'kg', workouts: [], routines: [{ id: 'r1', name: 'Push', ex: [] }], customEx: [], exWeights: {}, edited: { restSec: 5 }, restSec: 120, _wid: 'w-abc', _ts: 1 })const CURLS = { exercises: [{ exercise: 'dumbbell curl', sets: [{ reps: 12, weight: 12 }, { reps: 12, weight: 12 }, { reps: 10, weight: 12, failure: true }] }] }@@ -233,6 +234,47 @@ describe('found in review', () => {})})+describe('limits and the trail a write leaves', () => {+ beforeEach(async () => { api = await stubApi(DOC()) })+ const day = n => { const d = new Date(Date.now() - n * 86400000); return { ...CURLS, start: '07:00', date: d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0') } }++ test('a client looping on log_workout is stopped after WRITE_LIMIT saves, before it even reads the profile', async () => {+ for (let i = 1; i <= WRITE_LIMIT; i++) expect((await call(day(i))).logged).toBe(true)+ const gets = api.gets+ const err = await call(day(WRITE_LIMIT + 1)).catch(e => e)+ expect(err.code).toBe('ERATE')+ expect(err.message).not.toContain('—')+ expect(api.gets).toBe(gets)+ expect(api.puts).toHaveLength(WRITE_LIMIT)+ })++ test('dry runs and duplicates are not saves and do not use the budget up', async () => {+ for (let i = 0; i < WRITE_LIMIT + 2; i++) await call({ ...CURLS, dry_run: true })+ expect((await call(CURLS)).logged).toBe(true)+ for (let i = 0; i < WRITE_LIMIT + 2; i++) expect((await call(CURLS)).duplicate).toBe(true)+ expect((await call(day(3))).logged).toBe(true)+ })++ test('every saved workout leaves one line on stderr for the operator: what, when, which revision, never the token', async () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})+ try {+ const r = await call(CURLS)+ await call({ ...CURLS, dry_run: true })+ const lines = spy.mock.calls.map(c => c.join(' ')).filter(l => l.includes('log_workout'))+ expect(lines).toHaveLength(1)+ expect(lines[0]).toContain(r.workout_id)+ expect(lines[0]).toContain(r.date)+ expect(lines[0]).toContain('rev 8')+ expect(lines[0]).not.toContain(TOKEN)+ } finally { spy.mockRestore() }+ })++ test('what the model reads has no em dashes', () => {+ const texts = [logWorkout.description, ...Object.values(logWorkout.schema).map(z => z.description || '')]+ for (const t of texts) expect(t).not.toContain('—')+ })+})+describe('configuration', () => {test('missing config is ENOCONFIG naming both variables', async () => {await expect(logWorkout.handler(CURLS, { env: {} })).rejects.toMatchObject({ code: 'ENOCONFIG', message: expect.stringContaining('OPENGYM_TOKEN') })