Comments: trim to the established cadence

The MCP code came in with 5–8 line file headers, JSDoc on every
one-line wrapper, and inline explanations that referenced the PR
itself ("so the MCP server can reuse it") — none of which matches
api/server.js or frontend/src/lib/, where comments are one-line,
fact-shaped and never mention the change that introduced them.

Trimmed across mcp/src/*.js, i18n-core.js, i18n.js, exercises.js,
format.js, mcp/test/tools.test.js, mcp/vitest.config.js and
mcp/README.md. Tool prefaces lost their numbers; duplicate fs.watch
rationale folded into one; the ASCII import diagram in the README
replaced with a paragraph; the cross-references and self-references
removed. Also fixed two real defects: a corrupted Cyrillic word in a
state.js comment and a missing space in a tools.test.js comment.

No code changes; 92 frontend + 32 MCP tests still pass.
This commit is contained in:
Pengboi committed 2026-07-26 19:47:52 +01:00
1 parent 4143ab8676
commit 6aaf2a3eea
11 files changed
+93 -245

No files matched your search

+8 -21
View File
@@ -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) {
+3 -15
View File
@@ -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() }
+16 -43
View File
@@ -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',
+16 -29
View File
@@ -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.',