@trainheroic-unofficial/core 3.1.1 → 3.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
@@ -8,6 +8,12 @@ declare const idParam: import("zod").ZodUnion<readonly [import("zod").ZodNumber,
8
8
  declare function toId(value: string | number): number;
9
9
  declare const READ: {
10
10
  readonly readOnlyHint: true;
11
+ readonly destructiveHint: false;
12
+ readonly openWorldHint: true;
13
+ };
14
+ declare const ADDITIVE: {
15
+ readonly readOnlyHint: false;
16
+ readonly destructiveHint: false;
11
17
  readonly openWorldHint: true;
12
18
  };
13
19
  declare const SYNC: {
@@ -36,13 +42,14 @@ declare function attempt<T extends ToolHandlerResult>(fn: () => Promise<T>): Pro
36
42
  declare const DEFAULT_RESULT_BUDGET = 60000;
37
43
  /**
38
44
  * Clip an array to its first `keep` items and attach the `__truncated` marker describing what was
39
- * dropped. The marker is model-facing (tools instruct the model to key off `__truncated`), so its
40
- * shape has exactly one definition here: the size-budget path (`boundedSerialize`) and any tool
41
- * that deliberately caps a list (e.g. `athlete_exercises`) emit the same thing.
45
+ * dropped. Every budget fallback that trims a list uses this envelope (`{ items, __truncated }`),
46
+ * including in-place object-array truncation (the sliced array becomes `items` and `field` names
47
+ * the original key). `athlete_exercises` uses the same helper for a client-side catalog cap.
42
48
  */
43
- declare function clipArray<T>(items: readonly T[], keep: number, hint?: string): {
49
+ declare function clipArray<T>(items: readonly T[], keep: number, hint?: string, field?: string): {
44
50
  items: T[];
45
51
  __truncated: {
52
+ field?: string;
46
53
  returned: number;
47
54
  total: number;
48
55
  omitted: number;
@@ -52,10 +59,8 @@ declare function clipArray<T>(items: readonly T[], keep: number, hint?: string):
52
59
  /** Active budget. Overridable via TH_MCP_RESULT_BUDGET on Node; the default on workerd. */
53
60
  declare function resultBudget(): number;
54
61
  /**
55
- * Serialize `data` as JSON within `budget` characters. Small results are pretty-printed.
56
- * Oversized results degrade in order: trim a top-level array (wrapping it as
57
- * `{ items, __truncated }`), then a top-level object's largest array property (annotated
58
- * with `__truncated`), then a last-resort hard character cap. Pure and side-effect free.
62
+ * Serialize `data` within `budget` characters. Small JSON results are pretty-printed and small
63
+ * strings remain plain text. Oversized values become valid JSON truncation envelopes.
59
64
  */
60
65
  declare function boundedSerialize(data: unknown, budget: number, hint?: string): string;
61
66
  /** Per-tool guidance threaded into the truncation marker when a result is too large. */
@@ -187,4 +192,4 @@ declare function registerMessagingTools(server: McpServer, ctx: ToolContext): vo
187
192
  /** Register the full coach tool surface (roster, teams, programs, exercises, messaging). */
188
193
  declare function registerCoachTools(server: McpServer, ctx: ToolContext): void;
189
194
  //#endregion
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 };
195
+ export { ADDITIVE, 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 { athletePrescribeSetArgsSchema, athleteSessionRemoveArgsSchema, blockSpecSchema, coachLogSessionArgsSchema, coachLogSetArgsSchema, coachPrescribeSetArgsSchema, commentDraftSchema, dateString, exerciseCreateSchema, idArgSchema, logSessionArgsSchema, logSetArgsSchema, parseWorkoutDate, swapAthleteExerciseArgsSchema } from "@trainheroic-unofficial/dto";
1
+ import { athleteExerciseCatalogOutputSchema, athleteInviteOutputSchema, athleteMainLiftPrsOutputSchema, athletePrefsSchema, athletePrescribeSetArgsSchema, athleteProfileOutputSchema, athleteSessionRemoveArgsSchema, athleteSessionRemovedOutputSchema, athleteWorkingMaxListSchema, athleteWorkoutsOutputSchema, blockSpecSchema, coachAthleteTrainingOutputSchema, coachLogSessionArgsSchema, coachLogSetArgsSchema, coachPrescribeSetArgsSchema, commentDraftSchema, dateString, exerciseCreateSchema, exerciseCreatedOutputSchema, exerciseDeletedOutputSchema, exerciseForgottenOutputSchema, exerciseGetOutputSchema, exerciseHistoryOutputSchema, exerciseResolveOutputSchema, exerciseStatsSchema, exerciseSwapOutputSchema, 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";
2
2
  import { acceptedContent, inputRequired, inputResponse } from "@modelcontextprotocol/server";
3
3
  import { z } from "zod";
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";
4
+ import { ANALYTICS_METRIC_KEYS, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, addExercisesToWorkout, buildCommentPayload, buildSession, coerceInt, collectAdvisories, 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, 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, teamPublishTarget, teamVolume, toSetResults, updateTeam, updateTeamPublishSettings } 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;
@@ -10,6 +10,12 @@ function toId(value) {
10
10
  }
11
11
  const READ = {
12
12
  readOnlyHint: true,
13
+ destructiveHint: false,
14
+ openWorldHint: true
15
+ };
16
+ const ADDITIVE = {
17
+ readOnlyHint: false,
18
+ destructiveHint: false,
13
19
  openWorldHint: true
14
20
  };
15
21
  const SYNC = {
@@ -37,32 +43,36 @@ async function attempt(fn) {
37
43
  }
38
44
  /** Conservative per-result character cap, below the smallest host cap. */
39
45
  const DEFAULT_RESULT_BUDGET = 6e4;
46
+ /** Smallest cap that can still carry a useful structured truncation envelope. */
47
+ const MIN_RESULT_BUDGET = 256;
40
48
  /** Reserve for the `__truncated` marker so wrapping cannot push back over budget. */
41
49
  const MARKER_RESERVE = 300;
42
50
  const DEFAULT_ARRAY_HINT = "Result was truncated to fit the size budget. Narrow it with a filter/search argument or paginate to see the rest.";
43
51
  const DEFAULT_OBJECT_HINT = "Result was truncated to fit the size budget. Request a more specific id or sub-resource.";
44
52
  /**
45
53
  * Clip an array to its first `keep` items and attach the `__truncated` marker describing what was
46
- * dropped. The marker is model-facing (tools instruct the model to key off `__truncated`), so its
47
- * shape has exactly one definition here: the size-budget path (`boundedSerialize`) and any tool
48
- * that deliberately caps a list (e.g. `athlete_exercises`) emit the same thing.
54
+ * dropped. Every budget fallback that trims a list uses this envelope (`{ items, __truncated }`),
55
+ * including in-place object-array truncation (the sliced array becomes `items` and `field` names
56
+ * the original key). `athlete_exercises` uses the same helper for a client-side catalog cap.
49
57
  */
50
- function clipArray(items, keep, hint) {
58
+ function clipArray(items, keep, hint, field) {
59
+ const marker = {
60
+ returned: keep,
61
+ total: items.length,
62
+ omitted: items.length - keep,
63
+ hint: hint ?? DEFAULT_ARRAY_HINT
64
+ };
65
+ if (field !== void 0) marker.field = field;
51
66
  return {
52
67
  items: items.slice(0, keep),
53
- __truncated: {
54
- returned: keep,
55
- total: items.length,
56
- omitted: items.length - keep,
57
- hint: hint ?? DEFAULT_ARRAY_HINT
58
- }
68
+ __truncated: marker
59
69
  };
60
70
  }
61
71
  /** Active budget. Overridable via TH_MCP_RESULT_BUDGET on Node; the default on workerd. */
62
72
  function resultBudget() {
63
73
  const raw = (globalThis.process?.env)?.TH_MCP_RESULT_BUDGET;
64
74
  const n = raw ? Number(raw) : NaN;
65
- return Number.isFinite(n) && n > 0 ? n : DEFAULT_RESULT_BUDGET;
75
+ return Number.isFinite(n) && n >= MIN_RESULT_BUDGET ? n : DEFAULT_RESULT_BUDGET;
66
76
  }
67
77
  function isPlainObject(value) {
68
78
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -79,7 +89,7 @@ function largestPrefixCount(pieces, charBudget) {
79
89
  }
80
90
  return k;
81
91
  }
82
- /** Last resort: cap a string at the budget and label it as truncated, non-JSON output. */
92
+ /** Cap diagnostic text. Tool errors are text-only and are not output-schema validated. */
83
93
  function hardCap(text, budget, hint) {
84
94
  if (text.length <= budget) return text;
85
95
  const note = `\n\n[TRUNCATED: output exceeded ${budget} chars and is NOT valid JSON. ${hint ?? "Narrow the query (filter, paginate, or fetch a specific id)."}]`;
@@ -99,56 +109,86 @@ function largestArrayValuedKey(obj) {
99
109
  }
100
110
  return best;
101
111
  }
102
- /**
103
- * Serialize `data` as JSON within `budget` characters. Small results are pretty-printed.
104
- * Oversized results degrade in order: trim a top-level array (wrapping it as
105
- * `{ items, __truncated }`), then a top-level object's largest array property (annotated
106
- * with `__truncated`), then a last-resort hard character cap. Pure and side-effect free.
107
- */
108
- function boundedSerialize(data, budget, hint) {
109
- if (typeof data === "string") return hardCap(data, budget, hint);
110
- const compact = JSON.stringify(data) ?? "null";
112
+ function jsonValue(data) {
113
+ return JSON.parse(JSON.stringify(data) ?? "null");
114
+ }
115
+ function previewEnvelope(source, budget, hint) {
116
+ const total = source.length;
117
+ const makeValue = (preview, markerHint) => ({
118
+ preview,
119
+ __truncated: {
120
+ total,
121
+ omitted: total - preview.length,
122
+ hint: markerHint
123
+ }
124
+ });
125
+ let markerHint = hint ?? "Narrow the query (filter, paginate, or fetch a specific id).";
126
+ while (JSON.stringify(makeValue("", markerHint)).length > budget && markerHint.length > 0) markerHint = markerHint.slice(0, -1);
127
+ if (JSON.stringify(makeValue("", markerHint)).length > budget) throw new RangeError("Result budget is too small for a structured truncation envelope.");
128
+ let keep = Math.max(0, budget - JSON.stringify(makeValue("", markerHint)).length);
129
+ let value = makeValue(source.slice(0, keep), markerHint);
130
+ while (JSON.stringify(value).length > budget && keep > 0) {
131
+ keep = Math.max(0, keep - (JSON.stringify(value).length - budget));
132
+ value = makeValue(source.slice(0, keep), markerHint);
133
+ }
134
+ return value;
135
+ }
136
+ function boundedResult(data, budget, hint) {
137
+ if (typeof data === "string" && data.length <= budget) return {
138
+ text: data,
139
+ value: data
140
+ };
141
+ const value = jsonValue(data);
142
+ const compact = JSON.stringify(value);
111
143
  if (compact.length <= budget) {
112
- const pretty = JSON.stringify(data, null, 2) ?? "null";
113
- return pretty.length <= budget ? pretty : compact;
144
+ const pretty = JSON.stringify(value, null, 2);
145
+ return {
146
+ text: pretty.length <= budget ? pretty : compact,
147
+ value
148
+ };
114
149
  }
115
- if (Array.isArray(data)) {
116
- const k = largestPrefixCount(data.map((el) => JSON.stringify(el) ?? "null"), budget - MARKER_RESERVE);
117
- const out = JSON.stringify(clipArray(data, k, hint));
118
- if (out.length <= budget) return out;
119
- } else if (isPlainObject(data)) {
120
- const key = largestArrayValuedKey(data);
150
+ if (Array.isArray(value)) {
151
+ const truncated = clipArray(value, largestPrefixCount(value.map((element) => JSON.stringify(element)), budget - MARKER_RESERVE), hint);
152
+ const text = JSON.stringify(truncated);
153
+ if (text.length <= budget) return {
154
+ text,
155
+ value: truncated
156
+ };
157
+ } else if (isPlainObject(value)) {
158
+ const key = largestArrayValuedKey(value);
121
159
  if (key !== null) {
122
- const arr = data[key];
123
- const pieces = arr.map((el) => JSON.stringify(el) ?? "null");
124
- const restLen = (JSON.stringify({
125
- ...data,
126
- [key]: []
127
- }) ?? "{}").length;
128
- const k = largestPrefixCount(pieces, Math.max(0, budget - MARKER_RESERVE - restLen));
129
- const clone = {
130
- ...data,
131
- [key]: arr.slice(0, k),
132
- __truncated: {
133
- field: key,
134
- returned: k,
135
- total: arr.length,
136
- omitted: arr.length - k,
137
- hint: hint ?? DEFAULT_OBJECT_HINT
138
- }
160
+ const array = value[key];
161
+ const truncated = clipArray(array, largestPrefixCount(array.map((element) => JSON.stringify(element)), budget - MARKER_RESERVE), hint ?? DEFAULT_OBJECT_HINT, key);
162
+ const text = JSON.stringify(truncated);
163
+ if (text.length <= budget) return {
164
+ text,
165
+ value: truncated
139
166
  };
140
- const out = JSON.stringify(clone);
141
- if (out.length <= budget) return out;
142
167
  }
143
168
  }
144
- return hardCap(compact, budget, hint);
169
+ const truncated = previewEnvelope(typeof data === "string" ? data : compact, budget, hint);
170
+ return {
171
+ text: JSON.stringify(truncated),
172
+ value: truncated
173
+ };
174
+ }
175
+ /**
176
+ * Serialize `data` within `budget` characters. Small JSON results are pretty-printed and small
177
+ * strings remain plain text. Oversized values become valid JSON truncation envelopes.
178
+ */
179
+ function boundedSerialize(data, budget, hint) {
180
+ return boundedResult(data, budget, hint).text;
145
181
  }
146
182
  /** A successful tool result carrying JSON (or text) for the model, size-bounded. */
147
183
  function jsonResult(data, opts) {
148
- return { content: [{
149
- type: "text",
150
- text: boundedSerialize(data, resultBudget(), opts?.hint)
151
- }] };
184
+ const { text, value } = boundedResult(data, resultBudget(), opts?.hint);
185
+ return {
186
+ content: [{
187
+ type: "text",
188
+ text
189
+ }],
190
+ structuredContent: value
191
+ };
152
192
  }
153
193
  /** A tool-level error: returned in-band (isError) so the model can self-correct. */
154
194
  function errorResult(message) {
@@ -263,12 +303,6 @@ function enc(value) {
263
303
  }
264
304
  /** No-argument GET endpoints, registered from a table to keep the wiring compact. */
265
305
  const SIMPLE_GETS = [
266
- {
267
- name: "whoami",
268
- title: "Who am I",
269
- description: "The authenticated TrainHeroic coach profile (id, org_id, name, roles, trial days).",
270
- path: "/user/simple"
271
- },
272
306
  {
273
307
  name: "head_coach",
274
308
  title: "Head coach / org",
@@ -287,19 +321,51 @@ const SIMPLE_GETS = [
287
321
  description: "Unread counts including countMessagingNotViewed (cheap 'anything new?' poll).",
288
322
  path: "/v5/notifications/counts"
289
323
  },
324
+ {
325
+ name: "list_notifications",
326
+ title: "Notification list",
327
+ description: "Full notification list (GET /v5/notifications). Distinct from `notifications`, which returns unread counts only. Empty when there are no notifications.",
328
+ path: "/v5/notifications"
329
+ },
330
+ {
331
+ name: "list_subscriptions",
332
+ title: "Program subscriptions",
333
+ description: "Program subscriptions and subscribed teams (GET /1.0/coach/subscriptions). Returns `{subscriptions, teams}`.",
334
+ path: "/1.0/coach/subscriptions"
335
+ },
336
+ {
337
+ name: "list_prescription_templates",
338
+ title: "Prescription templates",
339
+ description: "Saved sets/reps schemes (GET /2.0/coach/workoutSetExercise/template). Use when picking a named prescription like '4 x 3' rather than typing set counts by hand.",
340
+ path: "/2.0/coach/workoutSetExercise/template"
341
+ },
290
342
  {
291
343
  name: "analytics_categories",
292
344
  title: "Analytics categories",
293
345
  description: "TrainHeroic's raw analytics catalog. Its keys are the API's own names and do NOT match analytics_query's `metric` values — choose the metric straight from analytics_query's (self-describing) enum instead; you rarely need this tool.",
294
346
  path: "/v5/analytics"
347
+ },
348
+ {
349
+ name: "list_session_templates",
350
+ title: "List session templates",
351
+ description: "Session templates in the coach library (GET /1.0/coach/workouts). Use a template id with session_save_as_template's inverse: this lists saved templates; session_save_as_template writes one from an existing session. Empty when the library has no templates yet.",
352
+ path: SESSION_TEMPLATES_LIST_PATH
295
353
  }
296
354
  ];
297
355
  /** Roster-level reads: the fixed GETs plus the filterable athlete and team lists. */
298
356
  function registerRosterReads(server, ctx) {
357
+ server.registerTool("whoami", {
358
+ title: "Who am I",
359
+ description: "The authenticated TrainHeroic coach profile (id, org_id, name, roles, trial days).",
360
+ inputSchema: {},
361
+ outputSchema: toolOutputSchema(userSimpleSchema),
362
+ annotations: READ
363
+ }, () => apiCall(ctx, "GET", "/user/simple"));
299
364
  for (const t of SIMPLE_GETS) server.registerTool(t.name, {
300
365
  title: t.title,
301
366
  description: t.description,
302
367
  inputSchema: {},
368
+ outputSchema: opaqueOutputSchema,
303
369
  annotations: READ
304
370
  }, () => apiCall(ctx, "GET", t.path));
305
371
  server.registerTool("list_athletes", {
@@ -309,6 +375,7 @@ function registerRosterReads(server, ctx) {
309
375
  q: z.string().optional(),
310
376
  limit: z.number().int().positive().max(500).optional()
311
377
  },
378
+ outputSchema: toolOutputSchema(z.array(z.json())),
312
379
  annotations: READ
313
380
  }, ({ q, limit }) => attempt(async () => {
314
381
  const res = await ctx.client.request("GET", "/v5/athletes");
@@ -325,13 +392,7 @@ function registerRosterReads(server, ctx) {
325
392
  return needles.every((n) => hay.includes(n));
326
393
  });
327
394
  }
328
- const total = rows.length;
329
- if (limit !== void 0 && rows.length > limit) return jsonResult({
330
- items: rows.slice(0, limit),
331
- returned: limit,
332
- total,
333
- note: "Limited client-side. Raise limit or narrow with q for the rest."
334
- });
395
+ if (limit !== void 0 && rows.length > limit) return jsonResult(clipArray(rows, limit, "Limited client-side. Raise limit or narrow with q for the rest."));
335
396
  return jsonResult(rows, { hint: "Filter with q (name/email substring) or cap with limit to shrink this list." });
336
397
  }));
337
398
  server.registerTool("list_teams", {
@@ -342,6 +403,7 @@ function registerRosterReads(server, ctx) {
342
403
  pageSize: z.number().int().positive().optional(),
343
404
  q: z.string().optional()
344
405
  },
406
+ outputSchema: opaqueOutputSchema,
345
407
  annotations: READ
346
408
  }, ({ page, pageSize, q }) => {
347
409
  const qs = new URLSearchParams();
@@ -358,12 +420,14 @@ function registerEntityReads(server, ctx) {
358
420
  title: "Get team",
359
421
  description: "Full team object by team id.",
360
422
  inputSchema: { teamId: idParam },
423
+ outputSchema: opaqueOutputSchema,
361
424
  annotations: READ
362
425
  }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}`));
363
426
  server.registerTool("list_team_codes", {
364
427
  title: "List team access codes",
365
428
  description: "Join/access codes for a team.",
366
429
  inputSchema: { teamId: idParam },
430
+ outputSchema: opaqueOutputSchema,
367
431
  annotations: READ
368
432
  }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}/teamCodes`));
369
433
  server.registerTool("athlete_lift_history", {
@@ -376,6 +440,7 @@ function registerEntityReads(server, ctx) {
376
440
  since: dateString.optional(),
377
441
  until: dateString.optional()
378
442
  },
443
+ outputSchema: toolOutputSchema(exerciseHistoryOutputSchema),
379
444
  annotations: READ
380
445
  }, ({ athleteId, exerciseId, raw, since, until }) => attempt(async () => {
381
446
  const detail = await fetchExerciseHistoryDetail(ctx.client, toId(exerciseId), toId(athleteId));
@@ -389,6 +454,7 @@ function registerEntityReads(server, ctx) {
389
454
  athleteIds: z.array(idParam).min(1),
390
455
  useMetric: z.boolean().optional()
391
456
  },
457
+ outputSchema: toolOutputSchema(rosterActivityOutputSchema),
392
458
  annotations: READ
393
459
  }, ({ athleteIds, useMetric }) => attempt(async () => jsonResult(await fetchRosterActivity(ctx.client, athleteIds.map(toId), useMetric ?? false), { hint: "Sorted most-recently-active first; lastLoggedDate null = never logged. The top row is the most recently active athlete." })));
394
460
  server.registerTool("athlete_training", {
@@ -399,6 +465,7 @@ function registerEntityReads(server, ctx) {
399
465
  year: z.number().int(),
400
466
  month: z.number().int().min(1).max(12)
401
467
  },
468
+ outputSchema: toolOutputSchema(coachAthleteTrainingOutputSchema),
402
469
  annotations: READ
403
470
  }, ({ athleteId, year, month }) => attempt(async () => {
404
471
  const raw = await fetchCoachAthleteCalendarSummary(ctx.client, toId(athleteId), year, month);
@@ -408,6 +475,7 @@ function registerEntityReads(server, ctx) {
408
475
  title: "Get program detail",
409
476
  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.",
410
477
  inputSchema: { programId: idParam },
478
+ outputSchema: opaqueOutputSchema,
411
479
  annotations: READ
412
480
  }, ({ programId }) => getProgram(ctx, toId(programId)));
413
481
  }
@@ -442,6 +510,7 @@ function registerTeamVolume(server, ctx) {
442
510
  dateStart: dateString,
443
511
  dateEnd: dateString
444
512
  },
513
+ outputSchema: toolOutputSchema(teamVolumeOutputSchema),
445
514
  annotations: READ
446
515
  }, ({ teamId, athleteIds, dateStart, dateEnd }) => attempt(async () => {
447
516
  const ids = athleteIds !== void 0 && athleteIds.length > 0 ? athleteIds.map(toId) : teamId !== void 0 ? await fetchTeamAthleteIds(ctx.client, toId(teamId)) : [];
@@ -455,9 +524,19 @@ function registerTeamVolume(server, ctx) {
455
524
  }
456
525
  function registerReadTools(server, ctx) {
457
526
  registerRosterReads(server, ctx);
527
+ registerCoachAthleteTeamCalendar(server, ctx);
458
528
  registerEntityReads(server, ctx);
459
529
  registerTeamVolume(server, ctx);
460
530
  }
531
+ function registerCoachAthleteTeamCalendar(server, ctx) {
532
+ server.registerTool("coach_athlete_team_calendar", {
533
+ title: "Coach-athlete team calendar",
534
+ description: "Companion calendar for a roster athlete (GET /v5/calendars/athletes/{id}/coachAthleteTeam). Distinct from workout_build's type-5 individual calendar. Returns title, logo, id, athlete_id, owner_user_id.",
535
+ inputSchema: { athleteId: idParam },
536
+ outputSchema: opaqueOutputSchema,
537
+ annotations: READ
538
+ }, ({ athleteId }) => apiCall(ctx, "GET", `/v5/calendars/athletes/${toId(athleteId)}/coachAthleteTeam`));
539
+ }
461
540
  //#endregion
462
541
  //#region src/tools/main-lifts.ts
463
542
  const monthsParam = z.number().int().positive().max(36).optional();
@@ -472,6 +551,7 @@ function registerMainLiftTools(server, ctx) {
472
551
  athleteId: idParam,
473
552
  months: monthsParam
474
553
  },
554
+ outputSchema: toolOutputSchema(athleteMainLiftPrsOutputSchema),
475
555
  annotations: READ
476
556
  }, ({ athleteId, months }) => attempt(async () => jsonResult(await fetchAthleteMainLiftPRs(ctx.client, toId(athleteId), months !== void 0 ? { months } : {}))));
477
557
  server.registerTool("roster_main_lift_prs", {
@@ -481,6 +561,7 @@ function registerMainLiftTools(server, ctx) {
481
561
  months: monthsParam,
482
562
  athleteIds: z.array(idParam).optional()
483
563
  },
564
+ outputSchema: toolOutputSchema(z.array(athleteMainLiftPrsOutputSchema)),
484
565
  annotations: READ
485
566
  }, ({ months, athleteIds }) => attempt(async () => {
486
567
  return jsonResult(await fetchRosterMainLiftPRs(ctx.client, {
@@ -497,12 +578,14 @@ function registerProfileTools(server, ctx, whoami, userId) {
497
578
  title: "Who am I (athlete)",
498
579
  description: "The logged-in account's identity (id, name, roles) from /user/simple.",
499
580
  inputSchema: {},
581
+ outputSchema: toolOutputSchema(userSimpleSchema),
500
582
  annotations: READ
501
583
  }, () => attempt(async () => jsonResult(await whoami())));
502
584
  server.registerTool("athlete_profile", {
503
585
  title: "Athlete profile + lifetime totals",
504
586
  description: "Lifetime training totals in one call — all-time session count (summary.sessions_count), total reps and volume, first/last logged date — plus the profile (name, units, dob). Use this for any 'how many sessions all-time / total volume ever' question rather than summing athlete_workouts windows. Set useMetric for kg/metric totals.",
505
587
  inputSchema: { useMetric: z.boolean().optional() },
588
+ outputSchema: toolOutputSchema(athleteProfileOutputSchema),
506
589
  annotations: READ
507
590
  }, ({ useMetric }) => attempt(async () => {
508
591
  const id = await userId();
@@ -516,12 +599,14 @@ function registerProfileTools(server, ctx, whoami, userId) {
516
599
  title: "Athlete preferences",
517
600
  description: "Notification and display preference flags for the athlete account.",
518
601
  inputSchema: {},
602
+ outputSchema: toolOutputSchema(athletePrefsSchema),
519
603
  annotations: READ
520
604
  }, () => attempt(async () => jsonResult(await fetchAthletePrefs(ctx.client))));
521
605
  server.registerTool("athlete_working_maxes", {
522
606
  title: "Working maxes",
523
607
  description: "The athlete's working max per exercise (drives % prescriptions). An entry can carry a null value: the exercise has a working-max slot but no number has been set yet, which means there is effectively no working max for it.",
524
608
  inputSchema: {},
609
+ outputSchema: toolOutputSchema(athleteWorkingMaxListSchema),
525
610
  annotations: READ
526
611
  }, () => attempt(async () => jsonResult(await fetchWorkingMaxes(ctx.client))));
527
612
  server.registerTool("athlete_leaderboard", {
@@ -533,6 +618,7 @@ function registerProfileTools(server, ctx, whoami, userId) {
533
618
  pageSize: z.number().int().positive().max(200).optional(),
534
619
  gender: z.number().int().optional()
535
620
  },
621
+ outputSchema: opaqueOutputSchema,
536
622
  annotations: READ
537
623
  }, ({ workoutId, page, pageSize, gender }) => attempt(async () => {
538
624
  const opts = {};
@@ -589,6 +675,7 @@ function registerExerciseTools$1(server, ctx, userId) {
589
675
  limit: z.number().int().positive().max(200).optional(),
590
676
  summary: z.boolean().optional()
591
677
  },
678
+ outputSchema: toolOutputSchema(athleteWorkoutsOutputSchema),
592
679
  annotations: READ
593
680
  }, (args) => runAthleteWorkouts(ctx, args));
594
681
  server.registerTool("athlete_exercises", {
@@ -598,6 +685,7 @@ function registerExerciseTools$1(server, ctx, userId) {
598
685
  q: z.string().optional(),
599
686
  limit: z.number().int().positive().optional()
600
687
  },
688
+ outputSchema: toolOutputSchema(athleteExerciseCatalogOutputSchema),
601
689
  annotations: READ
602
690
  }, (args) => runAthleteExercises(ctx, args));
603
691
  server.registerTool("athlete_exercise_history", {
@@ -609,6 +697,7 @@ function registerExerciseTools$1(server, ctx, userId) {
609
697
  since: dateString.optional(),
610
698
  until: dateString.optional()
611
699
  },
700
+ outputSchema: toolOutputSchema(exerciseHistoryOutputSchema),
612
701
  annotations: READ
613
702
  }, ({ exerciseId, raw, since, until }) => attempt(async () => {
614
703
  const detail = await fetchExerciseHistoryDetail(ctx.client, toId(exerciseId), await userId());
@@ -619,6 +708,7 @@ function registerExerciseTools$1(server, ctx, userId) {
619
708
  title: "Exercise personal records",
620
709
  description: "The all-time PR board for an exercise (reps/weight per rep-max, strength-standard filters). Get the exercise id from athlete_exercises. A lift is often logged under several name variants, each with its own board, so if a PR looks missing check the other variants. For a point-in-time snapshot use athlete_exercise_stats; for the dated session trend use athlete_exercise_history.",
621
710
  inputSchema: { exerciseId: idParam },
711
+ outputSchema: toolOutputSchema(personalRecordListSchema),
622
712
  annotations: READ
623
713
  }, ({ exerciseId }) => attempt(async () => jsonResult(await fetchPersonalRecords(ctx.client, toId(exerciseId)))));
624
714
  server.registerTool("athlete_exercise_stats", {
@@ -628,6 +718,7 @@ function registerExerciseTools$1(server, ctx, userId) {
628
718
  exerciseId: idParam,
629
719
  date: dateString
630
720
  },
721
+ outputSchema: toolOutputSchema(exerciseStatsSchema),
631
722
  annotations: READ
632
723
  }, ({ exerciseId, date }) => attempt(async () => jsonResult(await fetchExerciseStats(ctx.client, toId(exerciseId), await userId(), date))));
633
724
  }
@@ -644,6 +735,7 @@ function registerLogTargetsTool(server, ctx) {
644
735
  teamId: idParam.optional(),
645
736
  raw: z.boolean().optional()
646
737
  },
738
+ outputSchema: toolOutputSchema(logTargetsOutputSchema),
647
739
  annotations: READ
648
740
  }, ({ startDate, endDate, program, programId, teamId, raw }) => attempt(async () => {
649
741
  const all = await fetchAthleteWorkouts(ctx.client, startDate, endDate);
@@ -663,11 +755,8 @@ function registerSessionTools(server, ctx) {
663
755
  title: "Create personal workout session",
664
756
  description: "Create a new personal workout session for a given YYYY-MM-DD date on the athlete's personal calendar. Returns programWorkoutId, workoutId (pass to athlete_session_add_exercises), savedWorkoutId, groupId, and date.",
665
757
  inputSchema: { date: dateString },
666
- annotations: {
667
- readOnlyHint: false,
668
- destructiveHint: false,
669
- openWorldHint: true
670
- }
758
+ outputSchema: toolOutputSchema(personalWorkoutCreatedOutputSchema),
759
+ annotations: ADDITIVE
671
760
  }, ({ date }) => attempt(async () => jsonResult(await createPersonalWorkout(ctx.client, date))));
672
761
  server.registerTool("athlete_session_add_exercises", {
673
762
  title: "Add exercises to a personal workout session",
@@ -679,11 +768,8 @@ function registerSessionTools(server, ctx) {
679
768
  order: z.number().int().positive()
680
769
  })).min(1)
681
770
  },
682
- annotations: {
683
- readOnlyHint: false,
684
- destructiveHint: false,
685
- openWorldHint: true
686
- }
771
+ outputSchema: opaqueOutputSchema,
772
+ annotations: ADDITIVE
687
773
  }, ({ workoutId, exercises }) => attempt(async () => {
688
774
  const mapped = exercises.map((e) => ({
689
775
  exerciseId: toId(e.exerciseId),
@@ -698,6 +784,7 @@ function registerSessionTools(server, ctx) {
698
784
  ...athleteSessionRemoveArgsSchema.shape,
699
785
  confirm: z.boolean().optional()
700
786
  },
787
+ outputSchema: toolOutputSchema(athleteSessionRemovedOutputSchema),
701
788
  annotations: DESTRUCTIVE
702
789
  }, ({ programWorkoutId, date, confirm }, extra) => attempt(async () => {
703
790
  const id = toId(programWorkoutId);
@@ -740,6 +827,7 @@ function registerLogTool(server, ctx) {
740
827
  ...logSessionArgsSchema.shape,
741
828
  confirm: z.boolean().optional()
742
829
  },
830
+ outputSchema: toolOutputSchema(sessionLogOutputSchema),
743
831
  annotations: DESTRUCTIVE
744
832
  }, ({ date, exercises, confirm }, extra) => attempt(async () => {
745
833
  const blocked = confirmGate(extra, `Log a session of ${exercises.length} exercise(s) on ${date}? This writes to your coach-visible training log.`, confirm);
@@ -758,6 +846,7 @@ function registerLogTool(server, ctx) {
758
846
  ...logSetArgsSchema.shape,
759
847
  confirm: z.boolean().optional()
760
848
  },
849
+ outputSchema: toolOutputSchema(setLogOutputSchema),
761
850
  annotations: DESTRUCTIVE
762
851
  }, ({ date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
763
852
  const blocked = confirmGate(extra, `Log results to saved workout set ${toId(savedWorkoutSetId)} on ${date}? This writes to your coach-visible training log.`, confirm);
@@ -775,6 +864,7 @@ function registerLogTool(server, ctx) {
775
864
  ...athletePrescribeSetArgsSchema.shape,
776
865
  confirm: z.boolean().optional()
777
866
  },
867
+ outputSchema: toolOutputSchema(setPrescriptionOutputSchema),
778
868
  annotations: DESTRUCTIVE
779
869
  }, ({ date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
780
870
  const id = toId(savedWorkoutSetId);
@@ -801,6 +891,7 @@ function registerSwapTool(server, ctx) {
801
891
  ...swapAthleteExerciseArgsSchema.shape,
802
892
  confirm: z.boolean().optional()
803
893
  },
894
+ outputSchema: toolOutputSchema(exerciseSwapOutputSchema),
804
895
  annotations: DESTRUCTIVE
805
896
  }, ({ savedWorkoutSetExerciseId, exerciseId, confirm }, extra) => attempt(async () => {
806
897
  const sweId = toId(savedWorkoutSetExerciseId);
@@ -813,6 +904,29 @@ function registerSwapTool(server, ctx) {
813
904
  }));
814
905
  }));
815
906
  }
907
+ function registerCatalogReads(server, ctx) {
908
+ server.registerTool("athlete_circuits", {
909
+ title: "Circuit history",
910
+ description: "Named circuit history for the logged-in athlete (GET /v5/users/circuits/{recent|history}). kind defaults to recent. Empty when the athlete has no saved circuits. Distinct from circuit *blocks* in workout_build (type 1).",
911
+ inputSchema: { kind: z.enum(["recent", "history"]).optional() },
912
+ outputSchema: opaqueOutputSchema,
913
+ annotations: READ
914
+ }, ({ kind }) => attempt(async () => jsonResult(await fetchAthleteCircuits(ctx.client, kind ?? "recent"))));
915
+ server.registerTool("athlete_programming_programs", {
916
+ title: "Subscribed programs",
917
+ description: "Programs the athlete is subscribed to (GET /1.0/athlete/programming/programs). Not the coach list_programs surface. Empty when the athlete has no subscriptions.",
918
+ inputSchema: {},
919
+ outputSchema: opaqueOutputSchema,
920
+ annotations: READ
921
+ }, () => attempt(async () => jsonResult(await fetchAthleteProgrammingPrograms(ctx.client))));
922
+ server.registerTool("athlete_recent_exercises", {
923
+ title: "Recent exercises",
924
+ description: "Recently used exercises (GET /v5/users/exercises/recent). Distinct from athlete_exercises (full logged catalog) and athlete_exercise_history (one lift).",
925
+ inputSchema: {},
926
+ outputSchema: opaqueOutputSchema,
927
+ annotations: READ
928
+ }, () => attempt(async () => jsonResult(await fetchRecentExercises(ctx.client))));
929
+ }
816
930
  /**
817
931
  * Live tools over the logged-in user's own training (history, scheduled/completed workouts,
818
932
  * PRs, working maxes), plus a gated set-logging write. The athlete user id is
@@ -835,6 +949,7 @@ function registerAthleteTrainingTools(server, ctx) {
835
949
  };
836
950
  registerProfileTools(server, ctx, whoami, userId);
837
951
  registerExerciseTools$1(server, ctx, userId);
952
+ registerCatalogReads(server, ctx);
838
953
  registerLogTargetsTool(server, ctx);
839
954
  registerSessionTools(server, ctx);
840
955
  registerLogTool(server, ctx);
@@ -863,6 +978,7 @@ function registerAthleteTools(server, ctx) {
863
978
  message: z.string().optional(),
864
979
  confirm: z.boolean().optional()
865
980
  },
981
+ outputSchema: toolOutputSchema(athleteInviteOutputSchema),
866
982
  annotations: DESTRUCTIVE
867
983
  }, ({ teamId, emails, message, confirm }, extra) => attempt(async () => {
868
984
  const list = asEmailList(emails);
@@ -887,6 +1003,7 @@ function registerAthleteTools(server, ctx) {
887
1003
  athleteIds: z.array(idParam).min(1),
888
1004
  confirm: z.boolean().optional()
889
1005
  },
1006
+ outputSchema: opaqueOutputSchema,
890
1007
  annotations: DESTRUCTIVE
891
1008
  }, ({ athleteIds, confirm }, extra) => attempt(async () => {
892
1009
  const ids = athleteIds.map(toId);
@@ -898,6 +1015,7 @@ function registerAthleteTools(server, ctx) {
898
1015
  title: "Restore athletes",
899
1016
  description: "Restore previously archived athletes to the active roster (PUT /v5/athletes/restore).",
900
1017
  inputSchema: { athleteIds: z.array(idParam).min(1) },
1018
+ outputSchema: opaqueOutputSchema,
901
1019
  annotations: {
902
1020
  readOnlyHint: false,
903
1021
  idempotentHint: true,
@@ -928,6 +1046,7 @@ function registerAthleteSavedWorkouts(server, ctx) {
928
1046
  teamId: idParam.optional(),
929
1047
  raw: z.boolean().optional()
930
1048
  },
1049
+ outputSchema: toolOutputSchema(logTargetsOutputSchema),
931
1050
  annotations: READ
932
1051
  }, ({ athleteId, startDate, endDate, program, programId, teamId, raw }) => attempt(async () => {
933
1052
  const all = await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate);
@@ -950,6 +1069,7 @@ function registerAthleteLogTools(server, ctx) {
950
1069
  ...coachLogSetArgsSchema.shape,
951
1070
  confirm: z.boolean().optional()
952
1071
  },
1072
+ outputSchema: toolOutputSchema(setLogOutputSchema),
953
1073
  annotations: DESTRUCTIVE
954
1074
  }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
955
1075
  const aId = toId(athleteId);
@@ -969,6 +1089,7 @@ function registerAthleteLogTools(server, ctx) {
969
1089
  ...coachLogSessionArgsSchema.shape,
970
1090
  confirm: z.boolean().optional()
971
1091
  },
1092
+ outputSchema: toolOutputSchema(sessionLogOutputSchema),
972
1093
  annotations: DESTRUCTIVE
973
1094
  }, ({ athleteId, date, exercises, confirm }, extra) => attempt(async () => {
974
1095
  const aId = toId(athleteId);
@@ -993,6 +1114,7 @@ function registerAthleteSwapTool(server, ctx) {
993
1114
  ...swapAthleteExerciseArgsSchema.shape,
994
1115
  confirm: z.boolean().optional()
995
1116
  },
1117
+ outputSchema: toolOutputSchema(exerciseSwapOutputSchema),
996
1118
  annotations: DESTRUCTIVE
997
1119
  }, ({ savedWorkoutSetExerciseId, exerciseId, confirm }, extra) => attempt(async () => {
998
1120
  const sweId = toId(savedWorkoutSetExerciseId);
@@ -1018,6 +1140,7 @@ function registerAthletePrescribeTool(server, ctx) {
1018
1140
  ...coachPrescribeSetArgsSchema.shape,
1019
1141
  confirm: z.boolean().optional()
1020
1142
  },
1143
+ outputSchema: toolOutputSchema(setPrescriptionOutputSchema),
1021
1144
  annotations: DESTRUCTIVE
1022
1145
  }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
1023
1146
  const aId = toId(athleteId);
@@ -1033,11 +1156,6 @@ function registerAthletePrescribeTool(server, ctx) {
1033
1156
  }
1034
1157
  //#endregion
1035
1158
  //#region src/tools/teams.ts
1036
- const ADDITIVE$1 = {
1037
- readOnlyHint: false,
1038
- destructiveHint: false,
1039
- openWorldHint: true
1040
- };
1041
1159
  /**
1042
1160
  * Team write tools. The team reads (list_teams, get_team, list_team_codes) live in
1043
1161
  * reads.ts; this module covers create/rename/delete plus the join-code lifecycle.
@@ -1047,7 +1165,8 @@ function registerTeamTools(server, ctx) {
1047
1165
  title: "Create a team",
1048
1166
  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.",
1049
1167
  inputSchema: { title: z.string().min(1) },
1050
- annotations: ADDITIVE$1
1168
+ outputSchema: opaqueOutputSchema,
1169
+ annotations: ADDITIVE
1051
1170
  }, ({ title }) => apiCall(ctx, "POST", "/1.0/coach/team/createWithTitleAndCode", { body: { title } }));
1052
1171
  server.registerTool("team_update", {
1053
1172
  title: "Update a team",
@@ -1057,7 +1176,8 @@ function registerTeamTools(server, ctx) {
1057
1176
  title: z.string().min(1).optional(),
1058
1177
  groupProgram: idParam.optional()
1059
1178
  },
1060
- annotations: ADDITIVE$1
1179
+ outputSchema: opaqueOutputSchema,
1180
+ annotations: ADDITIVE
1061
1181
  }, ({ teamId, title, groupProgram }) => attempt(async () => {
1062
1182
  const args = { teamId: toId(teamId) };
1063
1183
  if (title !== void 0) args.title = title;
@@ -1071,6 +1191,7 @@ function registerTeamTools(server, ctx) {
1071
1191
  teamId: idParam,
1072
1192
  confirm: z.boolean().optional()
1073
1193
  },
1194
+ outputSchema: opaqueOutputSchema,
1074
1195
  annotations: DESTRUCTIVE
1075
1196
  }, ({ teamId, confirm }, extra) => attempt(async () => {
1076
1197
  const id = toId(teamId);
@@ -1085,7 +1206,8 @@ function registerTeamTools(server, ctx) {
1085
1206
  teamId: idParam,
1086
1207
  type: z.number().int().optional()
1087
1208
  },
1088
- annotations: ADDITIVE$1
1209
+ outputSchema: opaqueOutputSchema,
1210
+ annotations: ADDITIVE
1089
1211
  }, ({ teamId, type }) => apiCall(ctx, "POST", `/v5/teams/${toId(teamId)}/teamCodes`, { body: { type: type ?? 2 } }));
1090
1212
  server.registerTool("team_code_delete", {
1091
1213
  title: "Delete a team join code",
@@ -1094,6 +1216,7 @@ function registerTeamTools(server, ctx) {
1094
1216
  codeId: idParam,
1095
1217
  confirm: z.boolean().optional()
1096
1218
  },
1219
+ outputSchema: opaqueOutputSchema,
1097
1220
  annotations: DESTRUCTIVE
1098
1221
  }, ({ codeId, confirm }, extra) => attempt(async () => {
1099
1222
  const id = toId(codeId);
@@ -1101,14 +1224,41 @@ function registerTeamTools(server, ctx) {
1101
1224
  if (blocked) return blocked;
1102
1225
  return apiCall(ctx, "DELETE", `/v5/teamCodes/${id}`);
1103
1226
  }));
1227
+ registerTeamPublishSettings(server, ctx);
1228
+ }
1229
+ function registerTeamPublishSettings(server, ctx) {
1230
+ server.registerTool("team_publish_settings", {
1231
+ title: "Update team auto-publish",
1232
+ description: "Update a team's auto-publish settings (POST /1.0/coach/team/updatePublishSettings). Pass teamId or programId (the team's group_program). At least one of pub_enabled, pub_days, pub_time, pub_timezone is required. Athlete-facing — requires confirmation.",
1233
+ inputSchema: {
1234
+ teamId: idParam.optional(),
1235
+ programId: idParam.optional(),
1236
+ ...teamPublishPatchObject.shape,
1237
+ confirm: z.boolean().optional()
1238
+ },
1239
+ outputSchema: opaqueOutputSchema,
1240
+ annotations: DESTRUCTIVE
1241
+ }, ({ teamId, programId, pub_enabled, pub_days, pub_time, pub_timezone, confirm }, extra) => attempt(async () => {
1242
+ const blocked = confirmGate(extra, "Change auto-publish settings? This controls when athletes see programmed sessions.", confirm);
1243
+ if (blocked) return blocked;
1244
+ const patch = teamPublishPatchSchema.parse(definedProps({
1245
+ pub_enabled,
1246
+ pub_days,
1247
+ pub_time,
1248
+ pub_timezone
1249
+ }));
1250
+ const target = teamPublishTarget(definedProps({
1251
+ programId: programId !== void 0 ? toId(programId) : void 0,
1252
+ teamId: teamId !== void 0 ? toId(teamId) : void 0
1253
+ }));
1254
+ return jsonResult(await updateTeamPublishSettings(ctx.client, {
1255
+ ...target,
1256
+ patch
1257
+ }));
1258
+ }));
1104
1259
  }
1105
1260
  //#endregion
1106
1261
  //#region src/tools/programs.ts
1107
- const ADDITIVE = {
1108
- readOnlyHint: false,
1109
- destructiveHint: false,
1110
- openWorldHint: true
1111
- };
1112
1262
  /** Standalone program writes. Program reads live in reads.ts. */
1113
1263
  function registerProgramTools(server, ctx) {
1114
1264
  server.registerTool("program_create", {
@@ -1118,11 +1268,27 @@ function registerProgramTools(server, ctx) {
1118
1268
  kind: z.enum(PROGRAM_KINDS),
1119
1269
  name: z.string().trim().min(1)
1120
1270
  },
1271
+ outputSchema: toolOutputSchema(programCreatedOutputSchema),
1121
1272
  annotations: ADDITIVE
1122
1273
  }, ({ kind, name }) => attempt(async () => jsonResult(await createProgram(ctx.client, {
1123
1274
  kind,
1124
1275
  name
1125
1276
  }))));
1277
+ server.registerTool("program_delete", {
1278
+ title: "Delete a standalone program",
1279
+ description: "Delete a standalone calendar or fixed program (DELETE /v5/programs/{programId}). Accepts either list_programs id (container) or group_program (the underlying program id); container ids 401 if sent raw and are resolved automatically. Removes the calendar from the live account. Requires confirmation (elicitation, or confirm:true).",
1280
+ inputSchema: {
1281
+ programId: idParam,
1282
+ confirm: z.boolean().optional()
1283
+ },
1284
+ outputSchema: toolOutputSchema(programDeletedOutputSchema),
1285
+ annotations: DESTRUCTIVE
1286
+ }, ({ programId, confirm }, extra) => attempt(async () => {
1287
+ const id = toId(programId);
1288
+ const blocked = confirmGate(extra, `Delete standalone program ${id}? This removes the calendar from the live account.`, confirm);
1289
+ if (blocked) return blocked;
1290
+ return jsonResult(await deleteProgram(ctx.client, id));
1291
+ }));
1126
1292
  }
1127
1293
  //#endregion
1128
1294
  //#region src/tools/analytics.ts
@@ -1142,6 +1308,7 @@ function registerAnalyticsTools(server, ctx) {
1142
1308
  dateEnd: z.string().optional(),
1143
1309
  useMetric: z.boolean().optional()
1144
1310
  },
1311
+ outputSchema: opaqueOutputSchema,
1145
1312
  annotations: READ
1146
1313
  }, ({ metric, teamId, userIds, exerciseId, date, dateStart, dateEnd, useMetric }) => attempt(async () => jsonResult(await queryAnalytics(ctx.client, definedProps({
1147
1314
  metric,
@@ -1156,17 +1323,42 @@ function registerAnalyticsTools(server, ctx) {
1156
1323
  }
1157
1324
  //#endregion
1158
1325
  //#region src/tools/exercises.ts
1159
- /**
1160
- * Exercise library tools over the ExerciseIndex — a D1 mirror on the hosted server, an
1161
- * on-disk/in-memory cache locally. The descriptions stay at the interface level so they
1162
- * read correctly on both backends.
1163
- */
1164
- function registerExerciseTools(server, ctx) {
1165
- const index = ctx.index;
1326
+ function registerExerciseUpdate(server, index) {
1327
+ server.registerTool("exercise_update", {
1328
+ title: "Update custom exercise",
1329
+ description: "Update a custom exercise (POST /2.0/coach/exercise/update/{id}) and write it through to the mirror. Same body as exercise_create. Only works for exercises with can_edit:1.",
1330
+ inputSchema: {
1331
+ id: idParam,
1332
+ exercise: exerciseCreateSchema
1333
+ },
1334
+ outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
1335
+ annotations: ADDITIVE
1336
+ }, ({ id, exercise }) => attempt(async () => jsonResult(await index.update(toId(id), exercise))));
1337
+ }
1338
+ function registerExerciseDelete(server, index) {
1339
+ server.registerTool("exercise_delete", {
1340
+ title: "Delete custom exercise",
1341
+ description: "Delete a custom exercise on TrainHeroic (DELETE /v5/exercises/{id}) and drop it from the local mirror. Only works for exercises with can_edit:1. Built-in library exercises cannot be deleted. Requires confirmation (elicitation, or confirm:true). exercise_forget only clears the cache — use this to delete the live exercise.",
1342
+ inputSchema: {
1343
+ id: idParam,
1344
+ confirm: z.boolean().optional()
1345
+ },
1346
+ outputSchema: toolOutputSchema(exerciseDeletedOutputSchema),
1347
+ annotations: DESTRUCTIVE
1348
+ }, ({ id, confirm }, extra) => attempt(async () => {
1349
+ const exerciseId = toId(id);
1350
+ const blocked = confirmGate(extra, `Delete custom exercise ${exerciseId} from the live TrainHeroic library?`, confirm);
1351
+ if (blocked) return blocked;
1352
+ await index.remove(exerciseId);
1353
+ return jsonResult({ deleted: exerciseId });
1354
+ }));
1355
+ }
1356
+ function registerExerciseReads(server, index) {
1166
1357
  server.registerTool("exercise_resolve", {
1167
1358
  title: "Resolve exercise name",
1168
1359
  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.",
1169
1360
  inputSchema: { name: z.string().min(1) },
1361
+ outputSchema: toolOutputSchema(exerciseResolveOutputSchema),
1170
1362
  annotations: READ
1171
1363
  }, ({ name }) => attempt(async () => jsonResult(await index.resolve(name))));
1172
1364
  server.registerTool("exercise_search", {
@@ -1176,12 +1368,14 @@ function registerExerciseTools(server, ctx) {
1176
1368
  query: z.string().min(1),
1177
1369
  limit: z.number().int().positive().max(100).optional()
1178
1370
  },
1371
+ outputSchema: toolOutputSchema(z.array(exerciseViewSchema)),
1179
1372
  annotations: READ
1180
1373
  }, ({ query, limit }) => attempt(async () => jsonResult(await index.search(query, limit ?? 20))));
1181
1374
  server.registerTool("exercise_get", {
1182
1375
  title: "Get exercise",
1183
1376
  description: "Full exercise object (with units) by id.",
1184
1377
  inputSchema: { id: idParam },
1378
+ outputSchema: toolOutputSchema(exerciseGetOutputSchema),
1185
1379
  annotations: READ
1186
1380
  }, ({ id }) => attempt(async () => {
1187
1381
  const ex = await index.get(toId(id));
@@ -1191,29 +1385,40 @@ function registerExerciseTools(server, ctx) {
1191
1385
  title: "Sync exercise library",
1192
1386
  description: "Refresh the cached exercise index from TrainHeroic.",
1193
1387
  inputSchema: { force: z.boolean().optional() },
1388
+ outputSchema: opaqueOutputSchema,
1194
1389
  annotations: SYNC
1195
1390
  }, ({ force }) => attempt(async () => {
1196
1391
  if (force ?? false) return jsonResult(await index.refresh());
1197
1392
  await index.ensureFresh();
1198
1393
  return jsonResult(await index.stats());
1199
1394
  }));
1395
+ }
1396
+ /**
1397
+ * Exercise library tools over the ExerciseIndex — a D1 mirror on the hosted server, an
1398
+ * on-disk/in-memory cache locally. The descriptions stay at the interface level so they
1399
+ * read correctly on both backends.
1400
+ */
1401
+ function registerExerciseTools(server, ctx) {
1402
+ const index = ctx.index;
1403
+ registerExerciseReads(server, index);
1200
1404
  server.registerTool("exercise_create", {
1201
1405
  title: "Create custom exercise",
1202
1406
  description: "Create a custom exercise (POST /2.0/coach/exercise/create) and write it through to the mirror. Body example: {\"title\":\"Sandbag Clean\",\"param_1_type\":3,\"param_2_type\":1}.",
1203
1407
  inputSchema: { exercise: exerciseCreateSchema },
1204
- annotations: {
1205
- readOnlyHint: false,
1206
- destructiveHint: false,
1207
- openWorldHint: true
1208
- }
1408
+ outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
1409
+ annotations: ADDITIVE
1209
1410
  }, ({ exercise }) => attempt(async () => jsonResult(await index.create(exercise))));
1411
+ registerExerciseUpdate(server, index);
1412
+ registerExerciseDelete(server, index);
1210
1413
  server.registerTool("exercise_forget", {
1211
1414
  title: "Forget exercise (cache only)",
1212
- description: "Remove an exercise from the local mirror only. Run after deleting it via the API.",
1415
+ description: "Remove an exercise from the local mirror only. Does not call TrainHeroic — use exercise_delete to delete the live custom exercise.",
1213
1416
  inputSchema: { id: idParam },
1417
+ outputSchema: toolOutputSchema(exerciseForgottenOutputSchema),
1214
1418
  annotations: {
1215
1419
  readOnlyHint: false,
1216
1420
  idempotentHint: true,
1421
+ destructiveHint: false,
1217
1422
  openWorldHint: false
1218
1423
  }
1219
1424
  }, ({ id }) => attempt(async () => {
@@ -1224,6 +1429,7 @@ function registerExerciseTools(server, ctx) {
1224
1429
  title: "Exercise index stats",
1225
1430
  description: "Row counts and sync state for the cached exercise index.",
1226
1431
  inputSchema: {},
1432
+ outputSchema: opaqueOutputSchema,
1227
1433
  annotations: READ
1228
1434
  }, () => attempt(async () => jsonResult(await index.stats())));
1229
1435
  }
@@ -1242,11 +1448,8 @@ function registerBuild(server, ctx) {
1242
1448
  blocks: z.array(blockSpecSchema),
1243
1449
  instruction: z.string().optional()
1244
1450
  },
1245
- annotations: {
1246
- readOnlyHint: false,
1247
- destructiveHint: false,
1248
- openWorldHint: true
1249
- }
1451
+ outputSchema: toolOutputSchema(workoutBuildOutputSchema),
1452
+ annotations: ADDITIVE
1250
1453
  }, ({ programId, athleteId, date, timelineDay, blocks, instruction }) => attempt(async () => {
1251
1454
  if (date === void 0 && timelineDay === void 0) return errorResult("Provide either date (YYYY-M-D) or timelineDay.");
1252
1455
  const resolveArgs = {};
@@ -1286,10 +1489,8 @@ function registerReadPublish(server, ctx) {
1286
1489
  date: z.string(),
1287
1490
  pwId: z.number()
1288
1491
  },
1289
- annotations: {
1290
- readOnlyHint: true,
1291
- openWorldHint: true
1292
- }
1492
+ outputSchema: toolOutputSchema(workoutReadOutputSchema),
1493
+ annotations: READ
1293
1494
  }, ({ programId, date, pwId }) => attempt(async () => jsonResult(await readSession(ctx.client, programId, parseWorkoutDate(date), pwId))));
1294
1495
  server.registerTool("workout_publish", {
1295
1496
  title: "Publish a session",
@@ -1300,11 +1501,8 @@ function registerReadPublish(server, ctx) {
1300
1501
  pwId: z.number(),
1301
1502
  confirm: z.boolean().optional()
1302
1503
  },
1303
- annotations: {
1304
- readOnlyHint: false,
1305
- destructiveHint: true,
1306
- openWorldHint: true
1307
- }
1504
+ outputSchema: toolOutputSchema(workoutPublishOutputSchema),
1505
+ annotations: DESTRUCTIVE
1308
1506
  }, ({ programId, date, pwId, confirm }, extra) => attempt(async () => {
1309
1507
  const blocked = confirmGate(extra, `Publish session ${pwId} on ${date}? This is athlete-facing and immediate.`, confirm);
1310
1508
  if (blocked) return blocked;
@@ -1326,11 +1524,8 @@ function registerLifecycle(server, ctx) {
1326
1524
  pwId: z.number(),
1327
1525
  confirm: z.boolean().optional()
1328
1526
  },
1329
- annotations: {
1330
- readOnlyHint: false,
1331
- destructiveHint: true,
1332
- openWorldHint: true
1333
- }
1527
+ outputSchema: toolOutputSchema(removedSessionOutputSchema),
1528
+ annotations: DESTRUCTIVE
1334
1529
  }, ({ programId, pwId, confirm }, extra) => attempt(async () => {
1335
1530
  const blocked = confirmGate(extra, `Delete session ${pwId}? This removes it from the live calendar and is hard to undo.`, confirm);
1336
1531
  if (blocked) return blocked;
@@ -1344,11 +1539,8 @@ function registerLifecycle(server, ctx) {
1344
1539
  pwId: z.number(),
1345
1540
  confirm: z.boolean().optional()
1346
1541
  },
1347
- annotations: {
1348
- readOnlyHint: false,
1349
- destructiveHint: true,
1350
- openWorldHint: true
1351
- }
1542
+ outputSchema: opaqueOutputSchema,
1543
+ annotations: DESTRUCTIVE
1352
1544
  }, ({ pwId, confirm }, extra) => attempt(async () => {
1353
1545
  const blocked = confirmGate(extra, `Unpublish session ${pwId}? Athletes will no longer see it.`, confirm);
1354
1546
  if (blocked) return blocked;
@@ -1362,11 +1554,8 @@ function registerLifecycle(server, ctx) {
1362
1554
  pwId: z.number(),
1363
1555
  toDate: z.string()
1364
1556
  },
1365
- annotations: {
1366
- readOnlyHint: false,
1367
- destructiveHint: false,
1368
- openWorldHint: true
1369
- }
1557
+ outputSchema: opaqueOutputSchema,
1558
+ annotations: ADDITIVE
1370
1559
  }, ({ toProgramId, pwId, toDate }) => attempt(async () => jsonResult(await copySession(ctx.client, {
1371
1560
  toProgramId,
1372
1561
  pwId,
@@ -1376,18 +1565,43 @@ function registerLifecycle(server, ctx) {
1376
1565
  title: "Save a session to the library",
1377
1566
  description: "Save an existing session as a reusable template in the session library (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the workout_id.",
1378
1567
  inputSchema: { workoutId: z.number() },
1379
- annotations: {
1380
- readOnlyHint: false,
1381
- destructiveHint: false,
1382
- openWorldHint: true
1383
- }
1568
+ outputSchema: opaqueOutputSchema,
1569
+ annotations: ADDITIVE
1384
1570
  }, ({ workoutId }) => apiCall(ctx, "POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${workoutId}`));
1385
1571
  }
1572
+ function registerTemplateLibrary(server, ctx) {
1573
+ server.registerTool("session_template_create", {
1574
+ title: "Create a session template",
1575
+ description: "Create an empty reusable session template in the library (POST /v5/sessions/template). Distinct from session_save_as_template, which copies an existing session. Pass title and optional instruction.",
1576
+ inputSchema: sessionTemplateCreateSchema.shape,
1577
+ outputSchema: toolOutputSchema(sessionTemplateCreatedOutputSchema),
1578
+ annotations: ADDITIVE
1579
+ }, ({ title, instruction }) => attempt(async () => jsonResult(await createSessionTemplate(ctx.client, definedProps({
1580
+ title,
1581
+ instruction
1582
+ })))));
1583
+ server.registerTool("session_template_delete", {
1584
+ title: "Delete a session template",
1585
+ description: "Delete a library session template (DELETE /v5/sessions/template/{id}). Requires confirmation (elicitation, or confirm:true).",
1586
+ inputSchema: {
1587
+ id: idParam,
1588
+ confirm: z.boolean().optional()
1589
+ },
1590
+ outputSchema: opaqueOutputSchema,
1591
+ annotations: DESTRUCTIVE
1592
+ }, ({ id, confirm }, extra) => attempt(async () => {
1593
+ const templateId = toId(id);
1594
+ const blocked = confirmGate(extra, `Delete session template ${templateId} from the library?`, confirm);
1595
+ if (blocked) return blocked;
1596
+ return apiCall(ctx, "DELETE", `/v5/sessions/template/${templateId}`);
1597
+ }));
1598
+ }
1386
1599
  /** Workout building, read-back, publishing, and the session calendar lifecycle. */
1387
1600
  function registerWorkoutTools(server, ctx) {
1388
1601
  registerBuild(server, ctx);
1389
1602
  registerReadPublish(server, ctx);
1390
1603
  registerLifecycle(server, ctx);
1604
+ registerTemplateLibrary(server, ctx);
1391
1605
  }
1392
1606
  //#endregion
1393
1607
  //#region src/tools/messaging.ts
@@ -1396,6 +1610,7 @@ function registerReads(server, ctx) {
1396
1610
  title: "List conversations (live)",
1397
1611
  description: "List chat streams (id, kind, title) live from the API; no setup needed. Use the id to read/draft/send.",
1398
1612
  inputSchema: {},
1613
+ outputSchema: opaqueOutputSchema,
1399
1614
  annotations: READ
1400
1615
  }, () => attempt(async () => {
1401
1616
  return jsonResult((await fetchStreams(ctx.client)).map(({ stream, kind }) => ({
@@ -1414,12 +1629,14 @@ function registerReads(server, ctx) {
1414
1629
  limit: z.number().int().positive().max(200).optional(),
1415
1630
  afterCommentId: idParam.optional()
1416
1631
  },
1632
+ outputSchema: opaqueOutputSchema,
1417
1633
  annotations: READ
1418
1634
  }, ({ streamId, limit, afterCommentId }) => attempt(async () => jsonResult(await readLive(ctx.client, toId(streamId), limit ?? 20, afterCommentId === void 0 ? void 0 : toId(afterCommentId)))));
1419
1635
  server.registerTool("message_draft", {
1420
1636
  title: "Draft a message (preview only)",
1421
1637
  description: "Preview the exact payload and target WITHOUT sending. Always safe.",
1422
1638
  inputSchema: commentDraftSchema.shape,
1639
+ outputSchema: toolOutputSchema(messageDraftOutputSchema),
1423
1640
  annotations: READ
1424
1641
  }, ({ streamId, text, replyTo }) => attempt(async () => {
1425
1642
  const id = toId(streamId);
@@ -1439,6 +1656,7 @@ function registerWrites(server, ctx) {
1439
1656
  ...commentDraftSchema.shape,
1440
1657
  confirm: z.boolean().optional()
1441
1658
  },
1659
+ outputSchema: toolOutputSchema(messageSentOutputSchema),
1442
1660
  annotations: DESTRUCTIVE
1443
1661
  }, ({ streamId, text, replyTo, confirm }, extra) => attempt(async () => {
1444
1662
  const id = toId(streamId);
@@ -1457,6 +1675,7 @@ function registerWrites(server, ctx) {
1457
1675
  commentId: idParam,
1458
1676
  confirm: z.boolean().optional()
1459
1677
  },
1678
+ outputSchema: toolOutputSchema(messageDeletedOutputSchema),
1460
1679
  annotations: DESTRUCTIVE
1461
1680
  }, ({ streamId, commentId, confirm }, extra) => attempt(async () => {
1462
1681
  const blocked = confirmGate(extra, `Delete comment ${toId(commentId)} from stream ${toId(streamId)}? Acts on the live account.`, confirm);
@@ -1487,4 +1706,4 @@ function registerCoachTools(server, ctx) {
1487
1706
  registerMessagingTools(server, ctx);
1488
1707
  }
1489
1708
  //#endregion
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 };
1709
+ 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": "3.1.1",
3
+ "version": "3.3.0",
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.1.1",
29
- "@trainheroic-unofficial/js": "3.1.1"
28
+ "@trainheroic-unofficial/dto": "3.3.0",
29
+ "@trainheroic-unofficial/js": "3.3.0"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "^26.2.0",