@trainheroic-unofficial/coach-mcp 2.0.2 → 2.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 +128 -35
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -925,7 +925,7 @@ async function getJson(client, path, label) {
925
925
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
926
926
  return res.data;
927
927
  }
928
- async function getArray(client, path, label) {
928
+ async function getArray$1(client, path, label) {
929
929
  const res = await client.request("GET", path);
930
930
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
931
931
  return res.data;
@@ -995,25 +995,7 @@ function fetchExerciseHistoryDetail(client, exerciseId, userId) {
995
995
  }
996
996
  /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
997
997
  function fetchAthleteWorkouts(client, startDate, endDate) {
998
- return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
999
- }
1000
- /**
1001
- * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
1002
- * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
1003
- * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
1004
- * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
1005
- */
1006
- function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
1007
- return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
1008
- }
1009
- /**
1010
- * A coach's month view of a roster athlete's logged sessions
1011
- * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
1012
- * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
1013
- * `userId` in each row is the roster athlete, not the calling coach.
1014
- */
1015
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
1016
- return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
998
+ return getArray$1(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
1017
999
  }
1018
1000
  function nonEmpty(value) {
1019
1001
  return value !== void 0 && value !== null && String(value).trim() !== "";
@@ -1371,6 +1353,70 @@ function presentExerciseHistory(detail) {
1371
1353
  };
1372
1354
  }
1373
1355
  //#endregion
1356
+ //#region ../js/src/coach-athlete-calendar.ts
1357
+ async function getArray(client, path, label) {
1358
+ const res = await client.request("GET", path);
1359
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
1360
+ return res.data;
1361
+ }
1362
+ /**
1363
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
1364
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
1365
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
1366
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
1367
+ */
1368
+ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
1369
+ return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
1370
+ }
1371
+ /**
1372
+ * A coach's month view of a roster athlete's logged sessions
1373
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
1374
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
1375
+ * `userId` in each row is the roster athlete, not the calling coach.
1376
+ */
1377
+ function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
1378
+ return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
1379
+ }
1380
+ /**
1381
+ * Resolve a roster athlete's coach-writable calendar program id
1382
+ * (`GET /v5/calendars/athletes/{athleteId}?year=&month=`).
1383
+ *
1384
+ * Year and month are required by the API (HTTP 400 without them); the returned `programId` is
1385
+ * stable for the athlete, so any month works. This is the calendar the coach web app writes
1386
+ * with `createWorkoutForDay` when you open an athlete from My Athletes → calendar — distinct
1387
+ * from athlete-created `personal_cal` ad-hoc sessions.
1388
+ */
1389
+ async function fetchCoachAthleteCalendar(client, athleteId, year, month) {
1390
+ const path = `/v5/calendars/athletes/${athleteId}?year=${year}&month=${month}`;
1391
+ const res = await client.request("GET", path);
1392
+ if (!res.ok) {
1393
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
1394
+ throw new Error(`GET ${path} failed (HTTP ${res.status}): ${detail}`);
1395
+ }
1396
+ if (!isRecord(res.data)) throw new Error("Unexpected athlete calendar response.");
1397
+ const programId = coerceInt(res.data.id);
1398
+ if (programId === null || programId <= 0) throw new Error(`Athlete calendar for ${athleteId} did not include a program id.`);
1399
+ return {
1400
+ programId,
1401
+ title: str$1(res.data.title) ?? "",
1402
+ type: coerceInt(res.data.type),
1403
+ groupId: coerceInt(res.data.group_id)
1404
+ };
1405
+ }
1406
+ /**
1407
+ * Resolve the calendar program id for `workout_build` / `coach workout build`: either an
1408
+ * explicit team/group `programId`, or a roster `athleteId` (+ date) via
1409
+ * `fetchCoachAthleteCalendar`. Exactly one of programId / athleteId is required.
1410
+ */
1411
+ async function resolveBuildProgramId(client, args) {
1412
+ if (args.programId !== void 0 && args.athleteId !== void 0) throw new Error("Pass programId or athleteId, not both.");
1413
+ if (args.programId !== void 0) return args.programId;
1414
+ if (args.athleteId === void 0) throw new Error("Provide programId (team calendar) or athleteId (athlete calendar).");
1415
+ if (args.date === void 0) throw new Error("athleteId requires date (YYYY-M-D) to resolve the athlete calendar.");
1416
+ const [y, m] = parseWorkoutDate(args.date);
1417
+ return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
1418
+ }
1419
+ //#endregion
1374
1420
  //#region ../js/src/exercise-set-payload.ts
1375
1421
  function slotData(exercise, key) {
1376
1422
  const value = exercise?.[key];
@@ -2083,7 +2129,7 @@ async function collectAdvisories(blocks, index) {
2083
2129
  function calendarWriteError(method, path, status, detail) {
2084
2130
  const base = `${method} ${path} failed (HTTP ${status}): ${detail}`;
2085
2131
  if (!(path.includes("/createWorkoutForDay/") || path.includes("/createWorkoutForTimelineDay/") || path.includes("/copyProgramWorkout")) || status !== 500 && status !== 401) return new Error(base);
2086
- return /* @__PURE__ */ new Error(`${base}. This often means the program is another athlete's Coach Plan / personal calendar (personal_cal), which the coach calendar write endpoints do not support — workout_build and session_copy work on team/group programs (and the coach's own personal calendar), but there is currently no coach-facing tool to create sessions on another athlete's personal calendar.`);
2132
+ return /* @__PURE__ */ new Error(`${base}. This often means the programId is not a coach-writable calendar — use a team/group programId (list_teams → group_program) or resolve a roster athlete's calendar via GET /v5/calendars/athletes/{athleteId}?year=&month= (workout_build athleteId). Athlete-created personal_cal ad-hoc sessions are a different surface.`);
2087
2133
  }
2088
2134
  async function req(client, method, path, body) {
2089
2135
  const res = await client.request(method, path, body === void 0 ? void 0 : { body });
@@ -2270,6 +2316,36 @@ async function inviteAthletes(client, args) {
2270
2316
  };
2271
2317
  }
2272
2318
  /**
2319
+ * Update a team's title and/or reassign its calendar (`PUT /v5/teams/{teamId}`).
2320
+ *
2321
+ * The live API accepts `group_program` to point the team at an existing parent program /
2322
+ * calendar (e.g. another team's `group_program` from `list_teams`), but rejects a body that
2323
+ * has only `group_program` (HTTP 400 "Invalid parameters"). When `title` is omitted we read
2324
+ * the current title first so callers can re-link without renaming.
2325
+ */
2326
+ async function updateTeam(client, args) {
2327
+ if (args.title === void 0 && args.groupProgram === void 0) throw new Error("Provide title and/or groupProgram.");
2328
+ let title = args.title;
2329
+ if (title === void 0) {
2330
+ const existing = await client.request("GET", `/v5/teams/${args.teamId}`);
2331
+ if (!existing.ok) {
2332
+ const detail = typeof existing.data === "string" ? existing.data : JSON.stringify(existing.data);
2333
+ throw new Error(`GET /v5/teams/${args.teamId} failed (HTTP ${existing.status}): ${detail}`);
2334
+ }
2335
+ const rec = existing.data && typeof existing.data === "object" ? existing.data : null;
2336
+ title = typeof rec?.title === "string" ? rec.title : "";
2337
+ if (title.trim() === "") throw new Error(`Could not read current title for team ${args.teamId}; pass title explicitly.`);
2338
+ }
2339
+ const body = { title };
2340
+ if (args.groupProgram !== void 0) body.group_program = args.groupProgram;
2341
+ const res = await client.request("PUT", `/v5/teams/${args.teamId}`, { body });
2342
+ if (!res.ok) {
2343
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2344
+ throw new Error(`PUT /v5/teams/${args.teamId} failed (HTTP ${res.status}): ${detail}`);
2345
+ }
2346
+ return res.data;
2347
+ }
2348
+ /**
2273
2349
  * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2274
2350
  * The API wants the target date as a structured object (with weekday and an isToday flag),
2275
2351
  * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
@@ -3128,7 +3204,7 @@ function registerEntityReads(server, ctx) {
3128
3204
  }));
3129
3205
  server.registerTool("get_program", {
3130
3206
  title: "Get program detail",
3131
- description: "Full nested program structure (blocks + sessions) live from the API, by program id. Team/group programs only — Coach Plan / personal_cal program ids typically return HTTP 401 Cannot access program.",
3207
+ description: "Full nested program structure (blocks + sessions) live from the API, by program id. Works for team calendars and athlete coach calendars (type 5 from /v5/calendars/athletes/{id}). Some unrelated ids return HTTP 401 Cannot access program.",
3132
3208
  inputSchema: { programId: idParam },
3133
3209
  annotations: READ
3134
3210
  }, ({ 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."));
@@ -3414,19 +3490,25 @@ const ADDITIVE = {
3414
3490
  function registerTeamTools(server, ctx) {
3415
3491
  server.registerTool("team_create", {
3416
3492
  title: "Create a team",
3417
- description: "Create a team (POST /1.0/coach/team/createWithTitleAndCode). Also creates the team's calendar/program. Returns the new team including its calendar id. Use the team id with athlete_invite.",
3493
+ description: "Create a team (POST /1.0/coach/team/createWithTitleAndCode). Also creates the team's calendar/program. Returns the new team including its calendar id. Use the team id with athlete_invite. To point a new team at an existing calendar instead of its auto-created one, follow up with team_update groupProgram.",
3418
3494
  inputSchema: { title: z.string().min(1) },
3419
3495
  annotations: ADDITIVE
3420
3496
  }, ({ title }) => apiCall(ctx, "POST", "/1.0/coach/team/createWithTitleAndCode", { body: { title } }));
3421
3497
  server.registerTool("team_update", {
3422
- title: "Rename a team",
3423
- description: "Update a team's settings, e.g. its title (PUT /v5/teams/{teamId}).",
3498
+ title: "Update a team",
3499
+ description: "Update a team's title and/or reassign its calendar (PUT /v5/teams/{teamId}). Pass groupProgram (a program/calendar id — typically another team's group_program from list_teams, or get_team) to point this team at an existing parent program. At least one of title or groupProgram is required; when only groupProgram is set the current title is preserved.",
3424
3500
  inputSchema: {
3425
3501
  teamId: idParam,
3426
- title: z.string().min(1)
3502
+ title: z.string().min(1).optional(),
3503
+ groupProgram: idParam.optional()
3427
3504
  },
3428
3505
  annotations: ADDITIVE
3429
- }, ({ teamId, title }) => apiCall(ctx, "PUT", `/v5/teams/${toId(teamId)}`, { body: { title } }));
3506
+ }, ({ teamId, title, groupProgram }) => attempt(async () => {
3507
+ const args = { teamId: toId(teamId) };
3508
+ if (title !== void 0) args.title = title;
3509
+ if (groupProgram !== void 0) args.groupProgram = toId(groupProgram);
3510
+ return jsonResult(await updateTeam(ctx.client, args));
3511
+ }));
3430
3512
  server.registerTool("team_delete", {
3431
3513
  title: "Delete a team",
3432
3514
  description: "Delete a team (DELETE /v5/teams/{teamId}). Removes the team and its calendar from the live account; hard to undo. Requires confirmation (elicitation, or confirm:true).",
@@ -3570,13 +3652,14 @@ function registerExerciseTools(server, ctx) {
3570
3652
  }
3571
3653
  //#endregion
3572
3654
  //#region ../core/src/tools/workout.ts
3573
- /** Build a draft, read it back, and publish it. */
3655
+ /** Build a draft session (workout_build). */
3574
3656
  function registerBuild(server, ctx) {
3575
3657
  server.registerTool("workout_build", {
3576
3658
  title: "Build a workout session (draft)",
3577
- description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Works on team/group program calendars (and the authenticated coach's own personal calendar). Writing to another athlete's Coach Plan / personal_cal calendar is not supported (createWorkoutForDay returns HTTP 500). Two exercises in one block become a superset. A block with empty exercises and a non-empty block instruction is a text-only Circuit / Conditioning block (type 1). Add a block 'leaderboard' for a Red-Zone score, or a top-level 'instruction' for the session note (Coach Instructions). Returns the draft ids, a read-back, and unit advisories. Review, then workout_publish.",
3659
+ description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Pass programId for a team/group calendar (list_teams → group_program), or athleteId to write on that roster athlete's coach calendar (resolved via /v5/calendars/athletes/{id} — the same calendar the coach web app opens from My Athletes). athleteId requires date. Two exercises in one block become a superset. A block with empty exercises and a non-empty block instruction is a text-only Circuit / Conditioning block (type 1). Add a block 'leaderboard' for a Red-Zone score, or a top-level 'instruction' for the session note (Coach Instructions). Returns the draft ids, a read-back, and unit advisories. Review, then workout_publish.",
3578
3660
  inputSchema: {
3579
- programId: z.number(),
3661
+ programId: z.number().optional(),
3662
+ athleteId: idParam.optional(),
3580
3663
  date: z.string().optional(),
3581
3664
  timelineDay: z.number().optional(),
3582
3665
  blocks: z.array(blockSpecSchema),
@@ -3587,11 +3670,16 @@ function registerBuild(server, ctx) {
3587
3670
  destructiveHint: false,
3588
3671
  openWorldHint: true
3589
3672
  }
3590
- }, ({ programId, date, timelineDay, blocks, instruction }) => attempt(async () => {
3673
+ }, ({ programId, athleteId, date, timelineDay, blocks, instruction }) => attempt(async () => {
3591
3674
  if (date === void 0 && timelineDay === void 0) return errorResult("Provide either date (YYYY-M-D) or timelineDay.");
3675
+ const resolveArgs = {};
3676
+ if (programId !== void 0) resolveArgs.programId = programId;
3677
+ if (athleteId !== void 0) resolveArgs.athleteId = toId(athleteId);
3678
+ if (date !== void 0) resolveArgs.date = date;
3679
+ const resolved = await resolveBuildProgramId(ctx.client, resolveArgs);
3592
3680
  const typed = blocks;
3593
3681
  const opts = {
3594
- programId,
3682
+ programId: resolved,
3595
3683
  blocks: typed,
3596
3684
  publish: false
3597
3685
  };
@@ -3600,15 +3688,19 @@ function registerBuild(server, ctx) {
3600
3688
  if (instruction !== void 0) opts.instruction = instruction;
3601
3689
  const advisories = await collectAdvisories(typed, ctx.index);
3602
3690
  const built = await buildSession(ctx.client, opts);
3603
- const readback = opts.date ? await readSession(ctx.client, programId, opts.date, built.pwId) : null;
3691
+ const readback = opts.date ? await readSession(ctx.client, resolved, opts.date, built.pwId) : null;
3604
3692
  return jsonResult({
3605
3693
  ...built,
3694
+ programId: resolved,
3606
3695
  published: false,
3607
3696
  advisories,
3608
3697
  readback,
3609
3698
  note: "Draft created (unpublished). Review, then call workout_publish to make it athlete-facing."
3610
3699
  });
3611
3700
  }));
3701
+ }
3702
+ /** Read-back and publish for a built session. */
3703
+ function registerReadPublish(server, ctx) {
3612
3704
  server.registerTool("workout_read", {
3613
3705
  title: "Read a built session",
3614
3706
  description: "Read-back a session by programId, date (YYYY-M-D), and programWorkout id.",
@@ -3687,7 +3779,7 @@ function registerLifecycle(server, ctx) {
3687
3779
  }));
3688
3780
  server.registerTool("session_copy", {
3689
3781
  title: "Copy a session to a date",
3690
- description: "Copy/repeat a session to a target date on a program (POST .../copyProgramWorkout). toDate is YYYY-M-D. Creates a new session; review and publish it separately. Team/group (and own personal) calendars only — copying onto another athlete's personal_cal / Coach Plan toProgramId fails with HTTP 500.",
3782
+ description: "Copy/repeat a session to a target date on a program (POST .../copyProgramWorkout). toDate is YYYY-M-D. Creates a new session; review and publish it separately. toProgramId may be a team group_program or an athlete calendar program id (from /v5/calendars/athletes/{athleteId}?year=&month= / workout_build athleteId).",
3691
3783
  inputSchema: {
3692
3784
  toProgramId: z.number(),
3693
3785
  pwId: z.number(),
@@ -3717,6 +3809,7 @@ function registerLifecycle(server, ctx) {
3717
3809
  /** Workout building, read-back, publishing, and the session calendar lifecycle. */
3718
3810
  function registerWorkoutTools(server, ctx) {
3719
3811
  registerBuild(server, ctx);
3812
+ registerReadPublish(server, ctx);
3720
3813
  registerLifecycle(server, ctx);
3721
3814
  }
3722
3815
  //#endregion
@@ -3840,7 +3933,7 @@ var JsonFileLibraryCache = class {
3840
3933
  };
3841
3934
  //#endregion
3842
3935
  //#region package.json
3843
- var version = "2.0.2";
3936
+ var version = "2.1.0";
3844
3937
  //#endregion
3845
3938
  //#region src/server.ts
3846
3939
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "2.0.2",
3
+ "version": "2.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/core": "2.0.2",
25
- "@trainheroic-unofficial/js": "2.0.2"
24
+ "@trainheroic-unofficial/core": "2.1.0",
25
+ "@trainheroic-unofficial/js": "2.1.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.1.2",