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:
1 parent
fadeb17b6c
commit
92914dea43
9 files changed
+5641
No files matched your search
@@ -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'
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user