@trainheroic-unofficial/coach-mcp 1.3.0 → 1.4.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 +126 -17
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -512,7 +512,20 @@ async function confirmGate(server, requestId, message, confirmArg) {
512
512
  const SERVER_INSTRUCTIONS = "Speak to the user in plain, everyday language about their training. Describe what you are doing in the TrainHeroic app's own terms (for example, say you are creating a workout rather than naming a tool). Do not surface internal tool names (the snake_case identifiers such as athlete_session_create), raw parameter names, or numeric ids in your replies unless the user explicitly asks for them; they are implementation details. The tool descriptions cross-reference each other by name only so you can chain them correctly. Keep that wiring to yourself.";
513
513
  //#endregion
514
514
  //#region ../js/src/auth.ts
515
- const AUTH_URL = "https://apis.trainheroic.com/auth";
515
+ const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
516
+ /**
517
+ * The login endpoint, allowing an env override so a test harness can authenticate against a local
518
+ * fake backend. Precedence: an explicit `TH_AUTH_URL`, else `${TH_APIS_BASE}/auth` (login lives on
519
+ * the apis host, so it follows that base), else the real endpoint. Read via `globalThis.process`
520
+ * (no `import process`) to keep this module workerd-safe, and per call so a child-env override wins.
521
+ */
522
+ function authUrl() {
523
+ const env = globalThis.process?.env;
524
+ if (env?.TH_AUTH_URL && env.TH_AUTH_URL.length > 0) return env.TH_AUTH_URL;
525
+ const apis = env?.TH_APIS_BASE;
526
+ if (apis && apis.length > 0) return `${apis.replace(/\/$/, "")}/auth`;
527
+ return DEFAULT_AUTH_URL;
528
+ }
516
529
  /**
517
530
  * Authenticate against TrainHeroic. Returns the session bundle, or null on bad
518
531
  * credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
@@ -520,7 +533,7 @@ const AUTH_URL = "https://apis.trainheroic.com/auth";
520
533
  * is sent as the `session-token` header and works against both API hosts.
521
534
  */
522
535
  async function loginTrainHeroic(email, password) {
523
- const res = await fetch(AUTH_URL, {
536
+ const res = await fetch(authUrl(), {
524
537
  method: "POST",
525
538
  headers: {
526
539
  "content-type": "application/x-www-form-urlencoded",
@@ -543,8 +556,19 @@ async function loginTrainHeroic(email, password) {
543
556
  }
544
557
  //#endregion
545
558
  //#region ../js/src/client.ts
546
- const COACH_BASE = "https://api.trainheroic.com";
547
- const APIS_BASE = "https://apis.trainheroic.com";
559
+ const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
560
+ const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
561
+ /**
562
+ * Resolve an API host, allowing an env override. The override exists so a test harness can point
563
+ * the client at a local fake backend (and it doubles as a staging knob); production leaves these
564
+ * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
565
+ * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
566
+ * read per request (not at module load) so a value the harness sets in the child env always wins.
567
+ */
568
+ function envBase(key, fallback) {
569
+ const v = (globalThis.process?.env)?.[key];
570
+ return v && v.length > 0 ? v : fallback;
571
+ }
548
572
  var TrainHeroicAuthError = class extends Error {
549
573
  name = "TrainHeroicAuthError";
550
574
  };
@@ -583,7 +607,7 @@ var TrainHeroicClient = class {
583
607
  return this.#sessionId;
584
608
  }
585
609
  async request(method, path, options = {}) {
586
- const url = `${options.base === "apis" ? APIS_BASE : COACH_BASE}/${path.replace(/^\//, "")}`;
610
+ const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
587
611
  let session = await this.#ensureSession();
588
612
  let res = await this.#send(method, url, session, options.body);
589
613
  if (res.status === 401 || res.status === 403) {
@@ -1055,6 +1079,81 @@ function presentAthleteWorkouts(list) {
1055
1079
  return list.map(presentAthleteWorkout);
1056
1080
  }
1057
1081
  /**
1082
+ * Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
1083
+ * every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
1084
+ * workouts, so a caller wanting one program's session narrows it here. Match by `programId`/`teamId`
1085
+ * (exact, on the raw `program_id`/`team_id`) or by `programTitle` (case-insensitive substring on the
1086
+ * `program_title`/`team_title`) — the title match lets a caller target a program by name without
1087
+ * first resolving its id. Any one match keeps the workout; with no filter the list is unchanged.
1088
+ */
1089
+ function selectWorkoutsByProgram(list, filter) {
1090
+ const { programId, teamId, programTitle } = filter;
1091
+ const needle = programTitle?.trim().toLowerCase();
1092
+ if (programId === void 0 && teamId === void 0 && !needle) return [...list];
1093
+ return list.filter((pw) => {
1094
+ const rec = pw;
1095
+ if (programId !== void 0 && coerceInt(rec.program_id) === programId) return true;
1096
+ if (teamId !== void 0 && coerceInt(rec.team_id) === teamId) return true;
1097
+ if (needle) {
1098
+ if (`${str$1(rec.program_title) ?? ""} ${str$1(rec.team_title) ?? ""}`.toLowerCase().includes(needle)) return true;
1099
+ }
1100
+ return false;
1101
+ });
1102
+ }
1103
+ /**
1104
+ * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
1105
+ * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
1106
+ * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
1107
+ * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
1108
+ * `savedWorkoutSetExerciseId` straight off these rows. Each target also carries its program/team
1109
+ * so a caller can pick the right session when the athlete is on several. One row per saved set,
1110
+ * dropping any set with no resolvable id.
1111
+ */
1112
+ function presentLogTargets(list) {
1113
+ const targets = [];
1114
+ for (const pw of list) {
1115
+ const rec = pw;
1116
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1117
+ const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1118
+ if (!saved) continue;
1119
+ const date = str$1(rec.date) ?? "";
1120
+ const workoutTitle = str$1(rec.workout_title) ?? "";
1121
+ const program = str$1(rec.program_title);
1122
+ const programId = coerceInt(rec.program_id);
1123
+ const team = str$1(rec.team_title);
1124
+ const teamId = coerceInt(rec.team_id);
1125
+ const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
1126
+ for (const s of sets) {
1127
+ if (!isRecord(s)) continue;
1128
+ const savedWorkoutSetId = coerceInt(s.id);
1129
+ if (savedWorkoutSetId === null) continue;
1130
+ const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
1131
+ const id = coerceInt(ex.id);
1132
+ if (id === null) return null;
1133
+ return {
1134
+ savedWorkoutSetExerciseId: id,
1135
+ title: typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "",
1136
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type),
1137
+ prescribed: prescribedSets(ex),
1138
+ performed: performedSets(ex)
1139
+ };
1140
+ }).filter((e) => e !== null);
1141
+ targets.push({
1142
+ date,
1143
+ workoutTitle,
1144
+ program,
1145
+ programId,
1146
+ team,
1147
+ teamId,
1148
+ savedWorkoutSetId,
1149
+ setTitle: str$1(s.title),
1150
+ exercises
1151
+ });
1152
+ }
1153
+ }
1154
+ return targets;
1155
+ }
1156
+ /**
1058
1157
  * Flatten the coach athlete-calendar summary into compact per-session rows: title, the `logged`
1059
1158
  * flag (the reliable did-they-train signal), rpe/duration/notes, and the exercises performed with
1060
1159
  * the API's own set summary string (`abr`, e.g. "5 x 2 @ 205 lb"). The exercise titles here are
@@ -1374,7 +1473,7 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1374
1473
  throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1375
1474
  }
1376
1475
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1377
- if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
1476
+ if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
1378
1477
  const body = {
1379
1478
  ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
1380
1479
  ...extra
@@ -2640,7 +2739,7 @@ function historyInRange(presented, since, until) {
2640
2739
  //#region ../core/src/tools/reads.ts
2641
2740
  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.";
2642
2741
  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.";
2643
- 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.";
2742
+ 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 and carry NO per-session date — so this canNOT answer 'what did they do on <day>' (e.g. today); for a specific day use athlete_saved_workouts with startDate=endDate=that day instead. An empty list means no sessions that month.";
2644
2743
  function enc(value) {
2645
2744
  return encodeURIComponent(String(value));
2646
2745
  }
@@ -2944,25 +3043,35 @@ function registerAthleteTools(server, ctx) {
2944
3043
  * "Log for Athlete" flow. Kept in its own function so registerAthleteTools stays under the
2945
3044
  * oxlint max-lines-per-function cap.
2946
3045
  */
2947
- function registerAthleteLogTools(server, ctx) {
3046
+ function registerAthleteSavedWorkouts(server, ctx) {
2948
3047
  server.registerTool("athlete_saved_workouts", {
2949
3048
  title: "Roster athlete's saved workouts (with log ids)",
2950
- description: "A roster athlete's scheduled/logged workouts in an inclusive YYYY-MM-DD window — the coach-side view that carries the savedWorkoutSetId and savedWorkoutSetExerciseId that log_athlete_set needs. Get athleteId from list_athletes. Defaults to a presented view; set raw:true for the untouched API objects that expose those ids (each set's id is the savedWorkoutSetId; each savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId). athlete_training gives a whole-month overview but not these ids.",
3049
+ description: "A roster athlete's scheduled/logged workouts in an inclusive YYYY-MM-DD window. This is the DATE-PRECISE coach read: to answer 'what did <athlete> do/log on <day>' (e.g. today), pass startDate=endDate=that day — each row carries its date and the performed values (what the athlete actually logged), unlike athlete_training which is a whole-month overview with no per-session date. It is also the coach-side source of the savedWorkoutSetId and savedWorkoutSetExerciseId that log_athlete_set, prescribe_athlete_set, and swap_athlete_exercise need. Get athleteId from list_athletes. The default view is COMPACT: one row per saved set, each carrying its program/programId, the savedWorkoutSetId, and every exercise's savedWorkoutSetExerciseId with prescribed/performed values — so you read those ids straight off it, no raw needed. An athlete enrolled in many programs returns one row per program; narrow to one with program (a case-insensitive title substring, e.g. 'bodybuilding' — no id lookup needed), or programId/teamId if you already have the id. raw:true returns the untouched API objects, but that blob is large and can be truncated for a high-enrollment athlete — prefer the program filter + the default view. athlete_training gives a whole-month overview but not these ids.",
2951
3050
  inputSchema: {
2952
3051
  athleteId: idParam,
2953
3052
  startDate: dateString,
2954
3053
  endDate: dateString,
3054
+ program: z.string().optional(),
3055
+ programId: idParam.optional(),
3056
+ teamId: idParam.optional(),
2955
3057
  raw: z.boolean().optional()
2956
3058
  },
2957
3059
  annotations: READ
2958
- }, ({ athleteId, startDate, endDate, raw }) => attempt(async () => {
2959
- const workouts = await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate);
2960
- if (raw === true) return jsonResult(workouts, { hint: "Each set's id is the savedWorkoutSetId; each savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId. Pass both to log_athlete_set. Narrow the dates to shrink this." });
2961
- return jsonResult(presentAthleteWorkouts(workouts), { hint: "Set raw:true to get savedWorkoutSetId + savedWorkoutSetExerciseId for log_athlete_set." });
3060
+ }, ({ athleteId, startDate, endDate, program, programId, teamId, raw }) => attempt(async () => {
3061
+ const workouts = selectWorkoutsByProgram(await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate), definedProps({
3062
+ programTitle: program,
3063
+ programId: programId === void 0 ? void 0 : toId(programId),
3064
+ teamId: teamId === void 0 ? void 0 : toId(teamId)
3065
+ }));
3066
+ if (raw === true) return jsonResult(workouts, { hint: "Each set's id is the savedWorkoutSetId; each savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId. This raw blob is large — if truncated, pass program (a title substring) to target one program, or use the default (compact) view which carries the same ids." });
3067
+ return jsonResult(presentLogTargets(workouts), { hint: "One row per saved set: savedWorkoutSetId plus each savedWorkoutSetExerciseId, with the program it belongs to. Pass both ids to log_athlete_set / prescribe_athlete_set. Filter with program (title substring), programId, or teamId if the athlete is on several programs." });
2962
3068
  }));
3069
+ }
3070
+ function registerAthleteLogTools(server, ctx) {
3071
+ registerAthleteSavedWorkouts(server, ctx);
2963
3072
  server.registerTool("log_athlete_set", {
2964
3073
  title: "Log set results for a roster athlete",
2965
- description: "Coach-facing write: record entered results (reps/weight per set) for one of a roster athlete's saved workout sets on a given day, marking the set completed — the API equivalent of the app's \"Log for Athlete\". Writes to that athlete's training log and shows in their history. Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts (raw:true) for that athlete/day. Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3074
+ description: "Coach-facing write: record entered results (reps/weight per set) for one of a roster athlete's saved workout sets on a given day, marking the set completed — the API equivalent of the app's \"Log for Athlete\". Writes to that athlete's training log and shows in their history. Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts for that athlete/day (its default view carries both — pass programId there if the athlete is on several programs). Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
2966
3075
  inputSchema: {
2967
3076
  ...coachLogSetArgsSchema.shape,
2968
3077
  confirm: z.boolean().optional()
@@ -3003,7 +3112,7 @@ function registerAthleteLogTools(server, ctx) {
3003
3112
  function registerAthleteSwapTool(server, ctx) {
3004
3113
  server.registerTool("swap_athlete_exercise", {
3005
3114
  title: "Swap one exercise in a roster athlete's prescribed workout",
3006
- description: "Coach-facing write: replace one exercise in a roster athlete's scheduled workout with a different one, for that athlete only — the API equivalent of the app's per-athlete \"swap exercise\". The team/program prescription is left untouched, so other athletes on the same program keep the original exercise. Give savedWorkoutSetExerciseId (the athlete's own slot, from athlete_saved_workouts with raw:true) and exerciseId (the replacement, from exercise_resolve / exercise_search). Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3115
+ description: "Coach-facing write: replace one exercise in a roster athlete's scheduled workout with a different one, for that athlete only — the API equivalent of the app's per-athlete \"swap exercise\". The team/program prescription is left untouched, so other athletes on the same program keep the original exercise. Give savedWorkoutSetExerciseId (the athlete's own slot, from athlete_saved_workouts — its default view lists it per program) and exerciseId (the replacement, from exercise_resolve / exercise_search). Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3007
3116
  inputSchema: {
3008
3117
  ...swapAthleteExerciseArgsSchema.shape,
3009
3118
  confirm: z.boolean().optional()
@@ -3027,7 +3136,7 @@ function registerAthleteSwapTool(server, ctx) {
3027
3136
  function registerAthletePrescribeTool(server, ctx) {
3028
3137
  server.registerTool("prescribe_athlete_set", {
3029
3138
  title: "Prescribe reps/weight for a roster athlete's set",
3030
- description: "Coach-facing write: set the prescribed reps and/or weight for one of a roster athlete's scheduled workout sets, for that athlete only, WITHOUT marking it done — the API equivalent of the app's editing an athlete's prescribed values (\"prescribe weights for an athlete\"). The set stays open for the athlete to log against, and the team/program prescription is left untouched, so other athletes keep the original targets. param1 is reps, param2 is weight; pass one sets[] entry per prescribed set. The write REPLACES the slot's prescribed values (the sets you pass become the whole prescription, and an omitted param is cleared), so give the full per-set prescription you want. Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts (raw:true) for that athlete/day. To record a set as PERFORMED instead, use log_athlete_set. Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3139
+ description: "Coach-facing write: set the prescribed reps and/or weight for one of a roster athlete's scheduled workout sets, for that athlete only, WITHOUT marking it done — the API equivalent of the app's editing an athlete's prescribed values (\"prescribe weights for an athlete\"). The set stays open for the athlete to log against, and the team/program prescription is left untouched, so other athletes keep the original targets. param1 is reps, param2 is weight; pass one sets[] entry per prescribed set. The write REPLACES the slot's prescribed values (the sets you pass become the whole prescription, and an omitted param is cleared), so give the full per-set prescription you want. Get athleteId from list_athletes; get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_saved_workouts for that athlete/day — its default view lists both per program, so pass programId there if the athlete is on several. To record a set as PERFORMED instead, use log_athlete_set. Seeded demo athletes are read-only and will fail; use a real (invited) athlete. Requires confirmation (elicitation or confirm:true).",
3031
3140
  inputSchema: {
3032
3141
  ...coachPrescribeSetArgsSchema.shape,
3033
3142
  confirm: z.boolean().optional()
@@ -3463,7 +3572,7 @@ var JsonFileLibraryCache = class {
3463
3572
  };
3464
3573
  //#endregion
3465
3574
  //#region package.json
3466
- var version = "1.3.0";
3575
+ var version = "1.4.0";
3467
3576
  //#endregion
3468
3577
  //#region src/server.ts
3469
3578
  async function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "1.3.0",
3
+ "version": "1.4.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.3.0",
25
- "@trainheroic-unofficial/js": "1.3.0"
24
+ "@trainheroic-unofficial/core": "1.4.0",
25
+ "@trainheroic-unofficial/js": "1.4.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",