@trainheroic-unofficial/coach-mcp 0.6.2 → 0.6.4

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 +154 -6
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -726,9 +726,131 @@ async function getJson(client, path, label) {
726
726
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
727
727
  return res.data;
728
728
  }
729
+ async function getArray(client, path, label) {
730
+ const res = await client.request("GET", path);
731
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
732
+ return res.data;
733
+ }
734
+ /** Lifetime training totals. `use_metric` is required by the API (omitting it 400s). */
735
+ function fetchAthleteProfileSummary(client, userId, useMetric = false) {
736
+ return getJson(client, `/v5/athleteProfile/summary?user_id=${userId}&use_metric=${useMetric ? 1 : 0}`, "athlete profile summary");
737
+ }
738
+ /**
739
+ * Sort a roster-activity list most-recently-active first; never-logged rows (null date) last.
740
+ * Athletes tied on lastLoggedDate break by session count (more sessions first), so a tie is not
741
+ * left to arbitrary input order.
742
+ */
743
+ function sortRosterByRecency(rows) {
744
+ return [...rows].sort((a, b) => {
745
+ if (a.lastLoggedDate !== b.lastLoggedDate) {
746
+ if (a.lastLoggedDate === null) return 1;
747
+ if (b.lastLoggedDate === null) return -1;
748
+ return a.lastLoggedDate < b.lastLoggedDate ? 1 : -1;
749
+ }
750
+ return (b.sessionsCount ?? 0) - (a.sessionsCount ?? 0);
751
+ });
752
+ }
753
+ /**
754
+ * A coach's roster-activity ranking: each athlete's all-time training snapshot (session count,
755
+ * first/last logged date, total reps/volume), sorted most-recently-active first. There is no
756
+ * single roster-activity endpoint, so this fans out `/v5/athleteProfile/summary` per athlete with
757
+ * a small concurrency cap; pass the subset you care about for a large org. A failed or missing
758
+ * summary becomes a null-data row (sorted last), not an error.
759
+ */
760
+ async function fetchRosterActivity(client, athleteIds, useMetric = false) {
761
+ const rows = [];
762
+ const concurrency = 6;
763
+ for (let i = 0; i < athleteIds.length; i += concurrency) {
764
+ const chunk = athleteIds.slice(i, i + concurrency);
765
+ const settled = await Promise.all(chunk.map(async (id) => {
766
+ try {
767
+ return {
768
+ id,
769
+ summary: await fetchAthleteProfileSummary(client, id, useMetric)
770
+ };
771
+ } catch {
772
+ return {
773
+ id,
774
+ summary: null
775
+ };
776
+ }
777
+ }));
778
+ for (const { id, summary } of settled) {
779
+ const count = summary?.sessions_count ?? null;
780
+ const hasSessions = count !== null && count > 0;
781
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
782
+ rows.push({
783
+ athleteId: id,
784
+ sessionsCount: count,
785
+ firstLoggedDate: normDate(summary?.first_logged_date),
786
+ lastLoggedDate: normDate(summary?.last_logged_date),
787
+ totalReps: summary?.reps_sum ?? null,
788
+ totalVolume: summary?.volume_sum ?? null
789
+ });
790
+ }
791
+ }
792
+ return sortRosterByRecency(rows);
793
+ }
729
794
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
730
795
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
731
796
  }
797
+ /**
798
+ * A coach's month view of a roster athlete's logged sessions
799
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
800
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
801
+ * `userId` in each row is the roster athlete, not the calling coach.
802
+ */
803
+ function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
804
+ return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
805
+ }
806
+ /**
807
+ * Flatten the coach athlete-calendar summary into compact per-session rows: title, the `logged`
808
+ * flag (the reliable did-they-train signal), rpe/duration/notes, and the exercises performed with
809
+ * the API's own set summary string (`abr`, e.g. "5 x 2 @ 205 lb"). The exercise titles here are
810
+ * the discovery handle a coach otherwise lacks: read what the athlete actually did, then pull the
811
+ * specific lift's PRs.
812
+ */
813
+ function presentCoachAthleteTraining(raw, athleteId, year, month) {
814
+ const sessions = [];
815
+ let athleteName = null;
816
+ for (const item of raw) {
817
+ if (!isRecord(item)) continue;
818
+ if (athleteName === null && typeof item.athleteName === "string") athleteName = item.athleteName;
819
+ const exercises = [];
820
+ const sets = Array.isArray(item.sets) ? item.sets : [];
821
+ for (const set of sets) {
822
+ if (!isRecord(set)) continue;
823
+ const exs = Array.isArray(set.exercises) ? set.exercises : [];
824
+ for (const ex of exs) {
825
+ if (!isRecord(ex)) continue;
826
+ exercises.push({
827
+ exerciseId: coerceInt(ex.exercise_id),
828
+ title: typeof ex.title === "string" ? ex.title : "",
829
+ summary: typeof ex.abr === "string" && ex.abr !== "" ? ex.abr : null,
830
+ completed: coerceInt(ex.completed) === 1
831
+ });
832
+ }
833
+ }
834
+ sessions.push({
835
+ workoutId: coerceInt(item.workout_id),
836
+ savedWorkoutId: coerceInt(item.saved_workout_id),
837
+ title: typeof item.workout_title === "string" ? item.workout_title : "",
838
+ logged: coerceInt(item.logged) === 1,
839
+ completed: coerceInt(item.completed) === 1,
840
+ rpe: coerceInt(item.rpe),
841
+ durationMin: coerceInt(item.session_duration),
842
+ notes: typeof item.notes === "string" && item.notes !== "" ? item.notes : null,
843
+ exercises
844
+ });
845
+ }
846
+ return {
847
+ athleteId,
848
+ athleteName,
849
+ year,
850
+ month,
851
+ sessions
852
+ };
853
+ }
732
854
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
733
855
  function presentExerciseHistory(detail) {
734
856
  return {
@@ -1338,7 +1460,9 @@ function historyInRange(presented, since, until) {
1338
1460
  }
1339
1461
  //#endregion
1340
1462
  //#region ../core/src/tools/reads.ts
1341
- 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 summary, so query each lift you care about (squat, bench, deadlift, …) and an empty result just means the athlete has not logged that lift. liftPRs stay all-time; pass since/until (YYYY-MM-DD, inclusive) to window the session series. raw:true returns the untouched API object.";
1463
+ 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.";
1464
+ 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.";
1465
+ 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.";
1342
1466
  function enc(value) {
1343
1467
  return encodeURIComponent(String(value));
1344
1468
  }
@@ -1385,7 +1509,7 @@ function registerRosterReads(server, ctx) {
1385
1509
  }, () => apiCall(ctx, "GET", t.path));
1386
1510
  server.registerTool("list_athletes", {
1387
1511
  title: "List athletes",
1388
- description: "Every athlete on this coach's org roster, across all teams (not scoped to one team, and demo/placeholder athletes are included). `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. There is no per-athlete team field here, so to attribute athletes to a team use the team's roster. Optional q (case-insensitive substring filter over each athlete record) and limit, applied client-side, to keep large rosters small.",
1512
+ 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.",
1389
1513
  inputSchema: {
1390
1514
  q: z.string().optional(),
1391
1515
  limit: z.number().int().positive().max(500).optional()
@@ -1400,8 +1524,11 @@ function registerRosterReads(server, ctx) {
1400
1524
  if (!Array.isArray(res.data)) return jsonResult(res.data);
1401
1525
  let rows = res.data;
1402
1526
  if (q !== void 0) {
1403
- const needle = q.toLowerCase();
1404
- rows = rows.filter((row) => JSON.stringify(row).toLowerCase().includes(needle));
1527
+ const needles = q.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
1528
+ rows = rows.filter((row) => {
1529
+ const hay = JSON.stringify(row).toLowerCase();
1530
+ return needles.every((n) => hay.includes(n));
1531
+ });
1405
1532
  }
1406
1533
  const total = rows.length;
1407
1534
  if (limit !== void 0 && rows.length > limit) return jsonResult({
@@ -1460,6 +1587,27 @@ function registerEntityReads(server, ctx) {
1460
1587
  if (raw === true) return jsonResult(detail);
1461
1588
  return jsonResult(historyInRange(presentExerciseHistory(detail), since, until));
1462
1589
  }));
1590
+ server.registerTool("roster_activity", {
1591
+ title: "Roster training activity (recency)",
1592
+ description: ROSTER_ACTIVITY_DESC,
1593
+ inputSchema: {
1594
+ athleteIds: z.array(idParam).min(1),
1595
+ useMetric: z.boolean().optional()
1596
+ },
1597
+ annotations: READ
1598
+ }, ({ 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." })));
1599
+ server.registerTool("athlete_training", {
1600
+ title: "Athlete training month (roster)",
1601
+ description: ATHLETE_TRAINING_DESC,
1602
+ inputSchema: {
1603
+ athleteId: idParam,
1604
+ year: z.number().int(),
1605
+ month: z.number().int().min(1).max(12)
1606
+ },
1607
+ annotations: READ
1608
+ }, ({ athleteId, year, month }) => attempt(async () => {
1609
+ return jsonResult(presentCoachAthleteTraining(await fetchCoachAthleteCalendarSummary(ctx.client, toId(athleteId), year, month), toId(athleteId), year, month), { hint: "One session per row for the month. Use the exercise titles to pick lifts, then athlete_lift_history for their PRs." });
1610
+ }));
1463
1611
  server.registerTool("get_program", {
1464
1612
  title: "Get program detail",
1465
1613
  description: "Full nested program structure (blocks + sessions) live from the API, by program id.",
@@ -1702,7 +1850,7 @@ const BODY_KEY = {
1702
1850
  function registerAnalyticsTools(server, ctx) {
1703
1851
  server.registerTool("analytics_query", {
1704
1852
  title: "Pull an analytics report",
1705
- 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). 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.",
1853
+ 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.",
1706
1854
  inputSchema: {
1707
1855
  metric: z.enum(METRIC_KEYS),
1708
1856
  teamId: idParam.optional(),
@@ -2078,7 +2226,7 @@ var JsonFileLibraryCache = class {
2078
2226
  };
2079
2227
  //#endregion
2080
2228
  //#region package.json
2081
- var version = "0.6.2";
2229
+ var version = "0.6.4";
2082
2230
  //#endregion
2083
2231
  //#region src/server.ts
2084
2232
  async function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
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/js": "0.6.2",
25
- "@trainheroic-unofficial/core": "0.6.2"
24
+ "@trainheroic-unofficial/core": "0.6.4",
25
+ "@trainheroic-unofficial/js": "0.6.4"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",