@trainheroic-unofficial/coach-mcp 2.1.1 → 3.0.1

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 +38 -82
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -960,11 +960,6 @@ async function getJson(client, path, label) {
960
960
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
961
961
  return res.data;
962
962
  }
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
963
  /** Lifetime training totals. `use_metric` is required by the API (omitting it 400s). */
969
964
  function fetchAthleteProfileSummary(client, userId, useMetric = false) {
970
965
  return getJson(client, `/v5/athleteProfile/summary?user_id=${userId}&use_metric=${useMetric ? 1 : 0}`, "athlete profile summary");
@@ -994,8 +989,9 @@ function sortRosterByRecency(rows) {
994
989
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
995
990
  const rows = [];
996
991
  const concurrency = 6;
997
- for (let i = 0; i < athleteIds.length; i += concurrency) {
998
- const chunk = athleteIds.slice(i, i + concurrency);
992
+ const uniqueAthleteIds = [...new Set(athleteIds)];
993
+ for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
994
+ const chunk = uniqueAthleteIds.slice(i, i + concurrency);
999
995
  const settled = await Promise.all(chunk.map(async (id) => {
1000
996
  try {
1001
997
  return {
@@ -1028,10 +1024,6 @@ async function fetchRosterActivity(client, athleteIds, useMetric = false) {
1028
1024
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
1029
1025
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
1030
1026
  }
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
1027
  function nonEmpty(value) {
1036
1028
  return value !== void 0 && value !== null && String(value).trim() !== "";
1037
1029
  }
@@ -1643,30 +1635,6 @@ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
1643
1635
  };
1644
1636
  }
1645
1637
  /**
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
1638
  * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
1671
1639
  * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
1672
1640
  * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
@@ -1865,7 +1833,7 @@ function prescribedExerciseLabels(workouts) {
1865
1833
  return labels;
1866
1834
  }
1867
1835
  /** Group resolved exercises by saved set and write each set via the given log target. */
1868
- async function logResolvedExercises(client, target, date, resolved) {
1836
+ async function logResolvedExercises(client, target, workouts, resolved) {
1869
1837
  const bySet = /* @__PURE__ */ new Map();
1870
1838
  for (const r of resolved) {
1871
1839
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -1877,19 +1845,10 @@ async function logResolvedExercises(client, target, date, resolved) {
1877
1845
  }
1878
1846
  const out = [];
1879
1847
  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
- });
1848
+ const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
1890
1849
  out.push({
1891
1850
  savedWorkoutSetId: written.savedWorkoutSetId,
1892
- exercisesLogged: written.exercisesLogged
1851
+ exercisesLogged: written.exercisesWritten
1893
1852
  });
1894
1853
  }
1895
1854
  return out;
@@ -1922,7 +1881,7 @@ async function logSessionForAthlete(client, args) {
1922
1881
  const sets = await logResolvedExercises(client, {
1923
1882
  role: "coach",
1924
1883
  athleteId: args.athleteId
1925
- }, args.date, resolved);
1884
+ }, day, resolved);
1926
1885
  return {
1927
1886
  date: args.date,
1928
1887
  created: false,
@@ -2129,7 +2088,7 @@ function unitAdvisory(blockTitle, ex, defaults) {
2129
2088
  /**
2130
2089
  * Run unit advisories across a whole block list against an exercise index. Shared by the
2131
2090
  * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2132
- * index is loaded first, otherwise `defaults` returns null on a cold index and every
2091
+ * index is loaded first, otherwise the defaults map is empty on a cold index and every
2133
2092
  * advisory is silently dropped.
2134
2093
  */
2135
2094
  async function collectAdvisories(blocks, index) {
@@ -2138,14 +2097,12 @@ async function collectAdvisories(blocks, index) {
2138
2097
  block: b,
2139
2098
  ex
2140
2099
  })));
2141
- const defaults = await Promise.all(pairs.map((p) => {
2142
- const id = Number(p.ex.id);
2143
- return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
2144
- }));
2100
+ const ids = [...new Set(pairs.map((p) => Number(p.ex.id)).filter((id) => Number.isFinite(id)))];
2101
+ const defaultsById = await index.defaultsMany(ids);
2145
2102
  const notes = [];
2146
2103
  const warnings = [];
2147
- pairs.forEach((p, i) => {
2148
- const def = defaults[i];
2104
+ pairs.forEach((p) => {
2105
+ const def = defaultsById.get(Number(p.ex.id));
2149
2106
  if (!def) return;
2150
2107
  const advisory = unitAdvisory(p.block.title, p.ex, def);
2151
2108
  notes.push(...advisory.notes);
@@ -2158,6 +2115,7 @@ async function collectAdvisories(blocks, index) {
2158
2115
  }
2159
2116
  //#endregion
2160
2117
  //#region ../js/src/workout-session.ts
2118
+ const EXERCISE_SAVE_CONCURRENCY = 4;
2161
2119
  /**
2162
2120
  * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
2163
2121
  * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
@@ -2191,15 +2149,14 @@ async function buildSession(client, opts) {
2191
2149
  const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(blocks, workoutId));
2192
2150
  const byOrder = new Map(created.map((b) => [b.order, b.id]));
2193
2151
  let counter = 0;
2194
- const payloads = blocks.map((block, i) => {
2152
+ await mapPool(blocks.map((block, i) => {
2195
2153
  const wsid = byOrder.get(i + 1);
2196
2154
  if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2197
2155
  return block.exercises.map((ex, j) => {
2198
2156
  counter += 1;
2199
2157
  return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2200
2158
  });
2201
- });
2202
- await Promise.all(payloads.filter((p) => p.length > 0).map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2159
+ }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (payload) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", payload));
2203
2160
  if (opts.instruction !== void 0 && opts.instruction !== "") {
2204
2161
  const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2205
2162
  await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
@@ -2402,7 +2359,8 @@ async function copySession(client, args) {
2402
2359
  year,
2403
2360
  dayOfWeek,
2404
2361
  isToday: false
2405
- }
2362
+ },
2363
+ toTimelineDate: null
2406
2364
  } });
2407
2365
  if (!res.ok) {
2408
2366
  const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
@@ -2885,9 +2843,11 @@ async function deleteComment(client, streamId, commentId) {
2885
2843
  if (!res.ok) throw new Error(`Message delete failed (HTTP ${res.status}).`);
2886
2844
  return res.data;
2887
2845
  }
2888
- async function readLive(client, streamId, limit) {
2889
- const res = await client.request("GET", `/v5/messaging/streams/${streamId}/comments?lastCommentId=`);
2846
+ async function readLive(client, streamId, limit, afterCommentId) {
2847
+ const cursor = afterCommentId === void 0 ? "" : String(afterCommentId);
2848
+ const res = await client.request("GET", `/v5/messaging/streams/${streamId}/comments?lastCommentId=${cursor}`);
2890
2849
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`Message read failed (HTTP ${res.status}).`);
2850
+ if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
2891
2851
  return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
2892
2852
  }
2893
2853
  //#endregion
@@ -2991,12 +2951,16 @@ var ExerciseLibrary = class {
2991
2951
  if (!s) return null;
2992
2952
  return presentExercise(s.raw);
2993
2953
  }
2994
- async defaults(id) {
2995
- const s = this.#byId.get(id);
2996
- return s ? {
2997
- param1: s.param_1_type,
2998
- param2: s.param_2_type
2999
- } : null;
2954
+ async defaultsMany(ids) {
2955
+ const result = /* @__PURE__ */ new Map();
2956
+ for (const id of ids) {
2957
+ const s = this.#byId.get(id);
2958
+ if (s) result.set(id, {
2959
+ param1: s.param_1_type,
2960
+ param2: s.param_2_type
2961
+ });
2962
+ }
2963
+ return result;
3000
2964
  }
3001
2965
  async search(query, limit = 20) {
3002
2966
  await this.ensureFresh();
@@ -3014,21 +2978,12 @@ var ExerciseLibrary = class {
3014
2978
  }
3015
2979
  async resolve(name) {
3016
2980
  await this.ensureFresh();
3017
- let hit = this.#exact(name);
2981
+ const hit = this.#exact(name);
3018
2982
  if (hit) return {
3019
2983
  match: hit,
3020
2984
  candidates: [hit]
3021
2985
  };
3022
- let candidates = this.#searchOnly(name, 20);
3023
- if (candidates.length === 0) {
3024
- await this.refresh();
3025
- hit = this.#exact(name);
3026
- if (hit) return {
3027
- match: hit,
3028
- candidates: [hit]
3029
- };
3030
- candidates = this.#searchOnly(name, 20);
3031
- }
2986
+ const candidates = this.#searchOnly(name, 20);
3032
2987
  if (candidates.length === 1) return {
3033
2988
  match: candidates[0] ?? null,
3034
2989
  candidates
@@ -3868,13 +3823,14 @@ function registerReads(server, ctx) {
3868
3823
  }));
3869
3824
  server.registerTool("messaging_read", {
3870
3825
  title: "Read messages (live)",
3871
- 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.",
3826
+ 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.",
3872
3827
  inputSchema: {
3873
3828
  streamId: idParam,
3874
- limit: z.number().int().positive().max(200).optional()
3829
+ limit: z.number().int().positive().max(200).optional(),
3830
+ afterCommentId: idParam.optional()
3875
3831
  },
3876
3832
  annotations: READ
3877
- }, ({ streamId, limit }) => attempt(async () => jsonResult(await readLive(ctx.client, toId(streamId), limit ?? 20))));
3833
+ }, ({ streamId, limit, afterCommentId }) => attempt(async () => jsonResult(await readLive(ctx.client, toId(streamId), limit ?? 20, afterCommentId === void 0 ? void 0 : toId(afterCommentId)))));
3878
3834
  server.registerTool("message_draft", {
3879
3835
  title: "Draft a message (preview only)",
3880
3836
  description: "Preview the exact payload and target WITHOUT sending. Always safe.",
@@ -3970,7 +3926,7 @@ var JsonFileLibraryCache = class {
3970
3926
  };
3971
3927
  //#endregion
3972
3928
  //#region package.json
3973
- var version = "2.1.1";
3929
+ var version = "3.0.1";
3974
3930
  //#endregion
3975
3931
  //#region src/server.ts
3976
3932
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "2.1.1",
3
+ "version": "3.0.1",
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/core": "2.1.1",
25
- "@trainheroic-unofficial/js": "2.1.1"
24
+ "@trainheroic-unofficial/core": "3.0.1",
25
+ "@trainheroic-unofficial/js": "3.0.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.2.0",