@trainheroic-unofficial/core 3.0.1 → 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.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CallToolResult, InputRequiredResult, McpServer, ServerContext } from "@modelcontextprotocol/server";
2
- import { ExerciseIndex, RequestOptions, SessionExercise, TrainHeroicClient } from "@trainheroic-unofficial/js";
2
+ import { ClientResult, ExerciseIndex, RequestOptions, SessionExercise, TrainHeroicClient } from "@trainheroic-unofficial/js";
3
3
  //#region src/context.d.ts
4
4
  /** What a tool handler may return: a finished result or an MRTR input round. */
5
5
  type ToolHandlerResult = CallToolResult | InputRequiredResult;
@@ -66,6 +66,8 @@ type BudgetHint = {
66
66
  declare function jsonResult(data: unknown, opts?: BudgetHint): CallToolResult;
67
67
  /** A tool-level error: returned in-band (isError) so the model can self-correct. */
68
68
  declare function errorResult(message: string): CallToolResult;
69
+ /** Format an already-issued TrainHeroic response as a size-bounded tool result. */
70
+ declare function apiResponseResult(res: ClientResult, hint?: string): CallToolResult;
69
71
  /** Issue a TrainHeroic request and format the outcome as a tool result. */
70
72
  declare function apiCall(ctx: ToolContext, method: string, path: string, options?: RequestOptions, hint?: string): Promise<CallToolResult>;
71
73
  //#endregion
@@ -157,6 +159,10 @@ declare function registerAthleteTools(server: McpServer, ctx: ToolContext): void
157
159
  */
158
160
  declare function registerTeamTools(server: McpServer, ctx: ToolContext): void;
159
161
  //#endregion
162
+ //#region src/tools/programs.d.ts
163
+ /** Standalone program writes. Program reads live in reads.ts. */
164
+ declare function registerProgramTools(server: McpServer, ctx: ToolContext): void;
165
+ //#endregion
160
166
  //#region src/tools/analytics.d.ts
161
167
  /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
162
168
  declare function registerAnalyticsTools(server: McpServer, ctx: ToolContext): void;
@@ -181,4 +187,4 @@ declare function registerMessagingTools(server: McpServer, ctx: ToolContext): vo
181
187
  /** Register the full coach tool surface (roster, teams, programs, exercises, messaging). */
182
188
  declare function registerCoachTools(server: McpServer, ctx: ToolContext): void;
183
189
  //#endregion
184
- export { AthleteContext, BudgetHint, DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, ToolContext, ToolHandlerResult, apiCall, attempt, boundedSerialize, clipArray, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerCoachTools, registerExerciseTools, registerMainLiftTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
190
+ export { AthleteContext, BudgetHint, DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, ToolContext, ToolHandlerResult, apiCall, apiResponseResult, attempt, boundedSerialize, clipArray, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerCoachTools, registerExerciseTools, registerMainLiftTools, registerMessagingTools, registerProgramTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { athleteSessionRemoveArgsSchema, blockSpecSchema, coachLogSessionArgsSchema, coachLogSetArgsSchema, coachPrescribeSetArgsSchema, commentDraftSchema, dateString, exerciseCreateSchema, idArgSchema, logSessionArgsSchema, logSetArgsSchema, parseWorkoutDate, swapAthleteExerciseArgsSchema } from "@trainheroic-unofficial/dto";
1
+ import { athletePrescribeSetArgsSchema, athleteSessionRemoveArgsSchema, blockSpecSchema, coachLogSessionArgsSchema, coachLogSetArgsSchema, coachPrescribeSetArgsSchema, commentDraftSchema, dateString, exerciseCreateSchema, idArgSchema, logSessionArgsSchema, logSetArgsSchema, parseWorkoutDate, swapAthleteExerciseArgsSchema } from "@trainheroic-unofficial/dto";
2
2
  import { acceptedContent, inputRequired, inputResponse } from "@modelcontextprotocol/server";
3
3
  import { z } from "zod";
4
- import { ANALYTICS_METRIC_KEYS, addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, prescribeForAthlete, presentAthleteWorkouts, presentCoachAthleteTraining, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, readLive, readSession, removePersonalWorkout, removeSession, resolveBuildProgramId, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, updateTeam } from "@trainheroic-unofficial/js";
4
+ import { ANALYTICS_METRIC_KEYS, PROGRAM_KINDS, addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, collectAdvisories, copySession, createPersonalWorkout, createProgram, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkouts, presentCoachAthleteTraining, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, readLive, readSession, removePersonalWorkout, removeSession, resolveBuildProgramId, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, updateTeam } from "@trainheroic-unofficial/js";
5
5
  //#region src/context.ts
6
6
  /** A tool argument that accepts a numeric id as a number or a string of digits. */
7
7
  const idParam = idArgSchema;
@@ -160,15 +160,18 @@ function errorResult(message) {
160
160
  }]
161
161
  };
162
162
  }
163
+ /** Format an already-issued TrainHeroic response as a size-bounded tool result. */
164
+ function apiResponseResult(res, hint) {
165
+ if (!res.ok) {
166
+ const detail = hardCap(typeof res.data === "string" ? res.data : JSON.stringify(res.data) ?? "", resultBudget());
167
+ return errorResult(`TrainHeroic API error (HTTP ${res.status}): ${detail}`);
168
+ }
169
+ return jsonResult(res.data, { hint });
170
+ }
163
171
  /** Issue a TrainHeroic request and format the outcome as a tool result. */
164
172
  async function apiCall(ctx, method, path, options, hint) {
165
173
  return attempt(async () => {
166
- const res = await ctx.client.request(method, path, options);
167
- if (!res.ok) {
168
- const detail = hardCap(typeof res.data === "string" ? res.data : JSON.stringify(res.data) ?? "", resultBudget());
169
- return errorResult(`TrainHeroic API error (HTTP ${res.status}): ${detail}`);
170
- }
171
- return jsonResult(res.data, { hint });
174
+ return apiResponseResult(await ctx.client.request(method, path, options), hint);
172
175
  });
173
176
  }
174
177
  //#endregion
@@ -275,7 +278,7 @@ const SIMPLE_GETS = [
275
278
  {
276
279
  name: "list_programs",
277
280
  title: "List programs",
278
- 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.",
281
+ 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.",
279
282
  path: "/1.0/coach/programs"
280
283
  },
281
284
  {
@@ -403,10 +406,29 @@ function registerEntityReads(server, ctx) {
403
406
  }));
404
407
  server.registerTool("get_program", {
405
408
  title: "Get program detail",
406
- 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.",
409
+ 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.",
407
410
  inputSchema: { programId: idParam },
408
411
  annotations: READ
409
- }, ({ 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."));
412
+ }, ({ programId }) => getProgram(ctx, toId(programId)));
413
+ }
414
+ async function getProgram(ctx, programId) {
415
+ return attempt(async () => {
416
+ const detail = await ctx.client.request("GET", `/3.0/coach/program/${enc(programId)}`, { expectedStatuses: [401, 403] });
417
+ 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.");
418
+ const programs = await ctx.client.request("GET", "/1.0/coach/programs");
419
+ const program = Array.isArray(programs.data) ? programs.data.find((item) => isRecord(item) && coerceInt(item.id) === programId) : void 0;
420
+ if (!programs.ok || !program) return apiResponseResult(detail);
421
+ const actualProgramId = coerceInt(program.group_program);
422
+ if (actualProgramId !== null && actualProgramId !== programId) {
423
+ const actualDetail = await ctx.client.request("GET", `/3.0/coach/program/${enc(actualProgramId)}`, { expectedStatuses: [401, 403] });
424
+ 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.");
425
+ }
426
+ return jsonResult({
427
+ program,
428
+ detailAvailable: false,
429
+ 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."
430
+ });
431
+ });
410
432
  }
411
433
  /** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
412
434
  /** The windowed team-volume read — its own function so registerEntityReads stays under the cap. */
@@ -746,6 +768,24 @@ function registerLogTool(server, ctx) {
746
768
  results: toSetResults(results)
747
769
  }));
748
770
  }));
771
+ server.registerTool("athlete_prescribe_set", {
772
+ title: "Set your prescribed reps/weight without logging",
773
+ description: "Athlete-facing write: set the planned reps and/or weight for one of your scheduled workout sets WITHOUT recording it as performed. Use this when you know the target load before training but have not completed the set yet. The set stays open and nothing is added to exercise history. param1 is reps and param2 is weight; pass one sets[] entry per planned set. This write REPLACES the selected exercise's whole prescription, so include every planned set and every value you want to keep; an omitted param is cleared. Get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_log_targets. To record actual completed results, use athlete_log_set instead. Requires confirmation (elicitation or confirm:true).",
774
+ inputSchema: {
775
+ ...athletePrescribeSetArgsSchema.shape,
776
+ confirm: z.boolean().optional()
777
+ },
778
+ annotations: DESTRUCTIVE
779
+ }, ({ date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
780
+ const id = toId(savedWorkoutSetId);
781
+ const blocked = confirmGate(extra, `Set prescribed values on your saved workout set ${id} on ${date}? This changes your planned reps/weight but does not log the set as completed.`, confirm);
782
+ if (blocked) return blocked;
783
+ return jsonResult(await prescribeAthleteSet(ctx.client, {
784
+ date,
785
+ savedWorkoutSetId: id,
786
+ results: toSetResults(results)
787
+ }));
788
+ }));
749
789
  }
750
790
  /**
751
791
  * The athlete's own per-exercise swap, in its own function so registerLogTool/registerSessionTools
@@ -993,7 +1033,7 @@ function registerAthletePrescribeTool(server, ctx) {
993
1033
  }
994
1034
  //#endregion
995
1035
  //#region src/tools/teams.ts
996
- const ADDITIVE = {
1036
+ const ADDITIVE$1 = {
997
1037
  readOnlyHint: false,
998
1038
  destructiveHint: false,
999
1039
  openWorldHint: true
@@ -1007,7 +1047,7 @@ function registerTeamTools(server, ctx) {
1007
1047
  title: "Create a team",
1008
1048
  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.",
1009
1049
  inputSchema: { title: z.string().min(1) },
1010
- annotations: ADDITIVE
1050
+ annotations: ADDITIVE$1
1011
1051
  }, ({ title }) => apiCall(ctx, "POST", "/1.0/coach/team/createWithTitleAndCode", { body: { title } }));
1012
1052
  server.registerTool("team_update", {
1013
1053
  title: "Update a team",
@@ -1017,7 +1057,7 @@ function registerTeamTools(server, ctx) {
1017
1057
  title: z.string().min(1).optional(),
1018
1058
  groupProgram: idParam.optional()
1019
1059
  },
1020
- annotations: ADDITIVE
1060
+ annotations: ADDITIVE$1
1021
1061
  }, ({ teamId, title, groupProgram }) => attempt(async () => {
1022
1062
  const args = { teamId: toId(teamId) };
1023
1063
  if (title !== void 0) args.title = title;
@@ -1045,7 +1085,7 @@ function registerTeamTools(server, ctx) {
1045
1085
  teamId: idParam,
1046
1086
  type: z.number().int().optional()
1047
1087
  },
1048
- annotations: ADDITIVE
1088
+ annotations: ADDITIVE$1
1049
1089
  }, ({ teamId, type }) => apiCall(ctx, "POST", `/v5/teams/${toId(teamId)}/teamCodes`, { body: { type: type ?? 2 } }));
1050
1090
  server.registerTool("team_code_delete", {
1051
1091
  title: "Delete a team join code",
@@ -1063,6 +1103,28 @@ function registerTeamTools(server, ctx) {
1063
1103
  }));
1064
1104
  }
1065
1105
  //#endregion
1106
+ //#region src/tools/programs.ts
1107
+ const ADDITIVE = {
1108
+ readOnlyHint: false,
1109
+ destructiveHint: false,
1110
+ openWorldHint: true
1111
+ };
1112
+ /** Standalone program writes. Program reads live in reads.ts. */
1113
+ function registerProgramTools(server, ctx) {
1114
+ server.registerTool("program_create", {
1115
+ title: "Create a standalone program",
1116
+ 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.",
1117
+ inputSchema: {
1118
+ kind: z.enum(PROGRAM_KINDS),
1119
+ name: z.string().trim().min(1)
1120
+ },
1121
+ annotations: ADDITIVE
1122
+ }, ({ kind, name }) => attempt(async () => jsonResult(await createProgram(ctx.client, {
1123
+ kind,
1124
+ name
1125
+ }))));
1126
+ }
1127
+ //#endregion
1066
1128
  //#region src/tools/analytics.ts
1067
1129
  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.";
1068
1130
  /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
@@ -1418,10 +1480,11 @@ function registerCoachTools(server, ctx) {
1418
1480
  registerMainLiftTools(server, ctx);
1419
1481
  registerAthleteTools(server, ctx);
1420
1482
  registerTeamTools(server, ctx);
1483
+ registerProgramTools(server, ctx);
1421
1484
  registerAnalyticsTools(server, ctx);
1422
1485
  registerExerciseTools(server, ctx);
1423
1486
  registerWorkoutTools(server, ctx);
1424
1487
  registerMessagingTools(server, ctx);
1425
1488
  }
1426
1489
  //#endregion
1427
- export { DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, apiCall, attempt, boundedSerialize, clipArray, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerCoachTools, registerExerciseTools, registerMainLiftTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
1490
+ export { DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, apiCall, apiResponseResult, attempt, boundedSerialize, clipArray, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerCoachTools, registerExerciseTools, registerMainLiftTools, registerMessagingTools, registerProgramTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/core",
3
- "version": "3.0.1",
3
+ "version": "3.1.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,8 +25,8 @@
25
25
  "@cfworker/json-schema": "^4.1.1",
26
26
  "@modelcontextprotocol/server": "2.0.0",
27
27
  "zod": "^4.4.3",
28
- "@trainheroic-unofficial/dto": "3.0.1",
29
- "@trainheroic-unofficial/js": "3.0.1"
28
+ "@trainheroic-unofficial/dto": "3.1.1",
29
+ "@trainheroic-unofficial/js": "3.1.1"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "^26.2.0",