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.

MCP: preview_session — what a routine will actually open with

Ameer Khan733dfa9d3738
diff --git a/mcp/README.md b/mcp/README.md
index 0cff276ed..3d636692d 100644
--- a/mcp/README.md
+++ b/mcp/README.md
@@ -67,12 +67,13 @@ the server's stderr.
## Tools
-Eight read-only tools in v1:
+Nine read-only tools in v1:
| Tool | What it answers |
|---|---|
| `list_routines` | What routines are saved in my profile? (names + exercise counts) |
| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) |
+| `preview_session` | What will the app actually put on screen when I start this routine — after the progression policy and my history have overridden the plan? |
| `get_week_plan` | What's on my plan this week, including today with any date-specific override? |
| `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. |
| `get_workout` | Full set-by-set breakdown of one session, by `workout_id` or by date. On a day with two sessions the date alone returns both ids to pick from rather than guessing at one. |
@@ -80,6 +81,13 @@ Eight read-only tools in v1:
| `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. |
| `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. |
+`get_routine` and `preview_session` answer two different questions, and confusing them is the
+easiest way for a coach to give wrong advice. `get_routine` reports what the routine *stores*.
+`preview_session` reports what the athlete will actually *see*: a routine holding "squat 3×8 @
+60 kg" opens at 75 kg if the policy deloaded from the last logged session, and the rep counts
+come from history, not the plan. The routine's own numbers are the last fallback the session
+builder consults, not the first. Ask `preview_session` before naming a weight.
+
Each tool returns JSON the LLM can format as it likes; structured fields (sets, dates, levels)
are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to
re-interpret them.
@@ -112,7 +120,7 @@ dependencies landed in `frontend/`, no public exports changed.
cd mcp && npm test
```
-32 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture
+54 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
@@ -122,8 +130,8 @@ their own 92 tests in `frontend/src/lib/*.test.js`.
## Roadmap
- **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access.
-- **Phase 1.5:** a `progression_next` tool (what does the policy prescribe next?). No new
- deps; small surface area.
+- **Done (Phase 1.5):** `preview_session` — the policy's next prescription, the opening set
+ rows it produces, and which of plan / confirmed weight / history each number came from.
- **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the
admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify-
write of `state-<uid>.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`,
diff --git a/mcp/src/tools.js b/mcp/src/tools.js
index 3d20b40fc..bd5460427 100644
--- a/mcp/src/tools.js
+++ b/mcp/src/tools.js
@@ -4,10 +4,11 @@
import { z } from 'zod'
import { getState, getUser } from './state.js'
import {
- setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder
+ fmt, setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder
} from './labels.js'
import {
- modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId
+ modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId,
+ buildSets, applyIntensifierPlan, lastEntryFor
} from '../../frontend/src/lib/history.js'
import { exOr } from '../../frontend/src/lib/exercises.js'
import { isWarmupRow } from '../../frontend/src/lib/workout-model.js'
@@ -15,7 +16,7 @@ import {
estimate1RM, best1RM, e1rmSeries, DEFAULT_FORMULA, REP_CAP
} from '../../frontend/src/lib/onerm.js'
import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js'
-import { policyFor } from '../../frontend/src/lib/progression.js'
+import { policyFor, nextPrescription, applyPrescription } from '../../frontend/src/lib/progression.js'
/* ---------- helpers ---------- */
@@ -407,10 +408,146 @@ export const muscleBalance = {
}
}
+/* ---------- preview_session ---------- */
+
+// Where a number on the session screen actually came from. A routine's own sets/reps/weight
+// are the LAST fallback, not the first: buildSets() prefers the confirmed working weight and
+// the previous session's reps, and applyPrescription() then overwrites the weight with
+// whatever the progression policy decided. Reporting the winner is the whole point of this
+// tool — "the plan says 60" is not an answer to "what will the app show me".
+function sourceOf(S, cfg, plan, field) {
+ const decided = plan && plan.kind !== 'off' && plan.kind !== 'first' && plan[field] != null
+ if (decided) return 'progression'
+ if (field === 'weight') {
+ const conf = (S.exWeights || {})[cfg.id]
+ if (conf && conf.w > 0) return 'confirmed_weight'
+ }
+ return lastEntryFor(S, cfg.id) ? 'last_session' : 'routine_plan'
+}
+
+const SOURCE_TEXT = {
+ progression: 'the progression policy overrode the routine',
+ confirmed_weight: 'your confirmed working weight for this exercise',
+ last_session: 'carried over from the last time you did this exercise',
+ routine_plan: "the routine's own target"
+}
+
+/** preview_session — what starting this routine will actually put on screen. */
+export const previewSession = {
+ name: 'preview_session',
+ description:
+ 'Preview the session a routine will actually open with — the numbers the user will see after the progression policy and their training history have overridden the routine\'s own targets. This is NOT the same as get_routine: a routine storing "squat 3x8 @ 60kg" can open at 75kg because the policy deloaded from the last logged session, and reps carry from history rather than from the plan. Always call this (not get_routine) before telling someone what weight they are about to lift, or before judging whether an edit to a routine had any effect. Returns, per exercise, the planned target, the policy\'s decision and its stated reason, the opening set rows, and where each number came from. Defaults to today\'s scheduled routine.',
+ schema: {
+ routine_id: z.string().min(1).optional().describe('Routine to preview. Defaults to the routine scheduled for `date`.'),
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Date the session would be started on, YYYY-MM-DD. Affects which routine is scheduled and any one-off day override. Defaults to today.')
+ },
+ handler: ({ routine_id, date }) => {
+ const S = getState()
+ if (!S) return noState()
+ const now = new Date()
+ const iso = date || (now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-' + String(now.getDate()).padStart(2, '0'))
+
+ let r
+ if (routine_id) {
+ 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 }
+ } else {
+ r = effectiveRoutine(S, iso)
+ if (!r) return { date: iso, routine_id: null, routine_name: null, rest_day: true, note: 'no routine is scheduled for this date (rest day)', exercises: [] }
+ }
+
+ const unit = S.unit || 'kg'
+ const exercises = (r.ex || []).map((cfg, i) => {
+ const ex = exerciseOf(cfg.id, S)
+ const mode = modeOf({ ...cfg, id: cfg.id })
+ const plan = nextPrescription(S, cfg, r)
+ // Mirrors beginWorkout() exactly (sheets.jsx): build, apply the prescription, then stamp
+ // the intensifier. Anything less and the preview stops matching the real session.
+ const rows = applyIntensifierPlan(applyPrescription(buildSets(S, cfg), plan), cfg)
+ const work = rows.filter(s => !isWarmupRow(s))
+ const openW = work.length ? (work[0].w || 0) : 0
+ const openR = work.length ? (work[0].r || 0) : 0
+ const wSrc = sourceOf(S, cfg, plan, 'weight')
+ const rSrc = sourceOf(S, cfg, plan, 'reps')
+ return {
+ position: i + 1,
+ id: cfg.id,
+ name: ex.n,
+ mode,
+ policy: plan.policy,
+ policy_name: policyName(plan.policy),
+ planned: {
+ sets: cfg.sets || 1,
+ reps: mode === 'reps' ? (cfg.reps || 0) : undefined,
+ sec: mode === 'time' ? (cfg.sec || 0) : undefined,
+ min: mode === 'cardio' ? (cfg.min || 0) : undefined,
+ weight: cfg.weight != null ? cfg.weight : undefined,
+ summary: exLine(cfg, unit)
+ },
+ prescription: {
+ kind: plan.kind,
+ weight: plan.weight != null ? plan.weight : undefined,
+ reps: plan.reps != null ? plan.reps : undefined,
+ sets: plan.sets != null ? plan.sets : undefined,
+ sec: plan.sec != null ? plan.sec : undefined,
+ why: plan.why ? fmt(plan.why[0], plan.why.slice(1)) : null
+ },
+ opening_sets: rows.map(s => ({
+ phase: isWarmupRow(s) ? 'warmup' : 'work',
+ type: s.type || 'straight',
+ label: setLabel(cfg.id, { ...s, done: undefined }, { ...cfg, id: cfg.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
+ })),
+ weight_source: wSrc,
+ weight_source_text: SOURCE_TEXT[wSrc],
+ reps_source: mode === 'reps' ? rSrc : undefined,
+ reps_source_text: mode === 'reps' ? SOURCE_TEXT[rSrc] : undefined,
+ // The headline: did editing the routine change anything the user will see? Tracked per
+ // dimension — a bodyweight exercise whose weight is 0 either way still counts when the
+ // rep target moved, and saying which one moved saves the caller diffing it themselves.
+ changed: [
+ ...(mode === 'reps' && cfg.weight != null && openW !== cfg.weight ? ['weight'] : []),
+ ...(mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps ? ['reps'] : [])
+ ],
+ differs_from_plan:
+ (mode === 'reps' && cfg.weight != null && openW !== cfg.weight) ||
+ (mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps)
+ }
+ })
+
+ const differing = exercises.filter(e => e.differs_from_plan)
+ return {
+ date: iso,
+ routine_id: r.id,
+ routine_name: r.name,
+ unit,
+ policy: policyFor(null, r, 'reps'),
+ policy_name: policyName(policyFor(null, r, 'reps')),
+ exercises,
+ // Surfaced separately so a coach reading this cannot miss it: these are the exercises
+ // where what the routine stores and what the athlete will see are two different numbers.
+ overridden_count: differing.length,
+ overridden: differing.map(e => ({
+ name: e.name,
+ planned_weight: e.planned.weight,
+ opening_weight: e.opening_sets.filter(s => s.phase === 'work')[0]?.w ?? null,
+ planned_reps: e.planned.reps,
+ opening_reps: e.opening_sets.filter(s => s.phase === 'work')[0]?.r ?? null,
+ changed: e.changed,
+ reason: e.prescription.why || e.weight_source_text
+ }))
+ }
+ }
+}
+
/* ---------- registration list ---------- */
export const TOOLS = [
- listRoutines, getRoutine, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
+ listRoutines, getRoutine, previewSession, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
]
function noState() {
diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js
index 7b6e48060..9f52cd8d2 100644
--- a/mcp/test/tools.test.js
+++ b/mcp/test/tools.test.js
@@ -663,3 +663,126 @@ describe('shared: no-state fallback', () => {
// failure rather than inherits null silently.
afterAll(() => { _seedStateForTests(S = freshState()) })
})
+
+/* ---------- preview_session ---------- */
+
+// The gap this tool exists to close: a routine stores sets/reps/weight, but those are the
+// LAST fallback the session builder consults. These tests pin the precedence — progression
+// beats the confirmed working weight, which beats the routine's own number — because getting
+// it backwards is how a coach ends up telling someone to squat a weight the app never shows.
+describe('preview_session', () => {
+ const WD = new Date(FAKE_TODAY_ISO + 'T12:00:00Z').getDay()
+
+ // One routine, one exercise, scheduled for the pinned "today". Nothing from the demo seed,
+ // so the arithmetic below is checkable by hand.
+ function only(cfg, { prog = 'off', workouts = [], exWeights = {} } = {}) {
+ S.routines = [{ id: 'r-preview', name: 'Preview', emoji: 'barbell', prog, ex: [cfg] }]
+ S.week = { [WD]: 'r-preview' }
+ S.dayPlan = {}
+ S.workouts = workouts
+ S.exWeights = exWeights
+ _seedStateForTests(S)
+ }
+
+ test('defaults to the routine scheduled for today', () => {
+ only({ id: '0025', sets: 3, reps: 8, weight: 50 })
+ const r = call('preview_session')
+ expect(r.date).toBe(FAKE_TODAY_ISO)
+ expect(r.routine_name).toBe('Preview')
+ expect(r.exercises).toHaveLength(1)
+ expect(r.exercises[0].name).toBe('barbell bench press')
+ })
+
+ test('with no history and no confirmed weight, the routine\'s own number is what opens', () => {
+ only({ id: '0025', sets: 3, reps: 8, weight: 50 })
+ const e = call('preview_session').exercises[0]
+ expect(e.weight_source).toBe('routine_plan')
+ expect(e.opening_sets.map(s => s.w)).toEqual([50, 50, 50])
+ expect(e.opening_sets.map(s => s.r)).toEqual([8, 8, 8])
+ expect(e.differs_from_plan).toBe(false)
+ expect(call('preview_session').overridden_count).toBe(0)
+ })
+
+ test('a confirmed working weight beats the routine\'s number', () => {
+ only({ id: '0025', sets: 2, reps: 8, weight: 50 }, { exWeights: { '0025': { w: 72.5, d: '2026-07-20' } } })
+ const e = call('preview_session').exercises[0]
+ expect(e.weight_source).toBe('confirmed_weight')
+ expect(e.opening_sets.every(s => s.w === 72.5)).toBe(true)
+ expect(e.changed).toEqual(['weight'])
+ })
+
+ test('the progression policy beats both, and its reason is reported', () => {
+ // Every rep hit at 60 last time under linear progression → +2.5, regardless of the 100
+ // the routine stores.
+ only({ id: '0025', sets: 3, reps: 5, weight: 100 }, {
+ prog: 'linear',
+ exWeights: { '0025': { w: 100, d: '2026-07-20' } },
+ workouts: [{
+ id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
+ entries: [{
+ id: '0025',
+ target: { id: '0025', sets: 3, reps: 5, weight: 60 },
+ sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }]
+ }]
+ }]
+ })
+ const out = call('preview_session')
+ const e = out.exercises[0]
+ expect(e.prescription.kind).toBe('up')
+ expect(e.weight_source).toBe('progression')
+ expect(e.opening_sets.every(s => s.w === 62.5)).toBe(true)
+ expect(e.prescription.why).toMatch(/Every rep last time/)
+ expect(e.changed).toEqual(['weight'])
+
+ expect(out.overridden_count).toBe(1)
+ expect(out.overridden[0]).toMatchObject({
+ name: 'barbell bench press', planned_weight: 100, opening_weight: 62.5
+ })
+ expect(out.overridden[0].reason).toMatch(/Every rep last time/)
+ })
+
+ test('reps carry from the last session even when the routine asks for something else', () => {
+ only({ id: '0025', sets: 2, reps: 12, weight: 60 }, {
+ workouts: [{
+ id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
+ entries: [{
+ id: '0025',
+ target: { id: '0025', sets: 2, reps: 5, weight: 60 },
+ sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }]
+ }]
+ }]
+ })
+ const e = call('preview_session').exercises[0]
+ expect(e.opening_sets.map(s => s.r)).toEqual([5, 5]) // not the 12 the routine stores
+ expect(e.reps_source).toBe('last_session')
+ expect(e.changed).toContain('reps')
+ })
+
+ test('planned drop sets show up on the opening rows', () => {
+ only({ id: '0025', sets: 2, reps: 10, weight: 50, intensifier: { type: 'dropset', count: 1, pct: 20 } })
+ const e = call('preview_session').exercises[0]
+ expect(e.opening_sets.every(s => s.type === 'dropset')).toBe(true)
+ })
+
+ test('an explicit routine_id overrides the schedule', () => {
+ only({ id: '0025', sets: 3, reps: 8, weight: 50 })
+ const other = { id: 'r-other', name: 'Other', prog: 'off', ex: [{ id: '0043', sets: 5, reps: 5, weight: 80 }] }
+ S.routines.push(other)
+ _seedStateForTests(S)
+ expect(call('preview_session', { routine_id: 'r-other' }).routine_name).toBe('Other')
+ })
+
+ test('a rest day returns no exercises rather than an error', () => {
+ only({ id: '0025', sets: 3, reps: 8, weight: 50 })
+ S.week = {}
+ _seedStateForTests(S)
+ const r = call('preview_session')
+ expect(r.rest_day).toBe(true)
+ expect(r.exercises).toEqual([])
+ })
+
+ test('an unknown routine_id is an error, not an empty session', () => {
+ only({ id: '0025', sets: 3, reps: 8, weight: 50 })
+ expect(() => call('preview_session', { routine_id: 'nope' })).toThrow(/no routine with id/)
+ })
+})