@trainheroic-unofficial/coach-mcp 1.2.0 → 1.4.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.
- package/dist/server.mjs +423 -17
- package/package.json +3 -3
package/dist/server.mjs
CHANGED
|
@@ -512,7 +512,20 @@ async function confirmGate(server, requestId, message, confirmArg) {
|
|
|
512
512
|
const SERVER_INSTRUCTIONS = "Speak to the user in plain, everyday language about their training. Describe what you are doing in the TrainHeroic app's own terms (for example, say you are creating a workout rather than naming a tool). Do not surface internal tool names (the snake_case identifiers such as athlete_session_create), raw parameter names, or numeric ids in your replies unless the user explicitly asks for them; they are implementation details. The tool descriptions cross-reference each other by name only so you can chain them correctly. Keep that wiring to yourself.";
|
|
513
513
|
//#endregion
|
|
514
514
|
//#region ../js/src/auth.ts
|
|
515
|
-
const
|
|
515
|
+
const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
516
|
+
/**
|
|
517
|
+
* The login endpoint, allowing an env override so a test harness can authenticate against a local
|
|
518
|
+
* fake backend. Precedence: an explicit `TH_AUTH_URL`, else `${TH_APIS_BASE}/auth` (login lives on
|
|
519
|
+
* the apis host, so it follows that base), else the real endpoint. Read via `globalThis.process`
|
|
520
|
+
* (no `import process`) to keep this module workerd-safe, and per call so a child-env override wins.
|
|
521
|
+
*/
|
|
522
|
+
function authUrl() {
|
|
523
|
+
const env = globalThis.process?.env;
|
|
524
|
+
if (env?.TH_AUTH_URL && env.TH_AUTH_URL.length > 0) return env.TH_AUTH_URL;
|
|
525
|
+
const apis = env?.TH_APIS_BASE;
|
|
526
|
+
if (apis && apis.length > 0) return `${apis.replace(/\/$/, "")}/auth`;
|
|
527
|
+
return DEFAULT_AUTH_URL;
|
|
528
|
+
}
|
|
516
529
|
/**
|
|
517
530
|
* Authenticate against TrainHeroic. Returns the session bundle, or null on bad
|
|
518
531
|
* credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
|
|
@@ -520,7 +533,7 @@ const AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
|
520
533
|
* is sent as the `session-token` header and works against both API hosts.
|
|
521
534
|
*/
|
|
522
535
|
async function loginTrainHeroic(email, password) {
|
|
523
|
-
const res = await fetch(
|
|
536
|
+
const res = await fetch(authUrl(), {
|
|
524
537
|
method: "POST",
|
|
525
538
|
headers: {
|
|
526
539
|
"content-type": "application/x-www-form-urlencoded",
|
|
@@ -543,8 +556,19 @@ async function loginTrainHeroic(email, password) {
|
|
|
543
556
|
}
|
|
544
557
|
//#endregion
|
|
545
558
|
//#region ../js/src/client.ts
|
|
546
|
-
const
|
|
547
|
-
const
|
|
559
|
+
const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
|
|
560
|
+
const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
|
|
561
|
+
/**
|
|
562
|
+
* Resolve an API host, allowing an env override. The override exists so a test harness can point
|
|
563
|
+
* the client at a local fake backend (and it doubles as a staging knob); production leaves these
|
|
564
|
+
* unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
|
|
565
|
+
* — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
|
|
566
|
+
* read per request (not at module load) so a value the harness sets in the child env always wins.
|
|
567
|
+
*/
|
|
568
|
+
function envBase(key, fallback) {
|
|
569
|
+
const v = (globalThis.process?.env)?.[key];
|
|
570
|
+
return v && v.length > 0 ? v : fallback;
|
|
571
|
+
}
|
|
548
572
|
var TrainHeroicAuthError = class extends Error {
|
|
549
573
|
name = "TrainHeroicAuthError";
|
|
550
574
|
};
|
|
@@ -583,7 +607,7 @@ var TrainHeroicClient = class {
|
|
|
583
607
|
return this.#sessionId;
|
|
584
608
|
}
|
|
585
609
|
async request(method, path, options = {}) {
|
|
586
|
-
const url = `${options.base === "apis" ?
|
|
610
|
+
const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
|
|
587
611
|
let session = await this.#ensureSession();
|
|
588
612
|
let res = await this.#send(method, url, session, options.body);
|
|
589
613
|
if (res.status === 401 || res.status === 403) {
|
|
@@ -668,6 +692,14 @@ function coerceInt(value) {
|
|
|
668
692
|
}
|
|
669
693
|
return null;
|
|
670
694
|
}
|
|
695
|
+
function coerceNum(value) {
|
|
696
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
|
697
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
698
|
+
const n = Number(value);
|
|
699
|
+
return Number.isFinite(n) ? n : null;
|
|
700
|
+
}
|
|
701
|
+
return null;
|
|
702
|
+
}
|
|
671
703
|
function unitLabel(paramType) {
|
|
672
704
|
const t = coerceInt(paramType);
|
|
673
705
|
if (t === null) return null;
|
|
@@ -766,6 +798,24 @@ function rankSearch(rows, query, limit) {
|
|
|
766
798
|
};
|
|
767
799
|
}).sort((a, b) => b.score - a.score).slice(0, limit).map((s) => s.row);
|
|
768
800
|
}
|
|
801
|
+
/**
|
|
802
|
+
* Map over items with a bounded number of concurrent workers. Used to fan out upstream
|
|
803
|
+
* fetches (per-exercise history, the CLI export) without bursting the host all at once or,
|
|
804
|
+
* on workerd, blowing the subrequest budget.
|
|
805
|
+
*/
|
|
806
|
+
async function mapPool(items, limit, fn) {
|
|
807
|
+
const out = Array.from({ length: items.length });
|
|
808
|
+
let next = 0;
|
|
809
|
+
const worker = async () => {
|
|
810
|
+
while (next < items.length) {
|
|
811
|
+
const i = next;
|
|
812
|
+
next += 1;
|
|
813
|
+
out[i] = await fn(items[i], i);
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
|
|
817
|
+
return out;
|
|
818
|
+
}
|
|
769
819
|
//#endregion
|
|
770
820
|
//#region ../js/src/athlete.ts
|
|
771
821
|
async function getJson(client, path, label) {
|
|
@@ -1029,6 +1079,81 @@ function presentAthleteWorkouts(list) {
|
|
|
1029
1079
|
return list.map(presentAthleteWorkout);
|
|
1030
1080
|
}
|
|
1031
1081
|
/**
|
|
1082
|
+
* Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
|
|
1083
|
+
* every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
|
|
1084
|
+
* workouts, so a caller wanting one program's session narrows it here. Match by `programId`/`teamId`
|
|
1085
|
+
* (exact, on the raw `program_id`/`team_id`) or by `programTitle` (case-insensitive substring on the
|
|
1086
|
+
* `program_title`/`team_title`) — the title match lets a caller target a program by name without
|
|
1087
|
+
* first resolving its id. Any one match keeps the workout; with no filter the list is unchanged.
|
|
1088
|
+
*/
|
|
1089
|
+
function selectWorkoutsByProgram(list, filter) {
|
|
1090
|
+
const { programId, teamId, programTitle } = filter;
|
|
1091
|
+
const needle = programTitle?.trim().toLowerCase();
|
|
1092
|
+
if (programId === void 0 && teamId === void 0 && !needle) return [...list];
|
|
1093
|
+
return list.filter((pw) => {
|
|
1094
|
+
const rec = pw;
|
|
1095
|
+
if (programId !== void 0 && coerceInt(rec.program_id) === programId) return true;
|
|
1096
|
+
if (teamId !== void 0 && coerceInt(rec.team_id) === teamId) return true;
|
|
1097
|
+
if (needle) {
|
|
1098
|
+
if (`${str$1(rec.program_title) ?? ""} ${str$1(rec.team_title) ?? ""}`.toLowerCase().includes(needle)) return true;
|
|
1099
|
+
}
|
|
1100
|
+
return false;
|
|
1101
|
+
});
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
|
|
1105
|
+
* location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
|
|
1106
|
+
* This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
|
|
1107
|
+
* which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
|
|
1108
|
+
* `savedWorkoutSetExerciseId` straight off these rows. Each target also carries its program/team
|
|
1109
|
+
* so a caller can pick the right session when the athlete is on several. One row per saved set,
|
|
1110
|
+
* dropping any set with no resolvable id.
|
|
1111
|
+
*/
|
|
1112
|
+
function presentLogTargets(list) {
|
|
1113
|
+
const targets = [];
|
|
1114
|
+
for (const pw of list) {
|
|
1115
|
+
const rec = pw;
|
|
1116
|
+
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
1117
|
+
const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
|
|
1118
|
+
if (!saved) continue;
|
|
1119
|
+
const date = str$1(rec.date) ?? "";
|
|
1120
|
+
const workoutTitle = str$1(rec.workout_title) ?? "";
|
|
1121
|
+
const program = str$1(rec.program_title);
|
|
1122
|
+
const programId = coerceInt(rec.program_id);
|
|
1123
|
+
const team = str$1(rec.team_title);
|
|
1124
|
+
const teamId = coerceInt(rec.team_id);
|
|
1125
|
+
const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
|
|
1126
|
+
for (const s of sets) {
|
|
1127
|
+
if (!isRecord(s)) continue;
|
|
1128
|
+
const savedWorkoutSetId = coerceInt(s.id);
|
|
1129
|
+
if (savedWorkoutSetId === null) continue;
|
|
1130
|
+
const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
|
|
1131
|
+
const id = coerceInt(ex.id);
|
|
1132
|
+
if (id === null) return null;
|
|
1133
|
+
return {
|
|
1134
|
+
savedWorkoutSetExerciseId: id,
|
|
1135
|
+
title: typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "",
|
|
1136
|
+
units: exerciseUnits(ex.param_1_type, ex.param_2_type),
|
|
1137
|
+
prescribed: prescribedSets(ex),
|
|
1138
|
+
performed: performedSets(ex)
|
|
1139
|
+
};
|
|
1140
|
+
}).filter((e) => e !== null);
|
|
1141
|
+
targets.push({
|
|
1142
|
+
date,
|
|
1143
|
+
workoutTitle,
|
|
1144
|
+
program,
|
|
1145
|
+
programId,
|
|
1146
|
+
team,
|
|
1147
|
+
teamId,
|
|
1148
|
+
savedWorkoutSetId,
|
|
1149
|
+
setTitle: str$1(s.title),
|
|
1150
|
+
exercises
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
return targets;
|
|
1155
|
+
}
|
|
1156
|
+
/**
|
|
1032
1157
|
* Flatten the coach athlete-calendar summary into compact per-session rows: title, the `logged`
|
|
1033
1158
|
* flag (the reliable did-they-train signal), rpe/duration/notes, and the exercises performed with
|
|
1034
1159
|
* the API's own set summary string (`abr`, e.g. "5 x 2 @ 205 lb"). The exercise titles here are
|
|
@@ -1348,7 +1473,7 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
1348
1473
|
throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
|
|
1349
1474
|
}
|
|
1350
1475
|
const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
|
|
1351
|
-
if (!workoutSetExerciseId) throw new Error(`
|
|
1476
|
+
if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
|
|
1352
1477
|
const body = {
|
|
1353
1478
|
...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
|
|
1354
1479
|
...extra
|
|
@@ -1492,6 +1617,7 @@ function presentExerciseHistory(detail) {
|
|
|
1492
1617
|
description: p.description ?? null,
|
|
1493
1618
|
reps: p.reps ?? null,
|
|
1494
1619
|
weight: p.weight ?? null,
|
|
1620
|
+
units: p.units ?? null,
|
|
1495
1621
|
date: p.dateCompleted ?? null
|
|
1496
1622
|
})),
|
|
1497
1623
|
sessions: (detail.history ?? []).map((h) => ({
|
|
@@ -1509,6 +1635,37 @@ function presentExerciseHistory(detail) {
|
|
|
1509
1635
|
function emailList(emails) {
|
|
1510
1636
|
return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
|
|
1511
1637
|
}
|
|
1638
|
+
/** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
|
|
1639
|
+
function rosterName(rec) {
|
|
1640
|
+
const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
|
|
1641
|
+
if (full !== "") return full;
|
|
1642
|
+
const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
|
|
1643
|
+
return combined !== "" ? combined : null;
|
|
1644
|
+
}
|
|
1645
|
+
/**
|
|
1646
|
+
* The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
|
|
1647
|
+
* name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
|
|
1648
|
+
* and the warehouse store map the roster identically. Includes the account owner and
|
|
1649
|
+
* demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
|
|
1650
|
+
*/
|
|
1651
|
+
async function fetchCoachRoster(client, ids) {
|
|
1652
|
+
const res = await client.request("GET", "/v5/athletes");
|
|
1653
|
+
if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
|
|
1654
|
+
const keep = ids && ids.length > 0 ? new Set(ids) : null;
|
|
1655
|
+
const out = [];
|
|
1656
|
+
for (const row of res.data) {
|
|
1657
|
+
if (typeof row !== "object" || row === null) continue;
|
|
1658
|
+
const rec = row;
|
|
1659
|
+
const id = coerceInt(rec.id);
|
|
1660
|
+
if (id === null || id <= 0) continue;
|
|
1661
|
+
if (keep && !keep.has(id)) continue;
|
|
1662
|
+
out.push({
|
|
1663
|
+
id,
|
|
1664
|
+
name: rosterName(rec)
|
|
1665
|
+
});
|
|
1666
|
+
}
|
|
1667
|
+
return out;
|
|
1668
|
+
}
|
|
1512
1669
|
/**
|
|
1513
1670
|
* Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
|
|
1514
1671
|
* addresses (`POST /v5/emails/validate`), then invite the validated ones
|
|
@@ -1769,6 +1926,213 @@ async function teamVolume(client, args) {
|
|
|
1769
1926
|
};
|
|
1770
1927
|
}
|
|
1771
1928
|
//#endregion
|
|
1929
|
+
//#region ../js/src/main-lifts.ts
|
|
1930
|
+
/**
|
|
1931
|
+
* The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
|
|
1932
|
+
* first family that matches, so the more specific / easily-confused families come before the broad
|
|
1933
|
+
* overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
|
|
1934
|
+
* swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
|
|
1935
|
+
* This is the single place to edit the lift set.
|
|
1936
|
+
*/
|
|
1937
|
+
const MAIN_LIFT_FAMILIES = [
|
|
1938
|
+
{
|
|
1939
|
+
key: "cleanjerk",
|
|
1940
|
+
label: "Clean & Jerk",
|
|
1941
|
+
matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
|
|
1942
|
+
},
|
|
1943
|
+
{
|
|
1944
|
+
key: "snatch",
|
|
1945
|
+
label: "Snatch",
|
|
1946
|
+
matches: (t) => t.includes("snatch")
|
|
1947
|
+
},
|
|
1948
|
+
{
|
|
1949
|
+
key: "deadlift",
|
|
1950
|
+
label: "Deadlift",
|
|
1951
|
+
matches: (t) => t.includes("deadlift")
|
|
1952
|
+
},
|
|
1953
|
+
{
|
|
1954
|
+
key: "squat",
|
|
1955
|
+
label: "Squat",
|
|
1956
|
+
matches: (t) => t.includes("squat")
|
|
1957
|
+
},
|
|
1958
|
+
{
|
|
1959
|
+
key: "bench",
|
|
1960
|
+
label: "Bench Press",
|
|
1961
|
+
matches: (t) => t.includes("bench")
|
|
1962
|
+
},
|
|
1963
|
+
{
|
|
1964
|
+
key: "overhead",
|
|
1965
|
+
label: "Overhead Press",
|
|
1966
|
+
matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
|
|
1967
|
+
}
|
|
1968
|
+
];
|
|
1969
|
+
/** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
|
|
1970
|
+
function classifyMainLift(title) {
|
|
1971
|
+
const t = title.toLowerCase();
|
|
1972
|
+
for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
|
|
1973
|
+
return null;
|
|
1974
|
+
}
|
|
1975
|
+
const DEFAULT_MONTHS = 12;
|
|
1976
|
+
function pad2(n) {
|
|
1977
|
+
return String(n).padStart(2, "0");
|
|
1978
|
+
}
|
|
1979
|
+
/** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
|
|
1980
|
+
function isoDay(d) {
|
|
1981
|
+
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
|
1982
|
+
}
|
|
1983
|
+
/**
|
|
1984
|
+
* Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
|
|
1985
|
+
* logged workouts over the last `months` (default 12) — the program-workout range, the reliable
|
|
1986
|
+
* record of performed sets — buckets every performed exercise into a lift family, and for each
|
|
1987
|
+
* family picks the variant logged most often. Returns one entry per family the athlete has logged;
|
|
1988
|
+
* families they never trained are simply absent. (The monthly calendar summary is not used: it
|
|
1989
|
+
* comes back empty for some accounts that have logged sets in the range endpoint.)
|
|
1990
|
+
*/
|
|
1991
|
+
async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
|
|
1992
|
+
const months = opts.months ?? DEFAULT_MONTHS;
|
|
1993
|
+
const now = opts.now ?? /* @__PURE__ */ new Date();
|
|
1994
|
+
const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
|
|
1995
|
+
const tally = /* @__PURE__ */ new Map();
|
|
1996
|
+
let workouts = [];
|
|
1997
|
+
try {
|
|
1998
|
+
workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
|
|
1999
|
+
} catch {
|
|
2000
|
+
workouts = [];
|
|
2001
|
+
}
|
|
2002
|
+
for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
|
|
2003
|
+
if (ex.performed.length === 0 || ex.exerciseId === null) continue;
|
|
2004
|
+
const family = classifyMainLift(ex.title);
|
|
2005
|
+
if (family === null) continue;
|
|
2006
|
+
const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
|
|
2007
|
+
const prev = byId.get(ex.exerciseId);
|
|
2008
|
+
byId.set(ex.exerciseId, {
|
|
2009
|
+
count: (prev?.count ?? 0) + 1,
|
|
2010
|
+
title: prev?.title ?? ex.title
|
|
2011
|
+
});
|
|
2012
|
+
tally.set(family, byId);
|
|
2013
|
+
}
|
|
2014
|
+
const lifts = [];
|
|
2015
|
+
for (const family of MAIN_LIFT_FAMILIES) {
|
|
2016
|
+
const byId = tally.get(family.key);
|
|
2017
|
+
if (!byId || byId.size === 0) continue;
|
|
2018
|
+
let best = null;
|
|
2019
|
+
for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
|
|
2020
|
+
exerciseId,
|
|
2021
|
+
count,
|
|
2022
|
+
title
|
|
2023
|
+
};
|
|
2024
|
+
if (best) lifts.push({
|
|
2025
|
+
family: family.key,
|
|
2026
|
+
label: family.label,
|
|
2027
|
+
exerciseId: best.exerciseId,
|
|
2028
|
+
title: best.title
|
|
2029
|
+
});
|
|
2030
|
+
}
|
|
2031
|
+
return {
|
|
2032
|
+
athleteId,
|
|
2033
|
+
athleteName: null,
|
|
2034
|
+
lifts
|
|
2035
|
+
};
|
|
2036
|
+
}
|
|
2037
|
+
const PR_CONCURRENCY = 5;
|
|
2038
|
+
/** The heaviest PR on an exercise's board (ties broken by more reps). */
|
|
2039
|
+
function bestPr(liftPRs) {
|
|
2040
|
+
let best = null;
|
|
2041
|
+
for (const pr of liftPRs) {
|
|
2042
|
+
const weight = coerceNum(pr.weight);
|
|
2043
|
+
if (weight === null) continue;
|
|
2044
|
+
const reps = coerceInt(pr.reps);
|
|
2045
|
+
if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
|
|
2046
|
+
weight,
|
|
2047
|
+
reps,
|
|
2048
|
+
units: pr.units,
|
|
2049
|
+
date: pr.date
|
|
2050
|
+
};
|
|
2051
|
+
}
|
|
2052
|
+
return best;
|
|
2053
|
+
}
|
|
2054
|
+
/**
|
|
2055
|
+
* A roster athlete's best PR for each main lift. Discovers the lift variants they log
|
|
2056
|
+
* ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
|
|
2057
|
+
* The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
|
|
2058
|
+
* athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
|
|
2059
|
+
* render a stable row of columns.
|
|
2060
|
+
*/
|
|
2061
|
+
async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
|
|
2062
|
+
const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
|
|
2063
|
+
const byFamily = new Map(lifts.map((l) => [l.family, l]));
|
|
2064
|
+
return {
|
|
2065
|
+
athleteId,
|
|
2066
|
+
athleteName,
|
|
2067
|
+
prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
|
|
2068
|
+
const lift = byFamily.get(family.key);
|
|
2069
|
+
const base = {
|
|
2070
|
+
family: family.key,
|
|
2071
|
+
label: family.label
|
|
2072
|
+
};
|
|
2073
|
+
const empty = {
|
|
2074
|
+
exerciseId: null,
|
|
2075
|
+
title: null,
|
|
2076
|
+
weight: null,
|
|
2077
|
+
reps: null,
|
|
2078
|
+
units: null,
|
|
2079
|
+
date: null
|
|
2080
|
+
};
|
|
2081
|
+
if (!lift) return {
|
|
2082
|
+
...base,
|
|
2083
|
+
...empty
|
|
2084
|
+
};
|
|
2085
|
+
const known = {
|
|
2086
|
+
exerciseId: lift.exerciseId,
|
|
2087
|
+
title: lift.title
|
|
2088
|
+
};
|
|
2089
|
+
try {
|
|
2090
|
+
const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
|
|
2091
|
+
return {
|
|
2092
|
+
...base,
|
|
2093
|
+
...known,
|
|
2094
|
+
weight: best?.weight ?? null,
|
|
2095
|
+
reps: best?.reps ?? null,
|
|
2096
|
+
units: best?.units ?? null,
|
|
2097
|
+
date: best?.date ?? null
|
|
2098
|
+
};
|
|
2099
|
+
} catch {
|
|
2100
|
+
return {
|
|
2101
|
+
...base,
|
|
2102
|
+
...known,
|
|
2103
|
+
weight: null,
|
|
2104
|
+
reps: null,
|
|
2105
|
+
units: null,
|
|
2106
|
+
date: null
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
})
|
|
2110
|
+
};
|
|
2111
|
+
}
|
|
2112
|
+
const ROSTER_CONCURRENCY = 4;
|
|
2113
|
+
/**
|
|
2114
|
+
* Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
|
|
2115
|
+
* resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
|
|
2116
|
+
* `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
|
|
2117
|
+
* to the roster name when the per-athlete read can't supply one. This is the single roster-level
|
|
2118
|
+
* primitive the CLI, the MCP tool, and the warehouse store all build on.
|
|
2119
|
+
*/
|
|
2120
|
+
async function fetchRosterMainLiftPRs(client, opts = {}) {
|
|
2121
|
+
const roster = await fetchCoachRoster(client, opts.athleteIds);
|
|
2122
|
+
const inner = {
|
|
2123
|
+
...opts.months !== void 0 ? { months: opts.months } : {},
|
|
2124
|
+
...opts.now !== void 0 ? { now: opts.now } : {}
|
|
2125
|
+
};
|
|
2126
|
+
return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
|
|
2127
|
+
const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
|
|
2128
|
+
return {
|
|
2129
|
+
athleteId: athlete.id,
|
|
2130
|
+
athleteName: result.athleteName ?? athlete.name,
|
|
2131
|
+
prs: result.prs
|
|
2132
|
+
};
|
|
2133
|
+
});
|
|
2134
|
+
}
|
|
2135
|
+
//#endregion
|
|
1772
2136
|
//#region ../js/src/util.ts
|
|
1773
2137
|
/**
|
|
1774
2138
|
* Drop the keys whose value is `undefined`, so the result can be passed to a function or
|
|
@@ -2375,7 +2739,7 @@ function historyInRange(presented, since, until) {
|
|
|
2375
2739
|
//#region ../core/src/tools/reads.ts
|
|
2376
2740
|
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.";
|
|
2377
2741
|
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.";
|
|
2378
|
-
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
|
|
2742
|
+
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 and carry NO per-session date — so this canNOT answer 'what did they do on <day>' (e.g. today); for a specific day use athlete_saved_workouts with startDate=endDate=that day instead. An empty list means no sessions that month.";
|
|
2379
2743
|
function enc(value) {
|
|
2380
2744
|
return encodeURIComponent(String(value));
|
|
2381
2745
|
}
|
|
@@ -2557,6 +2921,37 @@ function registerReadTools(server, ctx) {
|
|
|
2557
2921
|
registerTeamVolume(server, ctx);
|
|
2558
2922
|
}
|
|
2559
2923
|
//#endregion
|
|
2924
|
+
//#region ../core/src/tools/main-lifts.ts
|
|
2925
|
+
const monthsParam = z.number().int().positive().max(36).optional();
|
|
2926
|
+
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.";
|
|
2927
|
+
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.";
|
|
2928
|
+
/** Coach main-lift PR reads: one athlete, or the whole roster at once. */
|
|
2929
|
+
function registerMainLiftTools(server, ctx) {
|
|
2930
|
+
server.registerTool("athlete_main_lift_prs", {
|
|
2931
|
+
title: "Athlete main-lift PRs (roster)",
|
|
2932
|
+
description: ATHLETE_DESC,
|
|
2933
|
+
inputSchema: {
|
|
2934
|
+
athleteId: idParam,
|
|
2935
|
+
months: monthsParam
|
|
2936
|
+
},
|
|
2937
|
+
annotations: READ
|
|
2938
|
+
}, ({ athleteId, months }) => attempt(async () => jsonResult(await fetchAthleteMainLiftPRs(ctx.client, toId(athleteId), months !== void 0 ? { months } : {}))));
|
|
2939
|
+
server.registerTool("roster_main_lift_prs", {
|
|
2940
|
+
title: "Roster main-lift PRs",
|
|
2941
|
+
description: ROSTER_DESC,
|
|
2942
|
+
inputSchema: {
|
|
2943
|
+
months: monthsParam,
|
|
2944
|
+
athleteIds: z.array(idParam).optional()
|
|
2945
|
+
},
|
|
2946
|
+
annotations: READ
|
|
2947
|
+
}, ({ months, athleteIds }) => attempt(async () => {
|
|
2948
|
+
return jsonResult(await fetchRosterMainLiftPRs(ctx.client, {
|
|
2949
|
+
...athleteIds ? { athleteIds: athleteIds.map(toId) } : {},
|
|
2950
|
+
...months !== void 0 ? { months } : {}
|
|
2951
|
+
}), { hint: "Pass athleteIds to scope to a few athletes, or lower months, to shrink this." });
|
|
2952
|
+
}));
|
|
2953
|
+
}
|
|
2954
|
+
//#endregion
|
|
2560
2955
|
//#region ../core/src/tools/athlete-training.ts
|
|
2561
2956
|
/** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
|
|
2562
2957
|
function mapSessionExercises(exercises) {
|
|
@@ -2648,25 +3043,35 @@ function registerAthleteTools(server, ctx) {
|
|
|
2648
3043
|
* "Log for Athlete" flow. Kept in its own function so registerAthleteTools stays under the
|
|
2649
3044
|
* oxlint max-lines-per-function cap.
|
|
2650
3045
|
*/
|
|
2651
|
-
function
|
|
3046
|
+
function registerAthleteSavedWorkouts(server, ctx) {
|
|
2652
3047
|
server.registerTool("athlete_saved_workouts", {
|
|
2653
3048
|
title: "Roster athlete's saved workouts (with log ids)",
|
|
2654
|
-
description: "A roster athlete's scheduled/logged workouts in an inclusive YYYY-MM-DD window
|
|
3049
|
+
description: "A roster athlete's scheduled/logged workouts in an inclusive YYYY-MM-DD window. This is the DATE-PRECISE coach read: to answer 'what did <athlete> do/log on <day>' (e.g. today), pass startDate=endDate=that day — each row carries its date and the performed values (what the athlete actually logged), unlike athlete_training which is a whole-month overview with no per-session date. It is also the coach-side source of the savedWorkoutSetId and savedWorkoutSetExerciseId that log_athlete_set, prescribe_athlete_set, and swap_athlete_exercise need. Get athleteId from list_athletes. The default view is COMPACT: one row per saved set, each carrying its program/programId, the savedWorkoutSetId, and every exercise's savedWorkoutSetExerciseId with prescribed/performed values — so you read those ids straight off it, no raw needed. An athlete enrolled in many programs returns one row per program; narrow to one with program (a case-insensitive title substring, e.g. 'bodybuilding' — no id lookup needed), or programId/teamId if you already have the id. raw:true returns the untouched API objects, but that blob is large and can be truncated for a high-enrollment athlete — prefer the program filter + the default view. athlete_training gives a whole-month overview but not these ids.",
|
|
2655
3050
|
inputSchema: {
|
|
2656
3051
|
athleteId: idParam,
|
|
2657
3052
|
startDate: dateString,
|
|
2658
3053
|
endDate: dateString,
|
|
3054
|
+
program: z.string().optional(),
|
|
3055
|
+
programId: idParam.optional(),
|
|
3056
|
+
teamId: idParam.optional(),
|
|
2659
3057
|
raw: z.boolean().optional()
|
|
2660
3058
|
},
|
|
2661
3059
|
annotations: READ
|
|
2662
|
-
}, ({ athleteId, startDate, endDate, raw }) => attempt(async () => {
|
|
2663
|
-
const workouts = await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate)
|
|
2664
|
-
|
|
2665
|
-
|
|
3060
|
+
}, ({ athleteId, startDate, endDate, program, programId, teamId, raw }) => attempt(async () => {
|
|
3061
|
+
const workouts = selectWorkoutsByProgram(await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate), definedProps({
|
|
3062
|
+
programTitle: program,
|
|
3063
|
+
programId: programId === void 0 ? void 0 : toId(programId),
|
|
3064
|
+
teamId: teamId === void 0 ? void 0 : toId(teamId)
|
|
3065
|
+
}));
|
|
3066
|
+
if (raw === true) return jsonResult(workouts, { hint: "Each set's id is the savedWorkoutSetId; each savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId. This raw blob is large — if truncated, pass program (a title substring) to target one program, or use the default (compact) view which carries the same ids." });
|
|
3067
|
+
return jsonResult(presentLogTargets(workouts), { hint: "One row per saved set: savedWorkoutSetId plus each savedWorkoutSetExerciseId, with the program it belongs to. Pass both ids to log_athlete_set / prescribe_athlete_set. Filter with program (title substring), programId, or teamId if the athlete is on several programs." });
|
|
2666
3068
|
}));
|
|
3069
|
+
}
|
|
3070
|
+
function registerAthleteLogTools(server, ctx) {
|
|
3071
|
+
registerAthleteSavedWorkouts(server, ctx);
|
|
2667
3072
|
server.registerTool("log_athlete_set", {
|
|
2668
3073
|
title: "Log set results for a roster athlete",
|
|
2669
|
-
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
|
|
3074
|
+
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 for that athlete/day (its default view carries both — pass programId there if the athlete is on several programs). Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
|
|
2670
3075
|
inputSchema: {
|
|
2671
3076
|
...coachLogSetArgsSchema.shape,
|
|
2672
3077
|
confirm: z.boolean().optional()
|
|
@@ -2707,7 +3112,7 @@ function registerAthleteLogTools(server, ctx) {
|
|
|
2707
3112
|
function registerAthleteSwapTool(server, ctx) {
|
|
2708
3113
|
server.registerTool("swap_athlete_exercise", {
|
|
2709
3114
|
title: "Swap one exercise in a roster athlete's prescribed workout",
|
|
2710
|
-
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
|
|
3115
|
+
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 — its default view lists it per program) 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).",
|
|
2711
3116
|
inputSchema: {
|
|
2712
3117
|
...swapAthleteExerciseArgsSchema.shape,
|
|
2713
3118
|
confirm: z.boolean().optional()
|
|
@@ -2731,7 +3136,7 @@ function registerAthleteSwapTool(server, ctx) {
|
|
|
2731
3136
|
function registerAthletePrescribeTool(server, ctx) {
|
|
2732
3137
|
server.registerTool("prescribe_athlete_set", {
|
|
2733
3138
|
title: "Prescribe reps/weight for a roster athlete's set",
|
|
2734
|
-
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
|
|
3139
|
+
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 for that athlete/day — its default view lists both per program, so pass programId there if the athlete is on several. 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).",
|
|
2735
3140
|
inputSchema: {
|
|
2736
3141
|
...coachPrescribeSetArgsSchema.shape,
|
|
2737
3142
|
confirm: z.boolean().optional()
|
|
@@ -3167,7 +3572,7 @@ var JsonFileLibraryCache = class {
|
|
|
3167
3572
|
};
|
|
3168
3573
|
//#endregion
|
|
3169
3574
|
//#region package.json
|
|
3170
|
-
var version = "1.
|
|
3575
|
+
var version = "1.4.0";
|
|
3171
3576
|
//#endregion
|
|
3172
3577
|
//#region src/server.ts
|
|
3173
3578
|
async function main() {
|
|
@@ -3187,6 +3592,7 @@ async function main() {
|
|
|
3187
3592
|
version
|
|
3188
3593
|
}, { instructions: SERVER_INSTRUCTIONS });
|
|
3189
3594
|
registerReadTools(server, ctx);
|
|
3595
|
+
registerMainLiftTools(server, ctx);
|
|
3190
3596
|
registerAthleteTools(server, ctx);
|
|
3191
3597
|
registerTeamTools(server, ctx);
|
|
3192
3598
|
registerAnalyticsTools(server, ctx);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/coach-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.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.
|
|
25
|
-
"@trainheroic-unofficial/js": "1.
|
|
24
|
+
"@trainheroic-unofficial/core": "1.4.0",
|
|
25
|
+
"@trainheroic-unofficial/js": "1.4.0"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@types/node": "^26.0.0",
|