@trainheroic-unofficial/coach-mcp 1.1.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/server.mjs +515 -45
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -163,17 +163,43 @@ const loggedSetSchema = z.object({
163
163
  param2: z.union([z.number(), z.string()]).optional()
164
164
  });
165
165
  /**
166
- * Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
167
- * roster `athleteId` whose set is being logged on their behalf.
166
+ * Args for the set-logging write. `date` (the workout's day) locates the saved
167
+ * workout via the range endpoint; `savedWorkoutSetId` picks the set to complete; `results`
168
+ * gives, per exercise in it, the entered value of each set (param 1 / param 2 by entry slot).
168
169
  */
169
- const coachLogSetArgsSchema = z.object({
170
+ const logSetArgsSchema = z.object({
170
171
  date: dateString,
171
172
  savedWorkoutSetId: idArgSchema,
172
173
  results: z.array(z.object({
173
174
  savedWorkoutSetExerciseId: idArgSchema,
174
175
  sets: z.array(loggedSetSchema).min(1)
175
176
  })).min(1)
176
- }).extend({ athleteId: idArgSchema });
177
+ });
178
+ /**
179
+ * Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
180
+ * roster `athleteId` whose set is being logged on their behalf.
181
+ */
182
+ const coachLogSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
183
+ /**
184
+ * Args for the coach prescription-override write. Structurally the same as
185
+ * {@link coachLogSetArgsSchema} (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but
186
+ * the values are prescribed targets (param1 = reps, param2 = weight) written to the athlete's
187
+ * plan without marking the set performed. It is a separate schema (not an alias) so a future
188
+ * prescribe-only constraint can be added here without changing the log args, and the write
189
+ * replaces the slot's prescribed values for this athlete only.
190
+ */
191
+ const coachPrescribeSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
192
+ /**
193
+ * Args for the coach per-athlete exercise swap: replace the exercise prescribed in one of a
194
+ * roster athlete's saved-workout slots with a different exercise, the API equivalent of the
195
+ * app's per-athlete "swap exercise". `savedWorkoutSetExerciseId` is that athlete's own slot id
196
+ * (the same id `coachLogSetArgsSchema` uses, read off athlete_saved_workouts raw);
197
+ * `exerciseId` is the replacement exercise. The team/program prescription is left untouched.
198
+ */
199
+ const swapAthleteExerciseArgsSchema = z.object({
200
+ savedWorkoutSetExerciseId: idArgSchema,
201
+ exerciseId: idArgSchema
202
+ });
177
203
  /**
178
204
  * Args for the coach variant of {@link logSessionArgsSchema}: the same shape plus the roster
179
205
  * `athleteId` whose session is being logged on their behalf.
@@ -642,6 +668,14 @@ function coerceInt(value) {
642
668
  }
643
669
  return null;
644
670
  }
671
+ function coerceNum(value) {
672
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
673
+ if (typeof value === "string" && value.trim() !== "") {
674
+ const n = Number(value);
675
+ return Number.isFinite(n) ? n : null;
676
+ }
677
+ return null;
678
+ }
645
679
  function unitLabel(paramType) {
646
680
  const t = coerceInt(paramType);
647
681
  if (t === null) return null;
@@ -740,6 +774,24 @@ function rankSearch(rows, query, limit) {
740
774
  };
741
775
  }).sort((a, b) => b.score - a.score).slice(0, limit).map((s) => s.row);
742
776
  }
777
+ /**
778
+ * Map over items with a bounded number of concurrent workers. Used to fan out upstream
779
+ * fetches (per-exercise history, the CLI export) without bursting the host all at once or,
780
+ * on workerd, blowing the subrequest budget.
781
+ */
782
+ async function mapPool(items, limit, fn) {
783
+ const out = Array.from({ length: items.length });
784
+ let next = 0;
785
+ const worker = async () => {
786
+ while (next < items.length) {
787
+ const i = next;
788
+ next += 1;
789
+ out[i] = await fn(items[i], i);
790
+ }
791
+ };
792
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
793
+ return out;
794
+ }
743
795
  //#endregion
744
796
  //#region ../js/src/athlete.ts
745
797
  async function getJson(client, path, label) {
@@ -1052,29 +1104,59 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
1052
1104
  }
1053
1105
  const MAX_PARAM_SLOTS = 10;
1054
1106
  /**
1055
- * Build the body for `PUT /1.0/athlete/savedworkoutsetexercise/{id}`. The body uses
1056
- * snake_case keys matching the live API response shape. Each set slot (1-10) gets a
1057
- * `param_N_made` flag (1 if data is present, 0 otherwise) and `param_1_data_N` /
1058
- * `param_2_data_N` string values.
1107
+ * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1108
+ * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
1109
+ * empty param slots optional; this narrows the id to a number and copies only the present per-set
1110
+ * values (so the per-set type stays free of `undefined` under exactOptionalPropertyTypes). Shared
1111
+ * by the MCP tools and the CLI so the mapping lives in one place rather than once per surface.
1112
+ */
1113
+ function toSetResults(results) {
1114
+ return results.map((r) => {
1115
+ const id = coerceInt(r.savedWorkoutSetExerciseId);
1116
+ if (id === null) throw new Error(`Invalid savedWorkoutSetExerciseId: ${String(r.savedWorkoutSetExerciseId)}`);
1117
+ return {
1118
+ savedWorkoutSetExerciseId: id,
1119
+ sets: r.sets.map((s) => {
1120
+ const slot = {};
1121
+ if (s.param1 !== void 0) slot.param1 = s.param1;
1122
+ if (s.param2 !== void 0) slot.param2 = s.param2;
1123
+ return slot;
1124
+ })
1125
+ };
1126
+ });
1127
+ }
1128
+ /**
1129
+ * Build the body for `PUT /1.0/{role}/savedworkoutsetexercise/{id}`. The body uses snake_case
1130
+ * keys matching the live API response shape. Each set slot (1-10) carries `param_1_data_N` /
1131
+ * `param_2_data_N` string values plus a `param_N_made` flag.
1132
+ *
1133
+ * `mode` selects which write this is — the same endpoint serves both:
1134
+ * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
1135
+ * and the exercise `completed` flag is 1 when any set has data.
1136
+ * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
1137
+ * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
1138
+ * coach edits an athlete's prescribed reps/weight.
1059
1139
  *
1060
1140
  * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1061
1141
  * required from the live exercise record; everything else is derived from `results`.
1062
1142
  *
1063
- * Exported for unit testing — callers should use `logAthleteSet` instead.
1143
+ * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
1064
1144
  */
1065
- function buildExerciseLogPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results) {
1145
+ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode) {
1066
1146
  if (results.length > MAX_PARAM_SLOTS) throw new Error(`At most ${MAX_PARAM_SLOTS} sets are supported per exercise; got ${results.length}.`);
1147
+ const performed = mode === "log";
1148
+ const hasData = results.some((s) => s.param1 !== void 0 || s.param2 !== void 0);
1067
1149
  const body = {
1068
1150
  id: savedWorkoutSetExerciseId,
1069
1151
  saved_workout_set_id: savedWorkoutSetId,
1070
1152
  workout_set_exercise_id: workoutSetExerciseId,
1071
- completed: results.some((s) => s.param1 !== void 0 || s.param2 !== void 0) ? 1 : 0
1153
+ completed: performed && hasData ? 1 : 0
1072
1154
  };
1073
1155
  for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
1074
1156
  const slot = results[i - 1];
1075
1157
  const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
1076
1158
  const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
1077
- body[`param_${i}_made`] = p1 !== "" || p2 !== "" ? 1 : 0;
1159
+ body[`param_${i}_made`] = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
1078
1160
  body[`param_1_data_${i}`] = p1;
1079
1161
  body[`param_2_data_${i}`] = p2;
1080
1162
  }
@@ -1175,7 +1257,11 @@ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
1175
1257
  * by the respective PUT bodies.
1176
1258
  */
1177
1259
  async function logAthleteSet(client, args) {
1178
- return writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results);
1260
+ const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
1261
+ return {
1262
+ savedWorkoutSetId: r.savedWorkoutSetId,
1263
+ exercisesLogged: r.exercisesWritten
1264
+ };
1179
1265
  }
1180
1266
  /**
1181
1267
  * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
@@ -1189,24 +1275,94 @@ async function logAthleteSet(client, args) {
1189
1275
  */
1190
1276
  async function logForAthlete(client, args) {
1191
1277
  const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
1192
- return writeSetResults(client, {
1278
+ const r = await writeSetResults(client, {
1193
1279
  role: "coach",
1194
1280
  athleteId: args.athleteId
1195
- }, workouts, args.savedWorkoutSetId, args.results);
1281
+ }, workouts, args.savedWorkoutSetId, args.results, "log");
1282
+ return {
1283
+ savedWorkoutSetId: r.savedWorkoutSetId,
1284
+ exercisesLogged: r.exercisesWritten
1285
+ };
1196
1286
  }
1197
1287
  /**
1198
- * Shared two-step set-log write behind {@link logAthleteSet} and {@link logForAthlete}.
1199
- * `target` selects the surface: `athlete` writes `/1.0/athlete/...`; `coach` writes
1200
- * `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body. Step 1 PUTs each
1201
- * exercise's entered data to its own endpoint (the only path that actually stores reps and
1202
- * weight). Step 2 marks the set completed; that body needs the app's camelCase in-memory
1203
- * shape and the full list of savedWorkoutSetExercise IDs in the set (not only the logged ones).
1288
+ * Coach prescription override: set the prescribed reps/weight for one of a roster athlete's saved
1289
+ * workout sets WITHOUT marking it performed — the API equivalent of the app's editing an athlete's
1290
+ * prescribed values. Writes each exercise's per-set targets via
1291
+ * `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` with `param_N_made = 0` /
1292
+ * `completed = 0`, and (unlike {@link logForAthlete}) skips the set-completion step, so the set
1293
+ * stays open for the athlete to log against.
1294
+ *
1295
+ * Overrides only this athlete's copy of the set; the team/program prescription is untouched, so
1296
+ * other athletes on the same program keep the original targets. The write REPLACES the slot's
1297
+ * prescribed values, so pass the full per-set prescription you want — `param1` is reps, `param2`
1298
+ * is weight, and an omitted param is written empty (clearing it), not left as-is.
1299
+ *
1300
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only and return 401/403; real (invited)
1301
+ * athletes accept it.
1204
1302
  */
1205
- async function writeSetResults(client, target, workouts, savedWorkoutSetId, results) {
1303
+ async function prescribeForAthlete(client, args) {
1304
+ const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
1305
+ const r = await writeSetResults(client, {
1306
+ role: "coach",
1307
+ athleteId: args.athleteId
1308
+ }, workouts, args.savedWorkoutSetId, args.results, "prescribe");
1309
+ return {
1310
+ savedWorkoutSetId: r.savedWorkoutSetId,
1311
+ exercisesPrescribed: r.exercisesWritten
1312
+ };
1313
+ }
1314
+ /**
1315
+ * Swap the exercise prescribed in one of an athlete's saved-workout slots for a different
1316
+ * exercise — the API equivalent of the app's per-athlete "swap exercise":
1317
+ * `PUT /v5/savedWorkoutSetExercises/{savedWorkoutSetExerciseId}?exerciseId={exerciseId}` with an
1318
+ * empty body. The new exercise rides in the query string, not the body.
1319
+ *
1320
+ * This overrides only this athlete's copy of the slot; the underlying team/program prescription
1321
+ * (`workout_set_exercise.exercise_id`) is untouched, so other athletes on the same program keep
1322
+ * the original exercise. A coach's session token may write another user's row because the row
1323
+ * already carries its owner's `user_id`.
1324
+ *
1325
+ * `savedWorkoutSetExerciseId` is the same id {@link logForAthlete}/{@link logAthleteSet} use,
1326
+ * read off the athlete's saved workouts (the raw view). `exerciseId` is any exercise id the org
1327
+ * can use (resolve one via the exercise index).
1328
+ *
1329
+ * NOTE: as with logging, TrainHeroic's seeded *demo* athletes are read-only and return 401/403;
1330
+ * real (invited) athletes accept the swap.
1331
+ */
1332
+ async function swapAthleteExercise(client, args) {
1333
+ const res = await client.request("PUT", `/v5/savedWorkoutSetExercises/${args.savedWorkoutSetExerciseId}?exerciseId=${args.exerciseId}`);
1334
+ if (!res.ok) {
1335
+ const readOnly = res.status === 401 || res.status === 403 ? ` Athlete may be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; swaps only persist for real (invited) athletes.` : "";
1336
+ throw new Error(`Swap failed (HTTP ${res.status}) for savedWorkoutSetExercise ${args.savedWorkoutSetExerciseId}.${readOnly}`);
1337
+ }
1338
+ const row = isRecord(res.data) ? res.data : {};
1339
+ const template = isRecord(row.workout_set_exercise) ? row.workout_set_exercise : {};
1340
+ const exercise = isRecord(row.exercise) ? row.exercise : {};
1341
+ return {
1342
+ savedWorkoutSetExerciseId: args.savedWorkoutSetExerciseId,
1343
+ athleteId: coerceInt(row.user_id),
1344
+ newExerciseId: coerceInt(row.exercise_id) ?? args.exerciseId,
1345
+ newExerciseTitle: str$1(exercise.title),
1346
+ originalTeamExerciseId: coerceInt(template.exercise_id)
1347
+ };
1348
+ }
1349
+ /**
1350
+ * Shared set-write behind {@link logAthleteSet}, {@link logForAthlete}, and
1351
+ * {@link prescribeForAthlete}. `target` selects the surface: `athlete` writes `/1.0/athlete/...`;
1352
+ * `coach` writes `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body.
1353
+ *
1354
+ * Step 1 PUTs each exercise's per-set values to its own endpoint (the only path that actually
1355
+ * stores reps and weight). `mode` decides what those values mean: `"log"` records them as a
1356
+ * performed result and runs Step 2, which marks the set completed (that body needs the app's
1357
+ * camelCase in-memory shape and the full list of savedWorkoutSetExercise IDs in the set, not only
1358
+ * the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
1359
+ * open.
1360
+ */
1361
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
1206
1362
  const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1207
1363
  const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1208
1364
  const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1209
- let exercisesLogged = 0;
1365
+ let exercisesWritten = 0;
1210
1366
  for (const result of results) {
1211
1367
  const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
1212
1368
  if (!ex) {
@@ -1220,25 +1376,27 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1220
1376
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1221
1377
  if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
1222
1378
  const body = {
1223
- ...buildExerciseLogPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets),
1379
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
1224
1380
  ...extra
1225
1381
  };
1226
1382
  const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
1227
1383
  if (!res.ok) {
1228
- const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for results — TrainHeroic's seeded demo/sample athletes return ${res.status} here; results only persist for real (invited) athletes.` : "";
1229
- throw new Error(`Failed to log exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1384
+ const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; writes only persist for real (invited) athletes.` : "";
1385
+ throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1230
1386
  }
1231
- exercisesLogged += 1;
1387
+ exercisesWritten += 1;
1388
+ }
1389
+ if (mode === "log") {
1390
+ const setBody = {
1391
+ ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1392
+ ...extra
1393
+ };
1394
+ const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1395
+ if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1232
1396
  }
1233
- const setBody = {
1234
- ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1235
- ...extra
1236
- };
1237
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1238
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1239
1397
  return {
1240
1398
  savedWorkoutSetId,
1241
- exercisesLogged
1399
+ exercisesWritten
1242
1400
  };
1243
1401
  }
1244
1402
  /** Flatten a day's prescribed saved sets into `{ savedWorkoutSetId, ex }` rows (both set keys). */
@@ -1360,6 +1518,7 @@ function presentExerciseHistory(detail) {
1360
1518
  description: p.description ?? null,
1361
1519
  reps: p.reps ?? null,
1362
1520
  weight: p.weight ?? null,
1521
+ units: p.units ?? null,
1363
1522
  date: p.dateCompleted ?? null
1364
1523
  })),
1365
1524
  sessions: (detail.history ?? []).map((h) => ({
@@ -1377,6 +1536,37 @@ function presentExerciseHistory(detail) {
1377
1536
  function emailList(emails) {
1378
1537
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
1379
1538
  }
1539
+ /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
1540
+ function rosterName(rec) {
1541
+ const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
1542
+ if (full !== "") return full;
1543
+ const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
1544
+ return combined !== "" ? combined : null;
1545
+ }
1546
+ /**
1547
+ * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
1548
+ * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
1549
+ * and the warehouse store map the roster identically. Includes the account owner and
1550
+ * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
1551
+ */
1552
+ async function fetchCoachRoster(client, ids) {
1553
+ const res = await client.request("GET", "/v5/athletes");
1554
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
1555
+ const keep = ids && ids.length > 0 ? new Set(ids) : null;
1556
+ const out = [];
1557
+ for (const row of res.data) {
1558
+ if (typeof row !== "object" || row === null) continue;
1559
+ const rec = row;
1560
+ const id = coerceInt(rec.id);
1561
+ if (id === null || id <= 0) continue;
1562
+ if (keep && !keep.has(id)) continue;
1563
+ out.push({
1564
+ id,
1565
+ name: rosterName(rec)
1566
+ });
1567
+ }
1568
+ return out;
1569
+ }
1380
1570
  /**
1381
1571
  * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
1382
1572
  * addresses (`POST /v5/emails/validate`), then invite the validated ones
@@ -1637,6 +1827,213 @@ async function teamVolume(client, args) {
1637
1827
  };
1638
1828
  }
1639
1829
  //#endregion
1830
+ //#region ../js/src/main-lifts.ts
1831
+ /**
1832
+ * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
1833
+ * first family that matches, so the more specific / easily-confused families come before the broad
1834
+ * overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
1835
+ * swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
1836
+ * This is the single place to edit the lift set.
1837
+ */
1838
+ const MAIN_LIFT_FAMILIES = [
1839
+ {
1840
+ key: "cleanjerk",
1841
+ label: "Clean & Jerk",
1842
+ matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
1843
+ },
1844
+ {
1845
+ key: "snatch",
1846
+ label: "Snatch",
1847
+ matches: (t) => t.includes("snatch")
1848
+ },
1849
+ {
1850
+ key: "deadlift",
1851
+ label: "Deadlift",
1852
+ matches: (t) => t.includes("deadlift")
1853
+ },
1854
+ {
1855
+ key: "squat",
1856
+ label: "Squat",
1857
+ matches: (t) => t.includes("squat")
1858
+ },
1859
+ {
1860
+ key: "bench",
1861
+ label: "Bench Press",
1862
+ matches: (t) => t.includes("bench")
1863
+ },
1864
+ {
1865
+ key: "overhead",
1866
+ label: "Overhead Press",
1867
+ matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
1868
+ }
1869
+ ];
1870
+ /** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
1871
+ function classifyMainLift(title) {
1872
+ const t = title.toLowerCase();
1873
+ for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
1874
+ return null;
1875
+ }
1876
+ const DEFAULT_MONTHS = 12;
1877
+ function pad2(n) {
1878
+ return String(n).padStart(2, "0");
1879
+ }
1880
+ /** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
1881
+ function isoDay(d) {
1882
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
1883
+ }
1884
+ /**
1885
+ * Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
1886
+ * logged workouts over the last `months` (default 12) — the program-workout range, the reliable
1887
+ * record of performed sets — buckets every performed exercise into a lift family, and for each
1888
+ * family picks the variant logged most often. Returns one entry per family the athlete has logged;
1889
+ * families they never trained are simply absent. (The monthly calendar summary is not used: it
1890
+ * comes back empty for some accounts that have logged sets in the range endpoint.)
1891
+ */
1892
+ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
1893
+ const months = opts.months ?? DEFAULT_MONTHS;
1894
+ const now = opts.now ?? /* @__PURE__ */ new Date();
1895
+ const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
1896
+ const tally = /* @__PURE__ */ new Map();
1897
+ let workouts = [];
1898
+ try {
1899
+ workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
1900
+ } catch {
1901
+ workouts = [];
1902
+ }
1903
+ for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
1904
+ if (ex.performed.length === 0 || ex.exerciseId === null) continue;
1905
+ const family = classifyMainLift(ex.title);
1906
+ if (family === null) continue;
1907
+ const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
1908
+ const prev = byId.get(ex.exerciseId);
1909
+ byId.set(ex.exerciseId, {
1910
+ count: (prev?.count ?? 0) + 1,
1911
+ title: prev?.title ?? ex.title
1912
+ });
1913
+ tally.set(family, byId);
1914
+ }
1915
+ const lifts = [];
1916
+ for (const family of MAIN_LIFT_FAMILIES) {
1917
+ const byId = tally.get(family.key);
1918
+ if (!byId || byId.size === 0) continue;
1919
+ let best = null;
1920
+ for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
1921
+ exerciseId,
1922
+ count,
1923
+ title
1924
+ };
1925
+ if (best) lifts.push({
1926
+ family: family.key,
1927
+ label: family.label,
1928
+ exerciseId: best.exerciseId,
1929
+ title: best.title
1930
+ });
1931
+ }
1932
+ return {
1933
+ athleteId,
1934
+ athleteName: null,
1935
+ lifts
1936
+ };
1937
+ }
1938
+ const PR_CONCURRENCY = 5;
1939
+ /** The heaviest PR on an exercise's board (ties broken by more reps). */
1940
+ function bestPr(liftPRs) {
1941
+ let best = null;
1942
+ for (const pr of liftPRs) {
1943
+ const weight = coerceNum(pr.weight);
1944
+ if (weight === null) continue;
1945
+ const reps = coerceInt(pr.reps);
1946
+ if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
1947
+ weight,
1948
+ reps,
1949
+ units: pr.units,
1950
+ date: pr.date
1951
+ };
1952
+ }
1953
+ return best;
1954
+ }
1955
+ /**
1956
+ * A roster athlete's best PR for each main lift. Discovers the lift variants they log
1957
+ * ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
1958
+ * The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
1959
+ * athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
1960
+ * render a stable row of columns.
1961
+ */
1962
+ async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
1963
+ const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
1964
+ const byFamily = new Map(lifts.map((l) => [l.family, l]));
1965
+ return {
1966
+ athleteId,
1967
+ athleteName,
1968
+ prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
1969
+ const lift = byFamily.get(family.key);
1970
+ const base = {
1971
+ family: family.key,
1972
+ label: family.label
1973
+ };
1974
+ const empty = {
1975
+ exerciseId: null,
1976
+ title: null,
1977
+ weight: null,
1978
+ reps: null,
1979
+ units: null,
1980
+ date: null
1981
+ };
1982
+ if (!lift) return {
1983
+ ...base,
1984
+ ...empty
1985
+ };
1986
+ const known = {
1987
+ exerciseId: lift.exerciseId,
1988
+ title: lift.title
1989
+ };
1990
+ try {
1991
+ const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
1992
+ return {
1993
+ ...base,
1994
+ ...known,
1995
+ weight: best?.weight ?? null,
1996
+ reps: best?.reps ?? null,
1997
+ units: best?.units ?? null,
1998
+ date: best?.date ?? null
1999
+ };
2000
+ } catch {
2001
+ return {
2002
+ ...base,
2003
+ ...known,
2004
+ weight: null,
2005
+ reps: null,
2006
+ units: null,
2007
+ date: null
2008
+ };
2009
+ }
2010
+ })
2011
+ };
2012
+ }
2013
+ const ROSTER_CONCURRENCY = 4;
2014
+ /**
2015
+ * Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
2016
+ * resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
2017
+ * `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
2018
+ * to the roster name when the per-athlete read can't supply one. This is the single roster-level
2019
+ * primitive the CLI, the MCP tool, and the warehouse store all build on.
2020
+ */
2021
+ async function fetchRosterMainLiftPRs(client, opts = {}) {
2022
+ const roster = await fetchCoachRoster(client, opts.athleteIds);
2023
+ const inner = {
2024
+ ...opts.months !== void 0 ? { months: opts.months } : {},
2025
+ ...opts.now !== void 0 ? { now: opts.now } : {}
2026
+ };
2027
+ return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
2028
+ const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
2029
+ return {
2030
+ athleteId: athlete.id,
2031
+ athleteName: result.athleteName ?? athlete.name,
2032
+ prs: result.prs
2033
+ };
2034
+ });
2035
+ }
2036
+ //#endregion
1640
2037
  //#region ../js/src/util.ts
1641
2038
  /**
1642
2039
  * Drop the keys whose value is `undefined`, so the result can be passed to a function or
@@ -2425,6 +2822,37 @@ function registerReadTools(server, ctx) {
2425
2822
  registerTeamVolume(server, ctx);
2426
2823
  }
2427
2824
  //#endregion
2825
+ //#region ../core/src/tools/main-lifts.ts
2826
+ const monthsParam = z.number().int().positive().max(36).optional();
2827
+ const ATHLETE_DESC = "A roster athlete's personal records for the main barbell lifts (squat, bench press, deadlift, overhead press, clean & jerk, snatch). Pass athleteId from list_athletes — nothing else. It auto-discovers which exercise VARIANT the athlete actually logs for each lift (e.g. 'Back Squat', not the empty 'Squat' library entry) by scanning their recent training, so you do NOT resolve exercise ids yourself. Returns one row per lift family in a fixed order; a lift the athlete has not logged comes back with null fields (no PR yet). `months` (default 12) is how far back to look for the logged variants.";
2828
+ const ROSTER_DESC = "Every roster athlete's main-lift PRs in one call — the squad board for squat/bench/deadlift/overhead press/clean & jerk/snatch. Same per-athlete discovery as athlete_main_lift_prs, fanned out across the roster (bounded), so it makes many upstream calls; expect a few seconds on a big roster. Optional athleteIds restricts it to a subset (else the whole roster from /v5/athletes); `months` (default 12) sets the look-back for logged variants.";
2829
+ /** Coach main-lift PR reads: one athlete, or the whole roster at once. */
2830
+ function registerMainLiftTools(server, ctx) {
2831
+ server.registerTool("athlete_main_lift_prs", {
2832
+ title: "Athlete main-lift PRs (roster)",
2833
+ description: ATHLETE_DESC,
2834
+ inputSchema: {
2835
+ athleteId: idParam,
2836
+ months: monthsParam
2837
+ },
2838
+ annotations: READ
2839
+ }, ({ athleteId, months }) => attempt(async () => jsonResult(await fetchAthleteMainLiftPRs(ctx.client, toId(athleteId), months !== void 0 ? { months } : {}))));
2840
+ server.registerTool("roster_main_lift_prs", {
2841
+ title: "Roster main-lift PRs",
2842
+ description: ROSTER_DESC,
2843
+ inputSchema: {
2844
+ months: monthsParam,
2845
+ athleteIds: z.array(idParam).optional()
2846
+ },
2847
+ annotations: READ
2848
+ }, ({ months, athleteIds }) => attempt(async () => {
2849
+ return jsonResult(await fetchRosterMainLiftPRs(ctx.client, {
2850
+ ...athleteIds ? { athleteIds: athleteIds.map(toId) } : {},
2851
+ ...months !== void 0 ? { months } : {}
2852
+ }), { hint: "Pass athleteIds to scope to a few athletes, or lower months, to shrink this." });
2853
+ }));
2854
+ }
2855
+ //#endregion
2428
2856
  //#region ../core/src/tools/athlete-training.ts
2429
2857
  /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
2430
2858
  function mapSessionExercises(exercises) {
@@ -2507,6 +2935,8 @@ function registerAthleteTools(server, ctx) {
2507
2935
  }
2508
2936
  }, ({ athleteIds }) => apiCall(ctx, "PUT", "/v5/athletes/restore", { body: { athleteIds: athleteIds.map(toId) } }));
2509
2937
  registerAthleteLogTools(server, ctx);
2938
+ registerAthleteSwapTool(server, ctx);
2939
+ registerAthletePrescribeTool(server, ctx);
2510
2940
  }
2511
2941
  /**
2512
2942
  * Coach "Log for Athlete": read a roster athlete's saved workouts (to get the log ids), then
@@ -2541,20 +2971,11 @@ function registerAthleteLogTools(server, ctx) {
2541
2971
  }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
2542
2972
  const aId = toId(athleteId);
2543
2973
  if (!await confirmGate(server, extra.requestId, `Log results to athlete ${aId}'s saved workout set ${toId(savedWorkoutSetId)} on ${date}? This writes to their coach-visible training log.`, confirm)) return errorResult(NOT_CONFIRMED);
2544
- const mapped = results.map((r) => ({
2545
- savedWorkoutSetExerciseId: toId(r.savedWorkoutSetExerciseId),
2546
- sets: r.sets.map((s) => {
2547
- const slot = {};
2548
- if (s.param1 !== void 0) slot.param1 = s.param1;
2549
- if (s.param2 !== void 0) slot.param2 = s.param2;
2550
- return slot;
2551
- })
2552
- }));
2553
2974
  return jsonResult(await logForAthlete(ctx.client, {
2554
2975
  athleteId: aId,
2555
2976
  date,
2556
2977
  savedWorkoutSetId: toId(savedWorkoutSetId),
2557
- results: mapped
2978
+ results: toSetResults(results)
2558
2979
  }));
2559
2980
  }));
2560
2981
  server.registerTool("coach_log_session", {
@@ -2575,6 +2996,54 @@ function registerAthleteLogTools(server, ctx) {
2575
2996
  }));
2576
2997
  }));
2577
2998
  }
2999
+ /**
3000
+ * Coach per-athlete exercise swap, kept in its own function so registerAthleteLogTools stays
3001
+ * under the oxlint max-lines-per-function cap.
3002
+ */
3003
+ function registerAthleteSwapTool(server, ctx) {
3004
+ server.registerTool("swap_athlete_exercise", {
3005
+ title: "Swap one exercise in a roster athlete's prescribed workout",
3006
+ description: "Coach-facing write: replace one exercise in a roster athlete's scheduled workout with a different one, for that athlete only — the API equivalent of the app's per-athlete \"swap exercise\". The team/program prescription is left untouched, so other athletes on the same program keep the original exercise. Give savedWorkoutSetExerciseId (the athlete's own slot, from athlete_saved_workouts with raw:true) and exerciseId (the replacement, from exercise_resolve / exercise_search). Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3007
+ inputSchema: {
3008
+ ...swapAthleteExerciseArgsSchema.shape,
3009
+ confirm: z.boolean().optional()
3010
+ },
3011
+ annotations: DESTRUCTIVE
3012
+ }, ({ savedWorkoutSetExerciseId, exerciseId, confirm }, extra) => attempt(async () => {
3013
+ const sweId = toId(savedWorkoutSetExerciseId);
3014
+ const exId = toId(exerciseId);
3015
+ if (!await confirmGate(server, extra.requestId, `Swap the exercise in saved workout slot ${sweId} to exercise ${exId}? This changes what this athlete is prescribed (their copy only).`, confirm)) return errorResult(NOT_CONFIRMED);
3016
+ return jsonResult(await swapAthleteExercise(ctx.client, {
3017
+ savedWorkoutSetExerciseId: sweId,
3018
+ exerciseId: exId
3019
+ }));
3020
+ }));
3021
+ }
3022
+ /**
3023
+ * Coach prescription override, kept in its own function so registerAthleteTools stays under the
3024
+ * oxlint max-lines-per-function cap. Lets a coach set the prescribed reps/weight for one of a
3025
+ * roster athlete's saved workout sets without marking it done — "prescribe weights for an athlete".
3026
+ */
3027
+ function registerAthletePrescribeTool(server, ctx) {
3028
+ server.registerTool("prescribe_athlete_set", {
3029
+ title: "Prescribe reps/weight for a roster athlete's set",
3030
+ description: "Coach-facing write: set the prescribed reps and/or weight for one of a roster athlete's scheduled workout sets, for that athlete only, WITHOUT marking it done — the API equivalent of the app's editing an athlete's prescribed values (\"prescribe weights for an athlete\"). The set stays open for the athlete to log against, and the team/program prescription is left untouched, so other athletes keep the original targets. param1 is reps, param2 is weight; pass one sets[] entry per prescribed set. The write REPLACES the slot's prescribed values (the sets you pass become the whole prescription, and an omitted param is cleared), so give the full per-set prescription you want. Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts (raw:true) for that athlete/day. To record a set as PERFORMED instead, use log_athlete_set. Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3031
+ inputSchema: {
3032
+ ...coachPrescribeSetArgsSchema.shape,
3033
+ confirm: z.boolean().optional()
3034
+ },
3035
+ annotations: DESTRUCTIVE
3036
+ }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
3037
+ const aId = toId(athleteId);
3038
+ if (!await confirmGate(server, extra.requestId, `Set prescribed values on athlete ${aId}'s saved workout set ${toId(savedWorkoutSetId)} on ${date}? This changes what this athlete is prescribed (their copy only); it does not mark the set done.`, confirm)) return errorResult(NOT_CONFIRMED);
3039
+ return jsonResult(await prescribeForAthlete(ctx.client, {
3040
+ athleteId: aId,
3041
+ date,
3042
+ savedWorkoutSetId: toId(savedWorkoutSetId),
3043
+ results: toSetResults(results)
3044
+ }));
3045
+ }));
3046
+ }
2578
3047
  //#endregion
2579
3048
  //#region ../core/src/tools/teams.ts
2580
3049
  const ADDITIVE = {
@@ -2994,7 +3463,7 @@ var JsonFileLibraryCache = class {
2994
3463
  };
2995
3464
  //#endregion
2996
3465
  //#region package.json
2997
- var version = "1.1.1";
3466
+ var version = "1.3.0";
2998
3467
  //#endregion
2999
3468
  //#region src/server.ts
3000
3469
  async function main() {
@@ -3014,6 +3483,7 @@ async function main() {
3014
3483
  version
3015
3484
  }, { instructions: SERVER_INSTRUCTIONS });
3016
3485
  registerReadTools(server, ctx);
3486
+ registerMainLiftTools(server, ctx);
3017
3487
  registerAthleteTools(server, ctx);
3018
3488
  registerTeamTools(server, ctx);
3019
3489
  registerAnalyticsTools(server, ctx);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "1.1.1",
3
+ "version": "1.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/sdk": "^1.29.0",
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/core": "1.1.1",
25
- "@trainheroic-unofficial/js": "1.1.1"
24
+ "@trainheroic-unofficial/core": "1.3.0",
25
+ "@trainheroic-unofficial/js": "1.3.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",