@trainheroic-unofficial/coach-mcp 3.1.0 → 3.1.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 +111 -15
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -279,6 +279,18 @@ const programWorkoutResponseSchema = z.looseObject({
279
279
  });
280
280
  /** The calendar edit-view response we read sessions back from. */
281
281
  const programsEditResponseSchema = z.looseObject({ programWorkouts: z.array(programWorkoutResponseSchema).optional() });
282
+ /** A standalone program create response (container id + usable calendar/program id). */
283
+ const programCreateResponseSchema = z.looseObject({
284
+ id: intLike,
285
+ title: z.string(),
286
+ programId: intLike,
287
+ group_program: intLike,
288
+ type: intLike,
289
+ program: z.looseObject({
290
+ id: intLike,
291
+ program_type: intLike
292
+ }).optional()
293
+ });
282
294
  //#endregion
283
295
  //#region ../dto/src/workout.ts
284
296
  /** A single exercise prescription inside a block. */
@@ -504,15 +516,18 @@ function errorResult(message) {
504
516
  }]
505
517
  };
506
518
  }
519
+ /** Format an already-issued TrainHeroic response as a size-bounded tool result. */
520
+ function apiResponseResult(res, hint) {
521
+ if (!res.ok) {
522
+ const detail = hardCap(typeof res.data === "string" ? res.data : JSON.stringify(res.data) ?? "", resultBudget());
523
+ return errorResult(`TrainHeroic API error (HTTP ${res.status}): ${detail}`);
524
+ }
525
+ return jsonResult(res.data, { hint });
526
+ }
507
527
  /** Issue a TrainHeroic request and format the outcome as a tool result. */
508
528
  async function apiCall(ctx, method, path, options, hint) {
509
529
  return attempt(async () => {
510
- const res = await ctx.client.request(method, path, options);
511
- if (!res.ok) {
512
- const detail = hardCap(typeof res.data === "string" ? res.data : JSON.stringify(res.data) ?? "", resultBudget());
513
- return errorResult(`TrainHeroic API error (HTTP ${res.status}): ${detail}`);
514
- }
515
- return jsonResult(res.data, { hint });
530
+ return apiResponseResult(await ctx.client.request(method, path, options), hint);
516
531
  });
517
532
  }
518
533
  //#endregion
@@ -722,7 +737,7 @@ var TrainHeroicClient = class {
722
737
  session = await this.#ensureSession();
723
738
  res = await this.#send(method, url, session, options.body);
724
739
  }
725
- if (!res.ok) notifyHttpError(this.#onHttpError, method, url, res.status);
740
+ if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
726
741
  const text = await res.text();
727
742
  let data = text;
728
743
  if (text.length > 0) try {
@@ -2234,6 +2249,45 @@ function readExercise(ex) {
2234
2249
  instruction: str(ex.instruction)
2235
2250
  };
2236
2251
  }
2252
+ const PROGRAM_KINDS = ["calendar", "fixed"];
2253
+ /**
2254
+ * Create a standalone ongoing calendar or fixed-length program.
2255
+ *
2256
+ * TrainHeroic returns both a container id and the underlying program id. They are deliberately
2257
+ * named separately here because `/3.0/coach/program/{containerId}` returns 401, while the
2258
+ * `programId` works. This write is not idempotent: callers must not blindly retry an uncertain
2259
+ * result. The live API currently accepts `name` but may generate its own title; `nameApplied`
2260
+ * reports what happened.
2261
+ */
2262
+ async function createProgram(client, args) {
2263
+ if (!PROGRAM_KINDS.includes(args.kind)) throw new Error(`Unknown program kind: ${String(args.kind)}.`);
2264
+ if (typeof args.name !== "string" || args.name.trim() === "") throw new Error("Program name must not be blank.");
2265
+ const requestedName = args.name.trim();
2266
+ const res = await client.request("POST", "/1.0/coach/programs/create", { body: {
2267
+ finite: args.kind === "fixed",
2268
+ name: requestedName
2269
+ } });
2270
+ if (!res.ok) {
2271
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2272
+ throw new Error(`Program create failed (HTTP ${res.status}): ${detail}`);
2273
+ }
2274
+ checkResponse(programCreateResponseSchema, res.data, "program create");
2275
+ const rec = isRecord(res.data) ? res.data : {};
2276
+ const nested = isRecord(rec.program) ? rec.program : {};
2277
+ const containerId = coerceInt(rec.id);
2278
+ const programId = coerceInt(rec.programId) ?? coerceInt(rec.group_program) ?? coerceInt(nested.id);
2279
+ if (containerId === null || programId === null) throw new Error("Program create response is missing the container id or program id.");
2280
+ if (typeof rec.title !== "string" || rec.title.trim() === "") throw new Error("Program create response is missing the assigned title.");
2281
+ const title = rec.title;
2282
+ return {
2283
+ containerId,
2284
+ programId,
2285
+ title,
2286
+ kind: args.kind,
2287
+ requestedName,
2288
+ nameApplied: title === requestedName
2289
+ };
2290
+ }
2237
2291
  /** Normalize one-or-many emails into a deduped, trimmed list. */
2238
2292
  function emailList(emails) {
2239
2293
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -3061,7 +3115,7 @@ const SIMPLE_GETS = [
3061
3115
  {
3062
3116
  name: "list_programs",
3063
3117
  title: "List programs",
3064
- description: "Coach programs (standalone only). This is often empty even for an active coach, because most programming lives as a team's group-program: if it returns [], call list_teams and read each team's group_program — do not conclude the coach has no programs.",
3118
+ description: "Coach programs (standalone only). This is often empty even for an active coach, because most programming lives as a team's group-program: if it returns [], call list_teams and read each team's group_program — do not conclude the coach has no programs. Each standalone row has two ids: id is its container/calendar id; group_program is the underlying program id used by workout writes. get_program accepts either one.",
3065
3119
  path: "/1.0/coach/programs"
3066
3120
  },
3067
3121
  {
@@ -3188,10 +3242,29 @@ function registerEntityReads(server, ctx) {
3188
3242
  }));
3189
3243
  server.registerTool("get_program", {
3190
3244
  title: "Get program detail",
3191
- 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.",
3245
+ description: "Program detail live from the API, by program id. Works for team calendars and athlete coach calendars (type 5 from /v5/calendars/athletes/{id}). For standalone rows from list_programs, accepts either id (the container id) or group_program (the underlying program id); container ids are resolved automatically. If neither detail endpoint is available, returns calendar metadata and next-step guidance instead.",
3192
3246
  inputSchema: { programId: idParam },
3193
3247
  annotations: READ
3194
- }, ({ 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."));
3248
+ }, ({ programId }) => getProgram(ctx, toId(programId)));
3249
+ }
3250
+ async function getProgram(ctx, programId) {
3251
+ return attempt(async () => {
3252
+ const detail = await ctx.client.request("GET", `/3.0/coach/program/${enc(programId)}`, { expectedStatuses: [401, 403] });
3253
+ if (detail.ok || detail.status !== 401 && detail.status !== 403) return apiResponseResult(detail, "This is a large, deep object. If it is truncated, fetch a narrower view (a specific session) instead.");
3254
+ const programs = await ctx.client.request("GET", "/1.0/coach/programs");
3255
+ const program = Array.isArray(programs.data) ? programs.data.find((item) => isRecord(item) && coerceInt(item.id) === programId) : void 0;
3256
+ if (!programs.ok || !program) return apiResponseResult(detail);
3257
+ const actualProgramId = coerceInt(program.group_program);
3258
+ if (actualProgramId !== null && actualProgramId !== programId) {
3259
+ const actualDetail = await ctx.client.request("GET", `/3.0/coach/program/${enc(actualProgramId)}`, { expectedStatuses: [401, 403] });
3260
+ if (actualDetail.ok || actualDetail.status !== 401 && actualDetail.status !== 403) return apiResponseResult(actualDetail, "This is a large, deep object. If it is truncated, fetch a narrower view (a specific session) instead.");
3261
+ }
3262
+ return jsonResult({
3263
+ program,
3264
+ detailAvailable: false,
3265
+ note: "TrainHeroic recognizes this as a valid standalone calendar, but its nested program-detail endpoint does not expose this calendar type. Use calendar/session reads instead; on the hosted server, programming_sync then programming_stored can read its dated sessions."
3266
+ });
3267
+ });
3195
3268
  }
3196
3269
  /** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
3197
3270
  /** The windowed team-volume read — its own function so registerEntityReads stays under the cap. */
@@ -3462,7 +3535,7 @@ function registerAthletePrescribeTool(server, ctx) {
3462
3535
  }
3463
3536
  //#endregion
3464
3537
  //#region ../core/src/tools/teams.ts
3465
- const ADDITIVE = {
3538
+ const ADDITIVE$1 = {
3466
3539
  readOnlyHint: false,
3467
3540
  destructiveHint: false,
3468
3541
  openWorldHint: true
@@ -3476,7 +3549,7 @@ function registerTeamTools(server, ctx) {
3476
3549
  title: "Create a team",
3477
3550
  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.",
3478
3551
  inputSchema: { title: z.string().min(1) },
3479
- annotations: ADDITIVE
3552
+ annotations: ADDITIVE$1
3480
3553
  }, ({ title }) => apiCall(ctx, "POST", "/1.0/coach/team/createWithTitleAndCode", { body: { title } }));
3481
3554
  server.registerTool("team_update", {
3482
3555
  title: "Update a team",
@@ -3486,7 +3559,7 @@ function registerTeamTools(server, ctx) {
3486
3559
  title: z.string().min(1).optional(),
3487
3560
  groupProgram: idParam.optional()
3488
3561
  },
3489
- annotations: ADDITIVE
3562
+ annotations: ADDITIVE$1
3490
3563
  }, ({ teamId, title, groupProgram }) => attempt(async () => {
3491
3564
  const args = { teamId: toId(teamId) };
3492
3565
  if (title !== void 0) args.title = title;
@@ -3514,7 +3587,7 @@ function registerTeamTools(server, ctx) {
3514
3587
  teamId: idParam,
3515
3588
  type: z.number().int().optional()
3516
3589
  },
3517
- annotations: ADDITIVE
3590
+ annotations: ADDITIVE$1
3518
3591
  }, ({ teamId, type }) => apiCall(ctx, "POST", `/v5/teams/${toId(teamId)}/teamCodes`, { body: { type: type ?? 2 } }));
3519
3592
  server.registerTool("team_code_delete", {
3520
3593
  title: "Delete a team join code",
@@ -3532,6 +3605,28 @@ function registerTeamTools(server, ctx) {
3532
3605
  }));
3533
3606
  }
3534
3607
  //#endregion
3608
+ //#region ../core/src/tools/programs.ts
3609
+ const ADDITIVE = {
3610
+ readOnlyHint: false,
3611
+ destructiveHint: false,
3612
+ openWorldHint: true
3613
+ };
3614
+ /** Standalone program writes. Program reads live in reads.ts. */
3615
+ function registerProgramTools(server, ctx) {
3616
+ server.registerTool("program_create", {
3617
+ title: "Create a standalone program",
3618
+ description: "Create either an ongoing calendar or a fixed-length standalone program (POST /1.0/coach/programs/create). Returns both containerId (the id shown by list_programs and used by calendar edit/sync reads) and programId (the id used by get_program and workout writes). TrainHeroic may generate a different title; inspect title and nameApplied. This write is not idempotent, so do not retry an uncertain result.",
3619
+ inputSchema: {
3620
+ kind: z.enum(PROGRAM_KINDS),
3621
+ name: z.string().trim().min(1)
3622
+ },
3623
+ annotations: ADDITIVE
3624
+ }, ({ kind, name }) => attempt(async () => jsonResult(await createProgram(ctx.client, {
3625
+ kind,
3626
+ name
3627
+ }))));
3628
+ }
3629
+ //#endregion
3535
3630
  //#region ../core/src/tools/analytics.ts
3536
3631
  const ANALYTICS_QUERY_DESC = "Read a TrainHeroic analytics report. The `metric` enum below IS the catalog — pick from it directly (analytics_categories lists the API's raw category names, which do NOT match these keys; you rarely need it). Team metrics (readiness-team, compliance-team, lift-progress-team) need teamId; athlete metrics (readiness-athlete, training-summary-athlete, lift-1rm-history, working-max-history) need userIds — get those from list_athletes. userIds takes MANY athletes in ONE call (pass the whole roster's ids at once); the report comes back with a row per athlete, so do not loop one id per call. For team-wide training volume there is no team summary metric: pass every athlete's userId to training-summary-athlete in a single call and the rows cover the team. An athlete with no logged sessions in range simply returns no rows (not an error). Use that for triage: training-summary-athlete with a single athleteId is the fastest 'has this athlete trained at all, and when' check — no rows means no logged training in range, so don't then fan out blind per-lift athlete_lift_history calls. Despite 'athlete' in the name this metric accepts 1–N userIds. readiness-team takes a single `date`; every other metric takes dateStart/dateEnd. lift-1rm-history, lift-progress-team, and working-max-history also need exerciseId. All dates are YYYY-MM-DD.";
3537
3632
  /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
@@ -3887,6 +3982,7 @@ function registerCoachTools(server, ctx) {
3887
3982
  registerMainLiftTools(server, ctx);
3888
3983
  registerAthleteTools(server, ctx);
3889
3984
  registerTeamTools(server, ctx);
3985
+ registerProgramTools(server, ctx);
3890
3986
  registerAnalyticsTools(server, ctx);
3891
3987
  registerExerciseTools(server, ctx);
3892
3988
  registerWorkoutTools(server, ctx);
@@ -3918,7 +4014,7 @@ var JsonFileLibraryCache = class {
3918
4014
  };
3919
4015
  //#endregion
3920
4016
  //#region package.json
3921
- var version = "3.1.0";
4017
+ var version = "3.1.1";
3922
4018
  //#endregion
3923
4019
  //#region src/server.ts
3924
4020
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "3.1.0",
3
+ "version": "3.1.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": "3.1.0",
25
- "@trainheroic-unofficial/js": "3.1.0"
24
+ "@trainheroic-unofficial/core": "3.1.1",
25
+ "@trainheroic-unofficial/js": "3.1.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.2.0",