@trainheroic-unofficial/core 4.2.0 → 4.3.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.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { CallToolResult, InputRequiredResult, McpServer, ServerContext } from "@modelcontextprotocol/server";
2
2
  import { ClientResult, ExerciseIndex, RequestOptions, SessionExercise, TrainHeroicClient } from "@trainheroic-unofficial/js";
3
- //#region src/context.d.ts
4
3
  /** What a tool handler may return: a finished result or an MRTR input round. */
5
4
  export type ToolHandlerResult = CallToolResult | InputRequiredResult;
6
5
  /** A tool argument that accepts a numeric id as a number or a string of digits. */
@@ -75,8 +74,6 @@ export declare function errorResult(message: string): CallToolResult;
75
74
  export declare function apiResponseResult(res: ClientResult, hint?: string): CallToolResult;
76
75
  /** Issue a TrainHeroic request and format the outcome as a tool result. */
77
76
  export declare function apiCall(ctx: ToolContext, method: string, path: string, options?: RequestOptions, hint?: string): Promise<CallToolResult>;
78
- //#endregion
79
- //#region src/confirm.d.ts
80
77
  /**
81
78
  * Returned when the user was asked and said no. It must not tell the model how to retry: the
82
79
  * refusal is the answer. (The `confirm: true` fallback for clients that cannot elicit is
@@ -103,8 +100,6 @@ export declare const NOT_CONFIRMED = "Not confirmed — the user declined. Nothi
103
100
  * a model-readable tool error that tells it how to recover while the gate remains closed.
104
101
  */
105
102
  export declare function confirmGate(ctx: ServerContext, message: string, confirmArg: boolean | undefined): ToolHandlerResult | undefined;
106
- //#endregion
107
- //#region src/instructions.d.ts
108
103
  /**
109
104
  * Server-level guidance passed as the MCP `instructions` string. The host model receives it
110
105
  * in the initialize result and treats it like a system hint. Its job is to stop tool-layer
@@ -114,15 +109,9 @@ export declare function confirmGate(ctx: ServerContext, message: string, confirm
114
109
  * leak further. This tells the host to keep that wiring internal and speak in app terms.
115
110
  */
116
111
  export declare const SERVER_INSTRUCTIONS: string;
117
- //#endregion
118
- //#region src/tools/reads.d.ts
119
112
  export declare function registerReadTools(server: McpServer, ctx: ToolContext): void;
120
- //#endregion
121
- //#region src/tools/main-lifts.d.ts
122
113
  /** Coach main-lift PR reads: one athlete, or the whole roster at once. */
123
114
  export declare function registerMainLiftTools(server: McpServer, ctx: ToolContext): void;
124
- //#endregion
125
- //#region src/tools/athlete-training.d.ts
126
115
  /**
127
116
  * Athlete tools need only the client (no exercise-library index), so they take a narrower
128
117
  * context than the coach tools. A full `ToolContext` also satisfies this, so the same ctx
@@ -146,8 +135,6 @@ export declare function mapSessionExercises(exercises: ReadonlyArray<{
146
135
  * resolved once from /user/simple and reused across tools.
147
136
  */
148
137
  export declare function registerAthleteTrainingTools(server: McpServer, ctx: AthleteContext): void;
149
- //#endregion
150
- //#region src/tools/athletes.d.ts
151
138
  /**
152
139
  * Athlete management. TrainHeroic has no "create athlete" primitive: a coach invites a
153
140
  * person by email to a team, and the athlete record only exists once they accept and set
@@ -156,39 +143,24 @@ export declare function registerAthleteTrainingTools(server: McpServer, ctx: Ath
156
143
  * (POST /v5/athletes/inviteToTeam). Both act on the live account, so the invite is gated.
157
144
  */
158
145
  export declare function registerAthleteTools(server: McpServer, ctx: ToolContext): void;
159
- //#endregion
160
- //#region src/tools/teams.d.ts
161
146
  /**
162
147
  * Team write tools. The team reads (list_teams, get_team, list_team_codes) live in
163
148
  * reads.ts; this module covers create/rename/delete plus the join-code lifecycle.
164
149
  */
165
150
  export declare function registerTeamTools(server: McpServer, ctx: ToolContext): void;
166
- //#endregion
167
- //#region src/tools/programs.d.ts
168
151
  /** Standalone program writes. Program reads live in reads.ts. */
169
152
  export declare function registerProgramTools(server: McpServer, ctx: ToolContext): void;
170
- //#endregion
171
- //#region src/tools/analytics.d.ts
172
153
  /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
173
154
  export declare function registerAnalyticsTools(server: McpServer, ctx: ToolContext): void;
174
- //#endregion
175
- //#region src/tools/exercises.d.ts
176
155
  /**
177
156
  * Exercise library tools over the ExerciseIndex — a D1 mirror on the hosted server, an
178
157
  * on-disk/in-memory cache locally. The descriptions stay at the interface level so they
179
158
  * read correctly on both backends.
180
159
  */
181
160
  export declare function registerExerciseTools(server: McpServer, ctx: ToolContext): void;
182
- //#endregion
183
- //#region src/tools/workout.d.ts
184
161
  /** Workout building, read-back, publishing, and the session calendar lifecycle. */
185
162
  export declare function registerWorkoutTools(server: McpServer, ctx: ToolContext): void;
186
- //#endregion
187
- //#region src/tools/messaging.d.ts
188
163
  /** Live messaging: list/read conversations, draft a message, and the gated send/delete. */
189
164
  export declare function registerMessagingTools(server: McpServer, ctx: ToolContext): void;
190
- //#endregion
191
- //#region src/tools/coach.d.ts
192
165
  /** Register the full coach tool surface (roster, teams, programs, exercises, messaging). */
193
- export declare function registerCoachTools(server: McpServer, ctx: ToolContext): void;
194
- //#endregion
166
+ export declare function registerCoachTools(server: McpServer, ctx: ToolContext): void;
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { athleteExerciseCatalogOutputSchema, athleteExerciseNoteArgsSchema, athleteExerciseNoteOutputSchema, athleteInviteOutputSchema, athleteMainLiftPrsOutputSchema, athletePrefsSchema, athletePrescribeSetArgsSchema, athleteProfileOutputSchema, athleteSessionRemoveArgsSchema, athleteSessionRemovedOutputSchema, athleteWorkingMaxListSchema, athleteWorkoutNoteArgsSchema, athleteWorkoutNoteObject, athleteWorkoutNoteOutputSchema, athleteWorkoutsOutputSchema, blockSpecSchema, coachAthleteTrainingOutputSchema, coachLogSessionArgsSchema, coachLogSetArgsSchema, coachPrescribeSetArgsSchema, commentDraftSchema, dateString, exerciseCreateSchema, exerciseCreatedOutputSchema, exerciseDeletedOutputSchema, exerciseForgottenOutputSchema, exerciseGetOutputSchema, exerciseHistoryOutputSchema, exerciseResolveOutputSchema, exerciseStatsSchema, exerciseSwapOutputSchema, exerciseUpdateSchema, exerciseViewSchema, idArgSchema, logSessionArgsSchema, logSetArgsSchema, logTargetsOutputSchema, messageDeletedOutputSchema, messageDraftOutputSchema, messageSentOutputSchema, opaqueOutputSchema, parseWorkoutDate, personalRecordListSchema, personalWorkoutCreatedOutputSchema, programCreatedOutputSchema, programDeletedOutputSchema, removedSessionOutputSchema, rosterActivityOutputSchema, sessionLogOutputSchema, sessionTemplateCreateSchema, sessionTemplateCreatedOutputSchema, setLogOutputSchema, setPrescriptionOutputSchema, swapAthleteExerciseArgsSchema, teamPublishPatchObject, teamPublishPatchSchema, teamVolumeOutputSchema, toolOutputSchema, userSimpleSchema, workoutBuildOutputSchema, workoutPublishOutputSchema, workoutReadOutputSchema } from "@trainheroic-unofficial/dto";
1
+ import { athleteExerciseCatalogOutputSchema, athleteExerciseNoteArgsSchema, athleteExerciseNoteOutputSchema, athleteInviteOutputSchema, athleteMainLiftPrsOutputSchema, athletePrefsSchema, athletePrescribeSetArgsSchema, athleteProfileOutputSchema, athleteSessionRemoveArgsSchema, athleteSessionRemovedOutputSchema, athleteWorkingMaxListSchema, athleteWorkoutNoteArgsSchema, athleteWorkoutNoteObject, athleteWorkoutNoteOutputSchema, athleteWorkoutsOutputSchema, blockSpecSchema, coachAthleteTrainingOutputSchema, coachLogSessionArgsSchema, coachLogSetArgsSchema, coachPrescribeSetArgsSchema, commentDraftSchema, dateString, exerciseCreateSchema, exerciseCreatedOutputSchema, exerciseDeletedOutputSchema, exerciseForgottenOutputSchema, exerciseGetOutputSchema, exerciseHistoryOutputSchema, exerciseResolveOutputSchema, exerciseStatsSchema, exerciseSwapOutputSchema, exerciseUpdateSchema, exerciseViewSchema, idArgSchema, logSessionArgsSchema, logSetArgsSchema, logTargetsOutputSchema, messageDeletedOutputSchema, messageDraftOutputSchema, messageSentOutputSchema, opaqueOutputSchema, parseWorkoutDate, personalRecordListSchema, personalWorkoutCreatedOutputSchema, programCreatedOutputSchema, programDeletedOutputSchema, removedSessionOutputSchema, rosterActivityOutputSchema, sessionLogOutputSchema, sessionSaveAsTemplateSchema, sessionTemplateCreateSchema, sessionTemplateCreatedOutputSchema, setLogOutputSchema, setPrescriptionOutputSchema, swapAthleteExerciseArgsSchema, teamPublishPatchObject, teamPublishPatchSchema, teamVolumeOutputSchema, toolOutputSchema, userSimpleSchema, workoutBuildOutputSchema, workoutPublishOutputSchema, workoutReadOutputSchema } from "@trainheroic-unofficial/dto";
2
2
  import { CLIENT_CAPABILITIES_META_KEY, acceptedContent, inputRequired, inputResponse } from "@modelcontextprotocol/server";
3
3
  import { z } from "zod";
4
- import { ANALYTICS_METRIC_KEYS, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, copySession, createPersonalWorkout, createProgram, createSessionTemplate, definedProps, deleteComment, deleteProgram, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, historyInRange, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkouts, presentCoachAthleteTraining, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, readLive, readSession, removePersonalWorkout, removeSession, resolveBuildProgramId, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setAthleteExerciseNote, setAthleteWorkoutNote, setSplitSummary, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, updateTeam, updateTeamPublishSettings } from "@trainheroic-unofficial/js";
5
- //#region src/context.ts
4
+ import { ANALYTICS_METRIC_KEYS, CoachMonthSummaryError, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, copySession, createPersonalWorkout, createProgram, createSessionTemplate, definedProps, deleteComment, deleteProgram, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, historyInRange, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkouts, presentCoachAthleteTraining, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, readLive, readSession, removePersonalWorkout, removeSession, resolveBuildProgramId, saveSessionAsTemplate, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setAthleteExerciseNote, setAthleteWorkoutNote, setSplitSummary, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, updateTeam, updateTeamPublishSettings } from "@trainheroic-unofficial/js";
5
+ // 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;
8
8
  function toId(value) {
@@ -216,8 +216,7 @@ async function apiCall(ctx, method, path, options, hint) {
216
216
  return apiResponseResult(await ctx.client.request(method, path, options), hint);
217
217
  });
218
218
  }
219
- //#endregion
220
- //#region src/confirm.ts
219
+ // src/confirm.ts
221
220
  /**
222
221
  * Returned when the user was asked and said no. It must not tell the model how to retry: the
223
222
  * refusal is the answer. (The `confirm: true` fallback for clients that cannot elicit is
@@ -273,8 +272,7 @@ function confirmGate(ctx, message, confirmArg) {
273
272
  }
274
273
  }) } });
275
274
  }
276
- //#endregion
277
- //#region src/instructions.ts
275
+ // src/instructions.ts
278
276
  /**
279
277
  * Server-level guidance passed as the MCP `instructions` string. The host model receives it
280
278
  * in the initialize result and treats it like a system hint. Its job is to stop tool-layer
@@ -284,8 +282,7 @@ function confirmGate(ctx, message, confirmArg) {
284
282
  * leak further. This tells the host to keep that wiring internal and speak in app terms.
285
283
  */
286
284
  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.";
287
- //#endregion
288
- //#region src/tools/reads.ts
285
+ // src/tools/reads.ts
289
286
  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.";
290
287
  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.";
291
288
  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.";
@@ -343,6 +340,20 @@ const SIMPLE_GETS = [
343
340
  path: SESSION_TEMPLATES_LIST_PATH
344
341
  }
345
342
  ];
343
+ /**
344
+ * Body of the athlete_training handler. TrainHeroic's month summary answers HTTP 500 for some
345
+ * athletes whose date-range read still works, so that failure names athlete_saved_workouts.
346
+ */
347
+ async function athleteTrainingResult(ctx, athleteId, year, month) {
348
+ let raw;
349
+ try {
350
+ raw = await fetchCoachAthleteCalendarSummary(ctx.client, athleteId, year, month);
351
+ } catch (error) {
352
+ if (error instanceof CoachMonthSummaryError && error.status === 500) return errorResult(`${error.message} Call athlete_saved_workouts with startDate and endDate spanning the month.`);
353
+ throw error;
354
+ }
355
+ return jsonResult(presentCoachAthleteTraining(raw, athleteId, year, month), { hint: "One session per row for the month. Use the exercise titles to pick lifts, then athlete_lift_history for their PRs." });
356
+ }
346
357
  /** Roster-level reads: the fixed GETs plus the filterable athlete and team lists. */
347
358
  function registerRosterReads(server, ctx) {
348
359
  server.registerTool("whoami", {
@@ -458,10 +469,7 @@ function registerEntityReads(server, ctx) {
458
469
  },
459
470
  outputSchema: toolOutputSchema(coachAthleteTrainingOutputSchema),
460
471
  annotations: READ
461
- }, ({ athleteId, year, month }) => attempt(async () => {
462
- const raw = await fetchCoachAthleteCalendarSummary(ctx.client, toId(athleteId), year, month);
463
- return jsonResult(presentCoachAthleteTraining(raw, toId(athleteId), year, month), { hint: "One session per row for the month. Use the exercise titles to pick lifts, then athlete_lift_history for their PRs." });
464
- }));
472
+ }, ({ athleteId, year, month }) => attempt(() => athleteTrainingResult(ctx, toId(athleteId), year, month)));
465
473
  server.registerTool("get_program", {
466
474
  title: "Get program detail",
467
475
  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.",
@@ -528,8 +536,7 @@ function registerCoachAthleteTeamCalendar(server, ctx) {
528
536
  annotations: READ
529
537
  }, ({ athleteId }) => apiCall(ctx, "GET", `/v5/calendars/athletes/${toId(athleteId)}/coachAthleteTeam`));
530
538
  }
531
- //#endregion
532
- //#region src/tools/main-lifts.ts
539
+ // src/tools/main-lifts.ts
533
540
  const monthsParam = z.number().int().positive().max(36).optional();
534
541
  const ATHLETE_DESC = "A roster athlete's personal records for the main barbell lifts (squat, bench press, deadlift, overhead press, clean & jerk, snatch). Pass athleteId from list_athletes — nothing else. It auto-discovers which exercise VARIANT the athlete actually logs for each lift (e.g. 'Back Squat', not the empty 'Squat' library entry) by scanning their recent training, so you do NOT resolve exercise ids yourself. Returns one row per lift family in a fixed order; a lift the athlete has not logged comes back with null fields (no PR yet). `months` (default 12) is how far back to look for the logged variants.";
535
542
  const ROSTER_DESC = "Every roster athlete's main-lift PRs in one call — the squad board for squat/bench/deadlift/overhead press/clean & jerk/snatch. Same per-athlete discovery as athlete_main_lift_prs, fanned out across the roster (bounded), so it makes many upstream calls; expect a few seconds on a big roster. Optional athleteIds restricts it to a subset (else the whole roster from /v5/athletes); `months` (default 12) sets the look-back for logged variants.";
@@ -561,8 +568,7 @@ function registerMainLiftTools(server, ctx) {
561
568
  }), { hint: "Pass athleteIds to scope to a few athletes, or lower months, to shrink this." });
562
569
  }));
563
570
  }
564
- //#endregion
565
- //#region src/tools/athlete-training.ts
571
+ // src/tools/athlete-training.ts
566
572
  /** Identity, profile, prefs, working maxes, leaderboard. */
567
573
  function registerProfileTools(server, ctx, whoami, userId) {
568
574
  server.registerTool("athlete_whoami", {
@@ -992,8 +998,7 @@ function registerAthleteTrainingTools(server, ctx) {
992
998
  registerLogTool(server, ctx);
993
999
  registerSwapTool(server, ctx);
994
1000
  }
995
- //#endregion
996
- //#region src/tools/athletes.ts
1001
+ // src/tools/athletes.ts
997
1002
  /** Normalize one-or-many emails into a deduped, trimmed list. */
998
1003
  function asEmailList(emails) {
999
1004
  return [...new Set((Array.isArray(emails) ? emails : [emails]).map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -1194,8 +1199,7 @@ function registerAthletePrescribeTool(server, ctx) {
1194
1199
  }));
1195
1200
  }));
1196
1201
  }
1197
- //#endregion
1198
- //#region src/tools/teams.ts
1202
+ // src/tools/teams.ts
1199
1203
  /**
1200
1204
  * Team write tools. The team reads (list_teams, get_team, list_team_codes) live in
1201
1205
  * reads.ts; this module covers create/rename/delete plus the join-code lifecycle.
@@ -1301,8 +1305,7 @@ function registerTeamPublishSettings(server, ctx) {
1301
1305
  }));
1302
1306
  }));
1303
1307
  }
1304
- //#endregion
1305
- //#region src/tools/programs.ts
1308
+ // src/tools/programs.ts
1306
1309
  /** Standalone program writes. Program reads live in reads.ts. */
1307
1310
  function registerProgramTools(server, ctx) {
1308
1311
  server.registerTool("program_create", {
@@ -1334,9 +1337,8 @@ function registerProgramTools(server, ctx) {
1334
1337
  return jsonResult(await deleteProgram(ctx.client, id));
1335
1338
  }));
1336
1339
  }
1337
- //#endregion
1338
- //#region src/tools/analytics.ts
1339
- 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.";
1340
+ // src/tools/analytics.ts
1341
+ 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, a weighted lift such as Back Squat (lift-1rm-history answers 'Invalid exercise id' for bodyweight, distance, and unknown exercises). All dates are YYYY-MM-DD.";
1340
1342
  /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
1341
1343
  function registerAnalyticsTools(server, ctx) {
1342
1344
  server.registerTool("analytics_query", {
@@ -1365,8 +1367,7 @@ function registerAnalyticsTools(server, ctx) {
1365
1367
  useMetric
1366
1368
  })), { hint: "Narrow with a tighter date range or fewer athletes." })));
1367
1369
  }
1368
- //#endregion
1369
- //#region src/tools/exercises.ts
1370
+ // src/tools/exercises.ts
1370
1371
  function registerExerciseUpdate(server, index) {
1371
1372
  server.registerTool("exercise_update", {
1372
1373
  title: "Update custom exercise",
@@ -1406,7 +1407,7 @@ function registerExerciseDelete(server, index) {
1406
1407
  function registerExerciseReads(server, index) {
1407
1408
  server.registerTool("exercise_resolve", {
1408
1409
  title: "Resolve exercise name",
1409
- description: "Map a name to an exercise id via the local mirror. Prefer this over exercise_search when you want a single authoritative id for a known name. Returns the match plus ranked candidates; when ambiguous, match is null and you should pick from candidates. Each result's `units` array lists the fixed measurement units by entry slot; they are fixed per exercise — check them before prescribing. `can_edit` is 1 only for the coach's own custom exercises and 0 for built-in library exercises.",
1410
+ description: "Map a name to an exercise id via the local mirror. Prefer this over exercise_search when you want a single authoritative id for a known name. Returns the match plus ranked candidates; when ambiguous, match is null and you should pick from candidates. Each result's `units` array lists the exercise's default measurement units by entry slot; workout_build uses them unless a prescription states another unit. `can_edit` is 1 only for the coach's own custom exercises and 0 for built-in library exercises.",
1410
1411
  inputSchema: { name: z.string().min(1) },
1411
1412
  outputSchema: toolOutputSchema(exerciseResolveOutputSchema),
1412
1413
  annotations: READ
@@ -1483,13 +1484,12 @@ function registerExerciseTools(server, ctx) {
1483
1484
  annotations: READ
1484
1485
  }, () => attempt(async () => jsonResult(await index.stats())));
1485
1486
  }
1486
- //#endregion
1487
- //#region src/tools/workout.ts
1487
+ // src/tools/workout.ts
1488
1488
  /** Build a draft session (workout_build). */
1489
1489
  function registerBuild(server, ctx) {
1490
1490
  server.registerTool("workout_build", {
1491
1491
  title: "Build a workout session (draft)",
1492
- 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 and a read-back. For each exercise, state primaryUnit when reps is present and secondaryUnit when weight is present; these are positional values, even when the unit is distance or time. Use exercise_resolve to check the exercise's fixed units before building. A mismatch fails before the draft is created. Exercises above 10 sets are split into consecutive same-titled blocks and require confirmation (elicitation, or confirm:true). Review, then workout_publish.",
1492
+ 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 and a read-back. For each exercise, state primaryUnit when reps is present and secondaryUnit when weight is present; these are positional values, even when the unit is distance or time. exercise_resolve lists each exercise's default units. A stated unit that differs from the default is set on this session, so % of max (secondaryUnit '%max') or RPE works on a built-in pounds lift and meters work on a miles exercise. A unit that conflicts with an explicit param_N_type fails before the draft is created. Exercises above 10 sets are split into consecutive same-titled blocks and require confirmation (elicitation, or confirm:true). Review, then workout_publish.",
1493
1493
  inputSchema: {
1494
1494
  programId: z.number().optional(),
1495
1495
  athleteId: idParam.optional(),
@@ -1619,11 +1619,15 @@ function registerLifecycle(server, ctx) {
1619
1619
  }))));
1620
1620
  server.registerTool("session_save_as_template", {
1621
1621
  title: "Save a session to the library",
1622
- description: "Save an existing session as a reusable template in the session library (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the workout_id.",
1623
- inputSchema: { workoutId: z.number() },
1622
+ description: "Copy an existing calendar session, with its blocks and exercises, into the session library as a new template (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the session's workoutId and pwId (workout_build returns both; workout_read returns both for a session on a date) and a title for the template.",
1623
+ inputSchema: sessionSaveAsTemplateSchema.shape,
1624
1624
  outputSchema: opaqueOutputSchema,
1625
1625
  annotations: ADDITIVE
1626
- }, ({ workoutId }) => apiCall(ctx, "POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${workoutId}`));
1626
+ }, ({ workoutId, pwId, title }) => attempt(async () => jsonResult(await saveSessionAsTemplate(ctx.client, {
1627
+ workoutId,
1628
+ pwId,
1629
+ title
1630
+ }))));
1627
1631
  }
1628
1632
  function registerTemplateLibrary(server, ctx) {
1629
1633
  server.registerTool("session_template_create", {
@@ -1659,8 +1663,7 @@ function registerWorkoutTools(server, ctx) {
1659
1663
  registerLifecycle(server, ctx);
1660
1664
  registerTemplateLibrary(server, ctx);
1661
1665
  }
1662
- //#endregion
1663
- //#region src/tools/messaging.ts
1666
+ // src/tools/messaging.ts
1664
1667
  function registerReads(server, ctx) {
1665
1668
  server.registerTool("messaging_conversations", {
1666
1669
  title: "List conversations (live)",
@@ -1750,8 +1753,7 @@ function registerMessagingTools(server, ctx) {
1750
1753
  registerReads(server, ctx);
1751
1754
  registerWrites(server, ctx);
1752
1755
  }
1753
- //#endregion
1754
- //#region src/tools/coach.ts
1756
+ // src/tools/coach.ts
1755
1757
  /** Register the full coach tool surface (roster, teams, programs, exercises, messaging). */
1756
1758
  function registerCoachTools(server, ctx) {
1757
1759
  registerReadTools(server, ctx);
@@ -1764,5 +1766,4 @@ function registerCoachTools(server, ctx) {
1764
1766
  registerWorkoutTools(server, ctx);
1765
1767
  registerMessagingTools(server, ctx);
1766
1768
  }
1767
- //#endregion
1768
1769
  export { ADDITIVE, 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": "4.2.0",
3
+ "version": "4.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,17 +22,17 @@
22
22
  "dist"
23
23
  ],
24
24
  "dependencies": {
25
- "@cfworker/json-schema": "^4.1.1",
26
- "@modelcontextprotocol/server": "2.3.1",
27
- "zod": "^4.6.5",
28
- "@trainheroic-unofficial/dto": "4.2.0",
29
- "@trainheroic-unofficial/js": "4.2.0"
25
+ "@cfworker/json-schema": "^4.1.6",
26
+ "@modelcontextprotocol/server": "2.4.0",
27
+ "zod": "^4.6.7",
28
+ "@trainheroic-unofficial/dto": "4.3.0",
29
+ "@trainheroic-unofficial/js": "4.3.0"
30
30
  },
31
31
  "devDependencies": {
32
- "@types/node": "^26.6.4",
33
- "tsdown": "^0.23.0",
32
+ "@types/node": "^26.6.6",
33
+ "tsdown": "^0.23.7",
34
34
  "typescript": "^7.0.2",
35
- "vitest": "^5.0.3"
35
+ "vitest": "^5.1.0"
36
36
  },
37
37
  "scripts": {
38
38
  "build": "tsdown",