MCP: read-only stdio server for LLM apps to query workout history

A Model Context Protocol bridge that lets an external LLM application (Claude Desktop,
Cursor, Cline, Continue, …) read a user's openGym profile directly from ./data — no new
container, no extra auth, no third-party service. The LLM client spawns the server
locally as a stdio process (per the official MCP model); reads the same state-<uid>.json
the api server writes; reuses the pure training helpers from frontend/src/lib/*.js so
the numbers it answers with match what the Stats screen shows exactly.

Eight tools in v1, all read-only:
 · list_routines, get_routine — names + exercise counts + per-exercise targets
 · get_week_plan — Mo/We/Fr assignments and today's routine, accounting for any
   date-specific overrides (a "rest" override cancels the day)
 · list_workouts, get_workout — newest-first session summaries + per-set breakdown
 · get_bodyweight — weigh-ins with the goal line and signed deltas vs goal
 · estimate_1rm — Epley/Brzycki/Lombardi formulas, all-time best + trend per exercise,
   or a PR table across all reps-mode exercises
 · muscle_balance — which muscles are trained vs neglected over a week/month/all window

State is read with fs.watch (mtime fallback for platforms where watchers are flaky) so
the server reflects a session the web UI just finished without a restart. No passkey
material, VAPID keys, or session secrets ever cross the boundary — handlers only ever
serialize fields from the state object plus the user's name from db.json.

The MCP server has exactly one runtime dependency beyond the SDK: none. zod is the SDK's
transitive; vitest and Stryker are devDeps only. Tests run against the demo seed fixture
(demoSeed.js) — 32 cases pinning the JSON shape and the most user-facing edge cases
(empty state, missing routine, rest-day override, zero-workout muscle_balance, three
1RM formulas, superset links, timed/cardio set labels).
This commit is contained in:
Pengboi committed 2026-07-26 19:34:09 +01:00
1 parent fadeb17b6c
commit 92914dea43
9 files changed
+5641

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
#!/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)
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { TOOLS } from './tools.js'
import { init, getUser } from './state.js'
const server = new McpServer({
name: 'opengym',
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.
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.
}
for (const t of TOOLS) {
server.tool(
t.name,
t.description,
t.schema,
async (params) => {
try {
const result = t.handler(params || {})
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] }
} catch (err) {
const code = err.code || 'ERROR'
return {
isError: true,
content: [{ type: 'text', text: `${code}: ${err.message}` }]
}
}
}
)
}
const transport = new StdioServerTransport()
await server.connect(transport)
// Process stays alive serving JSON-RPC over stdio until the LLM client disconnects.
+59
View File
@@ -0,0 +1,59 @@
// 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.
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. */
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
const load = cfg.weight ? ' · ' + fmtNum(cfg.weight) + ' ' + unit : ''
if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h`
if (mode === 'time') return `${n} × ${fmtSec(cfg.sec || 45)}${load}`
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() }
+152
View File
@@ -0,0 +1,152 @@
// 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.
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".
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 }
}
function reloadDb() { _db = readJsonOrNull(path.join(DATA_DIR, 'db.json')) || { users: [], creds: [], subs: [], invites: [] } }
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.
*/
function resolveUid() {
const envUid = (process.env.OPENGYM_UID || '').trim()
if (envUid) {
if (!/^[a-zA-Z0-9_-]+$/.test(envUid)) throw new Error(`OPENGYM_UID contains characters that aren't safe in a filename: ${JSON.stringify(envUid)}`)
return envUid
}
const files = fs.readdirSync(DATA_DIR)
.filter(f => /^state-[a-zA-Z0-9_-]+\.json$/.test(f))
.map(f => f.replace(/^state-/, '').replace(/\.json$/, ''))
if (files.length === 1) return files[0]
if (files.length === 0) {
reloadDb()
if (_db.users.length === 1) return _db.users[0].id
if (_db.users.length === 0) throw new Error(`no openGym users found in ${path.join(DATA_DIR, 'db.json')} — sign in at least once on a device`)
}
throw new Error(
`multiple openGym users found — set OPENGYM_UID to one of: ${files.join(', ')}\n` +
` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`
)
}
/** Set up the live state view: pick the uid, load db.json, attach the watcher, prime state. */
export function init() {
if (_uid !== null) return // idempotent
if (!fs.existsSync(DATA_DIR)) throw new Error(`OPENGYM_DATA dir does not exist: ${DATA_DIR}`)
_uid = resolveUid()
reloadDb()
const file = stateFile(_uid)
if (fs.existsSync(file)) {
_state = readJsonOrNull(file)
if (_state) _state = Object.assign({}, defaultsShape(), _state)
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.
try {
_watcher = fs.watch(file, () => {
// On change, simply clear the cache — the next getState() will re-read. Avoids reading
// twice if the watcher fires multiple events for one atomic-write (rename + create).
_state = undefined
_loadedMtime = 0
})
} 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. */
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.
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) {
const fresh = readJsonOrNull(file)
if (fresh) {
// Same shape the frontend builds on pullState — defaults merged with stored state so any
// field the app added since the snapshot was last saved shows up undefined-safe.
_state = Object.assign({}, defaultsShape(), fresh)
_loadedMtime = mtime
} else if (_state === undefined) {
_state = null // no state file at all — never signed in on a device
}
}
return _state
}
/** The user record (id + name) from db.json. Excludes passkeys/credentials and 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.
*/
export function _seedStateForTests(state) {
_uid = 'test-uid'
_db = { users: [{ id: _uid, name: 'Test', created: '2026-07-26T00:00:00.000Z' }], creds: [], subs: [], invites: [] }
_state = state
_loadedMtime = Number.MAX_SAFE_INTEGER // never re-read from disk in a test
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',
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], customEx: [], gifSize: 'full',
reminder: { on: false, time: '08:00', tz: null }
}
}
+362
View File
@@ -0,0 +1,362 @@
// 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.
import { z } from 'zod'
import { getState, getUser } from './state.js'
import {
fmt, setLabel, exLine, muscleName, policyName, friendlyDate, friendlyDuration, ratio, muscleOrder
} from './labels.js'
import {
modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId
} from '../../frontend/src/lib/history.js'
import { EXIDX, exOr } from '../../frontend/src/lib/exercises.js'
import {
estimate1RM, best1RM, e1rmSeries, FORMULAS, DEFAULT_FORMULA, REP_CAP
} from '../../frontend/src/lib/onerm.js'
import { loadOfWorkouts, rankOf, levelsOf, MUSCLES } from '../../frontend/src/lib/muscles.js'
/* ---------- helpers ---------- */
const ISO = /^\d{4}-\d{2}-\d{2}$/
function requireIso(v, name) {
const s = typeof v === 'string' ? v : ''
if (s && !ISO.test(s)) throw new Error(`${name} must be YYYY-MM-DD (got ${JSON.stringify(v)})`)
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.
function entryView(e, S) {
const ex = exOr(e.id)
const mode = modeOf(e.target || { id: e.id })
return {
id: e.id,
name: ex.n,
body_part: ex.bp || null,
mode,
target: e.target || null,
sets: (e.sets || []).map(s => ({
done: !!s.done,
label: setLabel(e.id, { ...s, done: undefined }, e.target || { id: e.id }),
w: Number(s.w) || 0,
r: Number(s.r) || 0,
sec: Number(s.sec) || 0,
min: Number(s.min) || 0,
speed: Number(s.speed) || 0
}))
}
}
// 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).
function prTable(S, formula) {
const byId = new Map()
for (const w of (S.workouts || [])) {
for (const e of (w.entries || [])) {
for (const s of (e.sets || [])) {
if (!s.done) continue
const est = estimate1RM(s.w, s.r, formula)
if (est == null) continue
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.
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 })
}
}
}
}
return [...byId.values()].sort((a, b) => b.est - a.est)
}
/* ---------- the 8 tools ---------- */
/** 1. 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.',
schema: {},
handler: () => {
const S = getState()
if (!S) return noState()
return {
unit: S.unit || 'kg',
routines: (S.routines || []).map(r => ({
id: r.id,
name: r.name,
emoji: r.emoji || null,
exercise_count: (r.ex || []).length,
superset_groups: [...new Set((r.ex || []).map(e => e.sg).filter(Boolean))].length || 0,
policy: r.policy || 'off'
}))
}
}
}
/** 2. 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.',
schema: { routine_id: z.string().min(1) },
handler: ({ routine_id }) => {
const S = getState()
if (!S) return noState()
const r = (S.routines || []).find(x => x.id === routine_id)
if (!r) { const e = new Error(`no routine with id ${JSON.stringify(routine_id)}`); e.code = 'ENOENT'; throw e }
return {
id: r.id,
name: r.name,
emoji: r.emoji || null,
policy: r.policy || 'off',
policy_name: policyName(r.policy || 'off'),
unit: S.unit || 'kg',
exercises: (r.ex || []).map((cfg, i) => {
const ex = exOr(cfg.id)
const mode = modeOf(cfg)
return {
position: i + 1,
id: cfg.id,
name: ex.n,
body_part: ex.bp || null,
mode,
sets: cfg.sets || 1,
reps: mode === 'reps' ? (cfg.reps || 0) : undefined,
reps_min: mode === 'reps' && cfg.repsMin != null ? cfg.repsMin : undefined,
sec: mode === 'time' ? (cfg.sec || 0) : undefined,
min: mode === 'cardio' ? (cfg.min || 0) : undefined,
speed: mode === 'cardio' ? (cfg.speed || 0) : undefined,
weight: cfg.weight != null ? cfg.weight : undefined,
increment: cfg.inc != null ? cfg.inc : undefined,
policy_override: cfg.policy || null,
superset_group: cfg.sg || null,
summary: exLine(cfg, S.unit || 'kg')
}
})
}
}
}
/** 3. 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).',
schema: {},
handler: () => {
const S = getState()
if (!S) return noState()
const today = new Date()
const isoToday = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0')
const todayWd = today.getDay()
return {
today: isoToday,
weekdays: [0, 1, 2, 3, 4, 5, 6].map(d => {
const rid = S.week?.[d] || null
const r = rid ? (S.routines || []).find(x => x.id === rid) : null
// Surface today's override only (not the whole dayPlan dict — usually empty, but might
// have grown from repeated "move this day" actions).
const overrideForToday = d === todayWd ? (S.dayPlan?.[isoToday] ?? null) : null
return {
weekday: d,
weekday_name: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d],
routine_id: rid,
routine_name: r?.name || null,
routine_emoji: r?.emoji || null,
override_for_today_or_null: overrideForToday
}
}),
today_routine_id: effectiveRoutineId(S, isoToday),
today_routine_name: effectiveRoutine(S, isoToday)?.name || null
}
}
}
/** 4. 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.',
schema: {
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD. Defaults to no lower bound (list most recent).'),
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.'),
limit: z.number().int().min(1).max(200).optional().describe('Max items to return. Defaults to 25.')
},
handler: ({ from, to, limit }) => {
const S = getState()
if (!S) return noState()
const lim = Math.min(Math.max(limit || 25, 1), 200)
const all = (S.workouts || []).slice().sort((a, b) => (b.d || '').localeCompare(a.d || ''))
const filtered = all.filter(w => {
if (from && w.d < from) return false
if (to && w.d > to) return false
return true
}).slice(0, lim)
return {
unit: S.unit || 'kg',
total_count: all.length,
returned_count: filtered.length,
workouts: filtered.map(w => ({
date: w.d,
routine_id: w.routineId || null,
routine_name: w.name || null,
exercise_count: (w.entries || []).length,
sets_done: setsDone(w),
sets_planned: plannedSets(w),
sets_ratio: ratio(setsDone(w), plannedSets(w)),
volume: workoutVolume(w),
duration_ms: w.end && w.start ? (w.end - w.start) : null,
duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null,
prs: (w.prs || []).length,
bodyweight_at_workout: w.bw || null
}))
}
}
}
function plannedSets(w) {
let n = 0
;(w.entries || []).forEach(e => { n += (e.sets || []).length })
return n
}
/** 5. 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.',
schema: { date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe('The workout date as YYYY-MM-DD') },
handler: ({ date }) => {
const S = getState()
if (!S) return noState()
const w = (S.workouts || []).find(x => x.d === date)
if (!w) { const e = new Error(`no workout on ${date}`); e.code = 'ENOENT'; throw e }
return {
date: w.d,
routine_id: w.routineId || null,
routine_name: w.name || null,
unit: S.unit || 'kg',
bodyweight_at_workout: w.bw || null,
volume: workoutVolume(w),
sets_done: setsDone(w),
sets_planned: plannedSets(w),
duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null,
prs: (w.prs || []).map(id => EXIDX[id]?.n || id),
entries: (w.entries || []).map(e => entryView(e, S))
}
}
}
/** 6. 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.',
schema: {
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD.'),
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.')
},
handler: ({ from, to }) => {
const S = getState()
if (!S) return noState()
const goal = S.targetW || null
const bw = (S.bodyweight || []).filter(b => {
if (from && b.d < from) return false
if (to && b.d > to) return false
return true
}).sort((a, b) => (a.d || '').localeCompare(b.d || ''))
const latest = bw.length ? bw[bw.length - 1] : null
return {
unit: S.unit || 'kg',
goal,
count: bw.length,
latest: latest ? { date: latest.d, weight: latest.w, delta_vs_goal: goal != null ? Math.round((latest.w - goal) * 10) / 10 : null } : null,
entries: bw.map(b => ({
date: b.d,
weight: b.w,
delta_vs_goal: goal != null ? Math.round((b.w - goal) * 10) / 10 : null
}))
}
}
}
/** 7. 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".`,
schema: {
exercise_id: z.string().optional().describe('An exercise id from list_routines, get_workout entries, or search_exercises (v1.5). If omitted, returns a full PR table.'),
formula: z.enum(['epley', 'brzycki', 'lombardi']).optional().describe(`Formula to use. Defaults to ${DEFAULT_FORMULA}.`)
},
handler: ({ exercise_id, formula }) => {
const S = getState()
if (!S) return noState()
const f = formula || DEFAULT_FORMULA
if (exercise_id) {
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.
return {
exercise: { id: exercise_id, name: ex.n, body_part: ex.bp || null },
formula: f,
best: best ? { est: best.est, w: best.w, r: best.r, date: best.d } : null,
trend: series.map(p => ({ date: p.d, est: p.y, w: p.w, r: p.r }))
}
}
return {
formula: f,
formula_note: `Estimates use the ${f} formula. Cap at ${REP_CAP} reps applies; r=1 is treated as the measurement, not an estimate.`,
pr_table: prTable(S, f)
}
}
}
/** 8. 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.',
schema: {
period: z.enum(['week', 'month', 'all']).describe('window: last 7 days, last 30 days, or all-time')
},
handler: ({ period }) => {
const S = getState()
if (!S) return noState()
const now = Date.now()
const cutoff = period === 'week' ? now - 7 * 86400000
: period === 'month' ? now - 30 * 86400000
: Number.NEGATIVE_INFINITY
const workouts = (S.workouts || []).filter(w => (w.start || new Date(w.d + 'T12:00:00').getTime()) >= cutoff)
const load = loadOfWorkouts(workouts)
const { worked, missed } = rankOf(load)
const levels = levelsOf(load)
return {
period,
cutoff_iso: period === 'all' ? null : new Date(cutoff).toISOString().slice(0, 10),
workouts_in_period: workouts.length,
worked: worked.map(slug => ({ slug, name: muscleName(slug), level: levels[slug], effective_sets: Math.round((load[slug] || 0) * 10) / 10 })),
neglected: missed.map(slug => ({ slug, name: muscleName(slug) })),
muscle_order_head_to_toe: muscleOrder()
}
}
}
/* ---------- registration list ---------- */
export const TOOLS = [
listRoutines, getRoutine, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
]
function noState() {
return {
error: 'no synced state yet — sign in at least once from a device so the openGym api can save a state file for this profile',
unit: 'kg'
}
}