@trainheroic-unofficial/coach-mcp 0.6.3 → 0.6.5

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 +691 -152
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -154,7 +154,11 @@ z.object({
154
154
  startDate: dateString,
155
155
  endDate: dateString
156
156
  });
157
- z.object({
157
+ /**
158
+ * Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
159
+ * roster `athleteId` whose set is being logged on their behalf.
160
+ */
161
+ const coachLogSetArgsSchema = z.object({
158
162
  date: dateString,
159
163
  savedWorkoutSetId: idArgSchema,
160
164
  results: z.array(z.object({
@@ -164,7 +168,7 @@ z.object({
164
168
  param2: z.union([z.number(), z.string()]).optional()
165
169
  })).min(1)
166
170
  })).min(1)
167
- });
171
+ }).extend({ athleteId: idArgSchema });
168
172
  //#endregion
169
173
  //#region ../dto/src/exercise.ts
170
174
  /** Body for creating a custom exercise; extra fields the API accepts are preserved. */
@@ -646,7 +650,7 @@ function withUnits(row) {
646
650
  * Present a full raw exercise object for display: drop the raw param-type codes and add the
647
651
  * positional `units` array. Keeps every other field of the raw object intact.
648
652
  */
649
- function presentExercise(raw) {
653
+ function presentExercise$1(raw) {
650
654
  const { param_1_type, param_2_type, ...rest } = raw;
651
655
  return {
652
656
  ...rest,
@@ -731,10 +735,79 @@ async function getArray(client, path, label) {
731
735
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
732
736
  return res.data;
733
737
  }
738
+ /** Lifetime training totals. `use_metric` is required by the API (omitting it 400s). */
739
+ function fetchAthleteProfileSummary(client, userId, useMetric = false) {
740
+ return getJson(client, `/v5/athleteProfile/summary?user_id=${userId}&use_metric=${useMetric ? 1 : 0}`, "athlete profile summary");
741
+ }
742
+ /**
743
+ * Sort a roster-activity list most-recently-active first; never-logged rows (null date) last.
744
+ * Athletes tied on lastLoggedDate break by session count (more sessions first), so a tie is not
745
+ * left to arbitrary input order.
746
+ */
747
+ function sortRosterByRecency(rows) {
748
+ return [...rows].sort((a, b) => {
749
+ if (a.lastLoggedDate !== b.lastLoggedDate) {
750
+ if (a.lastLoggedDate === null) return 1;
751
+ if (b.lastLoggedDate === null) return -1;
752
+ return a.lastLoggedDate < b.lastLoggedDate ? 1 : -1;
753
+ }
754
+ return (b.sessionsCount ?? 0) - (a.sessionsCount ?? 0);
755
+ });
756
+ }
757
+ /**
758
+ * A coach's roster-activity ranking: each athlete's all-time training snapshot (session count,
759
+ * first/last logged date, total reps/volume), sorted most-recently-active first. There is no
760
+ * single roster-activity endpoint, so this fans out `/v5/athleteProfile/summary` per athlete with
761
+ * a small concurrency cap; pass the subset you care about for a large org. A failed or missing
762
+ * summary becomes a null-data row (sorted last), not an error.
763
+ */
764
+ async function fetchRosterActivity(client, athleteIds, useMetric = false) {
765
+ const rows = [];
766
+ const concurrency = 6;
767
+ for (let i = 0; i < athleteIds.length; i += concurrency) {
768
+ const chunk = athleteIds.slice(i, i + concurrency);
769
+ const settled = await Promise.all(chunk.map(async (id) => {
770
+ try {
771
+ return {
772
+ id,
773
+ summary: await fetchAthleteProfileSummary(client, id, useMetric)
774
+ };
775
+ } catch {
776
+ return {
777
+ id,
778
+ summary: null
779
+ };
780
+ }
781
+ }));
782
+ for (const { id, summary } of settled) {
783
+ const count = summary?.sessions_count ?? null;
784
+ const hasSessions = count !== null && count > 0;
785
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
786
+ rows.push({
787
+ athleteId: id,
788
+ sessionsCount: count,
789
+ firstLoggedDate: normDate(summary?.first_logged_date),
790
+ lastLoggedDate: normDate(summary?.last_logged_date),
791
+ totalReps: summary?.reps_sum ?? null,
792
+ totalVolume: summary?.volume_sum ?? null
793
+ });
794
+ }
795
+ }
796
+ return sortRosterByRecency(rows);
797
+ }
734
798
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
735
799
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
736
800
  }
737
801
  /**
802
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
803
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
804
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
805
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
806
+ */
807
+ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
808
+ return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
809
+ }
810
+ /**
738
811
  * A coach's month view of a roster athlete's logged sessions
739
812
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
740
813
  * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
@@ -743,6 +816,171 @@ function fetchExerciseHistoryDetail(client, exerciseId, userId) {
743
816
  function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
744
817
  return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
745
818
  }
819
+ const SLOTS = 10;
820
+ function nonEmpty(value) {
821
+ return value !== void 0 && value !== null && String(value).trim() !== "";
822
+ }
823
+ /**
824
+ * Per-set prescriptions from the param_N_data slots, e.g. ["5 @ 225", "3 @ 245"] or ["AMRAP"].
825
+ * Values are kept raw (a non-numeric prescription like "AMRAP" or "8-12" must survive); the
826
+ * positional units come from the exercise's param types, mirroring the coach presenter.
827
+ */
828
+ function prescribedSets(ex) {
829
+ const out = [];
830
+ for (let i = 1; i <= SLOTS; i += 1) {
831
+ const p1 = ex[`param_1_data_${i}`];
832
+ const p2 = ex[`param_2_data_${i}`];
833
+ const has1 = nonEmpty(p1);
834
+ const has2 = nonEmpty(p2);
835
+ if (!has1 && !has2) continue;
836
+ if (has1 && has2) out.push(`${p1} @ ${p2}`);
837
+ else if (has1) out.push(String(p1));
838
+ else out.push(`@ ${p2}`);
839
+ }
840
+ return out;
841
+ }
842
+ /**
843
+ * The per-set values the athlete actually logged, read from a saved-copy exercise. A set
844
+ * counts as performed only when its `param_{i}_made` flag is 1: the saved copy pre-fills the
845
+ * `param_N_data` slots with the prescription, so the presence of data alone does not mean a
846
+ * set was done. `param_{i}_made` is the same per-set flag the logging write sets, and is the
847
+ * only reliable signal (the `completed` flags are often left at 0 on a logged session).
848
+ */
849
+ function performedSets(ex) {
850
+ const out = [];
851
+ for (let i = 1; i <= SLOTS; i += 1) {
852
+ if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
853
+ const p1 = ex[`param_1_data_${i}`];
854
+ const p2 = ex[`param_2_data_${i}`];
855
+ const has1 = nonEmpty(p1);
856
+ const has2 = nonEmpty(p2);
857
+ if (has1 && has2) out.push(`${p1} @ ${p2}`);
858
+ else if (has1) out.push(String(p1));
859
+ else if (has2) out.push(`@ ${p2}`);
860
+ }
861
+ return out;
862
+ }
863
+ function presentExercise(ex, performedById) {
864
+ const instruction = typeof ex.instruction === "string" && ex.instruction !== "" ? ex.instruction : null;
865
+ const id = coerceInt(ex.id);
866
+ return {
867
+ exerciseId: coerceInt(ex.exercise_id),
868
+ title: typeof ex.title === "string" ? ex.title : "",
869
+ instruction,
870
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type),
871
+ prescribed: prescribedSets(ex),
872
+ performed: (id !== null ? performedById.get(id) : void 0) ?? []
873
+ };
874
+ }
875
+ function presentBlock(set, performedById) {
876
+ const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
877
+ return {
878
+ order: coerceInt(set.order) ?? 0,
879
+ title: typeof set.title === "string" && set.title !== "" ? set.title : null,
880
+ instruction: typeof set.instruction === "string" && set.instruction !== "" ? set.instruction : null,
881
+ isTest: coerceInt(set.is_test) === 1,
882
+ exercises: exercises.filter(isRecord).map((ex) => presentExercise(ex, performedById))
883
+ };
884
+ }
885
+ function str$1(v) {
886
+ return typeof v === "string" && v !== "" ? v : null;
887
+ }
888
+ /** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
889
+ function savedSets(saved) {
890
+ const out = [];
891
+ for (const key of ["workoutSets", "addedWorkoutSets"]) {
892
+ const sets = Array.isArray(saved[key]) ? saved[key] : [];
893
+ for (const set of sets) {
894
+ if (!isRecord(set)) continue;
895
+ const exercises = (Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : []).filter(isRecord);
896
+ out.push({
897
+ set,
898
+ exercises
899
+ });
900
+ }
901
+ }
902
+ return out;
903
+ }
904
+ /**
905
+ * Map each prescription exercise id to the per-set values the athlete logged. In the saved
906
+ * copy, `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
907
+ * entered values live in the same `param_N_data` slots as a prescription — so the
908
+ * prescription reader works on them unchanged.
909
+ */
910
+ function performedByExerciseId(sets) {
911
+ const map = /* @__PURE__ */ new Map();
912
+ for (const { exercises } of sets) for (const ex of exercises) {
913
+ const id = coerceInt(ex.workout_set_exercise_id);
914
+ if (id === null) continue;
915
+ const values = performedSets(ex);
916
+ if (values.length > 0) map.set(id, values);
917
+ }
918
+ return map;
919
+ }
920
+ /** Present a logged set straight from the saved copy (athlete-added or personal work). */
921
+ function presentSavedBlock(set, exercises) {
922
+ return {
923
+ order: coerceInt(set.order) ?? 0,
924
+ title: typeof set.title === "string" && set.title !== "" ? set.title : null,
925
+ instruction: typeof set.instruction === "string" && set.instruction !== "" ? set.instruction : null,
926
+ isTest: coerceInt(set.is_test) === 1,
927
+ exercises: exercises.map((ex) => ({
928
+ exerciseId: coerceInt(ex.exercise_id),
929
+ title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
930
+ instruction: typeof ex.instruction === "string" && ex.instruction !== "" ? ex.instruction : null,
931
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type),
932
+ prescribed: [],
933
+ performed: performedSets(ex)
934
+ }))
935
+ };
936
+ }
937
+ /**
938
+ * Flatten one `/3.0/athlete/programworkout/range` item into a readable workout, merging the
939
+ * prescription (`summarizedSavedWorkout.workout`) with what the athlete logged
940
+ * (`summarizedSavedWorkout.saved_workout`). Each exercise carries both its `prescribed` and
941
+ * `performed` sets; athlete-added/personal work that has no prescription is appended as its
942
+ * own blocks. No `raw` is needed to see logged results.
943
+ */
944
+ function presentAthleteWorkout(raw) {
945
+ const rec = raw;
946
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
947
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
948
+ const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : {};
949
+ const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
950
+ const logged = savedSets(saved);
951
+ const performedById = performedByExerciseId(logged);
952
+ const blocks = prescriptionSets.map((s) => presentBlock(s, performedById)).sort((a, b) => a.order - b.order);
953
+ const prescribedIds = /* @__PURE__ */ new Set();
954
+ for (const s of prescriptionSets) {
955
+ const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
956
+ for (const ex of exs) {
957
+ if (!isRecord(ex)) continue;
958
+ const id = coerceInt(ex.id);
959
+ if (id !== null) prescribedIds.add(id);
960
+ }
961
+ }
962
+ for (const { set, exercises } of logged) {
963
+ const extra = exercises.filter((ex) => {
964
+ if (performedSets(ex).length === 0) return false;
965
+ const id = coerceInt(ex.workout_set_exercise_id);
966
+ return id === null || !prescribedIds.has(id);
967
+ });
968
+ if (extra.length > 0) blocks.push(presentSavedBlock(set, extra));
969
+ }
970
+ return {
971
+ id: coerceInt(rec.id),
972
+ date: str$1(rec.date) ?? "",
973
+ title: str$1(rec.workout_title) ?? "",
974
+ program: str$1(rec.program_title),
975
+ team: str$1(rec.team_title),
976
+ instruction: str$1(workout.instruction),
977
+ logged: blocks.some((b) => b.exercises.some((e) => e.performed.length > 0)),
978
+ blocks
979
+ };
980
+ }
981
+ function presentAthleteWorkouts(list) {
982
+ return list.map(presentAthleteWorkout);
983
+ }
746
984
  /**
747
985
  * Flatten the coach athlete-calendar summary into compact per-session rows: title, the `logged`
748
986
  * flag (the reliable did-they-train signal), rpe/duration/notes, and the exercises performed with
@@ -791,6 +1029,178 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
791
1029
  sessions
792
1030
  };
793
1031
  }
1032
+ const MAX_PARAM_SLOTS = 10;
1033
+ /**
1034
+ * Build the body for `PUT /1.0/athlete/savedworkoutsetexercise/{id}`. The body uses
1035
+ * snake_case keys matching the live API response shape. Each set slot (1-10) gets a
1036
+ * `param_N_made` flag (1 if data is present, 0 otherwise) and `param_1_data_N` /
1037
+ * `param_2_data_N` string values.
1038
+ *
1039
+ * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1040
+ * required from the live exercise record; everything else is derived from `results`.
1041
+ *
1042
+ * Exported for unit testing — callers should use `logAthleteSet` instead.
1043
+ */
1044
+ function buildExerciseLogPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results) {
1045
+ if (results.length > MAX_PARAM_SLOTS) throw new Error(`At most ${MAX_PARAM_SLOTS} sets are supported per exercise; got ${results.length}.`);
1046
+ const body = {
1047
+ id: savedWorkoutSetExerciseId,
1048
+ saved_workout_set_id: savedWorkoutSetId,
1049
+ workout_set_exercise_id: workoutSetExerciseId,
1050
+ completed: results.some((s) => s.param1 !== void 0 || s.param2 !== void 0) ? 1 : 0
1051
+ };
1052
+ for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
1053
+ const slot = results[i - 1];
1054
+ const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
1055
+ const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
1056
+ body[`param_${i}_made`] = p1 !== "" || p2 !== "" ? 1 : 0;
1057
+ body[`param_1_data_${i}`] = p1;
1058
+ body[`param_2_data_${i}`] = p2;
1059
+ }
1060
+ return body;
1061
+ }
1062
+ /**
1063
+ * Locate the target saved workout set across all program workouts on the given day.
1064
+ * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
1065
+ * can look up `workout_set_exercise_id` by `savedWorkoutSetExerciseId`, and the raw set
1066
+ * record so callers can build the set-completion PUT body via `buildSetCompletePayload`.
1067
+ */
1068
+ function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
1069
+ const available = [];
1070
+ for (const pw of workouts) {
1071
+ const rec = pw;
1072
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1073
+ const sw = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1074
+ if (!sw) continue;
1075
+ const sets = Array.isArray(sw.workoutSets) ? sw.workoutSets : [];
1076
+ for (const s of sets) {
1077
+ if (!isRecord(s)) continue;
1078
+ const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises.filter(isRecord) : [];
1079
+ if (coerceInt(s.id) === savedWorkoutSetId) {
1080
+ const savedWorkoutId = coerceInt(sw.id);
1081
+ if (!savedWorkoutId) continue;
1082
+ return {
1083
+ savedWorkoutId,
1084
+ exercises,
1085
+ rawSet: s
1086
+ };
1087
+ }
1088
+ const setId = coerceInt(s.id);
1089
+ if (setId !== null) {
1090
+ const exLabels = exercises.map((ex) => {
1091
+ const exId = coerceInt(ex.id);
1092
+ const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
1093
+ return exId === null ? null : `${exId} (${title})`;
1094
+ }).filter((x) => x !== null);
1095
+ available.push(`set ${setId} → exercise ids: ${exLabels.join(", ") || "none"}`);
1096
+ }
1097
+ }
1098
+ }
1099
+ const hint = available.length > 0 ? ` Saved workout sets present on this date: ${available.join("; ")}. Pass a "set N" id to --set (the savedWorkoutSetId), and the matching "exercise id" as savedWorkoutSetExerciseId in the results.` : " No saved workout is scheduled on this date — log against a date that has a workout (find it via athlete-workouts / coach athlete-workouts).";
1100
+ throw new Error(`Saved workout set ${savedWorkoutSetId} not found on this date.${hint}`);
1101
+ }
1102
+ /**
1103
+ * Build the body for `PUT /1.0/athlete/savedworkoutset/{id}` that marks the set completed.
1104
+ *
1105
+ * The API requires the **app's camelCase in-memory model**, not the snake_case shape the
1106
+ * GET endpoints return. Key field mappings from the raw set record:
1107
+ * saved_workout_id → sessionId
1108
+ * workout_set_id → workoutSetId
1109
+ * is_super_set (0/1) → isSuperSet (boolean)
1110
+ * plain_text (0/1) → isPlainText (boolean)
1111
+ * unit ("lb"/"kg") → isMetric (boolean)
1112
+ * workoutSetExercises[].id → exercises (array of IDs)
1113
+ *
1114
+ * `exerciseIds` must be the savedWorkoutSetExercise IDs (not workout_set_exercise_ids).
1115
+ *
1116
+ * Exported for unit testing — callers should use `logAthleteSet` instead.
1117
+ */
1118
+ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
1119
+ const id = coerceInt(rawSet.id);
1120
+ const sessionId = coerceInt(rawSet.saved_workout_id);
1121
+ const workoutSetId = coerceInt(rawSet.workout_set_id);
1122
+ if (!id || !sessionId || !workoutSetId) throw new Error("Raw set is missing required id / saved_workout_id / workout_set_id.");
1123
+ const unit = typeof rawSet.unit === "string" ? rawSet.unit : "";
1124
+ return {
1125
+ id,
1126
+ sessionId,
1127
+ workoutSetId,
1128
+ completed: complete ? "1" : "0",
1129
+ rx: coerceInt(rawSet.rx) ?? 0,
1130
+ version: coerceInt(rawSet.version) ?? 0,
1131
+ isMetric: unit.toLowerCase() === "kg",
1132
+ isSuperSet: rawSet.is_super_set === 1 || rawSet.is_super_set === true,
1133
+ isPlainText: rawSet.plain_text === 1 || rawSet.plain_text === true,
1134
+ title: typeof rawSet.title === "string" ? rawSet.title : "",
1135
+ instruction: typeof rawSet.instruction === "string" ? rawSet.instruction : "",
1136
+ notes: rawSet.notes ?? null,
1137
+ exercises: [...exerciseIds]
1138
+ };
1139
+ }
1140
+ /**
1141
+ * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
1142
+ * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
1143
+ * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
1144
+ * contract as {@link logAthleteSet}; the bodies are identical except each is stamped with
1145
+ * `athleteId`. The day is located through the coach range endpoint for that athlete.
1146
+ *
1147
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only for results and return 401 on the
1148
+ * data-write step; real (invited) athletes accept it.
1149
+ */
1150
+ async function logForAthlete(client, args) {
1151
+ const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
1152
+ return writeSetResults(client, {
1153
+ role: "coach",
1154
+ athleteId: args.athleteId
1155
+ }, workouts, args.savedWorkoutSetId, args.results);
1156
+ }
1157
+ /**
1158
+ * Shared two-step set-log write behind {@link logAthleteSet} and {@link logForAthlete}.
1159
+ * `target` selects the surface: `athlete` writes `/1.0/athlete/...`; `coach` writes
1160
+ * `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body. Step 1 PUTs each
1161
+ * exercise's entered data to its own endpoint (the only path that actually stores reps and
1162
+ * weight). Step 2 marks the set completed; that body needs the app's camelCase in-memory
1163
+ * shape and the full list of savedWorkoutSetExercise IDs in the set (not only the logged ones).
1164
+ */
1165
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results) {
1166
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1167
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1168
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1169
+ let exercisesLogged = 0;
1170
+ for (const result of results) {
1171
+ const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
1172
+ if (!ex) {
1173
+ const valid = exercises.map((e) => {
1174
+ const id = coerceInt(e.id);
1175
+ const title = typeof e.exercise_title === "string" && e.exercise_title || typeof e.title === "string" && e.title || "exercise";
1176
+ return id === null ? null : `${id} (${title})`;
1177
+ }).filter((x) => x !== null);
1178
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1179
+ }
1180
+ const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1181
+ if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
1182
+ const body = {
1183
+ ...buildExerciseLogPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets),
1184
+ ...extra
1185
+ };
1186
+ const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
1187
+ if (!res.ok) {
1188
+ 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.` : "";
1189
+ throw new Error(`Failed to log exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1190
+ }
1191
+ exercisesLogged += 1;
1192
+ }
1193
+ const setBody = {
1194
+ ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1195
+ ...extra
1196
+ };
1197
+ const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1198
+ if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1199
+ return {
1200
+ savedWorkoutSetId,
1201
+ exercisesLogged
1202
+ };
1203
+ }
794
1204
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
795
1205
  function presentExerciseHistory(detail) {
796
1206
  return {
@@ -811,6 +1221,197 @@ function presentExerciseHistory(detail) {
811
1221
  }))
812
1222
  };
813
1223
  }
1224
+ /** Normalize one-or-many emails into a deduped, trimmed list. */
1225
+ function emailList(emails) {
1226
+ return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
1227
+ }
1228
+ /**
1229
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
1230
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
1231
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
1232
+ */
1233
+ async function inviteAthletes(client, args) {
1234
+ const list = emailList(args.emails);
1235
+ if (list.length === 0) throw new Error("Provide at least one email address to invite.");
1236
+ const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
1237
+ if (!validation.ok) {
1238
+ const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
1239
+ throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
1240
+ }
1241
+ const valid = Array.isArray(validation.data) ? validation.data : list;
1242
+ if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
1243
+ const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
1244
+ teamType: 0,
1245
+ teamId: args.teamId,
1246
+ orgId: null,
1247
+ emails: valid,
1248
+ message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
1249
+ } });
1250
+ if (!invite.ok) {
1251
+ const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
1252
+ throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
1253
+ }
1254
+ return {
1255
+ teamId: args.teamId,
1256
+ invited: valid,
1257
+ result: invite.data
1258
+ };
1259
+ }
1260
+ /**
1261
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
1262
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
1263
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
1264
+ */
1265
+ async function copySession(client, args) {
1266
+ const [year, month, day] = parseWorkoutDate(args.toDate);
1267
+ const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
1268
+ const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
1269
+ const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
1270
+ toProgramId: args.toProgramId,
1271
+ pwId: args.pwId,
1272
+ toDate: {
1273
+ date: iso,
1274
+ day,
1275
+ month,
1276
+ year,
1277
+ dayOfWeek,
1278
+ isToday: false
1279
+ }
1280
+ } });
1281
+ if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
1282
+ return res.data;
1283
+ }
1284
+ const ANALYTICS_METRIC_KEYS = [
1285
+ "readiness-team",
1286
+ "readiness-athlete",
1287
+ "lift-1rm-history",
1288
+ "training-summary-athlete",
1289
+ "compliance-team",
1290
+ "lift-progress-team",
1291
+ "working-max-history"
1292
+ ];
1293
+ const ANALYTICS_METRICS = {
1294
+ "readiness-team": {
1295
+ path: "/v5/analytics/readiness/teams",
1296
+ scope: "team",
1297
+ inputs: ["date"],
1298
+ requires: ["date"]
1299
+ },
1300
+ "readiness-athlete": {
1301
+ path: "/v5/analytics/readiness/users",
1302
+ scope: "user",
1303
+ inputs: ["dateStart", "dateEnd"],
1304
+ requires: ["dateStart", "dateEnd"]
1305
+ },
1306
+ "lift-1rm-history": {
1307
+ path: "/v5/analytics/lift-one-rep-max-history/users",
1308
+ scope: "user",
1309
+ inputs: [
1310
+ "dateStart",
1311
+ "dateEnd",
1312
+ "exerciseId",
1313
+ "useMetric"
1314
+ ],
1315
+ requires: [
1316
+ "dateStart",
1317
+ "dateEnd",
1318
+ "exerciseId"
1319
+ ]
1320
+ },
1321
+ "training-summary-athlete": {
1322
+ path: "/v5/analytics/training-summary/users",
1323
+ scope: "user",
1324
+ inputs: ["dateStart", "dateEnd"],
1325
+ requires: ["dateStart", "dateEnd"]
1326
+ },
1327
+ "compliance-team": {
1328
+ path: "/v5/analytics/compliance",
1329
+ scope: "team",
1330
+ inputs: ["dateStart", "dateEnd"],
1331
+ requires: ["dateStart", "dateEnd"]
1332
+ },
1333
+ "lift-progress-team": {
1334
+ path: "/v5/analytics/lift-progress/teams",
1335
+ scope: "team",
1336
+ inputs: [
1337
+ "exerciseId",
1338
+ "dateStart",
1339
+ "dateEnd"
1340
+ ],
1341
+ requires: [
1342
+ "exerciseId",
1343
+ "dateStart",
1344
+ "dateEnd"
1345
+ ]
1346
+ },
1347
+ "working-max-history": {
1348
+ path: "/v5/analytics/working-max-history/users",
1349
+ scope: "user",
1350
+ inputs: [
1351
+ "exerciseId",
1352
+ "dateStart",
1353
+ "dateEnd",
1354
+ "useMetric"
1355
+ ],
1356
+ requires: ["exerciseId"]
1357
+ }
1358
+ };
1359
+ const ANALYTICS_BODY_KEY = {
1360
+ date: "date",
1361
+ dateStart: "date_start",
1362
+ dateEnd: "date_end",
1363
+ exerciseId: "exercise_id",
1364
+ useMetric: "use_metric"
1365
+ };
1366
+ /**
1367
+ * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
1368
+ * athlete metrics need one or more `userIds` (passed together — the report returns a row per
1369
+ * athlete). Throws a readable Error when a required input is missing or the call fails.
1370
+ */
1371
+ async function queryAnalytics(client, args) {
1372
+ const spec = ANALYTICS_METRICS[args.metric];
1373
+ const body = {};
1374
+ if (spec.scope === "team") {
1375
+ if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
1376
+ body.teamId = args.teamId;
1377
+ } else {
1378
+ if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
1379
+ body.user_ids = args.userIds.map((u) => String(u));
1380
+ }
1381
+ const inputs = {
1382
+ date: args.date,
1383
+ dateStart: args.dateStart,
1384
+ dateEnd: args.dateEnd,
1385
+ exerciseId: args.exerciseId,
1386
+ useMetric: args.useMetric
1387
+ };
1388
+ const missing = spec.requires.filter((k) => inputs[k] === void 0);
1389
+ if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
1390
+ for (const k of spec.inputs) {
1391
+ const v = inputs[k];
1392
+ if (v === void 0) continue;
1393
+ body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
1394
+ }
1395
+ const res = await client.request("POST", spec.path, { body });
1396
+ if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
1397
+ return res.data;
1398
+ }
1399
+ //#endregion
1400
+ //#region ../js/src/util.ts
1401
+ /**
1402
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
1403
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
1404
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
1405
+ * optional ones lose `undefined` from their value type.
1406
+ *
1407
+ * Example:
1408
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
1409
+ */
1410
+ function definedProps(obj) {
1411
+ const result = {};
1412
+ for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
1413
+ return result;
1414
+ }
814
1415
  //#endregion
815
1416
  //#region ../js/src/workout-encode.ts
816
1417
  const LEADERBOARD_TYPE = {
@@ -1298,7 +1899,7 @@ var ExerciseLibrary = class {
1298
1899
  await this.ensureFresh();
1299
1900
  const s = this.#byId.get(id);
1300
1901
  if (!s) return null;
1301
- return presentExercise(s.raw);
1902
+ return presentExercise$1(s.raw);
1302
1903
  }
1303
1904
  async defaults(id) {
1304
1905
  const s = this.#byId.get(id);
@@ -1401,6 +2002,7 @@ function historyInRange(presented, since, until) {
1401
2002
  //#endregion
1402
2003
  //#region ../core/src/tools/reads.ts
1403
2004
  const ATHLETE_LIFT_HISTORY_DESC = "A roster athlete's lift history for ONE exercise: the all-time PR board (liftPRs — each entry carries its rep-max label, weight, and the date it was set) plus the dated session series (sets, estimated 1RM). This is the coach-side way to answer 'show me <athlete>'s PRs / how is <athlete>'s squat trending' — pass athleteId from list_athletes and exerciseId from exercise_resolve. There is no cross-exercise PR rollup, so you query one lift at a time, but do NOT guess lift names blindly: first call athlete_training for the month(s) of interest — it lists every exercise the athlete actually performed (with the exact exercise the program used, e.g. 'Clean & Jerk' not 'Clean') — then bring those exerciseIds here. An empty result means that lift was not logged. liftPRs stay all-time; pass since/until (YYYY-MM-DD, inclusive) to window the session series. raw:true returns the untouched API object.";
2005
+ const ROSTER_ACTIVITY_DESC = "A coach's roster ranked by actual training recency: for each athleteId you pass (from list_athletes), the all-time sessionsCount, firstLoggedDate, lastLoggedDate, totalReps and totalVolume, sorted most-recently-active first. Use lastLoggedDate — the real training signal — NOT list_athletes' daysSinceLastLogin (app-login, not training) to answer 'who is my most recently active athlete' (the top row) or 'who is falling behind' (a stale or null lastLoggedDate, or low volume). A null lastLoggedDate means the athlete has never logged a session. This fans out one lookup per athlete, so for a large org pass only the athletes you care about. Then drill into a name with athlete_training (their month) or athlete_lift_history.";
1404
2006
  const ATHLETE_TRAINING_DESC = "A roster athlete's training for one calendar month (coach-side): one row per session with its title, the `logged` flag (the reliable did-they-train signal — true means they logged it), rpe, duration (minutes), notes, and the exercises they performed, each with a set summary like '5 x 2 @ 205 lb'. Use this to answer 'how has <athlete> been training lately' in ONE call, and as the discovery handle a coach otherwise lacks: read the exercise titles here to learn what the athlete actually did, then pass the lifts you care about to athlete_lift_history for their dated PR board. Pass athleteId from list_athletes and a year + month (1-12); query the current month, and the previous month for more history. Sessions are in calendar order within the month (the API carries no per-session date). An empty list means no sessions that month.";
1405
2007
  function enc(value) {
1406
2008
  return encodeURIComponent(String(value));
@@ -1448,7 +2050,7 @@ function registerRosterReads(server, ctx) {
1448
2050
  }, () => apiCall(ctx, "GET", t.path));
1449
2051
  server.registerTool("list_athletes", {
1450
2052
  title: "List athletes",
1451
- description: "Every athlete on this coach's org roster, across all teams (not scoped to one team; the account owner themselves and demo/placeholder athletes are included, so the roster count includes you). `daysSinceLastLogin` is app-login recency, not training activity — an athlete can have logged in today yet have no logged sessions; null means no login on record. For per-team attribution use each athlete's own `groups`/`groupTitles` (the teams they are enrolled in) and `teamCount`; there is no per-team roster endpoint or other per-athlete team field. Optional q (case-insensitive; each whitespace-separated word must appear in the record, so 'Kyle Jones' matches a 'Jones, [Demo] Kyle' entry) and limit, applied client-side, keep large rosters small.",
2053
+ description: "Every athlete on this coach's org roster, across all teams (not scoped to one team; the account owner themselves and demo/placeholder athletes are included, so the roster count includes you). `daysSinceLastLogin` is app-login recency, not training activity — an athlete can have logged in today yet have no logged sessions; null means no login on record. For per-team attribution use each athlete's own `groups`/`groupTitles` (the teams they are enrolled in) and `teamCount`; there is no per-team roster endpoint or other per-athlete team field. To rank athletes by real training recency (most recently active, or who is falling behind), pass their ids to roster_activity instead of reading daysSinceLastLogin. Optional q (case-insensitive; each whitespace-separated word must appear in the record, so 'Kyle Jones' matches a 'Jones, [Demo] Kyle' entry) and limit, applied client-side, keep large rosters small.",
1452
2054
  inputSchema: {
1453
2055
  q: z.string().optional(),
1454
2056
  limit: z.number().int().positive().max(500).optional()
@@ -1526,6 +2128,15 @@ function registerEntityReads(server, ctx) {
1526
2128
  if (raw === true) return jsonResult(detail);
1527
2129
  return jsonResult(historyInRange(presentExerciseHistory(detail), since, until));
1528
2130
  }));
2131
+ server.registerTool("roster_activity", {
2132
+ title: "Roster training activity (recency)",
2133
+ description: ROSTER_ACTIVITY_DESC,
2134
+ inputSchema: {
2135
+ athleteIds: z.array(idParam).min(1),
2136
+ useMetric: z.boolean().optional()
2137
+ },
2138
+ annotations: READ
2139
+ }, ({ athleteIds, useMetric }) => attempt(async () => jsonResult(await fetchRosterActivity(ctx.client, athleteIds.map(toId), useMetric ?? false), { hint: "Sorted most-recently-active first; lastLoggedDate null = never logged. The top row is the most recently active athlete." })));
1529
2140
  server.registerTool("athlete_training", {
1530
2141
  title: "Athlete training month (roster)",
1531
2142
  description: ATHLETE_TRAINING_DESC,
@@ -1552,7 +2163,6 @@ function registerReadTools(server, ctx) {
1552
2163
  }
1553
2164
  //#endregion
1554
2165
  //#region ../core/src/tools/athletes.ts
1555
- const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
1556
2166
  /** Normalize one-or-many emails into a deduped, trimmed list. */
1557
2167
  function asEmailList(emails) {
1558
2168
  return [...new Set((Array.isArray(emails) ? emails : [emails]).map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -1580,28 +2190,14 @@ function registerAthleteTools(server, ctx) {
1580
2190
  if (list.length === 0) return errorResult("Provide at least one email address to invite.");
1581
2191
  const id = toId(teamId);
1582
2192
  if (!await confirmGate(server, extra.requestId, `Invite ${list.join(", ")} to team ${id}? This emails them a real TrainHeroic invitation.`, confirm)) return errorResult(NOT_CONFIRMED);
1583
- const validation = await ctx.client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
1584
- if (!validation.ok) {
1585
- const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
1586
- return errorResult(`Email validation failed (HTTP ${validation.status}): ${detail}`);
1587
- }
1588
- const valid = Array.isArray(validation.data) ? validation.data : list;
1589
- if (valid.length === 0) return errorResult(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
1590
- const invite = await ctx.client.request("POST", "/v5/athletes/inviteToTeam", { body: {
1591
- teamType: 0,
1592
- teamId: id,
1593
- orgId: null,
1594
- emails: valid,
1595
- message: message ?? DEFAULT_INVITE_MESSAGE
1596
- } });
1597
- if (!invite.ok) {
1598
- const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
1599
- return errorResult(`Invite failed (HTTP ${invite.status}): ${detail}`);
1600
- }
1601
2193
  return jsonResult({
1602
2194
  invited: true,
1603
2195
  teamId: id,
1604
- result: invite.data
2196
+ result: (await inviteAthletes(ctx.client, definedProps({
2197
+ teamId: id,
2198
+ emails: list,
2199
+ message
2200
+ }))).result
1605
2201
  });
1606
2202
  }));
1607
2203
  server.registerTool("athlete_archive", {
@@ -1628,6 +2224,57 @@ function registerAthleteTools(server, ctx) {
1628
2224
  openWorldHint: true
1629
2225
  }
1630
2226
  }, ({ athleteIds }) => apiCall(ctx, "PUT", "/v5/athletes/restore", { body: { athleteIds: athleteIds.map(toId) } }));
2227
+ registerAthleteLogTools(server, ctx);
2228
+ }
2229
+ /**
2230
+ * Coach "Log for Athlete": read a roster athlete's saved workouts (to get the log ids), then
2231
+ * record set results on their behalf. The write is the API equivalent of the app's mobile
2232
+ * "Log for Athlete" flow. Kept in its own function so registerAthleteTools stays under the
2233
+ * oxlint max-lines-per-function cap.
2234
+ */
2235
+ function registerAthleteLogTools(server, ctx) {
2236
+ server.registerTool("athlete_saved_workouts", {
2237
+ title: "Roster athlete's saved workouts (with log ids)",
2238
+ description: "A roster athlete's scheduled/logged workouts in an inclusive YYYY-MM-DD window — the coach-side view that carries the savedWorkoutSetId and savedWorkoutSetExerciseId that log_athlete_set needs. Get athleteId from list_athletes. Defaults to a presented view; set raw:true for the untouched API objects that expose those ids (each set's id is the savedWorkoutSetId; each savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId). athlete_training gives a whole-month overview but not these ids.",
2239
+ inputSchema: {
2240
+ athleteId: idParam,
2241
+ startDate: dateString,
2242
+ endDate: dateString,
2243
+ raw: z.boolean().optional()
2244
+ },
2245
+ annotations: READ
2246
+ }, ({ athleteId, startDate, endDate, raw }) => attempt(async () => {
2247
+ const workouts = await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate);
2248
+ if (raw === true) return jsonResult(workouts, { hint: "Each set's id is the savedWorkoutSetId; each savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId. Pass both to log_athlete_set. Narrow the dates to shrink this." });
2249
+ return jsonResult(presentAthleteWorkouts(workouts), { hint: "Set raw:true to get savedWorkoutSetId + savedWorkoutSetExerciseId for log_athlete_set." });
2250
+ }));
2251
+ server.registerTool("log_athlete_set", {
2252
+ title: "Log set results for a roster athlete",
2253
+ description: "Coach-facing write: record entered results (reps/weight per set) for one of a roster athlete's saved workout sets on a given day, marking the set completed — the API equivalent of the app's \"Log for Athlete\". Writes to that athlete's training log and shows in their history. Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts (raw:true) for that athlete/day. Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
2254
+ inputSchema: {
2255
+ ...coachLogSetArgsSchema.shape,
2256
+ confirm: z.boolean().optional()
2257
+ },
2258
+ annotations: DESTRUCTIVE
2259
+ }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
2260
+ const aId = toId(athleteId);
2261
+ 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);
2262
+ const mapped = results.map((r) => ({
2263
+ savedWorkoutSetExerciseId: toId(r.savedWorkoutSetExerciseId),
2264
+ sets: r.sets.map((s) => {
2265
+ const slot = {};
2266
+ if (s.param1 !== void 0) slot.param1 = s.param1;
2267
+ if (s.param2 !== void 0) slot.param2 = s.param2;
2268
+ return slot;
2269
+ })
2270
+ }));
2271
+ return jsonResult(await logForAthlete(ctx.client, {
2272
+ athleteId: aId,
2273
+ date,
2274
+ savedWorkoutSetId: toId(savedWorkoutSetId),
2275
+ results: mapped
2276
+ }));
2277
+ }));
1631
2278
  }
1632
2279
  //#endregion
1633
2280
  //#region ../core/src/tools/teams.ts
@@ -1694,95 +2341,14 @@ function registerTeamTools(server, ctx) {
1694
2341
  }
1695
2342
  //#endregion
1696
2343
  //#region ../core/src/tools/analytics.ts
1697
- const METRIC_KEYS = [
1698
- "readiness-team",
1699
- "readiness-athlete",
1700
- "lift-1rm-history",
1701
- "training-summary-athlete",
1702
- "compliance-team",
1703
- "lift-progress-team",
1704
- "working-max-history"
1705
- ];
1706
- const METRICS = {
1707
- "readiness-team": {
1708
- path: "/v5/analytics/readiness/teams",
1709
- scope: "team",
1710
- inputs: ["date"],
1711
- requires: ["date"]
1712
- },
1713
- "readiness-athlete": {
1714
- path: "/v5/analytics/readiness/users",
1715
- scope: "user",
1716
- inputs: ["dateStart", "dateEnd"],
1717
- requires: ["dateStart", "dateEnd"]
1718
- },
1719
- "lift-1rm-history": {
1720
- path: "/v5/analytics/lift-one-rep-max-history/users",
1721
- scope: "user",
1722
- inputs: [
1723
- "dateStart",
1724
- "dateEnd",
1725
- "exerciseId",
1726
- "useMetric"
1727
- ],
1728
- requires: [
1729
- "dateStart",
1730
- "dateEnd",
1731
- "exerciseId"
1732
- ]
1733
- },
1734
- "training-summary-athlete": {
1735
- path: "/v5/analytics/training-summary/users",
1736
- scope: "user",
1737
- inputs: ["dateStart", "dateEnd"],
1738
- requires: ["dateStart", "dateEnd"]
1739
- },
1740
- "compliance-team": {
1741
- path: "/v5/analytics/compliance",
1742
- scope: "team",
1743
- inputs: ["dateStart", "dateEnd"],
1744
- requires: ["dateStart", "dateEnd"]
1745
- },
1746
- "lift-progress-team": {
1747
- path: "/v5/analytics/lift-progress/teams",
1748
- scope: "team",
1749
- inputs: [
1750
- "exerciseId",
1751
- "dateStart",
1752
- "dateEnd"
1753
- ],
1754
- requires: [
1755
- "exerciseId",
1756
- "dateStart",
1757
- "dateEnd"
1758
- ]
1759
- },
1760
- "working-max-history": {
1761
- path: "/v5/analytics/working-max-history/users",
1762
- scope: "user",
1763
- inputs: [
1764
- "exerciseId",
1765
- "dateStart",
1766
- "dateEnd",
1767
- "useMetric"
1768
- ],
1769
- requires: ["exerciseId"]
1770
- }
1771
- };
1772
- const BODY_KEY = {
1773
- date: "date",
1774
- dateStart: "date_start",
1775
- dateEnd: "date_end",
1776
- exerciseId: "exercise_id",
1777
- useMetric: "use_metric"
1778
- };
2344
+ const ANALYTICS_QUERY_DESC = "Read a TrainHeroic analytics report. The `metric` enum below IS the catalog — pick from it directly (analytics_categories lists the API's raw category names, which do NOT match these keys; you rarely need it). Team metrics (readiness-team, compliance-team, lift-progress-team) need teamId; athlete metrics (readiness-athlete, training-summary-athlete, lift-1rm-history, working-max-history) need userIds — get those from list_athletes. userIds takes MANY athletes in ONE call (pass the whole roster's ids at once); the report comes back with a row per athlete, so do not loop one id per call. For team-wide training volume there is no team summary metric: pass every athlete's userId to training-summary-athlete in a single call and the rows cover the team. An athlete with no logged sessions in range simply returns no rows (not an error). Use that for triage: training-summary-athlete with a single athleteId is the fastest 'has this athlete trained at all, and when' check — no rows means no logged training in range, so don't then fan out blind per-lift athlete_lift_history calls. Despite 'athlete' in the name this metric accepts 1–N userIds. readiness-team takes a single `date`; every other metric takes dateStart/dateEnd. lift-1rm-history, lift-progress-team, and working-max-history also need exerciseId. All dates are YYYY-MM-DD.";
1779
2345
  /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
1780
2346
  function registerAnalyticsTools(server, ctx) {
1781
2347
  server.registerTool("analytics_query", {
1782
2348
  title: "Pull an analytics report",
1783
- description: "Read a TrainHeroic analytics report. The `metric` enum below IS the catalog — pick from it directly (analytics_categories lists the API's raw category names, which do NOT match these keys; you rarely need it). Team metrics (readiness-team, compliance-team, lift-progress-team) need teamId; athlete metrics (readiness-athlete, training-summary-athlete, lift-1rm-history, working-max-history) need userIds — get those from list_athletes. userIds takes MANY athletes in ONE call (pass the whole roster's ids at once); the report comes back with a row per athlete, so do not loop one id per call. For team-wide training volume there is no team summary metric: pass every athlete's userId to training-summary-athlete in a single call and the rows cover the team. An athlete with no logged sessions in range simply returns no rows (not an error). Use that for triage: training-summary-athlete with a single athleteId is the fastest 'has this athlete trained at all, and when' check — no rows means no logged training in range, so don't then fan out blind per-lift athlete_lift_history calls. Despite 'athlete' in the name this metric accepts 1–N userIds. readiness-team takes a single `date`; every other metric takes dateStart/dateEnd. lift-1rm-history, lift-progress-team, and working-max-history also need exerciseId. All dates are YYYY-MM-DD.",
2349
+ description: ANALYTICS_QUERY_DESC,
1784
2350
  inputSchema: {
1785
- metric: z.enum(METRIC_KEYS),
2351
+ metric: z.enum(ANALYTICS_METRIC_KEYS),
1786
2352
  teamId: idParam.optional(),
1787
2353
  userIds: z.array(idParam).optional(),
1788
2354
  exerciseId: idParam.optional(),
@@ -1792,32 +2358,16 @@ function registerAnalyticsTools(server, ctx) {
1792
2358
  useMetric: z.boolean().optional()
1793
2359
  },
1794
2360
  annotations: READ
1795
- }, async ({ metric, teamId, userIds, exerciseId, date, dateStart, dateEnd, useMetric }) => {
1796
- const spec = METRICS[metric];
1797
- const inputs = {
1798
- date,
1799
- dateStart,
1800
- dateEnd,
1801
- exerciseId,
1802
- useMetric
1803
- };
1804
- const body = {};
1805
- if (spec.scope === "team") {
1806
- if (teamId === void 0) return errorResult(`${metric} needs teamId.`);
1807
- body.teamId = toId(teamId);
1808
- } else {
1809
- if (userIds === void 0 || userIds.length === 0) return errorResult(`${metric} needs userIds (one or more athlete ids).`);
1810
- body.user_ids = userIds.map((u) => String(toId(u)));
1811
- }
1812
- const missing = spec.requires.filter((k) => inputs[k] === void 0);
1813
- if (missing.length > 0) return errorResult(`${metric} also needs: ${missing.join(", ")}.`);
1814
- for (const k of spec.inputs) {
1815
- const v = inputs[k];
1816
- if (v === void 0) continue;
1817
- body[BODY_KEY[k]] = k === "exerciseId" ? String(toId(v)) : v;
1818
- }
1819
- return apiCall(ctx, "POST", spec.path, { body }, "Narrow with a tighter date range or fewer athletes.");
1820
- });
2361
+ }, ({ metric, teamId, userIds, exerciseId, date, dateStart, dateEnd, useMetric }) => attempt(async () => jsonResult(await queryAnalytics(ctx.client, definedProps({
2362
+ metric,
2363
+ teamId: teamId !== void 0 ? toId(teamId) : void 0,
2364
+ userIds: userIds?.map(toId),
2365
+ exerciseId: exerciseId !== void 0 ? toId(exerciseId) : void 0,
2366
+ date,
2367
+ dateStart,
2368
+ dateEnd,
2369
+ useMetric
2370
+ })), { hint: "Narrow with a tighter date range or fewer athletes." })));
1821
2371
  }
1822
2372
  //#endregion
1823
2373
  //#region ../core/src/tools/exercises.ts
@@ -2018,22 +2568,11 @@ function registerLifecycle(server, ctx) {
2018
2568
  destructiveHint: false,
2019
2569
  openWorldHint: true
2020
2570
  }
2021
- }, ({ toProgramId, pwId, toDate }) => attempt(async () => {
2022
- const [year, month, day] = parseWorkoutDate(toDate);
2023
- const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
2024
- return apiCall(ctx, "POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
2025
- toProgramId,
2026
- pwId,
2027
- toDate: {
2028
- date: `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`,
2029
- day,
2030
- month,
2031
- year,
2032
- dayOfWeek,
2033
- isToday: false
2034
- }
2035
- } });
2036
- }));
2571
+ }, ({ toProgramId, pwId, toDate }) => attempt(async () => jsonResult(await copySession(ctx.client, {
2572
+ toProgramId,
2573
+ pwId,
2574
+ toDate
2575
+ }))));
2037
2576
  server.registerTool("session_save_as_template", {
2038
2577
  title: "Save a session to the library",
2039
2578
  description: "Save an existing session as a reusable template in the session library (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the workout_id.",
@@ -2156,7 +2695,7 @@ var JsonFileLibraryCache = class {
2156
2695
  };
2157
2696
  //#endregion
2158
2697
  //#region package.json
2159
- var version = "0.6.3";
2698
+ var version = "0.6.5";
2160
2699
  //#endregion
2161
2700
  //#region src/server.ts
2162
2701
  async function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "0.6.3",
3
+ "version": "0.6.5",
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": "0.6.3",
25
- "@trainheroic-unofficial/js": "0.6.3"
24
+ "@trainheroic-unofficial/core": "0.6.5",
25
+ "@trainheroic-unofficial/js": "0.6.5"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",