@trainheroic-unofficial/coach-mcp 3.0.0 → 3.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 +27 -82
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -201,21 +201,12 @@ const coachLogSetArgsSchema = z.object({
201
201
  savedWorkoutSetId: idArgSchema,
202
202
  results: loggedExerciseResultsSchema
203
203
  }).extend({ athleteId: idArgSchema });
204
- /**
205
- * Args for the coach prescription-override write. Like {@link coachLogSetArgsSchema}
206
- * (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but the values are prescribed
207
- * targets (param1 = reps, param2 = weight) written to the athlete's plan without marking the set
208
- * performed. The write replaces this athlete's whole prescription for the set, so its sets are
209
- * positional and sequential by definition: it deliberately omits the log path's `slot` field (a
210
- * sparse, slot-targeted prescription has no meaning here) by building its results off
211
- * {@link loggedSetSchema} rather than {@link loggedSetWithSlotSchema}.
212
- */
204
+ /** Coach variant of {@link athletePrescribeSetArgsSchema}, with the roster athlete to update. */
213
205
  const coachPrescribeSetArgsSchema = z.object({
214
206
  date: dateString,
215
207
  savedWorkoutSetId: idArgSchema,
216
- athleteId: idArgSchema,
217
208
  results: prescribedExerciseResultsSchema
218
- });
209
+ }).extend({ athleteId: idArgSchema });
219
210
  /**
220
211
  * Args for the coach per-athlete exercise swap: replace the exercise prescribed in one of a
221
212
  * roster athlete's saved-workout slots with a different exercise, the API equivalent of the
@@ -960,11 +951,6 @@ async function getJson(client, path, label) {
960
951
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
961
952
  return res.data;
962
953
  }
963
- async function getArray$1(client, path, label) {
964
- const res = await client.request("GET", path);
965
- if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
966
- return res.data;
967
- }
968
954
  /** Lifetime training totals. `use_metric` is required by the API (omitting it 400s). */
969
955
  function fetchAthleteProfileSummary(client, userId, useMetric = false) {
970
956
  return getJson(client, `/v5/athleteProfile/summary?user_id=${userId}&use_metric=${useMetric ? 1 : 0}`, "athlete profile summary");
@@ -994,8 +980,9 @@ function sortRosterByRecency(rows) {
994
980
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
995
981
  const rows = [];
996
982
  const concurrency = 6;
997
- for (let i = 0; i < athleteIds.length; i += concurrency) {
998
- const chunk = athleteIds.slice(i, i + concurrency);
983
+ const uniqueAthleteIds = [...new Set(athleteIds)];
984
+ for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
985
+ const chunk = uniqueAthleteIds.slice(i, i + concurrency);
999
986
  const settled = await Promise.all(chunk.map(async (id) => {
1000
987
  try {
1001
988
  return {
@@ -1028,10 +1015,6 @@ async function fetchRosterActivity(client, athleteIds, useMetric = false) {
1028
1015
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
1029
1016
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
1030
1017
  }
1031
- /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
1032
- function fetchAthleteWorkouts(client, startDate, endDate) {
1033
- return getArray$1(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
1034
- }
1035
1018
  function nonEmpty(value) {
1036
1019
  return value !== void 0 && value !== null && String(value).trim() !== "";
1037
1020
  }
@@ -1643,30 +1626,6 @@ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
1643
1626
  };
1644
1627
  }
1645
1628
  /**
1646
- * Record entered set results for one saved workout set.
1647
- *
1648
- * **Two-step write (both required for data to persist):**
1649
- * 1. For each exercise in `results`:
1650
- * `PUT /1.0/athlete/savedworkoutsetexercise/{savedWorkoutSetExerciseId}` with the
1651
- * per-slot `param_N_data_M` values. This is the only path that actually stores reps
1652
- * and weight — the `savedworkoutset` PUT accepts the same fields but silently discards
1653
- * them.
1654
- * 2. `PUT /1.0/athlete/savedworkoutset/{savedWorkoutSetId}` with `completed:"1"` to
1655
- * mark the block done and make the entry visible as a logged set in history.
1656
- *
1657
- * The date is used to locate the saved workout (via the range endpoint) so we can resolve
1658
- * `saved_workout_id` and `workout_set_exercise_id` for each exercise. Both are required
1659
- * by the respective PUT bodies.
1660
- */
1661
- async function logAthleteSet(client, args) {
1662
- const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
1663
- return {
1664
- savedWorkoutSetId: r.savedWorkoutSetId,
1665
- exercisesLogged: r.exercisesWritten,
1666
- setCompleted: r.setCompleted
1667
- };
1668
- }
1669
- /**
1670
1629
  * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
1671
1630
  * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
1672
1631
  * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
@@ -1751,9 +1710,10 @@ async function swapAthleteExercise(client, args) {
1751
1710
  };
1752
1711
  }
1753
1712
  /**
1754
- * Shared set-write behind {@link logAthleteSet}, {@link logForAthlete}, and
1755
- * {@link prescribeForAthlete}. `target` selects the surface: `athlete` writes `/1.0/athlete/...`;
1756
- * `coach` writes `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body.
1713
+ * Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
1714
+ * {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
1715
+ * writes `/1.0/athlete/...`; `coach` writes `/1.0/coach/...{athleteId}` and stamps `athleteId` into
1716
+ * each body.
1757
1717
  *
1758
1718
  * Step 1 PUTs each exercise's per-set values to its own endpoint (the only path that actually
1759
1719
  * stores reps and weight). `mode` decides what those values mean: `"log"` records them as a
@@ -1865,7 +1825,7 @@ function prescribedExerciseLabels(workouts) {
1865
1825
  return labels;
1866
1826
  }
1867
1827
  /** Group resolved exercises by saved set and write each set via the given log target. */
1868
- async function logResolvedExercises(client, target, date, resolved) {
1828
+ async function logResolvedExercises(client, target, workouts, resolved) {
1869
1829
  const bySet = /* @__PURE__ */ new Map();
1870
1830
  for (const r of resolved) {
1871
1831
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -1877,19 +1837,10 @@ async function logResolvedExercises(client, target, date, resolved) {
1877
1837
  }
1878
1838
  const out = [];
1879
1839
  for (const [savedWorkoutSetId, results] of bySet) {
1880
- const written = target.role === "coach" ? await logForAthlete(client, {
1881
- athleteId: target.athleteId,
1882
- date,
1883
- savedWorkoutSetId,
1884
- results
1885
- }) : await logAthleteSet(client, {
1886
- date,
1887
- savedWorkoutSetId,
1888
- results
1889
- });
1840
+ const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
1890
1841
  out.push({
1891
1842
  savedWorkoutSetId: written.savedWorkoutSetId,
1892
- exercisesLogged: written.exercisesLogged
1843
+ exercisesLogged: written.exercisesWritten
1893
1844
  });
1894
1845
  }
1895
1846
  return out;
@@ -1922,7 +1873,7 @@ async function logSessionForAthlete(client, args) {
1922
1873
  const sets = await logResolvedExercises(client, {
1923
1874
  role: "coach",
1924
1875
  athleteId: args.athleteId
1925
- }, args.date, resolved);
1876
+ }, day, resolved);
1926
1877
  return {
1927
1878
  date: args.date,
1928
1879
  created: false,
@@ -2156,6 +2107,7 @@ async function collectAdvisories(blocks, index) {
2156
2107
  }
2157
2108
  //#endregion
2158
2109
  //#region ../js/src/workout-session.ts
2110
+ const EXERCISE_SAVE_CONCURRENCY = 4;
2159
2111
  /**
2160
2112
  * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
2161
2113
  * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
@@ -2189,15 +2141,14 @@ async function buildSession(client, opts) {
2189
2141
  const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(blocks, workoutId));
2190
2142
  const byOrder = new Map(created.map((b) => [b.order, b.id]));
2191
2143
  let counter = 0;
2192
- const payloads = blocks.map((block, i) => {
2144
+ await mapPool(blocks.map((block, i) => {
2193
2145
  const wsid = byOrder.get(i + 1);
2194
2146
  if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2195
2147
  return block.exercises.map((ex, j) => {
2196
2148
  counter += 1;
2197
2149
  return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2198
2150
  });
2199
- });
2200
- await Promise.all(payloads.filter((p) => p.length > 0).map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2151
+ }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (payload) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", payload));
2201
2152
  if (opts.instruction !== void 0 && opts.instruction !== "") {
2202
2153
  const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2203
2154
  await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
@@ -2884,9 +2835,11 @@ async function deleteComment(client, streamId, commentId) {
2884
2835
  if (!res.ok) throw new Error(`Message delete failed (HTTP ${res.status}).`);
2885
2836
  return res.data;
2886
2837
  }
2887
- async function readLive(client, streamId, limit) {
2888
- const res = await client.request("GET", `/v5/messaging/streams/${streamId}/comments?lastCommentId=`);
2838
+ async function readLive(client, streamId, limit, afterCommentId) {
2839
+ const cursor = afterCommentId === void 0 ? "" : String(afterCommentId);
2840
+ const res = await client.request("GET", `/v5/messaging/streams/${streamId}/comments?lastCommentId=${cursor}`);
2889
2841
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`Message read failed (HTTP ${res.status}).`);
2842
+ if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
2890
2843
  return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
2891
2844
  }
2892
2845
  //#endregion
@@ -3017,21 +2970,12 @@ var ExerciseLibrary = class {
3017
2970
  }
3018
2971
  async resolve(name) {
3019
2972
  await this.ensureFresh();
3020
- let hit = this.#exact(name);
2973
+ const hit = this.#exact(name);
3021
2974
  if (hit) return {
3022
2975
  match: hit,
3023
2976
  candidates: [hit]
3024
2977
  };
3025
- let candidates = this.#searchOnly(name, 20);
3026
- if (candidates.length === 0) {
3027
- await this.refresh();
3028
- hit = this.#exact(name);
3029
- if (hit) return {
3030
- match: hit,
3031
- candidates: [hit]
3032
- };
3033
- candidates = this.#searchOnly(name, 20);
3034
- }
2978
+ const candidates = this.#searchOnly(name, 20);
3035
2979
  if (candidates.length === 1) return {
3036
2980
  match: candidates[0] ?? null,
3037
2981
  candidates
@@ -3871,13 +3815,14 @@ function registerReads(server, ctx) {
3871
3815
  }));
3872
3816
  server.registerTool("messaging_read", {
3873
3817
  title: "Read messages (live)",
3874
- description: "Recent comments in a stream, live from the API (the stream is fetched whole, then trimmed to `limit`, default 20). Each comment's `isAuthor` is true when the logged-in user sent it — to answer 'did an athlete message me', look for comments with isAuthor:false. Timestamps are Unix seconds. An empty result means the thread has no messages.",
3818
+ description: "Comments in a stream, live from the API. Pass `afterCommentId` to fetch only newer comments upstream; cursor reads return the oldest unseen comments first, bounded by `limit`, so advance with the last returned comment ID to continue without gaps. Without it, the stream is fetched whole, then trimmed to `limit` (default 20). Each comment's `isAuthor` is true when the logged-in user sent it — to answer 'did an athlete message me', look for comments with isAuthor:false. Timestamps are Unix seconds. An empty result means the thread has no messages.",
3875
3819
  inputSchema: {
3876
3820
  streamId: idParam,
3877
- limit: z.number().int().positive().max(200).optional()
3821
+ limit: z.number().int().positive().max(200).optional(),
3822
+ afterCommentId: idParam.optional()
3878
3823
  },
3879
3824
  annotations: READ
3880
- }, ({ streamId, limit }) => attempt(async () => jsonResult(await readLive(ctx.client, toId(streamId), limit ?? 20))));
3825
+ }, ({ streamId, limit, afterCommentId }) => attempt(async () => jsonResult(await readLive(ctx.client, toId(streamId), limit ?? 20, afterCommentId === void 0 ? void 0 : toId(afterCommentId)))));
3881
3826
  server.registerTool("message_draft", {
3882
3827
  title: "Draft a message (preview only)",
3883
3828
  description: "Preview the exact payload and target WITHOUT sending. Always safe.",
@@ -3973,7 +3918,7 @@ var JsonFileLibraryCache = class {
3973
3918
  };
3974
3919
  //#endregion
3975
3920
  //#region package.json
3976
- var version = "3.0.0";
3921
+ var version = "3.1.0";
3977
3922
  //#endregion
3978
3923
  //#region src/server.ts
3979
3924
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "3.0.0",
3
+ "version": "3.1.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/server": "2.0.0",
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/js": "3.0.0",
25
- "@trainheroic-unofficial/core": "3.0.0"
24
+ "@trainheroic-unofficial/core": "3.1.0",
25
+ "@trainheroic-unofficial/js": "3.1.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.2.0",