@trainheroic-unofficial/coach-mcp 1.0.0 → 1.1.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 +304 -5
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -155,6 +155,14 @@ z.object({
155
155
  endDate: dateString
156
156
  });
157
157
  /**
158
+ * One entered set: the value of each parameter slot (param 1 / param 2 — e.g. reps / weight).
159
+ * Shared by every logging write so the per-set shape is defined once.
160
+ */
161
+ const loggedSetSchema = z.object({
162
+ param1: z.union([z.number(), z.string()]).optional(),
163
+ param2: z.union([z.number(), z.string()]).optional()
164
+ });
165
+ /**
158
166
  * Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
159
167
  * roster `athleteId` whose set is being logged on their behalf.
160
168
  */
@@ -163,10 +171,19 @@ const coachLogSetArgsSchema = z.object({
163
171
  savedWorkoutSetId: idArgSchema,
164
172
  results: z.array(z.object({
165
173
  savedWorkoutSetExerciseId: idArgSchema,
166
- sets: z.array(z.object({
167
- param1: z.union([z.number(), z.string()]).optional(),
168
- param2: z.union([z.number(), z.string()]).optional()
169
- })).min(1)
174
+ sets: z.array(loggedSetSchema).min(1)
175
+ })).min(1)
176
+ }).extend({ athleteId: idArgSchema });
177
+ /**
178
+ * Args for the coach variant of {@link logSessionArgsSchema}: the same shape plus the roster
179
+ * `athleteId` whose session is being logged on their behalf.
180
+ */
181
+ const coachLogSessionArgsSchema = z.object({
182
+ date: dateString,
183
+ exercises: z.array(z.object({
184
+ exerciseId: idArgSchema,
185
+ order: z.number().int().positive().optional(),
186
+ sets: z.array(loggedSetSchema).min(1)
170
187
  })).min(1)
171
188
  }).extend({ athleteId: idArgSchema });
172
189
  //#endregion
@@ -798,6 +815,10 @@ async function fetchRosterActivity(client, athleteIds, useMetric = false) {
798
815
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
799
816
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
800
817
  }
818
+ /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
819
+ function fetchAthleteWorkouts(client, startDate, endDate) {
820
+ return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
821
+ }
801
822
  /**
802
823
  * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
803
824
  * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
@@ -1138,6 +1159,25 @@ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
1138
1159
  };
1139
1160
  }
1140
1161
  /**
1162
+ * Record entered set results for one saved workout set.
1163
+ *
1164
+ * **Two-step write (both required for data to persist):**
1165
+ * 1. For each exercise in `results`:
1166
+ * `PUT /1.0/athlete/savedworkoutsetexercise/{savedWorkoutSetExerciseId}` with the
1167
+ * per-slot `param_N_data_M` values. This is the only path that actually stores reps
1168
+ * and weight — the `savedworkoutset` PUT accepts the same fields but silently discards
1169
+ * them.
1170
+ * 2. `PUT /1.0/athlete/savedworkoutset/{savedWorkoutSetId}` with `completed:"1"` to
1171
+ * mark the block done and make the entry visible as a logged set in history.
1172
+ *
1173
+ * The date is used to locate the saved workout (via the range endpoint) so we can resolve
1174
+ * `saved_workout_id` and `workout_set_exercise_id` for each exercise. Both are required
1175
+ * by the respective PUT bodies.
1176
+ */
1177
+ async function logAthleteSet(client, args) {
1178
+ return writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results);
1179
+ }
1180
+ /**
1141
1181
  * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
1142
1182
  * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
1143
1183
  * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
@@ -1201,6 +1241,118 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1201
1241
  exercisesLogged
1202
1242
  };
1203
1243
  }
1244
+ /** Flatten a day's prescribed saved sets into `{ savedWorkoutSetId, ex }` rows (both set keys). */
1245
+ function eachPrescribedExercise(workouts) {
1246
+ const rows = [];
1247
+ for (const pw of workouts) {
1248
+ const rec = pw;
1249
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1250
+ const sw = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1251
+ if (!sw) continue;
1252
+ const sets = [...Array.isArray(sw.workoutSets) ? sw.workoutSets : [], ...Array.isArray(sw.addedWorkoutSets) ? sw.addedWorkoutSets : []];
1253
+ for (const s of sets) {
1254
+ if (!isRecord(s)) continue;
1255
+ const savedWorkoutSetId = coerceInt(s.id);
1256
+ if (savedWorkoutSetId === null) continue;
1257
+ const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
1258
+ for (const ex of exercises) if (isRecord(ex)) rows.push({
1259
+ savedWorkoutSetId,
1260
+ ex
1261
+ });
1262
+ }
1263
+ }
1264
+ return rows;
1265
+ }
1266
+ /**
1267
+ * Locate a single prescribed exercise on the given day's workouts, returning the saved set it
1268
+ * belongs to and its saved-set-exercise id. Used by the coach path, which can only log against
1269
+ * what is already on the athlete's calendar. Returns null when the exercise is not prescribed
1270
+ * that day.
1271
+ */
1272
+ function findPrescribedExercise(workouts, exerciseId, used) {
1273
+ for (const { savedWorkoutSetId, ex } of eachPrescribedExercise(workouts)) {
1274
+ const sweId = coerceInt(ex.id);
1275
+ if (sweId === null || used.has(sweId)) continue;
1276
+ if (coerceInt(ex.exercise_id) === exerciseId) return {
1277
+ savedWorkoutSetId,
1278
+ savedWorkoutSetExerciseId: sweId
1279
+ };
1280
+ }
1281
+ return null;
1282
+ }
1283
+ /** List the prescribed exercises on a day as `id (title)` labels, for not-found errors. */
1284
+ function prescribedExerciseLabels(workouts) {
1285
+ const labels = [];
1286
+ for (const { ex } of eachPrescribedExercise(workouts)) {
1287
+ const id = coerceInt(ex.exercise_id);
1288
+ if (id === null) continue;
1289
+ const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
1290
+ labels.push(`${id} (${title})`);
1291
+ }
1292
+ return labels;
1293
+ }
1294
+ /** Group resolved exercises by saved set and write each set via the given log target. */
1295
+ async function logResolvedExercises(client, target, date, resolved) {
1296
+ const bySet = /* @__PURE__ */ new Map();
1297
+ for (const r of resolved) {
1298
+ const list = bySet.get(r.savedWorkoutSetId) ?? [];
1299
+ list.push({
1300
+ savedWorkoutSetExerciseId: r.savedWorkoutSetExerciseId,
1301
+ sets: [...r.sets]
1302
+ });
1303
+ bySet.set(r.savedWorkoutSetId, list);
1304
+ }
1305
+ const out = [];
1306
+ for (const [savedWorkoutSetId, results] of bySet) {
1307
+ const written = target.role === "coach" ? await logForAthlete(client, {
1308
+ athleteId: target.athleteId,
1309
+ date,
1310
+ savedWorkoutSetId,
1311
+ results
1312
+ }) : await logAthleteSet(client, {
1313
+ date,
1314
+ savedWorkoutSetId,
1315
+ results
1316
+ });
1317
+ out.push(written);
1318
+ }
1319
+ return out;
1320
+ }
1321
+ /**
1322
+ * Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
1323
+ * off-plan session on another user's calendar (the personal-calendar endpoints are self-scoped),
1324
+ * so this logs against the session the athlete already has on that date: each requested exercise
1325
+ * is resolved to a prescribed saved set and its results are written via the coach "Log for
1326
+ * Athlete" surface. Throws a readable error naming the prescribed exercises when one is missing.
1327
+ */
1328
+ async function logSessionForAthlete(client, args) {
1329
+ if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
1330
+ const day = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
1331
+ const used = /* @__PURE__ */ new Set();
1332
+ const resolved = args.exercises.map((e) => {
1333
+ const hit = findPrescribedExercise(day, e.exerciseId, used);
1334
+ if (!hit) {
1335
+ const labels = prescribedExerciseLabels(day);
1336
+ const present = labels.length > 0 ? `Prescribed on ${args.date}: ${labels.join(", ")}.` : `Nothing is prescribed for athlete ${args.athleteId} on ${args.date}.`;
1337
+ throw new Error(`Exercise ${e.exerciseId} is not on athlete ${args.athleteId}'s calendar for ${args.date}, so there is no set to log it against. ${present} A coach can only log against an existing session; build/publish a session for the athlete first if it is missing.`);
1338
+ }
1339
+ used.add(hit.savedWorkoutSetExerciseId);
1340
+ return {
1341
+ exerciseId: e.exerciseId,
1342
+ ...hit,
1343
+ sets: e.sets
1344
+ };
1345
+ });
1346
+ const sets = await logResolvedExercises(client, {
1347
+ role: "coach",
1348
+ athleteId: args.athleteId
1349
+ }, args.date, resolved);
1350
+ return {
1351
+ date: args.date,
1352
+ created: false,
1353
+ sets
1354
+ };
1355
+ }
1204
1356
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1205
1357
  function presentExerciseHistory(detail) {
1206
1358
  return {
@@ -1396,6 +1548,94 @@ async function queryAnalytics(client, args) {
1396
1548
  if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
1397
1549
  return res.data;
1398
1550
  }
1551
+ /**
1552
+ * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
1553
+ * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
1554
+ * there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
1555
+ * given id, matched as a string. Throws when the roster fetch fails.
1556
+ */
1557
+ async function fetchTeamAthleteIds(client, teamId) {
1558
+ const res = await client.request("GET", "/v5/athletes");
1559
+ if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
1560
+ const rows = Array.isArray(res.data) ? res.data : [];
1561
+ const want = String(teamId);
1562
+ const ids = [];
1563
+ for (const row of rows) {
1564
+ if (row === null || typeof row !== "object") continue;
1565
+ const rec = row;
1566
+ if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
1567
+ const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
1568
+ if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
1569
+ }
1570
+ return ids;
1571
+ }
1572
+ function toNum(v) {
1573
+ const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
1574
+ return Number.isFinite(n) ? n : 0;
1575
+ }
1576
+ /**
1577
+ * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
1578
+ * analytics report already returns the team in one call — one row per logged session across all
1579
+ * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
1580
+ * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
1581
+ * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
1582
+ * all-time `fetchRosterActivity` snapshot, which has no date range.
1583
+ */
1584
+ async function teamVolume(client, args) {
1585
+ if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
1586
+ const report = await queryAnalytics(client, {
1587
+ metric: "training-summary-athlete",
1588
+ userIds: args.athleteIds,
1589
+ dateStart: args.dateStart,
1590
+ dateEnd: args.dateEnd
1591
+ });
1592
+ const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
1593
+ const byAthlete = /* @__PURE__ */ new Map();
1594
+ for (const row of rows) {
1595
+ const athleteId = toNum(row.user_id);
1596
+ if (athleteId === 0) continue;
1597
+ const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
1598
+ const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
1599
+ const existing = byAthlete.get(athleteId);
1600
+ if (existing) {
1601
+ existing.sessions += 1;
1602
+ existing.reps += toNum(row.reps);
1603
+ existing.volume += toNum(row.volume);
1604
+ if (date !== null) {
1605
+ if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
1606
+ if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
1607
+ }
1608
+ } else byAthlete.set(athleteId, {
1609
+ athleteId,
1610
+ name,
1611
+ sessions: 1,
1612
+ reps: toNum(row.reps),
1613
+ volume: toNum(row.volume),
1614
+ firstLoggedDate: date,
1615
+ lastLoggedDate: date
1616
+ });
1617
+ }
1618
+ const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
1619
+ const totals = athletes.reduce((acc, a) => ({
1620
+ athletes: acc.athletes + 1,
1621
+ sessions: acc.sessions + a.sessions,
1622
+ reps: acc.reps + a.reps,
1623
+ volume: acc.volume + a.volume
1624
+ }), {
1625
+ athletes: 0,
1626
+ sessions: 0,
1627
+ reps: 0,
1628
+ volume: 0
1629
+ });
1630
+ return {
1631
+ window: {
1632
+ start: args.dateStart,
1633
+ end: args.dateEnd
1634
+ },
1635
+ athletes,
1636
+ totals
1637
+ };
1638
+ }
1399
1639
  //#endregion
1400
1640
  //#region ../js/src/util.ts
1401
1641
  /**
@@ -2157,9 +2397,51 @@ function registerEntityReads(server, ctx) {
2157
2397
  }, ({ programId }) => apiCall(ctx, "GET", `/3.0/coach/program/${enc(programId)}`, void 0, "This is a large, deep object. If it is truncated, fetch a narrower view (a specific session) instead."));
2158
2398
  }
2159
2399
  /** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
2400
+ /** The windowed team-volume read — its own function so registerEntityReads stays under the cap. */
2401
+ function registerTeamVolume(server, ctx) {
2402
+ server.registerTool("team_volume", {
2403
+ title: "Team training volume over a date window",
2404
+ description: "Team-wide training volume (and reps/sessions) scoped to an inclusive YYYY-MM-DD window — the date-ranged answer to 'how much did the team train over the last two weeks'. Pass either teamId (its roster is resolved automatically) or an explicit athleteIds list (from list_athletes); dateStart and dateEnd are required. Returns one row per athlete who logged in range plus the rolled-up team totals (volume is in lb). For an all-time, undated snapshot use roster_activity instead.",
2405
+ inputSchema: {
2406
+ teamId: idParam.optional(),
2407
+ athleteIds: z.array(idParam).optional(),
2408
+ dateStart: dateString,
2409
+ dateEnd: dateString
2410
+ },
2411
+ annotations: READ
2412
+ }, ({ teamId, athleteIds, dateStart, dateEnd }) => attempt(async () => {
2413
+ const ids = athleteIds !== void 0 && athleteIds.length > 0 ? athleteIds.map(toId) : teamId !== void 0 ? await fetchTeamAthleteIds(ctx.client, toId(teamId)) : [];
2414
+ if (ids.length === 0) throw new Error("Provide athleteIds, or a teamId whose roster has athletes. No athletes resolved for this team — pass athleteIds from list_athletes instead.");
2415
+ return jsonResult(await teamVolume(ctx.client, {
2416
+ athleteIds: ids,
2417
+ dateStart,
2418
+ dateEnd
2419
+ }), { hint: "Rows cover only athletes who logged in range; totals roll them up. Narrow the window or athletes to shrink." });
2420
+ }));
2421
+ }
2160
2422
  function registerReadTools(server, ctx) {
2161
2423
  registerRosterReads(server, ctx);
2162
2424
  registerEntityReads(server, ctx);
2425
+ registerTeamVolume(server, ctx);
2426
+ }
2427
+ //#endregion
2428
+ //#region ../core/src/tools/athlete-training.ts
2429
+ /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
2430
+ function mapSessionExercises(exercises) {
2431
+ return exercises.map((e) => {
2432
+ const sets = e.sets.map((s) => {
2433
+ const slot = {};
2434
+ if (s.param1 !== void 0) slot.param1 = s.param1;
2435
+ if (s.param2 !== void 0) slot.param2 = s.param2;
2436
+ return slot;
2437
+ });
2438
+ const mapped = {
2439
+ exerciseId: toId(e.exerciseId),
2440
+ sets
2441
+ };
2442
+ if (e.order !== void 0) mapped.order = e.order;
2443
+ return mapped;
2444
+ });
2163
2445
  }
2164
2446
  //#endregion
2165
2447
  //#region ../core/src/tools/athletes.ts
@@ -2275,6 +2557,23 @@ function registerAthleteLogTools(server, ctx) {
2275
2557
  results: mapped
2276
2558
  }));
2277
2559
  }));
2560
+ server.registerTool("coach_log_session", {
2561
+ title: "Log a roster athlete's session by exercise",
2562
+ description: "Coach-facing write: log results for a roster athlete by exercise on a given day, without hunting for saved-set ids. Give athleteId, a YYYY-MM-DD date, and a list of exercises (each with its entered sets), and each is matched to a set already on that athlete's calendar for the date. The API has no way to put an off-plan session on an athlete's calendar, so this only logs against an EXISTING session — if an exercise is not prescribed that day the call fails and names what is. Get athleteId from list_athletes and exerciseIds from athlete_saved_workouts. Seeded demo athletes are read-only. Requires confirmation (elicitation or confirm:true).",
2563
+ inputSchema: {
2564
+ ...coachLogSessionArgsSchema.shape,
2565
+ confirm: z.boolean().optional()
2566
+ },
2567
+ annotations: DESTRUCTIVE
2568
+ }, ({ athleteId, date, exercises, confirm }, extra) => attempt(async () => {
2569
+ const aId = toId(athleteId);
2570
+ if (!await confirmGate(server, extra.requestId, `Log a session of ${exercises.length} exercise(s) for athlete ${aId} on ${date}? This writes to their coach-visible training log.`, confirm)) return errorResult(NOT_CONFIRMED);
2571
+ return jsonResult(await logSessionForAthlete(ctx.client, {
2572
+ athleteId: aId,
2573
+ date,
2574
+ exercises: mapSessionExercises(exercises)
2575
+ }));
2576
+ }));
2278
2577
  }
2279
2578
  //#endregion
2280
2579
  //#region ../core/src/tools/teams.ts
@@ -2695,7 +2994,7 @@ var JsonFileLibraryCache = class {
2695
2994
  };
2696
2995
  //#endregion
2697
2996
  //#region package.json
2698
- var version = "1.0.0";
2997
+ var version = "1.1.0";
2699
2998
  //#endregion
2700
2999
  //#region src/server.ts
2701
3000
  async function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "1.0.0",
3
+ "version": "1.1.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.0.0",
25
- "@trainheroic-unofficial/js": "1.0.0"
24
+ "@trainheroic-unofficial/js": "1.1.0",
25
+ "@trainheroic-unofficial/core": "1.1.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",