@trainheroic-unofficial/coach-mcp 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/server.mjs +298 -1
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -668,6 +668,14 @@ function coerceInt(value) {
668
668
  }
669
669
  return null;
670
670
  }
671
+ function coerceNum(value) {
672
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
673
+ if (typeof value === "string" && value.trim() !== "") {
674
+ const n = Number(value);
675
+ return Number.isFinite(n) ? n : null;
676
+ }
677
+ return null;
678
+ }
671
679
  function unitLabel(paramType) {
672
680
  const t = coerceInt(paramType);
673
681
  if (t === null) return null;
@@ -766,6 +774,24 @@ function rankSearch(rows, query, limit) {
766
774
  };
767
775
  }).sort((a, b) => b.score - a.score).slice(0, limit).map((s) => s.row);
768
776
  }
777
+ /**
778
+ * Map over items with a bounded number of concurrent workers. Used to fan out upstream
779
+ * fetches (per-exercise history, the CLI export) without bursting the host all at once or,
780
+ * on workerd, blowing the subrequest budget.
781
+ */
782
+ async function mapPool(items, limit, fn) {
783
+ const out = Array.from({ length: items.length });
784
+ let next = 0;
785
+ const worker = async () => {
786
+ while (next < items.length) {
787
+ const i = next;
788
+ next += 1;
789
+ out[i] = await fn(items[i], i);
790
+ }
791
+ };
792
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
793
+ return out;
794
+ }
769
795
  //#endregion
770
796
  //#region ../js/src/athlete.ts
771
797
  async function getJson(client, path, label) {
@@ -1492,6 +1518,7 @@ function presentExerciseHistory(detail) {
1492
1518
  description: p.description ?? null,
1493
1519
  reps: p.reps ?? null,
1494
1520
  weight: p.weight ?? null,
1521
+ units: p.units ?? null,
1495
1522
  date: p.dateCompleted ?? null
1496
1523
  })),
1497
1524
  sessions: (detail.history ?? []).map((h) => ({
@@ -1509,6 +1536,37 @@ function presentExerciseHistory(detail) {
1509
1536
  function emailList(emails) {
1510
1537
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
1511
1538
  }
1539
+ /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
1540
+ function rosterName(rec) {
1541
+ const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
1542
+ if (full !== "") return full;
1543
+ const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
1544
+ return combined !== "" ? combined : null;
1545
+ }
1546
+ /**
1547
+ * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
1548
+ * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
1549
+ * and the warehouse store map the roster identically. Includes the account owner and
1550
+ * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
1551
+ */
1552
+ async function fetchCoachRoster(client, ids) {
1553
+ const res = await client.request("GET", "/v5/athletes");
1554
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
1555
+ const keep = ids && ids.length > 0 ? new Set(ids) : null;
1556
+ const out = [];
1557
+ for (const row of res.data) {
1558
+ if (typeof row !== "object" || row === null) continue;
1559
+ const rec = row;
1560
+ const id = coerceInt(rec.id);
1561
+ if (id === null || id <= 0) continue;
1562
+ if (keep && !keep.has(id)) continue;
1563
+ out.push({
1564
+ id,
1565
+ name: rosterName(rec)
1566
+ });
1567
+ }
1568
+ return out;
1569
+ }
1512
1570
  /**
1513
1571
  * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
1514
1572
  * addresses (`POST /v5/emails/validate`), then invite the validated ones
@@ -1769,6 +1827,213 @@ async function teamVolume(client, args) {
1769
1827
  };
1770
1828
  }
1771
1829
  //#endregion
1830
+ //#region ../js/src/main-lifts.ts
1831
+ /**
1832
+ * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
1833
+ * first family that matches, so the more specific / easily-confused families come before the broad
1834
+ * overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
1835
+ * swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
1836
+ * This is the single place to edit the lift set.
1837
+ */
1838
+ const MAIN_LIFT_FAMILIES = [
1839
+ {
1840
+ key: "cleanjerk",
1841
+ label: "Clean & Jerk",
1842
+ matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
1843
+ },
1844
+ {
1845
+ key: "snatch",
1846
+ label: "Snatch",
1847
+ matches: (t) => t.includes("snatch")
1848
+ },
1849
+ {
1850
+ key: "deadlift",
1851
+ label: "Deadlift",
1852
+ matches: (t) => t.includes("deadlift")
1853
+ },
1854
+ {
1855
+ key: "squat",
1856
+ label: "Squat",
1857
+ matches: (t) => t.includes("squat")
1858
+ },
1859
+ {
1860
+ key: "bench",
1861
+ label: "Bench Press",
1862
+ matches: (t) => t.includes("bench")
1863
+ },
1864
+ {
1865
+ key: "overhead",
1866
+ label: "Overhead Press",
1867
+ matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
1868
+ }
1869
+ ];
1870
+ /** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
1871
+ function classifyMainLift(title) {
1872
+ const t = title.toLowerCase();
1873
+ for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
1874
+ return null;
1875
+ }
1876
+ const DEFAULT_MONTHS = 12;
1877
+ function pad2(n) {
1878
+ return String(n).padStart(2, "0");
1879
+ }
1880
+ /** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
1881
+ function isoDay(d) {
1882
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
1883
+ }
1884
+ /**
1885
+ * Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
1886
+ * logged workouts over the last `months` (default 12) — the program-workout range, the reliable
1887
+ * record of performed sets — buckets every performed exercise into a lift family, and for each
1888
+ * family picks the variant logged most often. Returns one entry per family the athlete has logged;
1889
+ * families they never trained are simply absent. (The monthly calendar summary is not used: it
1890
+ * comes back empty for some accounts that have logged sets in the range endpoint.)
1891
+ */
1892
+ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
1893
+ const months = opts.months ?? DEFAULT_MONTHS;
1894
+ const now = opts.now ?? /* @__PURE__ */ new Date();
1895
+ const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
1896
+ const tally = /* @__PURE__ */ new Map();
1897
+ let workouts = [];
1898
+ try {
1899
+ workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
1900
+ } catch {
1901
+ workouts = [];
1902
+ }
1903
+ for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
1904
+ if (ex.performed.length === 0 || ex.exerciseId === null) continue;
1905
+ const family = classifyMainLift(ex.title);
1906
+ if (family === null) continue;
1907
+ const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
1908
+ const prev = byId.get(ex.exerciseId);
1909
+ byId.set(ex.exerciseId, {
1910
+ count: (prev?.count ?? 0) + 1,
1911
+ title: prev?.title ?? ex.title
1912
+ });
1913
+ tally.set(family, byId);
1914
+ }
1915
+ const lifts = [];
1916
+ for (const family of MAIN_LIFT_FAMILIES) {
1917
+ const byId = tally.get(family.key);
1918
+ if (!byId || byId.size === 0) continue;
1919
+ let best = null;
1920
+ for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
1921
+ exerciseId,
1922
+ count,
1923
+ title
1924
+ };
1925
+ if (best) lifts.push({
1926
+ family: family.key,
1927
+ label: family.label,
1928
+ exerciseId: best.exerciseId,
1929
+ title: best.title
1930
+ });
1931
+ }
1932
+ return {
1933
+ athleteId,
1934
+ athleteName: null,
1935
+ lifts
1936
+ };
1937
+ }
1938
+ const PR_CONCURRENCY = 5;
1939
+ /** The heaviest PR on an exercise's board (ties broken by more reps). */
1940
+ function bestPr(liftPRs) {
1941
+ let best = null;
1942
+ for (const pr of liftPRs) {
1943
+ const weight = coerceNum(pr.weight);
1944
+ if (weight === null) continue;
1945
+ const reps = coerceInt(pr.reps);
1946
+ if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
1947
+ weight,
1948
+ reps,
1949
+ units: pr.units,
1950
+ date: pr.date
1951
+ };
1952
+ }
1953
+ return best;
1954
+ }
1955
+ /**
1956
+ * A roster athlete's best PR for each main lift. Discovers the lift variants they log
1957
+ * ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
1958
+ * The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
1959
+ * athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
1960
+ * render a stable row of columns.
1961
+ */
1962
+ async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
1963
+ const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
1964
+ const byFamily = new Map(lifts.map((l) => [l.family, l]));
1965
+ return {
1966
+ athleteId,
1967
+ athleteName,
1968
+ prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
1969
+ const lift = byFamily.get(family.key);
1970
+ const base = {
1971
+ family: family.key,
1972
+ label: family.label
1973
+ };
1974
+ const empty = {
1975
+ exerciseId: null,
1976
+ title: null,
1977
+ weight: null,
1978
+ reps: null,
1979
+ units: null,
1980
+ date: null
1981
+ };
1982
+ if (!lift) return {
1983
+ ...base,
1984
+ ...empty
1985
+ };
1986
+ const known = {
1987
+ exerciseId: lift.exerciseId,
1988
+ title: lift.title
1989
+ };
1990
+ try {
1991
+ const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
1992
+ return {
1993
+ ...base,
1994
+ ...known,
1995
+ weight: best?.weight ?? null,
1996
+ reps: best?.reps ?? null,
1997
+ units: best?.units ?? null,
1998
+ date: best?.date ?? null
1999
+ };
2000
+ } catch {
2001
+ return {
2002
+ ...base,
2003
+ ...known,
2004
+ weight: null,
2005
+ reps: null,
2006
+ units: null,
2007
+ date: null
2008
+ };
2009
+ }
2010
+ })
2011
+ };
2012
+ }
2013
+ const ROSTER_CONCURRENCY = 4;
2014
+ /**
2015
+ * Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
2016
+ * resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
2017
+ * `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
2018
+ * to the roster name when the per-athlete read can't supply one. This is the single roster-level
2019
+ * primitive the CLI, the MCP tool, and the warehouse store all build on.
2020
+ */
2021
+ async function fetchRosterMainLiftPRs(client, opts = {}) {
2022
+ const roster = await fetchCoachRoster(client, opts.athleteIds);
2023
+ const inner = {
2024
+ ...opts.months !== void 0 ? { months: opts.months } : {},
2025
+ ...opts.now !== void 0 ? { now: opts.now } : {}
2026
+ };
2027
+ return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
2028
+ const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
2029
+ return {
2030
+ athleteId: athlete.id,
2031
+ athleteName: result.athleteName ?? athlete.name,
2032
+ prs: result.prs
2033
+ };
2034
+ });
2035
+ }
2036
+ //#endregion
1772
2037
  //#region ../js/src/util.ts
1773
2038
  /**
1774
2039
  * Drop the keys whose value is `undefined`, so the result can be passed to a function or
@@ -2557,6 +2822,37 @@ function registerReadTools(server, ctx) {
2557
2822
  registerTeamVolume(server, ctx);
2558
2823
  }
2559
2824
  //#endregion
2825
+ //#region ../core/src/tools/main-lifts.ts
2826
+ const monthsParam = z.number().int().positive().max(36).optional();
2827
+ const ATHLETE_DESC = "A roster athlete's personal records for the main barbell lifts (squat, bench press, deadlift, overhead press, clean & jerk, snatch). Pass athleteId from list_athletes — nothing else. It auto-discovers which exercise VARIANT the athlete actually logs for each lift (e.g. 'Back Squat', not the empty 'Squat' library entry) by scanning their recent training, so you do NOT resolve exercise ids yourself. Returns one row per lift family in a fixed order; a lift the athlete has not logged comes back with null fields (no PR yet). `months` (default 12) is how far back to look for the logged variants.";
2828
+ const ROSTER_DESC = "Every roster athlete's main-lift PRs in one call — the squad board for squat/bench/deadlift/overhead press/clean & jerk/snatch. Same per-athlete discovery as athlete_main_lift_prs, fanned out across the roster (bounded), so it makes many upstream calls; expect a few seconds on a big roster. Optional athleteIds restricts it to a subset (else the whole roster from /v5/athletes); `months` (default 12) sets the look-back for logged variants.";
2829
+ /** Coach main-lift PR reads: one athlete, or the whole roster at once. */
2830
+ function registerMainLiftTools(server, ctx) {
2831
+ server.registerTool("athlete_main_lift_prs", {
2832
+ title: "Athlete main-lift PRs (roster)",
2833
+ description: ATHLETE_DESC,
2834
+ inputSchema: {
2835
+ athleteId: idParam,
2836
+ months: monthsParam
2837
+ },
2838
+ annotations: READ
2839
+ }, ({ athleteId, months }) => attempt(async () => jsonResult(await fetchAthleteMainLiftPRs(ctx.client, toId(athleteId), months !== void 0 ? { months } : {}))));
2840
+ server.registerTool("roster_main_lift_prs", {
2841
+ title: "Roster main-lift PRs",
2842
+ description: ROSTER_DESC,
2843
+ inputSchema: {
2844
+ months: monthsParam,
2845
+ athleteIds: z.array(idParam).optional()
2846
+ },
2847
+ annotations: READ
2848
+ }, ({ months, athleteIds }) => attempt(async () => {
2849
+ return jsonResult(await fetchRosterMainLiftPRs(ctx.client, {
2850
+ ...athleteIds ? { athleteIds: athleteIds.map(toId) } : {},
2851
+ ...months !== void 0 ? { months } : {}
2852
+ }), { hint: "Pass athleteIds to scope to a few athletes, or lower months, to shrink this." });
2853
+ }));
2854
+ }
2855
+ //#endregion
2560
2856
  //#region ../core/src/tools/athlete-training.ts
2561
2857
  /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
2562
2858
  function mapSessionExercises(exercises) {
@@ -3167,7 +3463,7 @@ var JsonFileLibraryCache = class {
3167
3463
  };
3168
3464
  //#endregion
3169
3465
  //#region package.json
3170
- var version = "1.2.0";
3466
+ var version = "1.3.0";
3171
3467
  //#endregion
3172
3468
  //#region src/server.ts
3173
3469
  async function main() {
@@ -3187,6 +3483,7 @@ async function main() {
3187
3483
  version
3188
3484
  }, { instructions: SERVER_INSTRUCTIONS });
3189
3485
  registerReadTools(server, ctx);
3486
+ registerMainLiftTools(server, ctx);
3190
3487
  registerAthleteTools(server, ctx);
3191
3488
  registerTeamTools(server, ctx);
3192
3489
  registerAnalyticsTools(server, ctx);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/sdk": "^1.29.0",
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/core": "1.2.0",
25
- "@trainheroic-unofficial/js": "1.2.0"
24
+ "@trainheroic-unofficial/core": "1.3.0",
25
+ "@trainheroic-unofficial/js": "1.3.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",