@trainheroic-unofficial/core 1.0.0 → 1.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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @trainheroic-unofficial/core
2
2
 
3
3
  The shared [MCP](https://modelcontextprotocol.io) (Model Context Protocol) tool layer for
4
- TrainHeroic. Each tool — a function an AI assistant can call — is defined once here and reused
4
+ TrainHeroic. Each tool (a function an AI assistant can call) is defined once here and reused
5
5
  by both servers: the local stdio server (`@trainheroic-unofficial/coach-mcp`) and the hosted
6
6
  Cloudflare worker (`@trainheroic-unofficial/cloudflare`). You only need this package if you
7
7
  are building your own MCP server; to _use_ the tools, run one of those servers.
@@ -20,8 +20,8 @@ A server builds a `ToolContext` and passes it, along with its MCP server instanc
20
20
  `registerXxxTools(server, ctx)` functions (the `register*` names below are the real exports;
21
21
  `registerXxxTools` is shorthand for all of them). `ToolContext` is `{ client, index }`: an
22
22
  authenticated `TrainHeroicClient` (from `@trainheroic-unofficial/js`) and anything implementing
23
- the `ExerciseIndex` interface — the in-memory `ExerciseLibrary` here, or the hosted worker's
24
- D1-backed store.
23
+ the `ExerciseIndex` interface (the in-memory `ExerciseLibrary` here, or the hosted worker's
24
+ D1-backed store).
25
25
 
26
26
  Install it alongside the MCP SDK and the `js` client (both peers you construct from):
27
27
 
@@ -66,26 +66,24 @@ Each `register*` function registers a group of tools, and the individual tool na
66
66
  sees are snake_case (e.g. `analytics_query`, `exercise_resolve`). The groups:
67
67
 
68
68
  - coach reads (profile, athletes, teams, programs, notifications, analytics catalog)
69
- - athlete management (`registerAthleteTools` — the coach's _roster_ view: invite, archive, restore)
69
+ - athlete management (`registerAthleteTools`, the coach's _roster_ view: invite, archive, restore)
70
70
  - team management (create, rename, delete, join codes)
71
71
  - analytics report pulls (`analytics_query`: readiness, 1RM (one-rep max) and working-max history, training summary, compliance, lift progress)
72
72
  - exercise library operations (resolve, search, get, sync, create, forget, stats)
73
73
  - the workout/session lifecycle (build a draft, read it back, publish, unpublish, copy, save as template, remove)
74
74
  - messaging (list, read, draft, send, delete)
75
75
 
76
- There is no raw-request escape hatch; every endpoint reaches the model through a typed tool.
76
+ Every endpoint reaches the model through a typed tool; the surface has no raw-request escape hatch.
77
77
  (`registerAthleteTools` here is the coach's roster view, distinct from the athlete's own
78
78
  training tools that the athlete server registers.)
79
79
 
80
80
  Tools return their result in-band. A failure comes back as an error result the model can read
81
- and correct, not a thrown exception. Reads are annotated read-only. Athlete-facing or
81
+ and self-correct from. Reads are annotated read-only. Athlete-facing or
82
82
  destructive actions (publish, unpublish, remove, send, delete, archive, team/code delete) pass
83
- through a confirmation gate: it asks the client to confirm via MCP elicitation, falls back to
84
- an explicit `confirm: true` argument when the client cannot prompt, and fails closed if neither
85
- is satisfied.
83
+ through a confirmation gate. The gate prefers MCP elicitation; when the client cannot elicit,
84
+ it accepts an explicit `confirm: true` argument. It fails closed if neither condition is met.
86
85
 
87
- The D1-backed warehouse sync tools are not here; they live in the `cloudflare` package
88
- because they depend on its storage.
86
+ The D1-backed warehouse sync tools live in the `cloudflare` package because they depend on its storage.
89
87
 
90
88
  ## Develop
91
89
 
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ExerciseIndex, RequestOptions, TrainHeroicClient } from "@trainheroic-unofficial/js";
1
+ import { ExerciseIndex, RequestOptions, SessionExercise, TrainHeroicClient } from "@trainheroic-unofficial/js";
2
2
  import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
 
@@ -71,7 +71,6 @@ declare function confirmGate(server: McpServer, requestId: string | number | und
71
71
  declare const SERVER_INSTRUCTIONS: string;
72
72
  //#endregion
73
73
  //#region src/tools/reads.d.ts
74
- /** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
75
74
  declare function registerReadTools(server: McpServer, ctx: ToolContext): void;
76
75
  //#endregion
77
76
  //#region src/tools/athlete-training.d.ts
@@ -83,6 +82,15 @@ declare function registerReadTools(server: McpServer, ctx: ToolContext): void;
83
82
  type AthleteContext = {
84
83
  client: TrainHeroicClient;
85
84
  };
85
+ /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
86
+ declare function mapSessionExercises(exercises: ReadonlyArray<{
87
+ exerciseId: number | string;
88
+ order?: number | undefined;
89
+ sets: ReadonlyArray<{
90
+ param1?: number | string | undefined;
91
+ param2?: number | string | undefined;
92
+ }>;
93
+ }>): SessionExercise[];
86
94
  /**
87
95
  * Live tools over the logged-in user's own training (history, scheduled/completed workouts,
88
96
  * PRs, working maxes), plus a gated set-logging write. The athlete user id is
@@ -127,4 +135,4 @@ declare function registerWorkoutTools(server: McpServer, ctx: ToolContext): void
127
135
  /** Live messaging: list/read conversations, draft a message, and the gated send/delete. */
128
136
  declare function registerMessagingTools(server: McpServer, ctx: ToolContext): void;
129
137
  //#endregion
130
- export { AthleteContext, BudgetHint, DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, ToolContext, apiCall, attempt, boundedSerialize, confirmGate, errorResult, idParam, jsonResult, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerExerciseTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
138
+ export { AthleteContext, BudgetHint, DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, ToolContext, apiCall, attempt, boundedSerialize, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerExerciseTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { blockSpecSchema, coachLogSetArgsSchema, commentDraftSchema, dateString, exerciseCreateSchema, idArgSchema, logSetArgsSchema, parseWorkoutDate } from "@trainheroic-unofficial/dto";
1
+ import { blockSpecSchema, coachLogSessionArgsSchema, coachLogSetArgsSchema, commentDraftSchema, dateString, exerciseCreateSchema, idArgSchema, logSessionArgsSchema, logSetArgsSchema, parseWorkoutDate } from "@trainheroic-unofficial/dto";
2
2
  import { z } from "zod";
3
- import { ANALYTICS_METRIC_KEYS, addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchWorkingMaxes, inviteAthletes, isRecord, logAthleteSet, logForAthlete, presentAthleteWorkouts, presentCoachAthleteTraining, presentExerciseHistory, publishSession, queryAnalytics, readLive, readSession, removeSession, searchExerciseHistory, selectWorkouts, sendComment, summarizeAthleteWorkouts } from "@trainheroic-unofficial/js";
3
+ import { ANALYTICS_METRIC_KEYS, addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, presentAthleteWorkouts, presentCoachAthleteTraining, presentExerciseHistory, publishSession, queryAnalytics, readLive, readSession, removeSession, searchExerciseHistory, selectWorkouts, sendComment, summarizeAthleteWorkouts, teamVolume } from "@trainheroic-unofficial/js";
4
4
  //#region src/context.ts
5
5
  /** A tool argument that accepts a numeric id as a number or a string of digits. */
6
6
  const idParam = idArgSchema;
@@ -377,9 +377,32 @@ function registerEntityReads(server, ctx) {
377
377
  }, ({ 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."));
378
378
  }
379
379
  /** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
380
+ /** The windowed team-volume read — its own function so registerEntityReads stays under the cap. */
381
+ function registerTeamVolume(server, ctx) {
382
+ server.registerTool("team_volume", {
383
+ title: "Team training volume over a date window",
384
+ description: "Team-wide training volume (and reps/sessions) scoped to an inclusive YYYY-MM-DD window — the date-ranged answer to 'how much did the team train over the last two weeks'. Pass either teamId (its roster is resolved automatically) or an explicit athleteIds list (from list_athletes); dateStart and dateEnd are required. Returns one row per athlete who logged in range plus the rolled-up team totals (volume is in lb). For an all-time, undated snapshot use roster_activity instead.",
385
+ inputSchema: {
386
+ teamId: idParam.optional(),
387
+ athleteIds: z.array(idParam).optional(),
388
+ dateStart: dateString,
389
+ dateEnd: dateString
390
+ },
391
+ annotations: READ
392
+ }, ({ teamId, athleteIds, dateStart, dateEnd }) => attempt(async () => {
393
+ const ids = athleteIds !== void 0 && athleteIds.length > 0 ? athleteIds.map(toId) : teamId !== void 0 ? await fetchTeamAthleteIds(ctx.client, toId(teamId)) : [];
394
+ if (ids.length === 0) throw new Error("Provide athleteIds, or a teamId whose roster has athletes. No athletes resolved for this team — pass athleteIds from list_athletes instead.");
395
+ return jsonResult(await teamVolume(ctx.client, {
396
+ athleteIds: ids,
397
+ dateStart,
398
+ dateEnd
399
+ }), { hint: "Rows cover only athletes who logged in range; totals roll them up. Narrow the window or athletes to shrink." });
400
+ }));
401
+ }
380
402
  function registerReadTools(server, ctx) {
381
403
  registerRosterReads(server, ctx);
382
404
  registerEntityReads(server, ctx);
405
+ registerTeamVolume(server, ctx);
383
406
  }
384
407
  //#endregion
385
408
  //#region src/tools/athlete-training.ts
@@ -547,8 +570,40 @@ function registerSessionTools(server, ctx) {
547
570
  return jsonResult(await addExercisesToWorkout(ctx.client, toId(workoutId), mapped), { hint: "Each top-level id is a savedWorkoutSetId; savedWorkoutSetExercises[].id is the savedWorkoutSetExerciseId for athlete_log_set." });
548
571
  }));
549
572
  }
550
- /** The gated set-logging write. */
573
+ /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
574
+ function mapSessionExercises(exercises) {
575
+ return exercises.map((e) => {
576
+ const sets = e.sets.map((s) => {
577
+ const slot = {};
578
+ if (s.param1 !== void 0) slot.param1 = s.param1;
579
+ if (s.param2 !== void 0) slot.param2 = s.param2;
580
+ return slot;
581
+ });
582
+ const mapped = {
583
+ exerciseId: toId(e.exerciseId),
584
+ sets
585
+ };
586
+ if (e.order !== void 0) mapped.order = e.order;
587
+ return mapped;
588
+ });
589
+ }
590
+ /** The gated set-logging writes (by saved-set id, and the by-exercise ad-hoc session). */
551
591
  function registerLogTool(server, ctx) {
592
+ server.registerTool("athlete_log_session", {
593
+ title: "Log a whole session by exercise",
594
+ description: "Athlete-facing write for logging what you actually did, with NO coach-scheduled workout required — use this for off-plan training (accessory work, a makeup lift, an unplanned gym session). Give a YYYY-MM-DD date and a list of exercises, each with its entered sets (param1/param2, e.g. reps/weight). It reuses a personal session already on that date or creates one, then logs the sets. Get each exerciseId from athlete_exercises. To log against a workout a coach already scheduled, use athlete_log_set instead. Requires confirmation (elicitation or confirm:true).",
595
+ inputSchema: {
596
+ ...logSessionArgsSchema.shape,
597
+ confirm: z.boolean().optional()
598
+ },
599
+ annotations: DESTRUCTIVE
600
+ }, ({ date, exercises, confirm }, extra) => attempt(async () => {
601
+ if (!await confirmGate(server, extra.requestId, `Log a session of ${exercises.length} exercise(s) on ${date}? This writes to your coach-visible training log.`, confirm)) return errorResult(NOT_CONFIRMED);
602
+ return jsonResult(await logAdHocSession(ctx.client, {
603
+ date,
604
+ exercises: mapSessionExercises(exercises)
605
+ }));
606
+ }));
552
607
  server.registerTool("athlete_log_set", {
553
608
  title: "Log completed set results",
554
609
  description: "Athlete-facing write: record entered results (reps/weight per set) for a saved workout set on a given day, marking the set completed. Writes to the athlete's (coach-visible) training log and shows in exercise history. Get savedWorkoutSetId + savedWorkoutSetExerciseId from athlete_workouts (raw:true). Requires confirmation (elicitation or confirm:true).",
@@ -714,6 +769,23 @@ function registerAthleteLogTools(server, ctx) {
714
769
  results: mapped
715
770
  }));
716
771
  }));
772
+ server.registerTool("coach_log_session", {
773
+ title: "Log a roster athlete's session by exercise",
774
+ description: "Coach-facing write: log results for a roster athlete by exercise on a given day, without hunting for saved-set ids. Give athleteId, a YYYY-MM-DD date, and a list of exercises (each with its entered sets), and each is matched to a set already on that athlete's calendar for the date. The API has no way to put an off-plan session on an athlete's calendar, so this only logs against an EXISTING session — if an exercise is not prescribed that day the call fails and names what is. Get athleteId from list_athletes and exerciseIds from athlete_saved_workouts. Seeded demo athletes are read-only. Requires confirmation (elicitation or confirm:true).",
775
+ inputSchema: {
776
+ ...coachLogSessionArgsSchema.shape,
777
+ confirm: z.boolean().optional()
778
+ },
779
+ annotations: DESTRUCTIVE
780
+ }, ({ athleteId, date, exercises, confirm }, extra) => attempt(async () => {
781
+ const aId = toId(athleteId);
782
+ if (!await confirmGate(server, extra.requestId, `Log a session of ${exercises.length} exercise(s) for athlete ${aId} on ${date}? This writes to their coach-visible training log.`, confirm)) return errorResult(NOT_CONFIRMED);
783
+ return jsonResult(await logSessionForAthlete(ctx.client, {
784
+ athleteId: aId,
785
+ date,
786
+ exercises: mapSessionExercises(exercises)
787
+ }));
788
+ }));
717
789
  }
718
790
  //#endregion
719
791
  //#region src/tools/teams.ts
@@ -1109,4 +1181,4 @@ function registerMessagingTools(server, ctx) {
1109
1181
  registerWrites(server, ctx);
1110
1182
  }
1111
1183
  //#endregion
1112
- export { DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, apiCall, attempt, boundedSerialize, confirmGate, errorResult, idParam, jsonResult, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerExerciseTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
1184
+ export { DEFAULT_RESULT_BUDGET, DESTRUCTIVE, NOT_CONFIRMED, READ, SERVER_INSTRUCTIONS, SYNC, apiCall, attempt, boundedSerialize, confirmGate, errorResult, idParam, jsonResult, mapSessionExercises, registerAnalyticsTools, registerAthleteTools, registerAthleteTrainingTools, registerExerciseTools, registerMessagingTools, registerReadTools, registerTeamTools, registerWorkoutTools, resultBudget, toId };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/core",
3
- "version": "1.0.0",
3
+ "version": "1.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/sdk": "^1.29.0",
27
27
  "zod": "^4.4.3",
28
- "@trainheroic-unofficial/dto": "1.0.0",
29
- "@trainheroic-unofficial/js": "1.0.0"
28
+ "@trainheroic-unofficial/dto": "1.1.1",
29
+ "@trainheroic-unofficial/js": "1.1.1"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "^26.0.0",