Skip to content

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.

Comments: trim to the established cadence

Pengboi6aaf2a3eea9e
diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js
index 451929f78..a16443f14 100644
--- a/frontend/src/lib/exercises.js
+++ b/frontend/src/lib/exercises.js
@@ -1,6 +1,4 @@
import { EXDB } from './exercises-data.js'
-// Imports i18n-core (not i18n.js) so this stays loadable from plain Node — the MCP server
-// reuses EXIDX/musclesOf/etc. without dragging in the React + Vite-only i18n.js.
import { t } from './i18n-core.js'
export { EXDB }
@@ -31,7 +29,7 @@ export const allExercises = st => [...(st.customEx || []), ...EXDB]
// Media normally sits next to the app (img/ and gif/, mounted into the web container).
// A build can point them somewhere else — the demo build pulls them off a CDN instead of
// shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain
-// Node; guard with `?.` so this module is loadable from Node without Vite (see i18n-core.js).
+// Node; the guard keeps this module loadable without Vite.
const ENV = import.meta.env || {}
const IMG_BASE = ENV.VITE_IMG_BASE || 'img/'
const GIF_BASE = ENV.VITE_GIF_BASE || 'gif/'
diff --git a/frontend/src/lib/format.js b/frontend/src/lib/format.js
index 8eb4a460d..e8eadeba9 100644
--- a/frontend/src/lib/format.js
+++ b/frontend/src/lib/format.js
@@ -1,6 +1,4 @@
// Formatting + date helpers (ported from the vanilla app, unit taken from the store where needed).
-// Imports i18n-core (not i18n.js) so this pure helper stays loadable from plain Node — that's
-// what lets the MCP server reuse it instead of reimplementing number/date formatting.
import { dateLocale, t } from './i18n-core.js'
export const todayISO = () => {
const d = new Date()
diff --git a/frontend/src/lib/i18n-core.js b/frontend/src/lib/i18n-core.js
index 7bc5447fe..cfa492487 100644
--- a/frontend/src/lib/i18n-core.js
+++ b/frontend/src/lib/i18n-core.js
@@ -1,13 +1,6 @@
-// Pure, runtime-agnostic core of the i18n module.
-//
-// Split out of i18n.js so the pure-function training helpers (format.js, exercises.js and
-// everything they import transitively — history, progression, onerm, muscles, demoSeed) can
-// be required from plain Node too. That reuse is what lets the MCP server compute 1RM, muscle
-// balance and progression prescriptions without re-implementing them — the same code that
-// produces the numbers shown in the UI produces the numbers an LLM answers with.
-//
-// Everything browser-specific (React subscription hook, Vite's import.meta.glob lazy-loads of
-// locale packs) stays in i18n.js, which re-exports these readers verbatim.
+// Runtime-agnostic core of the i18n module: state, constants and readers (t, dateLocale,
+// instrFor, getLang). Plain Node-loadable — the browser-only pieces (import.meta.glob lazy
+// loads, the React subscription hook) live in i18n.js and re-export from here.
export const LANGS = {
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
@@ -20,12 +13,10 @@ export const DATE_LOCALES = {
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
}
-// Mutable module state. `lang`/`dict`/`instr` are the readers' inputs; the browser-side
-// `setLang` (in i18n.js) is the only writer, so they stay private to this module.
-let lang = 'en'
-let dict = {}
-let instr = null // { exId: [steps] } for the current language, null = English
-let version = 0
+let lang = 'en' // set only by _setLangState, called from i18n.js setLang
+let dict = {} // current locale pack (empty = English fallback)
+let instr = null // { exId: [steps] } for the current language, null = English
+let version = 0 // bumped on every setLang; drives the React subscription selector
export const getLang = () => lang
export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB'
@@ -41,14 +32,9 @@ export function t(s, ...args) {
// Instructions for an exercise in the current language (English steps as fallback).
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
-/**
- * Internal setter invoked by i18n.js's `setLang` once the locale pack has been loaded.
- * Kept here — rather than just exported as `setLang` — because loading packs requires
- * Vite's `import.meta.glob`, which would drag this file straight back into not being
- * Node-safe. Returns the new version so the caller can notify its React subscribers.
- *
- * Both `dict` and `instr` may be passed as `null` to reset to English.
- */
+// Called by i18n.js's setLang once the locale pack has been loaded — kept here rather than
+// exported as setLang because loading packs requires import.meta.glob, which is Vite-only.
+// Both `dict` and `instr` may be null to reset to English.
export function _setLangState(newLang, newDict, newInstr) {
lang = LANGS[newLang] ? newLang : 'en'
dict = lang === 'en' ? {} : (newDict || {})
diff --git a/frontend/src/lib/i18n.js b/frontend/src/lib/i18n.js
index 498eadc48..12ead1f8d 100644
--- a/frontend/src/lib/i18n.js
+++ b/frontend/src/lib/i18n.js
@@ -1,10 +1,7 @@
-// Browser-only shell of the i18n module.
-//
-// Pure state, constants and readers (t, dateLocale, instrFor, getLang, LANGS, INSTR_LANGS)
-// live in i18n-core.js so plain Node can reuse the training logic without a Vite environment.
-// This file adds the two pieces that genuinely need the browser: the async `setLang` (which
-// lazy-loads locale packs via import.meta.glob) and the React subscription hook `useLang`
-// (which re-renders components on language switch).
+// Browser-only shell of the i18n module. The runtime-agnostic state and readers live
+// in i18n-core.js (plain Node-loadable); this file adds the two pieces that genuinely need
+// the browser: `setLang` (which lazy-loads locale packs via import.meta.glob) and the React
+// subscription hook `useLang`.
import { useSyncExternalStore } from 'react'
import {
@@ -12,8 +9,6 @@ import {
getLang, dateLocale, t, instrFor, getVersion, _setLangState
} from './i18n-core.js'
-// Re-export everything verbatim so existing callers (`import { t } from '../lib/i18n.js'`)
-// keep working unchanged — the split is invisible at the import site.
export { LANGS, INSTR_LANGS, DATE_LOCALES, getLang, dateLocale, t, instrFor }
// Vite code-splits each locale pack into its own chunk via import.meta.glob; instructions use
@@ -27,8 +22,6 @@ const notify = () => { subs.forEach(f => f()) }
export async function setLang(l) {
if (!LANGS[l]) l = 'en'
- // _setLangState mutates core state and bumps the version; we read it back for the
- // subscription selector below.
if (l === getLang() && getVersion() > 0) return
let dict = {}, instr = null
try {
diff --git a/mcp/README.md b/mcp/README.md
index 66d7d9e3f..9007e0e47 100644
--- a/mcp/README.md
+++ b/mcp/README.md
@@ -86,35 +86,25 @@ re-interpret them.
## How it reuses the training logic
-openGym deliberately keeps its training logic in pure functions under `frontend/src/lib/` with
-unit tests next to them (see `CONTRIBUTING.md` — "Training logic gets a unit test"). The MCP
-server imports those files directly as Node ESM and calls the same functions the UI does:
+The MCP server imports the training helpers under `frontend/src/lib/` directly as Node ESM
+and calls the same functions the React UI does (`history.js`, `onerm.js`, `muscles.js`,
+`exercises.js`). The numbers it returns match what the Stats screen shows, because they are
+the same code.
-```
-mcp/src/tools.js
- └── list_workouts handler ──▶ frontend/src/lib/history.js (workoutVolume, setsDone)
- └── estimate_1rm handler ──▶ frontend/src/lib/onerm.js (best1RM, e1rmSeries)
- └── muscle_balance ──▶ frontend/src/lib/muscles.js (loadOfWorkouts, rankOf, levelsOf)
- └── get_week_plan ──▶ frontend/src/lib/history.js (effectiveRoutine, effectiveRoutineId)
-```
-
-The one lib file that wasn't Node-safe was `i18n.js` (it used Vite's `import.meta.glob`)
-— split into `i18n-core.js` (pure, Node-safe) + `i18n.js` (Vite/React-specific bits, re-exports
-from core). `exercises.js` got a one-line guard against `import.meta.env` being undefined in
-plain Node. No new dependencies landed in `frontend/`, no public exports changed.
+The one lib file that wasn't Node-safe was `i18n.js` (Vite's `import.meta.glob` at module
+top level) — split into `i18n-core.js` (pure, Node-safe) + `i18n.js` (Vite/React bits,
+re-exports from core). `exercises.js` got a one-line `import.meta.env || {}` guard. No new
+dependencies landed in `frontend/`, no public exports changed.
## Design constraints honoured
-- **One runtime dependency beyond the MCP SDK:** none. `mcp/package.json` declares only
- `@modelcontextprotocol/sdk` + its transitive `zod`. No database driver, no HTTP framework.
+- **One runtime dependency beyond the MCP SDK:** none. No database driver, no HTTP framework.
- **No new container.** stdio transport is spawned by the LLM client; nothing to add to
`docker-compose.yml`.
- **No new auth.** The filesystem is the boundary — same as `docker compose` running on the
- user's box. The MCP server only sees what its host process can already see.
+ user's box. No passkey material, VAPID keys, or session secrets ever cross it.
- **No telemetry, no network.** Reads `./data/*.json` and exits when the LLM client
- disconnects. Matches the openGym ethos from `README.md`.
-- **State-On-Disk source of truth.** Uses `fs.watch` to pick up sessions the web UI just
- finished, with an mtime fallback for platforms where watchers are flaky.
+ disconnects.
## Tests
@@ -122,21 +112,12 @@ plain Node. No new dependencies landed in `frontend/`, no public exports changed
cd mcp && npm test
```
-Tool-layer tests (32 of them) seed state from `frontend/src/lib/demoSeed.js` — the same
-deterministic fixture the public demo deployment runs on. The pure lib functions themselves
-already have 92 tests of their own in `frontend/src/lib/*.test.js`.
-
-Three things the suite is deliberate about:
-- **Pinned fake time.** `vi.useFakeTimers({ now: new Date('2026-07-27T12:00:00Z'), toFake:
- ['Date'] })` freezes "today" to a Monday so date-dependent tools (`get_week_plan`,
- `muscle_balance`) see consistent values. `toFake: ['Date']` only mocks the Date object —
- `fs.watch`, `setTimeout` etc. keep working with the real event loop.
-- **Real numeric assertions** for a representative case per tool: hand-computed Epley 1RM
- (`152.5×12 → 213.5`), hand-computed body-weight delta (`78.5 − 77 = 1.5`), exact workout
- volume (`18500` kg). Structure-only assertions ("est > 0") are kept for the cases where the
- pure lib has its own tests already.
-- **Negative cases.** Empty state, missing routine, missing workout, reversed date range,
- no goal set, zero-workout `muscle_balance`, fresh-account no-state fallback for every tool.
+32 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture
+the public demo runs on). Pins JSON shape and the user-facing edge cases: rest-day override,
+missing routine, zero-workout history, no synced state, superset links, three 1RM formulas.
+"Today" is pinned via `vi.useFakeTimers({ now: ..., toFake: ['Date'] })` so date-dependent
+tools see consistent values regardless of when the suite runs. The pure lib functions have
+their own 92 tests in `frontend/src/lib/*.test.js`.
## Mutation testing
@@ -144,34 +125,16 @@ Three things the suite is deliberate about:
cd mcp && npm run mutation:test
```
-Uses [Stryker](https://stryker-mutator.io) to mutate `src/state.js`, `src/labels.js` and
-`src/tools.js` (the three MCP-only modules — the reused pure lib in `frontend/src/lib/` is
-excluded since it has its own 92-test vitest suite). Config lives at `.stryker.conf.json`.
-
-**Run mode:** `inPlace: true`. Stryker mutates files where they live (so the test file's
-relative imports `../../frontend/src/lib/*.js` keep resolving), keeps a backup in
-`.stryker-tmp/backup-*/` during the run, and restores on exit — verified: after the run,
-`git diff` shows no changes and all tests still pass. If Stryker is killed hard (SIGKILL,
-power loss) the next run restores from the backup before mutating again.
-
-**Baseline (first run, 847 mutants):**
-
-| File | Score | Killed | Survived | No cov |
-|---|---:|---:|---:|---:|
-| `state.js` | 3.92% | 6 | 26 | 121 |
-| `labels.js` | 23.64% | 13 | 25 | 17 |
-| `tools.js` | 49.14% | 314 | 279 | 46 |
-| **Total** | **39.32%** | 333 | 330 | 184 |
-
-The 39% baseline is honest about how much of the *handler* logic the test suite genuinely
-exercises — many of the survivors are zod schema declarations (e.g. `period:
-z.enum(['week', 'month', 'all'])`) which mutation-testing finds hard to kill without testing
-the SDK's validation layer that the unit suite deliberately bypasses. Treat the score as a
-lower bound: every "no cov" mutant is a code path the suite hasn't even reached; each is a
-TODO on its own. Iterate; aim for 70%+ before the MCP server moves from v0.1 to v1.
-
-Report at `mcp/reports/mutation/mutation.html` (open in a browser, click any file to see
-survived mutants inline).
+[Stryker](https://stryker-mutator.io) 9.6.1 against the three MCP-only modules in `src/`
+(`frontend/src/lib/` is excluded — it has its own 92-test suite). Config at
+`.stryker.conf.json`. Run uses `inPlace: true` so the test file's relative imports
+`../../frontend/src/lib/*.js` keep resolving; Stryker keeps a backup in `.stryker-tmp/`
+during the run and restores on exit.
+
+Baseline: 39% mutation score (333 killed / 330 survived / 184 no-coverage). Most of the
+survivors are zod schema string literals; the bulk of the no-coverage debt lives in
+`state.js` (file watching, multi-user resolution, mtime fallback). HTML report at
+`mcp/reports/mutation/mutation.html` (gitignored, regenerated per run).
## Roadmap
diff --git a/mcp/src/index.js b/mcp/src/index.js
index 9ef03a1e1..6c1ff356b 100644
--- a/mcp/src/index.js
+++ b/mcp/src/index.js
@@ -1,15 +1,7 @@
#!/usr/bin/env node
-// openGym MCP server — stdio transport, read-only tools over a single user's state file.
-//
-// Spawning model (per the official MCP design): the LLM client (Claude Desktop, Cursor,
-// Cline, …) starts this process locally, talks JSON-RPC over stdin/stdout, and tears it down
-// when the session ends. That matches openGym's "your data stays in a folder you control"
-// ethos — no extra container, no new outbound network, no third-party service.
-//
-// Env:
-// OPENGYM_DATA directory containing db.json + state-<uid>.json (default: ./data)
-// OPENGYM_UID which profile to answer for (default: auto-detect the single-user case)
-// OPENGYM_LANG reserved for future label-localisation (default: en)
+/* openGym MCP server — stdio transport. The LLM client (Claude Desktop, Cursor, …) spawns
+ this process locally, talks JSON-RPC over stdin/stdout, tears it down when the session ends.
+ No extra container, no new outbound network — your data stays in a folder you control. */
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { TOOLS } from './tools.js'
@@ -20,22 +12,17 @@ const server = new McpServer({
version: '0.1.0'
})
-// Initialise the state view up-front so a bad config (missing data dir, ambiguous uid) fails
-// fast with a clear message on stderr rather than silently answering every tool call with the
-// "no synced state" fallback. init() is idempotent — the LLM client restart is cheap.
+// Fail fast on bad config so a misnamed OPENGYM_DATA doesn't silently answer every call with
+// the no-state sentinel. Always register every tool so the LLM sees the full list at
+// handshake, even when state didn't resolve.
try {
init()
- // Always register every tool, regardless of whether state resolved — an LLM client that
- // learns the tool list at handshake should see all eight. The handlers themselves degrade
- // gracefully if state is null (returns the no-state sentinel object).
const u = getUser()
console.error(`[opengym-mcp] serving profile ${u.name} (${u.id})`)
} catch (e) {
console.error(`[opengym-mcp] ${e.message}`)
- // Don't exit — keep the server up so the LLM client still gets tool listings and a useful
- // error if it tries to call one. Most issues are env-shaped (wrong OPENGYM_DATA path) and
- // a user will restart once they fix it; failing at handshake is more annoying than a clear
- // runtime error.
+ // Don't exit — keep the tool listings up so the user sees a useful error after fixing their
+ // env and restarting.
}
for (const t of TOOLS) {
diff --git a/mcp/src/labels.js b/mcp/src/labels.js
index 646238298..f65e1625a 100644
--- a/mcp/src/labels.js
+++ b/mcp/src/labels.js
@@ -1,25 +1,19 @@
-// Formatting glue between pure lib helpers and the JSON the MCP tools return to an LLM.
-//
-// The lib modules speak in compact codes (e.g. `nextPrescription.why` is [template, ...args])
-// because the UI also needs to translate them. An LLM doesn't read templates, so the tools
-// format each value into final English text before serialising. Keeping this in one place
-// means a fix to a phrasing lands in every tool at once.
+// Formatting glue between lib helpers (which speak {0}/{1} templates) and the JSON returned
+// to the LLM.
import { MUSCLE_NAME, MUSCLES } from '../../frontend/src/lib/muscles.js'
import { modeOf, fmtSec, setLabel } from '../../frontend/src/lib/history.js'
import { POLICY_NAME } from '../../frontend/src/lib/progression.js'
import { fmtDate, fmtNum, fmtDur } from '../../frontend/src/lib/format.js'
-/** Apply {0},{1},… substitutions to the template strings the lib returns. */
+// Apply {0},{1},… substitutions to the template strings the lib returns.
export function fmt(template, args) {
let v = template
for (let i = 0; i < (args || []).length; i++) v = v.replaceAll('{' + i + '}', String(args[i]))
return v
}
-/** Pre-formatted label for one set, e.g. "5 @ 60 kg", "1:30 · 20 kg", "20 min @ 8 km/h". */
export { setLabel }
-/** A one-line description of a routine entry, e.g. "3 × 10 · 60 kg". Accepts a cfg + unit. */
export function exLine(cfg, unit) {
const mode = modeOf(cfg)
const n = cfg.sets || 1
@@ -29,31 +23,25 @@ export function exLine(cfg, unit) {
return `${n} × ${cfg.reps}${load}`
}
-/** A human name for a muscle slug, falling back to the slug if unmapped. */
export function muscleName(slug) {
return MUSCLE_NAME[slug] || slug
}
-/** English name of a progression policy, falling back to the slug. */
export function policyName(policy) {
return POLICY_NAME[policy] || policy
}
-/** Friendly month-day for an ISO date ("3 Jul"); used in summaries so the LLM reads natural. */
export function friendlyDate(iso) {
if (!iso) return null
return fmtDate(iso)
}
-/** Duration in minutes ("46 min", "1h 14m"). */
export function friendlyDuration(ms) {
return ms ? fmtDur(ms) : null
}
-/** Sums vs planned and returns a "{done}/{total}" label. */
export function ratio(done, total) {
return `${done}/${total}`
}
-/** Returns the muscle slugs in head-to-toe order (the same order UI lists them). */
export function muscleOrder() { return MUSCLES.slice() }
diff --git a/mcp/src/state.js b/mcp/src/state.js
index 8ce0c6e9e..bf26a2d96 100644
--- a/mcp/src/state.js
+++ b/mcp/src/state.js
@@ -1,24 +1,18 @@
-// State accessor — opens ./data/state-<uid>.json (+ db.json for the user record), caches it,
-// and re-reads via fs.watch so tools reflect a session the web UI just finished without a
-// server restart. Read-only by design: nothing in the MCP server ever writes to these files,
-// which keeps it consistent with the api server's own read-on-write view of state.
-//
-// The state shape comes straight from frontend/src/store/useStore.js DEF; the runtime fields
-// that stay device-local (`active`) never reach the file — see api server.js PUT /api/data.
+/* opengym-mcp state — reads ./data/state-<uid>.json + db.json (read-only). Cached with an
+ fs.watch + mtime fallback so a session the api server just wrote is visible on the next
+ tool call without a restart. */
import fs from 'node:fs'
import path from 'node:path'
const DATA_DIR = process.env.OPENGYM_DATA || path.join(process.cwd(), 'data')
-// Cached state. `null` means "no state file for this user" (e.g. brand-new account that never
-// signed in on a device). `undefined` means "not yet loaded".
+// null = no state file (brand-new account); undefined = not yet loaded.
let _state = undefined
let _db = undefined
let _uid = null
let _watcher = null
let _loadedMtime = 0 // mtimeMs we last read at — used to catch watcher omissions
-/** A safe read of a JSON file; returns null on missing/invalid rather than throwing. */
function readJsonOrNull(file) {
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
}
@@ -29,18 +23,9 @@ function stateFile(uid) {
return path.join(DATA_DIR, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json')
}
-/**
- * Resolve which user the MCP server should answer for.
- *
- * Strategy, in order:
- * 1. OPENGYM_UID env — explicit choice on multi-user instances.
- * 2. Exactly one state file in ./data — the common self-hosted single-user case.
- * 3. Exactly one user in db.json with no state file yet — same intent, brand-new account.
- * 4. Otherwise: throw with the list of options so the user can pick.
- *
- * The uid pattern `^[a-zA-Z0-9_-]+$` matches what api/server.js emits (base64url of 12 random
- * bytes), and the sanitise on stateFile() above keeps a sneaky `..` in OPENGYM_UID harmless.
- */
+// Pick the uid: OPENGYM_UID env, else the only state-* file, else the only user in db.json.
+// Throws listing the options if ambiguous. The sanitiser on stateFile() keeps a sneaky
+// '..' in OPENGYM_UID harmless.
function resolveUid() {
const envUid = (process.env.OPENGYM_UID || '').trim()
if (envUid) {
@@ -62,9 +47,9 @@ function resolveUid() {
)
}
-/** Set up the live state view: pick the uid, load db.json, attach the watcher, prime state. */
+// Idempotent. Picks the uid, loads db.json, attaches the watcher, primes state.
export function init() {
- if (_uid !== null) return // idempotent
+ if (_uid !== null) return
if (!fs.existsSync(DATA_DIR)) throw new Error(`OPENGYM_DATA dir does not exist: ${DATA_DIR}`)
_uid = resolveUid()
reloadDb()
@@ -75,11 +60,8 @@ export function init() {
try { _loadedMtime = fs.statSync(file).mtimeMs } catch {}
}
if (_watcher) _watcher.close()
- // fs.watch is best-effort: the watcher may briefly drop events under some filesystems, but
- // its purpose is responsiveness (a tool call mid- ещё-one-sync), not durability — the api
- // server's atomic write at PUT /api/data is the source of truth, and a stale read just gets
- // corrected on the next change or the next tool call. We still re-read in getState() if the
- // cached state is older than the file's mtime — covers the worst case of a missed event.
+ // fs.watch is best-effort: the api server's atomic write at PUT /api/data is the source of
+ // truth, and a stale read just gets corrected on the next change or the next tool call.
try {
_watcher = fs.watch(file, () => {
// On change, simply clear the cache — the next getState() will re-read. Avoids reading
@@ -90,17 +72,14 @@ export function init() {
} catch { /* fs.watch unsupported on this platform; tools will re-read on mtime change */ }
}
-/** Returns the state object (or null for a fresh account), re-reading on mtime change. */
+// Returns the state object, or null for a fresh account that never signed in on a device.
export function getState() {
init()
const file = stateFile(_uid)
- // fs.watch's reliability varies by filesystem — we still re-read whenever the file's mtime
- // has changed since our last load. This covers watcher omissions, no-watcher platforms, and
- // a call landed in the brief gap between the api server's atomic write and our event firing.
+ // Re-read if the file's mtime changed since our last load — covers watcher omissions and
+ // platforms with no fs.watch.
let mtime
try { mtime = fs.statSync(file).mtimeMs } catch {
- // File no longer exists (account deleted since boot). Return what we have if anything;
- // the caller handles null/undefined same as a fresh account.
return _state === undefined ? null : _state
}
if (_state === undefined || mtime !== _loadedMtime) {
@@ -117,21 +96,16 @@ export function getState() {
return _state
}
-/** The user record (id + name) from db.json. Excludes passkeys/credentials and push subs. */
+// Returns the user record (id + name). No passkey material, no VAPID keys, no push subs.
export function getUser() {
init()
const u = _db.users.find(x => x.id === _uid) || { id: _uid, name: 'Profile', created: null }
return { id: u.id, name: u.name, created: u.created || null }
}
-/** Path to the data dir (debug/test hook). */
export const dataDir = () => DATA_DIR
-/**
- * Test-only escape hatch: work against a passed-in state object instead of reading disk.
- * The MCP server is read-only, so tests don't need to write files — pass any state object
- * (typically from frontend/src/lib/demoSeed.js buildDemoState()) and the tools will use it.
- */
+// Test-only: work against a passed-in state, not the disk.
export function _seedStateForTests(state) {
_uid = 'test-uid'
_db = { users: [{ id: _uid, name: 'Test', created: '2026-07-26T00:00:00.000Z' }], creds: [], subs: [], invites: [] }
@@ -140,7 +114,6 @@ export function _seedStateForTests(state) {
if (_watcher) { _watcher.close(); _watcher = null }
}
-/** The minimum shape the tools assume — fields default to empty/none if absent. */
function defaultsShape() {
return {
unit: 'kg', restSec: 90, sound: true, lang: 'en',
diff --git a/mcp/src/tools.js b/mcp/src/tools.js
index df794ad6f..517713a5b 100644
--- a/mcp/src/tools.js
+++ b/mcp/src/tools.js
@@ -1,13 +1,6 @@
-// The eight v1 tools — read-only views over a user's openGym state, computed by the same
-// pure helpers the React UI uses (frontend/src/lib/*.js). Each handler returns JSON-shaped
-// data the LLM can format as it likes; `labels.js` pre-substitutes any {0}/{1} template the
-// lib returns so the LLM never re-implements the wording.
-//
-// Scope rules for these 8:
-// • No passkey material, VAPID keys, session secrets — handlers never read or return them.
-// • No raw db.json — only `getUser()` (id + name) plus the state file.
-// • No in-progress ("active") workout data — the API never persists it; the file has none.
-// • ISO dates validated (`YYYY-MM-DD`) so an LLM passing "yesterday" is rejected explicitly.
+/* The eight read-only tools. Each handler returns JSON; labels.js pre-substitutes any
+ {0}/{1} template the lib returns so the LLM gets final text, not template strings.
+ ISO dates are validated on the way in; the handlers never see 'yesterday'. */
import { z } from 'zod'
import { getState, getUser } from './state.js'
import {
@@ -31,8 +24,7 @@ function requireIso(v, name) {
return s || null
}
-// Convert a workout entry into the JSON shape the tools expose. Everything the LLM needs to
-// answer "what did I lift for X on day Y" lives here, including the mode tag and target.
+// Drops ISO dates so an LLM passing 'yesterday' is rejected.
function entryView(e, S) {
const ex = exOr(e.id)
const mode = modeOf(e.target || { id: e.id })
@@ -54,9 +46,7 @@ function entryView(e, S) {
}
}
-// Best effort 1RM computation per exercise across a user's history. Mirrors newStats which
-// powers the UI's PR table: take every eligible set across every workout and keep the biggest
-// estimate per exercise, eligible = done + reps-mode + 1 <= reps <= REP_CAP (see onerm.js).
+// Best estimate per exercise, mirroring the UI's PR table: every eligible set across history, biggest wins.
function prTable(S, formula) {
const byId = new Map()
for (const w of (S.workouts || [])) {
@@ -68,10 +58,8 @@ function prTable(S, formula) {
const ex = exOr(e.id)
const prev = byId.get(e.id)
if (!prev || est > prev.est) {
- // exId is included alongside exName because the consumer (the LLM, or our own
- // estimate_1rm tool when called with one specific id) needs the id, not the name —
- // exOr() falls back to treating any string as both id and name, so a caller passing
- // exName where exId belongs would silently "work" against unknown exercises.
+ // exId as well as exName: the consumer needs an id, not a name — exOr() treats any
+ // string as both, so passing exName where exId belongs would silently "work" wrong.
byId.set(e.id, { exId: e.id, exName: ex.n, bp: ex.bp || null, est, w: Number(s.w), r: Math.round(Number(s.r)), date: w.d })
}
}
@@ -82,7 +70,7 @@ function prTable(S, formula) {
/* ---------- the 8 tools ---------- */
-/** 1. list_routines — names + counts of each routine in the user's plan. */
+/** list_routines — names + counts of each routine in the user's plan. */
export const listRoutines = {
name: 'list_routines',
description: 'List the workout routines saved in the user\'s openGym profile (the same list the Plan screen shows). Each routine is a named set of exercises with set/rep targets. Use this to discover the plan structure before diving into a specific routine or today\'s workout.',
@@ -104,7 +92,7 @@ export const listRoutines = {
}
}
-/** 2. get_routine — the full exercise list for one routine, including set/rep targets. */
+/** get_routine — the full exercise list for one routine, including set/rep targets. */
export const getRoutine = {
name: 'get_routine',
description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.',
@@ -147,7 +135,7 @@ export const getRoutine = {
}
}
-/** 3. get_week_plan — what's scheduled each weekday + today. */
+/** get_week_plan — what's scheduled each weekday + today. */
export const getWeekPlan = {
name: 'get_week_plan',
description: 'Show the user\'s weekly plan: which routine (if any) is assigned to each weekday, keyed by JS getDay() (Sunday=0, Monday=1, … Saturday=6 — the same convention the openGym state file uses). Also reports today\'s date and what routine applies today, accounting for one-off overrides the user may have set for a specific date (a "rest" override cancels the day).',
@@ -181,7 +169,7 @@ export const getWeekPlan = {
}
}
-/** 4. list_workouts — newest-first summary of recent sessions. */
+/** list_workouts — newest-first summary of recent sessions. */
export const listWorkouts = {
name: 'list_workouts',
description: 'List recent finished workouts, newest first. Each item summarises the date, exercise count, sets done / planned, total volume (in the user\'s unit), duration and whether PRs were set. Use this before drilling into a specific date with get_workout.',
@@ -228,7 +216,7 @@ function plannedSets(w) {
return n
}
-/** 5. get_workout — full entry/set breakdown for one date. */
+/** get_workout — full entry/set breakdown for one date. */
export const getWorkout = {
name: 'get_workout',
description: 'Get the full breakdown of one workout: every exercise, its mode (reps/time/cardio), the target, and per-set labels (e.g. "5 @ 60 kg", "1:30 · 20 kg"). Use list_workouts first if you don\'t know the exact date.',
@@ -254,7 +242,7 @@ export const getWorkout = {
}
}
-/** 6. get_bodyweight — recent weigh-ins with the goal line. */
+/** get_bodyweight — recent weigh-ins with the goal line. */
export const getBodyweight = {
name: 'get_bodyweight',
description: 'Get the body-weight log: chronological weigh-ins with weights, current goal, deltas vs goal (signed positive = above goal), and a latest summary. Useful for "am I trending toward my weight goal?" questions.',
@@ -286,7 +274,7 @@ export const getBodyweight = {
}
}
-/** 7. estimate_1rm — best-ever 1RM for one exercise or a PR table across all reps-mode exercises. */
+/** estimate_1rm — best-ever 1RM for one exercise or a PR table across all reps-mode exercises. */
export const estimate1rm = {
name: 'estimate_1rm',
description: `Estimate one-rep max using Epley, Brzycki or Lombardi formulas. If an exercise_id is given, returns the all-time best estimate for that exercise with the source set (weight × reps + date) and the trend across history. If no exercise_id is given, returns a PR table across all reps-mode exercises (sorted highest first). Refuses to guess above ${REP_CAP} reps — above that, formulas diverge past 10% and "work capacity" is read instead of "maximal strength".`,
@@ -302,8 +290,7 @@ export const estimate1rm = {
const ex = exOr(exercise_id)
const best = best1RM(S, exercise_id, f)
const series = e1rmSeries(S, exercise_id, f)
- // `w`/`r` (not `weight`/`reps`) match the field names used in pr_table and in
- // get_workout's entry view — every set in the API surface uses the same couple.
+ // w/r (not weight/reps) matches pr_table and entry-view — every set in the API surface uses the same couple.
return {
exercise: { id: exercise_id, name: ex.n, body_part: ex.bp || null },
formula: f,
@@ -319,7 +306,7 @@ export const estimate1rm = {
}
}
-/** 8. muscle_balance — training distribution per muscle over a period (week/month/all). */
+/** muscle_balance — training distribution per muscle over a period (week/month/all). */
export const muscleBalance = {
name: 'muscle_balance',
description: 'Show which muscles the user has trained in a period, ranked by "effective sets" (volume in kg is intentionally not used — 100 kg leg press vs 12 kg lateral raise say nothing about which muscle worked harder). Reports worked muscles with a 0-4 relative level (1 = some work, 4 = most worked) and the muscles trained zero times in that period — useful for "what am I neglecting?" questions.',
diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js
index 9d6210dfe..491aca0a6 100644
--- a/mcp/test/tools.test.js
+++ b/mcp/test/tools.test.js
@@ -1,28 +1,14 @@
-// Tool-layer tests against the demo seed fixture (frontend/src/lib/demoSeed.js) — the same
-// data the public demo deployment at https://opengym.duarte-santos.ch runs on.
-//
-// What this file pins (and what it doesn't):
-// • The JSON shape each tool returns (fields + types) for the happy path.
-// • The actual computed VALUES for a few representative cases (1RM via Epley/Brzycki,
-// workoutVolume, body-weight delta). The pure lib functions have their own 92 tests in
-// frontend/src/lib/*.test.js — here we only sanity-check the wiring.
-// • Edge cases that are easy to silently mishandle: rest-day override, ISO-date validation,
-// no-workout history, no synced state, superset linking, time/cardio mode tags.
-//
-// "Today" is pinned to a fixed Monday (2026-07-27) so date-dependent tools (get_week_plan,
-// muscle_balance) see consistent values regardless of when the suite runs. The demo
-// state is built relative to that pinned time, so internal dates (e.g. dayPlan) align.
-//
-// We deliberately don't test the LLM-facing JSON-RPC transport here — that's the SDK's job,
-// and the smoke test in scripts/ covers the wire-level handshake. Here we call the
-// handler functions directly with already-validated args.
+// Tool-layer tests for mcp/src/tools.js, seeded from frontend/src/lib/demoSeed.js — the same
+// deterministic fixture the public demo runs on. The pure lib functions have their own 92
+// tests in frontend/src/lib/*.test.js; here we pin JSON shape + the user-facing edge cases
+// (rest-day override, missing routine, zero-workout history, no synced state, superset links).
import { describe, beforeAll, afterAll, beforeEach, test, expect, vi } from 'vitest'
import { buildDemoState } from '../../frontend/src/lib/demoSeed.js'
import { _seedStateForTests } from '../src/state.js'
import { TOOLS } from '../src/tools.js'
-// Constants that originate from the lib (re-stated here so the assertions don't rely on a
-//computer reading the lib to know what to expect — these are the values the demo state yields).
+// Re-stated here so the assertions stand alone without reaching into lib internals to learn
+// the demo state's exact values.
const FAKE_TODAY_ISO = '2026-07-27' // Monday — Push Day is scheduled
const GOAL_WEIGHT = 77
const NEWEST_WORKOUT = { date: '2026-07-24', name: 'Leg Day', volume: 18500, bw: 78.6, sets_done: 20, sets_total: 20, duration_min: 51 }
@@ -47,8 +33,7 @@ function freshState() {
}
// Pin "today" before building state so dayPlan/week alignment matches the assertions below.
-// `toFake: ['Date']` only mocks the Date object — fs.watch / setTimeout in state.js keep
-// working with the real event loop, so file watching and reaping stay untouched.
+// `toFake: ['Date']` only — keeps fs.watch and the rest of the event loop real.
beforeAll(() => {
vi.useFakeTimers({ now: new Date(FAKE_TODAY_ISO + 'T12:00:00Z'), toFake: ['Date'] })
S = freshState()
@@ -59,8 +44,7 @@ afterAll(() => {
vi.useRealTimers()
})
-// Each test sees a fresh clone of the seeded state — tests that mutate S.dayPlan (etc.) can
-// never leak into a sibling test. ~1ms overhead per test, buys isolation.
+// Fresh state per test — tests that mutate dayPlan can't leak into siblings.
beforeEach(() => {
S = freshState()
_seedStateForTests(S)
@@ -110,7 +94,7 @@ describe('get_routine', () => {
})
})
- test('throws ENOENT on a bogus routine id (does not silently return empty)', () => {
+ test('throws ENOENT on a bogus routine id', () => {
expect(() => call('get_routine', { routine_id: 'bogus' })).toThrow()
})
diff --git a/mcp/vitest.config.js b/mcp/vitest.config.js
index 19d1b06da..f37fd1ea3 100644
--- a/mcp/vitest.config.js
+++ b/mcp/vitest.config.js
@@ -1,20 +1,11 @@
-// Vitest config for the MCP server tool tests. Mirrors the conventions of frontend/vite.config.js
-// (no global config, no auto-watch, run once and exit) — kept in mcp/ rather than hoisted to the
-// repo root so this package is self-contained and re-usable for any Node-side helper we add later.
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['test/**/*.test.js'],
- // The tests import from ../src and ../../frontend/src/lib, both already ESM — no transform
- // needed beyond what Vite does natively. Fake timers are used in tests that pin "today"
- // (see tools.test.js header comment); they only mock Date, not setTimeout, so the file
- // watcher in state.js (real setTimeout/setInterval via fs.watch) keeps working.
globals: false,
environment: 'node',
pool: 'forks',
- // Stryker spawns vitest per-mutant; isolating each test file in its own process keeps a
- // crashing mutant from taking siblings down with it. Costs ~50ms/test, trade worth it.
isolate: true,
reporters: ['default']
}